A while-loop is a statement of the form
while(condition) { statements }The statements are called the loop body. The loop starts by testing whether condition is true (or nonzero). If it is, then the statements in the loop body are performed and the loop goes back to its top, testing the condition again. The loop keeps going until it reaches its top and finds that condition is false (or 0). At that point, the loop ends. For example,
int n = 0;
while(n < 4)
{
printf("%i\n", n);
n++;
}
writes
0 1 2 3
Watch out: semicolons
Do not write a semicolon after the condition. For example,
int n= 0; while(n < 4); { printf("%i\n", n); n++; }keeps going forever. The problem is that the loop body is a semicolon, which is a do nothing statement. |
Watch out: else after while
A while-loop does not have an else part. When it ends,
it just ends. So do not write
while(test) { loop body } else { do something } |
Watch out: uninitialized variables
A while-loop can perform its body no times. Look at
the following
function definition.
int demo(int n) { int result; int t = n; int sum = 0; while(t > 0) { sum = sum + t; result = sum; t--; } return result; }Notice that, if n ≤ 0, then the loop body is not performed at all, so no value is ever stored into variable result. The function returns a junk value. That is easy to fix. A little thought shows that result is unnecessary. It is just the same as sum. So the following does the job. int demo(int n) { int t = n; int sum = 0; while(t > 0) { sum = sum + t; t--; } return sum; } |
Watch out: initializing and updating control variables
Suppose that you have some statements STEP that you want to perform n times. Using a while-loop, write C++ statements to do that. Just write STEP to stand for whatever you want to repeat. Answer
If n is nonnegative integer and x is an integer that is not 0 then you can compute xn by initializing p = 1 and then multiplying p by x a total of n times. Write C++ statements that accomplish that, leaving p = xn. Answer
Suppose that n is a positive integer. A proper divisior of n is an integer k where 0 < k < n and k is a divisor (or factor) of n. For example, 2 is a proper divisor of 6. Say that n is perfect if n is equal to the sum of all of its proper divisors. For example, 6 is perfect because the proper divisors of 6 are 1, 2 and 3 and 1 + 2 + 3 = 6.
Write C++ statements that set variable sum equal to the sum of the proper divisors of n (where variable n has already been given a value) and sets variable perf to true if n is perfect, false if not.
Answer