8.3 While Loops

Chapter Table of Contents

Ch. 8 Loops

Section Table of Contents

While Loop

Analyze the code below, which utilizes a while loop.
import java.util.Scanner; Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int num = input.nextInt(); // prints num, num - 1, nim - 2, ... 1 while (num > 0) { System.out.println(num--); }
Sample output:
Enter an integer: 7 7 6 5 4 3 2 1
A while loop is a lot simpler than a for loop since it only has one input: the condition. Basically, as long as the specified expression is true, the code within the while loop will be executed. The boolean value of expression is checked at the start of each iteration, and as soon as it evaluates to false, the loop stops. In the above example, I have indicated that the loop should continue as long as num is greater than 0. Every time the loop runs, I decrease the value of num by 1 after printing the current value of num (since it’s a post-decrement), so the loop runs num times.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.