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; }
Solution
The output of the code will be 35.
Here's the step-by-step explanation:
- The code starts with the variable
nset to 5 andsumset to 0. - It enters a do-while loop, which will continue as long as
nis greater than or equal to 1. - Inside the loop, there's a for loop that starts with
iequal tonand decreasesiby 1 each iteration untiliis 0. - In each iteration of the for loop,
iis added tosum. - After the for loop finishes,
nis decreased by 2. - The do-while loop then repeats with the new value of
n, and the process continues untilnis less than 1. - The final value of
sumis 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.
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?
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.