Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Member-only story

Learning C++ with Program Templates: Do Something a Specified Number of Times

--

Press enter or click to view image in full size
Photo by Desola Lanre-Ologun on Unsplash

There are many computer programming problems that involves performing a set of actions a specific number of times. For example, a grade average program for five students needs to prompt the user five times to enter a grade in order to determine the average for the class. There is a program template that handles this situation: Do Something a Specified Number of Times.

This template typically uses the for statement in its implementation, so we’ll start there before we get to the template itself.

The for Statement

The for statement is used for iteration when you know in advance how many iterations your program needs. Here is the syntax template for the for statement (lcv — loop control variable):

for (data-type lcv = value; condition, modify-lcv) {
statement(s);
}

In most situations, the lcv will be an integer since we are using the variable to count the number of iterations. Here is an example that displays the integers 1 through 10:

for (int i = 1; i <= 10; i++) {
cout << i << endl;
}

It is possible to move the initialization of the lcv to outside the for statement, as in this code fragment:

--

--

Mike McMillan
Mike McMillan

Written by Mike McMillan

Mike McMillan writes about technology and running.

Dev Genius
Dev Genius

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development