- 2070 Asar · 3+2 marks
Correct program: do-while and pow
Short answer
After correcting syntax errors (missing ;, print to printf, return void to return 0, adding math.h), the program runs an infinite loop printing 1 endlessly because integer division 5/3 is 1, so i stays 1 and sum is always 1; the final root line is never reached.
Rewrite the following program by correcting any syntactical errors, if present. Also show the output of the corrected code.
#include <stdio.h>
int main ( )
{
float root, int i = 1;
do { sum = 2i - 1;
print ("\t%d\n", sum);
i *= 5/3;
} while (sum <= 15)
root = pow (i, 1/2);
print ("\n%.3f", root);
return void;
}
Errors found
float root, int i = 1;mixes two types in one declaration; writefloat root; int i = 1, sum;.sumis not declared.2i - 1is invalid; write2*i - 1.printshould beprintf(twice).- A
;is missing afterwhile (sum <= 15). return void;should bereturn 0;.powneeds#include <math.h>.- (Logic, not syntax)
1/2is integer division and equals 0, sopow(i, 1/2)ispow(i, 0)= 1; write1.0/2(or usesqrt).
Corrected code (syntax errors only)
#include <stdio.h>
#include <math.h>
int main(void)
{
float root;
int i = 1, sum;
do {
sum = 2 * i - 1;
printf("\t%d\n", sum);
i *= 5 / 3;
} while (sum <= 15);
root = pow(i, 1 / 2);
printf("\n%.3f", root);
return 0;
}
Output
Because 5/3 is integer division, it equals 1, so i *= 5/3 leaves i at 1 forever. Then sum is always 1, sum <= 15 is always true, and the program never ends. It prints the following endlessly:
1
1
1
1
...
The final root line is never reached.
What the program intends
If the update is meant to move i forward (for example i += 1), the loop prints the odd numbers 1, 3, 5, ..., 17 (it stops when sum reaches 17, which is greater than 15), then i is 10 and root = sqrt(10):
#include <stdio.h>
#include <math.h>
int main(void)
{
float root;
int i = 1, sum;
do {
sum = 2 * i - 1;
printf("\t%d\n", sum);
i += 1;
} while (sum <= 15);
root = pow(i, 1.0 / 2);
printf("\n%.3f", root);
return 0;
}
1
3
5
7
9
11
13
15
17
3.162
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Correct program: Celsius to Fahrenheit · Computer Programming, chapter 3
- Correct program: case array and average · Computer Programming, chapter 3
- Correct program: character arrays · Computer Programming, chapter 7
- Output of arithmetic expression program · Computer Programming, chapter 3
- Print float to 2 and 4 decimals · Computer Programming, chapter 4
- Need of stdio.h header file · Computer Programming, chapter 3
- Cube of int, float, double by overloading · Object Oriented Programming, chapter 3
- Trellis decoding of 1/2 rate conv. code (3-bit errors) · Data Communication, chapter 8 · asked 2×
- Trellis decoding of 1/2 rate conv. code (2-bit errors) · Data Communication, chapter 8 · asked 2×