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);
}
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.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development