Hits: 6

# (C programming Example for Beginners)

# C Program to Calculate the Sum of Natural Numbers

#### In this example, you will learn to calculate the sum of natural numbers entered by the user.

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

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.

The above programs don’t work properly if the user enters a negative integer. Here is a little modification to the above program where we keep taking input from the user until a positive integer is entered.

## 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;
}
```

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause.The information presented here could also be found in public knowledge domains.