Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the following code?

static int i = 5;

main()
{
int sum = 0;
do
{
sum += (1/i);
}while(0 < i--);
printf("sum of the series is %d", sum);
}

 

  • A.It will print the sum of the series 1/5+1/4+…+1/1.
  • B.It will produce a compilation error.
  • C.It will produce a run time error.
  • D.None

Answer: C

Correct answer: It will produce a run time error.

The loop is do { sum += 1/i; } while (0 < i--);. Because the test is 0 < i--, the last successful test happens when i is 1, and the post-decrement then leaves i at 0 - so the body runs once more and evaluates 1/0. Integer division by zero is a run-time fault, not something the compiler can catch, so the program crashes. (Had it survived, integer division would have made every term but 1/1 zero, so sum would have been 1, not the series in the first option.)

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.