/** * Name: Erica Eddy * Course: CSCI 241 - Computer Science I * Section: 001 or 002 * Assignment: 1 * * This example shows how to take a while loop and turn it into a do-while * loop. The key is that the body of a do-while loop will always execute * at least once, even if the condition starts out as false. * * We also see how to write an equivalent while loop, given a do-while loop. * The key is that we must include the loop body outside of checking the * condition to make sure that code executes at least once. */ import java.util.*; public class WhileDoWhile { public static void main (String [] args) { int x; Scanner input = new Scanner(System.in); // priming read (to get an initial value for x) System.out.print("Enter value for x (4 or lower): "); x = input.nextInt(); while (x > 4) { System.out.print("Enter value for x (4 or lower): "); x = input.nextInt(); } // equivalent do-while x = 2; do { System.out.print("Enter value for x: "); x = input.nextInt(); } while (x > 4); //new do-while //Here is a do-while which will print "CS-241" one time only //when x = 0. Try other initial values for x in these loops to //see what happens. x = 0; do { System.out.println("CS-241"); x = x - 1; } while (x > 0); // Print a blank line to separate loop output System.out.println("---------"); // this while loop will never have its body executed x = 0; while (x > 0) { System.out.println("CS-241"); x = x - 1; } // // Print a blank line to separate loop output System.out.println("---------"); // this is a direct translation of the do-while loop; // it repeats the body code outside of checking the loop condition x = 0; System.out.println("CS-241"); x = x - 1; while (x > 0) { System.out.println("CS-241"); x = x - 1; } } }