Changing the Step Size

So far the loop examples in this chapter have increased or decreased the loop counter by one in each cycle. You can change that by changing the update expression. The program in Listing 5.5, for example, increases the loop counter by a user-selected step size. Rather than use i++ as the update expression, it uses the expression i = i + by, where by is the user-selected step size.

Listing 5.5. bigstep.cpp

// bigstep.cpp -- count as directed#include <iostream>int main(){    using std::cout;   // a using declaration    using std::cin;    using std::endl;    cout << "Enter an integer: ";    int by;    cin >> by;    cout << "Counting by " << by << "s:\n";    for (int i = 0; i < 100; i = i + by)        cout << i << endl;    return ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.