/* */ Click to Join Live Class with Shankar sir Call 9798158723

Do-While Loop in Java


Do-While loop is similar to the while loop.when a set of statements have to be repeatedly executed at least once untile a certain condition is reached. When we do not know exactly how many time a set of statement have to be repeated do while can be used.


Syntex :-

do {
// Statements
}while(Boolean_expression);

How Do-While Loop Works in Java.

  • step 1:-
    The initialization statement is executed first
  • step 2:-
    Then, the test expression is evaluated. If the test expression is evaluated to false, then the while loop gets terminated and the control comes out of the while loop.
  • step 3:-
    if the test expression is evaluated to true,The statements defined inside the while loop will repeatedly execute until the given condition fails.
  • step 4:-
    After successful execution of statements inside the body of the while loop, the update expression is executed.
  • step 5:-
    Again the test expression is evaluated.


Q.) Java program to find the sum of positive numbers using do-while loop.
   

    
import java.util.Scanner;

public class Main 
{
  public static void main(String[] args) 
  {
    // Take input from the user
    // create an object of Scanner class
    Scanner sc = new Scanner(System.in);
	   
    int sum = 0;
    int num = 0;

    // do...while loop continues 
    // until entered number is positive
    do {
      // add only positive numbers
      sum += num;
      System.out.println("Enter a number");
      num = sc.nextInt();
    } 
    while(num >= 0); 
	   
    System.out.println("The sum of entered positive numbers is " + sum);
    sc.close();
  }
}
Output
Enter a number: 4,
Enter a number: 6
Enter a number: 2
Enter a number: 8
Enter a number: 5
Enter a number: 1
Enter a number: 3
Enter a number: -9
The sum of entered positive numbers is 29