🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

For Loop

C++ For Loop Overview

The for Loop in C++:

The for loop in C++ is a versatile loop structure that allows you to execute a block of code repeatedly for a specific number of iterations. It consists of three main parts: initialization, condition, and iteration expression. The basic syntax of a for loop is as follows:


for (initialization; condition; iteration) {
    // Code to be executed in each iteration
}

Here's an example of a simple for loop that prints the numbers from 1 to 5:


#include <iostream>

int main() {
    for (int i = 1; i <= 5; ++i) {
        std::cout << i << " ";
    }

    return 0;
}

In this example:

  • int i = 1 is the initialization part, where you declare and initialize a loop control variable i.
  • i <= 5 is the condition part, which is checked before each iteration. The loop continues as long as this condition is true.
  • ++i is the iteration part, which is executed after each iteration. It increments the loop control variable.

The output of this program will be:


1 2 3 4 5

You can customize the for loop based on your specific requirements. For example, you can change the initialization, condition, or iteration expressions to create loops with different behaviors.


#include <iostream>

int main() {
    // Loop with a different initialization and iteration
    for (int i = 10; i >= 1; --i) {
        std::cout << i << " ";
    }

    std::cout << std::endl;

    // Loop with a different initialization, condition, and iteration
    for (int i = 0; i < 20; i += 2) {
        std::cout << i << " ";
    }

    return 0;
}

In these examples, the first loop counts down from 10 to 1, and the second loop counts even numbers from 0 to 18.

Remember to use break and continue statements when necessary to control the flow of the loop. The break statement can be used to exit the loop prematurely, and the continue statement can be used to skip the rest of the loop body and move to the next iteration.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.