Looping Statements in java
for loop in java
Syntax:-
for(initialization;condition;increment/decrement)
{
//statement or code to be executed
}
Working of - for loop
Example of - for loop
Example 1:- To display Hello 10 times
for(int i=1;i<=10;i++)
System.out.println(“Hello”);
Examples of - for loop
Example 1:- To display natural numbers from 1 to 10
for(int i=1;i<=10;i++)
System.out.println(i);
Example 2:- To display natural numbers from 10 to 1
for(int i=10;i>=1;i--)
System.out.println(i);
Examples of - for loop
Example 3:- To display odd numbers from 1 to 10
a) for(int i=1;i<=10;i=i+2) b) for(int i=1;i<=10;i++)
System.out.println(i); if(i%2!=0)System.out.println(i);
Example 4:- To display odd numbers from 10 to 1
for(int i=9;i>=1;i=i-2) b) for(int i=10;i>=1;i--)
System.out.println(i); if(i%2!=0)System.out.println(i);
Variations in for loop
Multiple Initializations, conditions and updations
for( int i = 1,j=1;i<=10&j<=12;i++,j+=2)
System.out.println(i+j);
Optional expressions
int i=1;
for(;i<=10;)
{
System.out.println(i);
i++;
}
while loop in java
Syntax:-
initialization;
while(condition)
{
//code to be executed
//updation
}
Working of - while loop
Initialization;
while(condition)
{
//code to be executed
//updation
}
do..while loop in java
Syntax:-
initialization;
do
{
//code to be executed
//updation
}
while(cond);
Working of – do...while loop
initialization;
do
{
//code to be executed
//updation
while(cond);
Entry controlled loop Vs Exit controlled loop
Entry controlled loop:- for loop and while loop are called
entry controlled loop as the test condition is checked at the
beginning of the loop.
Loop body is not executed if the condition is false.
Exit controlled loop:- do..while loop is an exit controlled loop
as the test condition is checked at the end of the loop.
Loop body is executed at least once irrespective of the given
loop condition.
Infinite loop
A loop that doesn't have any termination as the loop condition
is always true is called infinite loop.
Eg 1:-
for(int i = 1;i>0;i++)
System.out.println(i);
Eg 2:-
for(;;)
System.out.println(“Hello”);
Eg 3:-
for(i=1;i<=10;i--);
System.out.println(i);
Empty loop or time delay loop
A loop that doesnt contain any loop body statements to be
executed is called empty loop.
Eg 1:-
for( i = 1;i>0;i++);
System.out.println(i);
Eg 2:-
for(int i=1;i<=100000;i++)
{
// time delay loop
}
Converting for loop to while loop
for(initialization;cond;updation) initialization;
while(cond)
{
{
loop body statements; loop body statements;
} updation;
}
int i = 1;
for(int i =1;i<=10;i++) while(i<=10)
{ {
System.out.println(i); System.out.println(i);
} i++;
}