Pages

Thursday, September 8, 2016

do while loop (java)

do while loop

This is another type of loop ,In which a statement in the body is executed before any condition. And as we can see that clearly from the name as well, In the while loop & do while loop one major different is ...
In while loop compiler 1st checks the condition of a while loop
But in do while loop body is executed one time always before any condition.



The syntax of do while loop is as follow



  do{
   1 body
     
 2  incrementation
     }


     3 while(condition);



Example 1 : 

write down a program and print out assalam-o-alaikum 10 times



    /*variable intitiallization*/

int i = 1;

    do{
      
     /*out put*/
      
System.out.println("Assalam-o-alaikum");
 
   /*incrementation*/
    i = i + 1;
    }
   
    /*condition*/
   

    while(i <= 10);



Out put

Assalam-o-alaikum
Assalam-o-alaikum
Assalam-o-alaikum
Assalam-o-alaikum
Assalam-o-alaikum
Assalam-o-alaikum
Assalam-o-alaikum
Assalam-o-alaikum
Assalam-o-alaikum
Assalam-o-alaikum



Explanation of Example : 1




1 . In the do while loop the compiler first check the body what ever in the body is , it executes essentially. In the above example Assalam-o-alaikum executed for one time without check any variabe any condition.

2. After wards it goes and increments the value you initiallized before the do body.In the above example it changed to 2.

3. After incrementation it checks wether the condition we have in the while is true or not if its true.Compiler goes back to body and executes body statements.

4.And this proccess is in progress until the given condition become false.
In the above example the condition became false when the value of i reached to 11.






Example 2 :

write down a program in do while loop take name in the input from the user and print the name back to the user . repeat this proccess for five users



package doWhileLoop;

import java.util.Scanner;

public class main {
    public static void main(String[]args){
 
/*variable intitiallization*/
Scanner scan = new Scanner(System.in);
int i = 1;
String  j;
    do{
      
    
      
   System.out.println("Enter your name");
   j = scan.nextLine();
   System.out.println("Your name is " +j);

    i = i + 1;
    }
   
    /*condition*/
   
    while(i <= 5);
}
   

}



Out put

Enter your name
riaz
Your name is riaz
Enter your name
waseem
Your name is waseem
Enter your name
rafeeq
Your name is rafeeq
Enter your name
talha
Your name is talha
Enter your name
abdul wahaab
Your name is abdul wahaab



No comments:

Post a Comment