While Loop
Part of the Fundamentals section of Coddy's Java journey. Lesson 43 of 73.
A while loop is different from the for loop. A for loop has initialization, condition and update parts in its header, so it suits counting through a known range of values. A while loop has only a condition and keeps iterating as long as that condition is met.
To use a while loop write:
while (condition) {
code
}The code will execute only if the condition is true.
A for loop can do the same work, but a while loop is clearer when you do not know in advance how many times the code should repeat, such as reading input until the user types "quit".
Challenge
BeginnerWrite a program that gets one input, double number.
Use a while loop to divide the input by 2 as long as the number is bigger or equal to 3.5.
Print the first number that is smaller than 3.5.
Try it yourself
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your code below
scanner.close();
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - ElsePractice on your own: Online Java compiler