Write a C program to find the sum of first n natural numbers
Description: Take a number n as input. Print the sum of numbers from 1 to n.
Hint:
- Keep a variable
sum = 0and add each number to it in a loop.
C program to find the sum of natural numbers
#include <stdio.h>
int main(void) {
int n, sum = 0;
printf("Enter n: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("Sum of 1 to %d = %d\n", n, sum);
return 0;
}
Output:
Output of the above program is
Enter n: 10
Sum of 1 to 10 = 55
How it works
- The loop adds 1, 2, 3 … up to n into
sum. - There is also a formula:
n * (n + 1) / 2, which gives 55 for n = 10 without a loop.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |