Page Content

Tutorials

What Are The C++ Loops With Code Examples?

C++ Loops

Iteration statements, also referred to as loops, are essential flow-of-control statements in C++. They enable a software to run a statement or set of statements repeatedly. There is a controlling expression (or condition) that determines the amount of repeats. While, do-while, and for loops (including the range-based for loop that was added in C++11) are among the loop types that C++ offers.

In C++, a condition is an expression that returns a true or false result. A value of 0 (zero) in C++ becomes false, while any other non-zero value becomes true. Curly braces {} must be used to enclose multiple statements that must be a part of the body of a loop in order to create a compound statement or block. Only the variables stated inside that block and any blocks nested inside it are visible.

The various iteration statements are broken down as follows:

while Loop

As long as a specified condition is true, a while statement repeatedly runs a target statement (or block). Before the body of the loop is run, the condition is tested. The body of the loop won’t run at all if the condition is initially false. While loops are frequently employed in situations where the number of iterations is unknown in advance, like when reading input through to the end of a file.

Syntax:

while (condition)
    statement; // or a code block { ... }

Example of Code (while loop):

#include <iostream>
int main() {
    int val = 1; // Loop variable initialization outside the loop body 
    int sum = 0;
    // Keep executing the while as long as val is less than or equal to 10 
    while (val <= 10) { // Condition is evaluated before each execution 
        sum += val;    // Adds val to sum 
        ++val;         // Increments val 
    } // The curly braces delimit the block of statements for the loop body 
    std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
    return 0;
}

Output

Sum of 1 to 10 inclusive is 55

As long as val is less than or equal to 10, the while loop in this example keeps running. The body of the loop updates the sum and val.

do while Loop

Similar to a while loop, a do-while statement tests its condition after the body of the statement is finished. This guarantees that, regardless of the condition’s initial value, the loop body gets run at least once. Curly braces {} are always needed for the do-while loop body, even if it only has one statement, in contrast to while and for loops. A semicolon marks the end of the while portion of the do-while statement. do-statements should be avoided since they might lead to mistakes and misunderstandings, mainly because the body always does one execution before the condition is assessed.

Syntax:

do {
    statement(s); // Must be a code block { ... } 
} while (condition); 

Code Example (do-while statement):

#include <iostream>
int main() {
    char choice;
    do {
        std::cout << "Do you want to continue? (y/n): ";
        std::cin >> choice;
    } while (choice == 'y' || choice == 'Y'); // Condition tested after execution 
    std::cout << "Exited loop." << std::endl;
    return 0;
}

Output

Do you want to continue? (y/n): y
Do you want to continue? (y/n): Y
Do you want to continue? (y/n): n
Exited loop.

Because the do block runs before the while condition is tested, the user will always be prompted at least once in this case.

for Loop

Code that includes initialising a variable, testing it in a condition, then incrementing (or decrementing) it can be succinctly shortened with the classic for statement. The loop header is where it collects all loop-control components.

Syntax:

for (init-statement; condition; expression)
    statement; // or a code block { ... } 

The following is the flow of how the for loop is executed:

init-statement: Carried out once at the start of the loop. Loop control variables, whose scope is restricted to the for statement itself, can be declared and initialized. The comma operator can be used to declare many variables.

condition: Assessed before to every iteration. The body of the loop runs if true. If it is false, the loop ends.

expression (often increment): Carried out prior to the condition being reevaluated, following the completion of the loop body for every iteration. This expression can be any valid expression, but it usually increases or decreases the loop variable.

A for statement requires at least two semicolons to be entered, although any one of the three phrases can be left off. Since the controlling expression is taken to be true if it is absent, an empty for(;;) statement creates an infinite loop.

Code Example (for statement):

#include <iostream>
int main() {
    // Loop to print numbers from 0 to 9
    for (int i = 0; i < 10; ++i) { // init: int i = 0; condition: i < 10; expression: ++i 
        std::cout << i << " "; // Loop body executes 10 times, for i from 0 to 9 
    }
    std::cout << std::endl;
    // Example with multiple statements in loop body and different increment
    for (int num = 1; num <= 10; ++num) {
        std::cout << "Number: " << num << "\tSquare: " << num * num << std::endl;
    }
    return 0;
}

Output

0 1 2 3 4 5 6 7 8 9 
Number: 1	Square: 1
Number: 2	Square: 4
Number: 3	Square: 9
Number: 4	Square: 16
Number: 5	Square: 25
Number: 6	Square: 36
Number: 7	Square: 49
Number: 8	Square: 64
Number: 9	Square: 81
Number: 10	Square: 100

In this example, i is initialized to 0, the loop continues as long as i < 10, and after each iteration, i is increased by 1.

Range-based Statement (C++11)

The range-based for loop is a more straightforward for statement that was introduced in the C++11 standard. Loops are as short as those in languages like Python since it is made to iterate through every element of a container or other sequence. Many library containers work well with this loop approach.

Syntax:

for (declaration : expression)
    statement; // or a code block { ... } 

The expression needs to represent a sequence, such as an array, braced initialiser list, or object of type std::string or std::vector with begin() and end() members that return iterators. On each repetition, the value of the subsequent element in the sequence is used to initialise the variable defined by the declaration.

Code Example (Range-based for statement):

#include <iostream>
#include <vector> // For std::vector
#include <string> // For std::string
int main() {
    std::vector<int> numbers = {10, 20, 30, 40, 50}; // 'expression' is a vector
    std::string text = "Hello"; // 'expression' is a string
    // Iterate through the vector 'numbers' \
    std::cout << "Numbers: ";
    for (int num : numbers) { // 'num' is declared for each element in 'numbers'
        std::cout << num << " ";
    }
    std::cout << std::endl;
    // Iterate through the string 'text' to print each character \
    std::cout << "Characters: ";
    for (char c : text) { // 'c' is declared for each character in 'text'
        std::cout << c << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

10 20 30 40 50 
H e l l o 

For moving through a sequence from start to finish, this loop is easy to use and efficient. A range-based for loop, on the other hand, is not appropriate for changing the container by adding or removing elements during iteration since it caches the sequence’s end() value, which could invalidate iterators.

You can also read What Are Conditional Statements In C++ With Code Examples?

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index