* In both programs, the loop is iterated
n
number of times. And, in each iteration, the value of
i
is added to
sum
and
i
is incremented by
1
.
* Though both programs are technically correct, it is better to use
for
loop in this case. It's because the number of iterations is known.
Read Input Until a Positive Integer is Entered :
#include <stdio.h>
int main() {
int n, i, sum = 0;
do {
printf("Enter a positive integer: ");
scanf("%d", &n);
} while (n <= 0);
for (i = 1; i <= n; ++i) {
sum += i;
}
printf("Sum = %d", sum);
return 0;
}​
Output :
Enter a positive integer: 4
Sum = 10​