Iteration Statement in JAVA
There may be a situation where we need to execute a block of code.
This statement are executed in order, except when a jump statement is encountered.
JAVA has very flexible 3 looping mechanism, you can use one of the following three loop.
- while loop.
- do while loop.
- for loop.
1 )- while loop :-
It is a control structure that allows to repeat a task, a certain no. of time while executing the while loop. if the Boolean expression is true then the action inside the loop will be executed. this will continue as long as the expression result is true. The key point of the while loop is the loop might not ever run if the expression is false.
Syntax :-
while(expression)
{
statement;
++ or --
}
ex :-
WAP to print first no.:
class test
{
public static void main(string args[])
{
int a = 1;
while(a>=10)
{
System.out.println(a);
a = a+1;
}
}
}
2 )- do...while loop :-
A do...while loop is similar to a while loop except a do while is guarantee to execute at least once.
The do while statement allows the expression to appears at the end of the loop, so the statement in the loop execute once before the Boolean is tested.
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in JAVA programming checks its condition at the bottom of the loop.
Syntax :-
do{
statement ;
++ or --
}while(expression);
ex :-
WAP to print the 1-10 no.
class test
{
public static void main(String args[])
{
int i = 1;
do
{
System.out.println(i);
i++
}while(i<=10);
}
}
3 )- for loop :-
The for loop is form 1 no. to another no. and increased by a specific value of time. A for loop is a control structure that allows you to write a loop that need to be execute a specific no. of time.
In computer science, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly.
Syntax :-
for(initialization; condition; increment/decrement)
{
statement;
}
ex :-
WAP to print 1st 10 numbers.
class test
{
public static void main(String args[])
{
int i = 1;
for(i = 1; i<=10; i++)
{
System.out.println(i);
}
}
}
4 )- for each :-
It is used for iterating over elements of array and collection.
Syntax :-
foreach(datatype variable_name : array_name or collection)
{
statement;
}
ex :-
class test
{
public static void main(String args[])
{
int a[]= {10, 20, 30, 40};
foreach(int b : a)
{
System.out.println(b);
}
}
}
0 Comments