Looping statements are used when we want to repeat the block of code multiple times as long as a certain conditions remains true.
There are three main looping statements.
- for loop
- while loop
- do while loop
for loop:
The for loop is ideal when the number of executions known in advance.
Syntax:
for(initialization; condition; Increment/decrement)
Example: For printing numbers form 1 ot 7
for(int i = 1; i<=7; i++)
{
System.out.println(i);
}
Output:
1
2
3
4
5
6
7
while lopp:
The while loop used when the number of execution is not fixed and depends on the condition.
Syntax:
initialization;
while(condition)
{
//code to be executed
increment/decrement;
}
Example:
int i = 1;
while(i<=3)
{
System.out.println(i);
i++;
}
Output:
1
2
3
Top comments (0)