Skip to main content

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; write float root; int i = 1, sum;.
  • sum is not declared.
  • 2i - 1 is invalid; write 2*i - 1.
  • print should be printf (twice).
  • A ; is missing after while (sum <= 15).
  • return void; should be return 0;.
  • pow needs #include <math.h>.
  • (Logic, not syntax) 1/2 is integer division and equals 0, so pow(i, 1/2) is pow(i, 0) = 1; write 1.0/2 (or use sqrt).

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)

All Computer Programming chapter 3 questions →