Friday 9 March 2012

Loop in java


Looping is used to develop programs which are having some repetitive process. When a particular block of statement have to reapete then loops are used . it makes the programmer job easier , because instead of writing same lines again and again , loop can be used.
 Loop is consist of  two segments one is body and other is exit condition . exit condition is a condition which will end the loop. Means the sequence of statement will reapete until the condition is true.
A looping process have four main steps , which are as follows:
1)      Setting and initialization of a counter
2)      Execution of statements
3)      Test for condition that whether  the condition is true or false
4)      Increment/decrement counter;
Java supports three type of loop statements :
While
Do while
For
While loop:- while loop is an entry-controlled loop statement . at first step the test condition is evaluated , if it is true then the statement is executed and if it is false the exit from loop. After execution of statement again the condition is evaluated and this process is repeated until the condition is true.
Syntax of while
Initialization :
While (test condition){
Body of loop
Increment/decrement
}  
Example of while loop
class whileLoop{
                public static void main(String args[]){
int i=0;
while(i<5){
System.out.println(i);
i++;
}
}
}
Output:
0
 1
2
3
4
Do while loop:-
In while loop first condition is tested then body of loop is executed .In in do while loop first the body of loop is executed and then condition is executed. So the minimum chance of execution of while loop is 0 an the minimum chance of execution of do while loop is 1. Because whether the condition is true or false the statement will be executed atleast for one time.
Syntax of do while loop
Initialization
do
{
Body of loop
}
While(test condition)
We can use nested loop that is loop inside loop according to requirement .
class doWhileLoop{
                public static void main(String args[]){
int row, column, x;
row=1;
do{
column =1;
do{
x=row*column;
column=column+1;
}while(column<=3);
System.out.println();
Row=row+1;
}while(row<=3);
}
}
Output
1    2   3
2    4    6
3   6     9

For loop:-
For loop is most widely used loop and very useful loop .because in for loop initialization , condition and increment/decrement are in a single row.
Syntax of for loop
For(initialization; test condition; increment/decrement){
Body of loop
}

Example of for loop:
public class foorloop {
      public static void main(String[] args) {
            for(int i=1;i<=10;i++){
                  System.out.println("2  * " +i + "=" + 2*i );
            }
      }
}

Output
2  * 1=2
2  * 2=4
2  * 3=6
2  * 4=8
2  * 5=10
2  * 6=12
2  * 7=14
2  * 8=16
2  * 9=18
2  * 10=20

We can use nested loops that is loop inside loop as many as required . There is no limit of nesting loops .

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...