How do you execute a for-loop in C++?

What is a for-loop?

Imagine a situation where you have to print something a hundred times. How would you do that?

You could type the command a hundred times, or maybe copy-paste it repeatedly.

Of course, that’d be quite tedious. This is where loops come into use. When using a for-loop, those hundred lines of code can be written in as few as three to four statements.

A for-loop allows a particular set of statements written inside the loop to be executed repeatedly until a specified condition is satisfied.

Syntax of a for-loop

for (initialize; condition; increment) {
// Block of code to be repeated
}

Example of a for-loop

int main() {
for (int n = 1; n < 10; n++) {
// Block of code to be repeated
cout << "Value of n = " << n << endl;
}
return 0;
}

The loop will run 9 times starting from n = 1 as long as n < 10, that is, until n = 9. The for-loop starts with n = 1, executes 1 time and then increments with 1 as stated in the increment section ‘n++’. The loop ends when n = 10 and the condition is not met.

Copyright ©2024 Educative, Inc. All rights reserved