Skip to content

Loops

Loops are a fundamental control structure in C++ that allow you to repeat actions efficiently based on a condition. Whether you need to iterate while a condition is true, ensure a block of code runs at least once, or repeat a set number of times, loops provide the flexibility to handle various scenarios. In this section, we’ll explore three common types of loops: while, do-while, and for.

A flow chart that shows a repetition based flow chart

A while loop evaluates its condition at the top of the loop, before executing the body. If the condition evaluates to true, the loop continues executing the body repeatedly. Once the condition becomes false, the loop is skipped, and the program moves on to the commands that follow. This makes while loops ideal for situations where the number of iterations depends on a dynamic condition rather than a fixed count.

The basic syntax of a while loop in C++ is as follows:

while (condition) {
// Body of the loop
}
  • No Semicolon: The while statement should not end with a semicolon after the condition. Adding one will result in a syntax error or unintended behavior.

  • Scope: Variables declared inside the loop block are local to that block and cannot be accessed outside of it. For example:

while (condition) {
int x = 10; // 'x' is only accessible within this block
}
// x is no longer accessible here

The following is an example of a use case for a while loop:

  1. Asks the user to enter a number that represents where to start a countdown from.

  2. The user’s number is used in a while loop condition to check that it is greater than 0.

  3. The current number is logged to the terminal and then decremented.

  4. After the while loop finishes, a message is logged to signal the end of the countdown.

driver.cc
// Copyright 2024 CSCE240
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
cout << "Enter an integer to countdown from:" << endl;
int countdown;
cin >> countdown;
while (countdown > 0) {
cout << countdown << endl;
--countdown;
}
cout << "Lift Off!!!" << endl;
return 0;
}

A do-while loop evaluates its condition at the bottom of the loop, ensuring that the body of the loop is executed at least once, regardless of the condition. If the condition evaluates to true, the loop continues executing. Once the condition becomes false, the loop terminates, and the program proceeds with the commands that follow. This structure is particularly useful when the loop’s body must run at least once before checking the condition.

The basic syntax of a do-while loop in C++ is as follows:

do {
// Body of the loop
} while (condition);
  • Semicolon: Unlike other loops, a do-while loop requires a semicolon (;) at the end of the while statement. Omitting it will result in a syntax error.

This structure ensures that the loop is executed at least once, with clear rules for writing valid and readable do-while loops.

A do-while loop is particularly useful in scenarios where user input must be validated, and the program requires the input to be processed at least once before rechecking the condition. For example:

driver.cc
// Copyright 2024 CSCE240
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
int number;
do {
cout << "Enter a number between 1 and 10:" << endl;
cin >> number;
} while (number < 1 || number > 10);
cout << "You entered: " << number << endl;
return 0;
}

A for loop is a concise way to write counter-controlled loops in C++. It is particularly useful when the number of iterations is known before the loop begins. By combining the initialization, condition, and update in a single line, for loops make the code cleaner and easier to read compared to while or do-while loops in such scenarios.

The basic syntax of a for loop in C++ is as follows:

for (initialization; condition; update) {
// Body of the loop
}
  • No Semicolon: The for statement does not end with a semicolon after the parenthesis. Adding one will cause errors or unintended behavior.

  • Braces: Braces {} are optional if the body of the loop contains only a single statement. However, using braces is recommended for readability and to avoid errors when modifying the loop.

for (int i = 0; i < 5; ++i)
statement; // No braces needed for a single line
  • Local Scope: Variables declared in the parenthesis are local to the loop block and cannot be accessed outside of it. For example:
for (int i = 0; i < 5; ++i) {
std::cout << i << std::endl; // 'i' is accessible here
}
// std::cout << i; // Error: 'i' is not accessible here

A classic example of when to use a for loop is the FizzBuzz algorithmic problem.

Write a loop that prints all numbers from 1 to 30 except for the following cases:

  • If a number is divisible by 3, print Fizz

  • If a number is divisible by 5 and not by 3, print Buzz

  • If a number is divisible by 3 and 5, print FizzBuzz

driver.cc
// Copyright 2024 CSCE240
#include <iostream>
using std::cout;
using std::endl;
int main() {
const int kCount = 30;
for (int i = 1; i <= kCount; ++i) {
if (i % 3 == 0 && i % 5 == 0) {
cout << "FizzBuzz" << endl;
} else if (i % 5 == 0) {
cout << "Buzz" << endl;
} else if (i % 3 == 0) {
cout << "Fizz" << endl;
} else {
cout << i << endl;
}
}
return 0;
}

The break and continue commands are used to control the flow of loops in specific ways:

  • break: Immediately exits the current loop or code block, skipping any remaining iterations or commands. It is often used to terminate a loop when a specific condition is met.

The following code is an algorithm to find the Least Common Multiple of two numbers within a Max Range:

driver.cc
// Copyright 2024 CSCE240
#include <iostream>
using std::cout;
using std::endl;
int main() {
// Lowest Common Multiples of x and y using a max range of kRange
const int kRange = 100;
int x = 4, y = 5;
// Assume no Least Common Multiple exists
int lcm = 0;
// Make looping faster by iterating by the max amount instead of 1
// Used for demonstration in case you didn't know x and y
int max = x > y ? x : y;
// Start at the max value and increment by the max value
for (int i = max; i <= kRange; i += max) {
if (i % x == 0 && i % y == 0) {
lcm = i;
break;
}
}
if (lcm == 0) {
cout << "No Least Common Multiple found for " << x << " and " << y
<< " in a max range of " << kRange << "." << endl;
} else {
cout << "The Least Common Multiple for " << x << " and " << y << " is "
<< lcm << "." << endl;
}
}
  • continue: Skips the remaining commands in the body of the loop and moves directly to the next iteration. This is useful when you want to bypass certain parts of the loop for specific cases without exiting the loop entirely.

The following snippet prints odd numbers within a range:

driver.cc
// Copyright 2024 CSCE240
#include <iostream>
using std::cout;
using std::endl;
int main() {
// Print only odd numbers
const int kRange = 10;
for (int i = 1; i <= kRange; ++i) {
if (i % 2 == 0) {
continue;
} else {
cout << i << endl;
}
}
}

A list of general style requirements for do-while loops, for loops, and while loops can be found in the control structures page.