WHAT'S NEW?
Loading...

Do and while loop in java


The logical expression is called a loop condition or simply a condition; it is a statement can be either a simple or compound statement in a body of the loop. To avoid the endless infinite loop where the loop executes continuously without ending the process, make sure that the loop’s body contains one or more statement that ensure that the loop condition eventually returns to be false until such time the condition meets the actual output.
In this sample program determine the difference between do and while loop in java given the following example code.
Do Loop
import java.util.*;
public class doloop
{
   static Scanner console = new Scanner(System.in);
  
   public static void main(String[]args)
   {
       int index=1;
       int num;
       int num1;
       int num2;
       int ans;
     
       System.out.println("Enter how many number do you want to process: ");
       num = console.nextInt();
       do
       {
        System.out.println("Enter the 1st number : ");
        num1 = console.nextInt();
        System.out.println("Enter the 2nd  number: ");
        num2 = console.nextInt();
       
        ans = num1 + num2;
        System.out.println("The sum of two numbers is: " + ans);
        index ++;  //increment by 1 until the number meets the number entered
             
        }while(index<=num);
         System.out.println("You've already done " + num + " steps");
         System.exit(0);      
    }

 }

While Loop
import java.util.*;
public class whileloop
{
   static Scanner console = new Scanner(System.in);
  
   public static void main(String[]args)
   {
       int index=1;
       int num;
       int num1;
       int num2;
       int ans;
     
       System.out.println("Enter how many number do you want to process: ");
       num = console.nextInt();
       while (index<=num)
       {
        System.out.println("Enter the 1st  number: ");
        num1 = console.nextInt();
        System.out.println("Enter the 2nd  number: ");
        num2 = console.nextInt();
       
        ans = num1 + num2;
        System.out.println("The sum of two numbers is: " + ans);
        index ++;  //increment by 1 until the number meets the number entered            
        }
         System.out.println("You've already done " + num + " steps");
         System.exit(0);
   }
  
}


The above code determines the number entered by the user that we are going to process. If the number meets the input of a user, the programs automatically stop.

Note: The final output still the same.


1 comment: Leave Your Comments