Saturday 8 November 2014

Loops in JAVA


Loops are used to execute a particular block of code repeatedly.
General structure of while loop in java
while(condition){
body of loop
}
Here body of the loop executes until condition satisfies.
Let's take an example

Find out the output.

Output will be 123456789. Understand why it is so.
I have used System.out.print(x) here. It prints only x value here. Where as System.out.println(x) prints x value and a new line.
Do-whlie loop in java
It is almost similar while loop with a bit contrast.
General structure
do{
body goes here
}while(condition);
It works exactly as while loop except that loop body here executes at least once here, even if the condition is wrong. Like it first executes the body and then checks the condition. If the condition is true it repeats, else gets out of the loop.
For loop in java
General structure of for loop
for(initialization; condition; iteration) {
// body
}
initialization section specifies variable which are going to be used, we can declare and define new variables also.
Condition is the terminating condition for this for loop. Whenever condition becomes false control comes out of the for loop.
Lets take an example
class for_demo{
         public static void main(String args[]){
                     for(int i=0;i<=10;i++){
                              System.out.println(“i = ”+i);
                        }
            }
}
Output:
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10
Understand how it comes.

No comments:

Post a Comment