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.
// 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:
";
for (int i = 0; i < 100; i = i + by)
cout << i << endl;
return 0;
}
Here is a sample run of the program in Listing 5.5:
Enter an integer: 17
Counting by 17s:
0
17
34
51
68
85
When i
reaches the value 102, the loop quits. The main point here is that the update expression can be any valid expression. For example, if you want to square i
and add 10
in each cycle, you can use i = i * i + 10
.
Another point to note is that it often is a better idea to test for inequality than equality. For example, the test i == 100
would have failed in this case because i
skips over the value 100
.
Finally, this example illustrates the use of using
declarations instead of a using
directive.
18.188.211.106