Lecture 13
Lecture 13
Lecture 13
Looping
Part 2
CS 1428
Fall 2011
Jill Seaman
Lecture 13
Examples:
int num = 10;
num++; //equivalent to: num = num + 1;
num--; //equivalent to: num = num - 1;
++num; //equivalent to: num = num + 1;
--num; //equivalent to: num = num - 1; 4
Postfix and Prefix: why?
Watch out
What is output in each case?
int x = 13;
if (x++ > 13)
cout << “x greater than 13” << endl;
cout << x << endl;
int x = 13;
if (++x > 13)
cout << “x greater than 13” << endl;
cout << x << endl;
for
the for statement:
for (expr1; expr2; expr3)
statement
expr1; // initialize
while (expr2) { // test
statement
expr3; // update
} 9
for example
Example:
int number;
for (number = 1; number <= 3; number++)
{
cout << “Student” << number << endl;
}
cout << “Done” << endl;
Output:
Student1
Student2
Student3
Done
10
Counters: Redo
The example using while to output table of
squares of ints 1 through 8:.
cout << “Number Number Squared” << endl;
cout << “------ --------------” << endl;
int num = 1;
while (num <= 8)
{
cout << num << “ “ << (num * num) << endl;
num = num + 1; // increment the counter
}
Watch out
What is output?
int x;
for (x=1; x <= 10; x++) {
cout << “Repeat!” << endl;
x++;
}
cout << “Done!” << endl;
What is output? Note: no semicolon
int x;
for (x = 10; x > 0; x = x-2)
cout << x << endl;
Non-deterministic count
How many rows are output?
int maxCount;
cout << “How many squares do you want?” << endl;
cin >> maxCount;
cout << “Number Number Squared” << endl;
cout << “------ --------------” << endl;
int num;
for (num = 1; num <= maxCount; num++)
cout << num << “ “ << (num * num) << endl;
It depends . . .
It’s still a count controlled loop, even though the
count is not known until run-time.
14
The exprs are optional
You may omit any of the three exprs in the for
loop header
int value, incr;
cout << “Enter the starting value: “;
cin >> value;
for ( ; value <= 100; )
{
cout << “Please enter the increment amount: “;
cin >> incr;
value = value + incr;
cout << value << endl;
}
// technically it’s a count controlled loop, but use a while
Watchout:
for ( ; ; )
cout << “Hello!” << endl;
15