Answer:
For loop Version:
#include <stdio.h>
int main()
{
int number, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &number);
for (int i = 0; i <= number; i++) {
if(number == 0)
break;
sum += number;
printf("Enter a positive integer: ");
scanf("%d", &number);
}
printf("Sum is: %d", sum);
return 0;
}
- - - - -
While Loop Version:
#include <stdio.h>
int main()
{
int number, sum = 0, i = 0;
printf("Enter a positive integer: ");
scanf("%d", &number);
while (number != 0) {
sum += number;
printf("Enter a positive integer: ");
scanf("%d", &number);
}
printf("Sum is: %d", sum);
return 0;
}
Do-while Loop Version:
#include <stdio.h>
int main()
{
int number, sum = 0, i = 0;
do {
printf("Enter a positive integer: ");
scanf("%d", &number);
sum += number;
} while (number != 0);
printf("Sum is: %d", sum);
return 0;
}
Explanation:
- Initialize the variables
- Ask the user for the numbers until the user enters 0
- Calculate and print the sum