Text Size
Thursday, October 22, 2020

Content

Simple Loops in Java

There are three basic types of loops in Java: the for loop, the while loop, and the do loop.  Each type is explained below.

For Loops:

for (starting value; ending condition; iteration){
statement;
}

A for loop has three basic sections:

  1. The starting value on the loop's counter.
  2. The ending condition of the loop (what number will the loop stop at).
  3. The iteration: What will the counter count up or down by.

For example:
for (int count=1; count<100; count++)
statement;

This loop will start at count = 1. As long as count is less than (<) 100 the loop will continue to function. Count will add one to itself: count++.

While Loops:

while (condition){
statement;
}

A while loop is simpler than a for loop. A while loop will continue to loop as long as the condition is true.

For example:
while (int x != 10)
statement;

This loop will continue as long as x is not ten. If x's value is ten when the loop tests the condition the loop will stop.

Do Loops:

do {
statement;
while (condition);

For example:

int x = 3;
do
statement;
while (x < 10);

This loop would do the statement at least once and repeat as long as x is less than ten.

Example:

Download

Leave your comments

0
terms and condition.
  • No comments found
Parent Category: ICS3U