The for and while loop in java
We often arrive in this situation when we need to unwind a block of instructions several times. Java provides three types of loops:- for loop
- while loop
- do loop. while
The for loop in java
The for loop allows statements to be executed inside the block in repetition a certain number of times. It is useful when you know how many times the task will be repeated.
The syntax is as follows:
for(initialization, expression, increment)
- Initialization initializes the loop, .
- The loop stops when the expression condition is false.
- The variable increments or decrements after each execution.
for(int i = 0 ; i < 10 ; i++)Output:
System.out.println(i);
0The three for expressions are optional, An infinite loop is created as follows:
1
2
3
4
5
6
7
8
9
for( ; ; )
//instructions
The foreach loop in java
Another loop called the advanced for loop(Enhanced for ) designed for table browsing and data collections such as ArrayList. The following program implements the advanced for loop to iterate through array:String[] t = {"a","b","c","d","e","f","g","h","i","j","k"};Output:
for(String s:t)
System.out.println(s);
a
b
c
d
e
f
g
h
i
j
k
The while loop in java h2>The while loop executes the block as long as the condition is true. Its syntax is as follows:
while(expression)
//instructions
The condition of the expression evaluates and returns a Boolean value. If it is true, the while loop executes the block and continues execution until the expression evaluation returns a value false.
Example:
int nb=8;
while(nb> 0)
System.out.println(nb--);
Result:
8
7
6
5
4
3
2
1
The do-while loop in java
while(expression)The condition of the expression evaluates and returns a Boolean value. If it is true, the while loop executes the block and continues execution until the expression evaluation returns a value false.
//instructions
Example:
while(nb> 0)
System.out.println(nb--);
7
6
5
4
3
2
1
The do-while loop is similar to while except that do-while checks the condition at the end of the loop, so the block is executed at least once as shown in its syntax:
do {
//bloc
}while(expression);
Example:
nb=1;Output:
do{
System.out.println(nb++);
}while(nb%10!=0);
1References:
2
3
4
5
6
7
8
9
Java: Loops and conditional structures
oracle: The for Statement
oracle : The while Statement