#include <stdio.h> int main(void) { int i = 1; int sum = 0; int status = 0; printf("Variation 1\n"); while (i < 10) { sum = sum + 2 + i; i = i + 1; printf("sum = %d, i = %d \n", sum, i); } i = 1; sum = 0; printf("\nVariation 2\n"); while (i < 10) { sum = sum/3 + i*i; i = i + 1; printf("sum = %d, i = %d \n", sum, i); } return status; } /* END OF MAIN */
![]() | int i = 1; int sum = 0; int status = 0; |
Three integer variables are declared and initialized. |
![]() | while (i < 10) { sum = sum + 2 + i; i = i + 1; printf("sum = %d, i = %d \n", sum, i); } |
The following loop is executed as long as the value of i is less than 10. Each time the loop is executed, sum is set equal to the value it had at the beginning of the loop, plus the current value of i+2. i is then incremented by one, and the two values are printed out. At the end of the loop, the condition is checked again; since i starts with the value 1 and is increased by one each time, the loop will be executed 9 times. |
![]() | i = 1; sum = 0; |
Reset the variables (otherwise the second loop will not be executed) |
![]() | while (i < 10) { sum = sum/3 + i*i; i = i + 1; printf("sum = %d, i = %d \n", sum, i); } |
One more time, except this time sum is set to a third of the value it had, plus the square of i. |
![]() | return status; |
Terminate program. Output of the program: Variation 1 sum = 3, i = 2 sum = 7, i = 3 sum = 12, i = 4 sum = 18, i = 5 sum = 25, i = 6 sum = 33, i = 7 sum = 42, i = 8 sum = 52, i = 9 sum = 63, i = 10 Variation 2 sum = 1, i = 2 sum = 4, i = 3 sum = 10, i = 4 sum = 19, i = 5 sum = 31, i = 6 sum = 46, i = 7 sum = 64, i = 8 sum = 85, i = 9 sum = 109, i = 10 |