The positive numbers 1, 2, 3... are known as natural numbers. The sum of natural numbers up to 10 is:
sum = 1 + 2 + 3 + ... + 10
Sum of Natural Numbers Using for Loop
#include <stdio.h>
int main() {
int n, i, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
sum += i;
}
printf("Sum = %d", sum);
return 0;
}
The above program takes input from the user and stores it in the variable n. Then, for
loop is used to calculate the sum up to n.
Sum of Natural Numbers Using while Loop
#include <stdio.h>
int main() {
int n, i, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
i = 1;
while (i <= n) {
sum += i;
++i;
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter a positive integer: 100 Sum = 5050
Comments
Post a Comment