Menu
Coddy logo textTech

While Loop

Part of the Fundamentals section of Coddy's C++ journey — lesson 43 of 74.

A while loop is different from the for loop. A for loop is commonly used to iterate over a specific range, whereas a while loop allows us to keep iterating as long as a certain condition is met.

To use a while loop write:

while (condition) {
	code
}

The code will execute only if the condition is true.

Note: if the loop body contains only a single statement, the curly braces are optional:

while (condition)
	code;

There are many use cases where a while would solve the problem, but the for loop would not. Keep in mind, however, that a for loop is not strictly limited to iterating over a range — its initialization and update steps are optional, so both loop types can be made to behave similarly.

challenge icon

Challenge

Beginner

Write 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.

Cheat sheet

A while loop executes code as long as a condition is true:

while (condition) {
	code
}

Unlike for loops that iterate over a specific range, while loops continue based on a condition being met.

Try it yourself

#include <iostream>

int main() {
    // Write your code below
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals