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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access