Knowee
Questions
Features
Study Tools

What will be the output of the following code?Note: This question helps in clearing AMCAT interview.12345678910111213#include <stdio.h> int main() { int n = 5, sum = 0; do { for (int i = n; i > 0; i--) { sum += i; } n -= 2; } while (n >= 1); printf("%d", sum); return 0; }

Question

What will be the output of the following code?Note: This question helps in clearing AMCAT interview.12345678910111213#include <stdio.h> int main() { int n = 5, sum = 0; do { for (int i = n; i > 0; i--) { sum += i; } n -= 2; } while (n >= 1); printf("%d", sum); return 0; }

🧐 Not the exact question you are looking for?Go ask a question

Solution

The output of the code will be 35.

Here's the step-by-step explanation:

  1. The code starts with the variable n set to 5 and sum set to 0.
  2. It enters a do-while loop, which will continue as long as n is greater than or equal to 1.
  3. Inside the loop, there's a for loop that starts with i equal to n and decreases i by 1 each iteration until i is 0.
  4. In each iteration of the for loop, i is added to sum.
  5. After the for loop finishes, n is decreased by 2.
  6. The do-while loop then repeats with the new value of n, and the process continues until n is less than 1.
  7. The final value of sum is then printed.

So, the calculation will be as follows:

  • First iteration of do-while loop: n = 5, sum = 0 + 5 + 4 + 3 + 2 + 1 = 15
  • Second iteration: n = 3, sum = 15 + 3 + 2 + 1 = 21
  • Third iteration: n = 1, sum = 21 + 1 = 22
  • Fourth iteration: n = -1, the loop ends.

So, the final output will be 22.

This problem has been solved

Similar Questions

What will be the output of the following program?Note: This question helps in clearing the AMCAT exam

What is the output for the following code?Note: This question helps in clearing conceptual technical interviews for service-based companies.

What will be the output of the following code?

What happens if we compile the below code?Note: This question helps in clearing AMCAT test.

What will be the output of the following program?

1/4

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.