q1612749 q1612749 - 2 months ago 7
Java Question

Converting a while loop in a do-while loop in Java

I know this question has been asked several times already. Feel free to mark it as a duplicate. Anyway, I'd rather ask the community since I am still uncertain.

I should convert this while loop in a do-while loop.
Any thoughts?

public class DoWhile {
public static void main(String[] args) {

Scanner input = new Scanner(System.in); int sum = 0;
System.out.println("Enter an integer " +
"(the input ends if it is 0)"); int number = input.nextInt(); while (number != 0) {
sum += number;
System.out.println("Enter an integer " +
"(the input ends if it is 0)"); number = input.nextInt();
}
}
}

Answer

You cant just simple convert any while loop to do while loop , the main difference between them is in do while loop you have an iteration that will happen regardless of the condition.

      public class DoWhile {
           public static void main(String[] args) {

             Scanner input = new Scanner(System.in); int sum = 0;
          do{ System.out.println("Enter an integer " +"(the input ends if it is  0)"); 
          int number = input.nextInt(); 
          sum += number;
      }while (number != 0) ;


       }
       }