This is used to execute the program repeatedly until a specific condition is met.
Three types of loops are;
- for loop.
- while loop.
- do-while loop.
for loop;-
Syntax:-
For(initialization; condition; update statement)
{
Statement
}
Note:
First initialized content is executed only one time. Then the test expression is executed, if the test expression is false then the loop gets terminated.
Example-
class Student
{
Public static void main(String args[])
{
int i=7;
for(i=1; i<8; i++)
{
System.out.println(“i”);
}
}
}
Output-
1 2 3 4 5 6 7.
While loop;-
Syntax-
Initialization;
While(testcondition)
{
Statement inside the body is executed
}
Example-
class Student { public static void main { int i=2; while(i<=9) { System.out.println(i); i++; } } }
Output-
2 3 4 5 6 7 8 9.
Do-while;-
The do-while loop is similar to the while loop. The body of do while loop is executed at least one. Only, the test expression is evaluated.
Syntax-
do
{
// statements inside the body of the loop
}
while (testExpression);
Example-
class Student
{
public static void main(String args[])
{
int i=12;
do
{
System.out.println(i);
i++;
}
while(i<=18)
}
}
Output-
12 13 14 15 16 18
Can you answer this question?
Answer
0 Answers