Here is a collection of while and do-while statements. Identify:
i. those that are correct, and are likely to give the programmers intent;
ii. those that are correct, but unlikely to give the programmer's intent, and
iii. what compiler error will the rest generate?
Assume all variables have been declared, but not necessarily initialized.
a) ```
cin >> n;
while (-1 != n)
{
sum = 0;
sum = sum + n;
}
```
b) ```
cin >> value;
while ( value != -1 )
sum = sum + value;
cin >> value;
```
c) ```
cin >> n;
int i = 1,
>>Semicolon not comma
while ( i < n );
sum = sum + i;
i++;
```
d) ```
cin >> count >> limit;
do
count++
while ( count ??count > limit );
```
e) ```
cin >> x;
do
x++;
while( x > x );
```
a) This compiles. It is unlikely to be what the programmer intended. What the intent might be is hard to guess, since the value of sum is reset to 0 each time the loop executes.
b) This compiles. The indentation suggests that the programmer intended the two lines following the to be in the body of the loop. The second of these is not controlled by the while clause, resulting in an infinite loop .
>>Something is wrong. Maybe the indentataion??
c) This compiles. There are two intent errors evident: the semicolon on the second line and the missing braces. If the loop is entered, this is an infinite loop, since the statement controlled by the loop is the null statement inserted by the semicolon on the second line changes neither i nor n. The intent evidently was to run the loop n or n-1 times.
d) The syntax error is a semicolon missing from count++.
e) This compiles, but the loop executes its body only once. It is difficult to guess what the programmers intent might have been, but this probably isn't it!
You might also like to view...
The default value for the repeat attribute is no-repeat
Indicate whether the statement is true or false
Which of the following cable types can be susceptible to crosstalk? (Select the two best answers.)
A. Fiber-optic B. Twisted-pair C. Coaxial D. Data emanation