Trusted answers to developer questions

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

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.

RELATED TAGS

c++
for-loop
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?