OneBite.Dev - Coding blog in a bite size

Do A For Loop In C++

Code snippet for how to Do A For Loop In C++ with sample and detail explanation

The C++ language is a widely-used programming language that is particularly known for its flexibility and efficiency. In this article, we will be focusing on one of the most fundamental components of this language, which is the ‘For’ loop.

Code snippet for ‘For’ Loop in C++

Let’s start with a very basic example of a ‘For’ loop in C++.

#include<iostream>

int main() {
    for (int i = 0; i < 10; i++) {
        std::cout << i << "\n";
    }
    return 0;
}

Code Explanation for ‘For’ Loop in C++

Let’s break down this code snippet step by step to give you a better understanding of the ‘For’ loop in C++.

#include<iostream>

Firstly, the #include<iostream> line is a preprocessor command, telling the C++ compiler to include the iostream standard file. This file allows for the input and output operations in C++.

int main() {

The int main() line is the beginning of the main function. Every C++ program must have a main() function as an entry point for the program.

for (int i = 0; i < 10; i++) {

Next is the ‘For’ loop syntax. The for(int i = 0; i < 10; i++) line initializes value i to 0; checks the condition i < 10; if this condition is true, it executes the code inside the loop then increments i by one (i++), this process will continue until i < 10 is no longer true.

std::cout << i << "\n";

Inside the ‘For’ loop, the std::cout << i << "\n"; line is responsible for printing the value of i and a new line after every loop iteration.

return 0;
}

Finally, the return 0; line signifies the successful termination of the main() function. The closing } indicates the end of the main() function.

That’s it! This is how you can create a simple ‘For’ loop in a C++ program. This loop will print the numbers 0 to 9, each on a new line.

c-plus-plus