The actual calculation behind:-
1. while(i<=n) { sum = sum + i;
i++;
}
or
or
2. for(i = 1; i<=n; i++) {
sum += i; // sum = sum + i;
}
advantages of for loop:-
- more easier.
- makes code concise and more clean.
sum += i; // sum = sum + i;
}
advantages of for loop:-
- more easier.
- makes code concise and more clean.
// First sum of natural numbers in C language
#include <stdio.h>
int main() {
int n, sum = 0; /// sum = 0 stores the number in memory
printf("Enter your first N natural number: ");
scanf("%d", &n);
// Using a loop to calculate the sum
// for(int i = 1; i <= n; i++) {
// printf("%d\n", i);
// sum += i;
// }
sum = (n*(n+1))/2;
printf("The first sum of %d Natural numbers are: %d\n", n, sum);
return 0;
}
No comments:
Post a Comment