Find the error(s) in each of the following code segments and explain how to correct it:
```
a) i = 1;
while (i <= 10);
++i;
}
b) for (k = 0.1; k != 1.0; k += 0.1)
{
Console.WriteLine(k);
}
c) switch (n)
{
case 1:
Console.WriteLine("The number is 1");
case 2:
Console.WriteLine("The number is 2");
break;
default:
Console.WriteLine("The number is not 1 or 2");
break;
}
d) The following code should display the values 1 to 10:
n = 1;
while (n < 10)
{
Console.WriteLine(n++);
}
```
a. Error: The semicolon after the while header causes an infinite loop, and there’s a
missing left brace for the body of the while statement.
Correction: Remove the semicolon and add a { before the loop’s body.
b. Error: Using a floating-point number to control a for statement may not work, because floating-point numbers are represented only approximately by most computers.
Correction: Use an integer, and perform the proper calculation in order to get the values you desire:
```
for (k = 1; k < 10; ++k)
{
Console.WriteLine((double) k / 10);
}
```
c. Error: case 1 cannot fall through into case 2.
Correction: Terminate the case in some way, such as adding a break statement at the
end of the statements for the first case.
d. Error: The wrong operator is used in the while iteration-continuation condition.
Correction: Use <= rather than <, or change 10 to 11.
You might also like to view...
Using the font shorthand property, values must be specified for the ____ property.
A. font-style B. font-weight C. font-size D. all of the above
Compare the uses of a one- and two-variable data table.
What will be an ideal response?