Gadgets

Tuesday, 24 November 2015

while and do while loop programs in java

While and do while loops
while loop: 
It will check the condition first then if the condition is true, then the inside actions loop will be executed. This will continue until condition is true. When condition will become false, loop will exit.
public class WhileTest {
    public static void main(String a[])  {
        int i=5;
        System.out.println("print numbers between 5 to 15");
        while(i<=15)  {            
            System.out.println(i);
            i++;
        }
    }
}
 
Output:
print numbers between 5 to 15
5
6
7
8
9
10
11
12
13
14
15 
do while loop: 
First loop will execute and then condition is check. It will check the condition first then if the    condition is true, then the inside actions loop will be executed. This will continue until condition  is true. When condition will become false, loop will exit. 
public class DoWhileTest {
    public static void main(String a[])  {
        int i=10;
        System.out.println("numbers between 10 to 20");
        do {            
            System.out.println(i);
            i++;
        }while(i<=20);
    }    
}
Output:
numbers between 10 to 20
10
11
12
13
14
15
16
17
18
19
20

No comments:

Post a Comment