Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

# C Program to Find the Sum of First N Natural Numbers

Last Updated on July 29, 2024 by Abhishek Sharma

C programming is a powerful language that offers control over system resources and memory. One of the foundational exercises for beginners is to write a C program to find the sum of the first N natural numbers. This exercise not only helps in understanding basic programming concepts like loops and conditional statements but also in grasping how to handle user input and output in C. Calculating the sum of the first N natural numbers is a common problem that demonstrates the use of simple arithmetic operations and iterative control structures.

## Approaches to Find the Sum of First N Natural Numbers

Here, we will discuss four different approaches to writing a C program to find the sum of first n natural numbers.

### Approach 1: C Program to Find the Sum of First N Natural Numbers Using Formula

Two natural numbers that follow one another have a difference of 1. The progression of natural numbers is an arithmetic progression since every pair of subsequent numbers has the same difference. An arithmetic progression goes as follows: a, a+d, a+2d, a+3d,…, where a is the first element of the number and d is the difference between two succeeding numbers in the progression.

The following formula can be used to determine the sum of n numbers in an arithmetic progression,

``Sn=(n∗(2a+(n−1)∗d))/2``

where,

• The series’ first term is a.
• The common difference between any two terms in a series is called d.
• The series number of terms is n.

The preceding formula can be further condensed into the equation for the sum of natural numbers, (n(n+1))/2, by substituting a=1 and d=1 in the equation.
The number of elements in the sequence is represented by the symbol n in the equation.

Program to Calculate the Sum of Natural Numbers Using Formula
It is possible to use the C programming language to implement the formula given in the previous section.

Example
The formula for calculating the sum of natural numbers can be used to generate the following code,

```#include <stdio.h>
int main() {

int natural_number;
natural_number = 10;
int sum;
// formula for the sum of natural numbers
sum = natural_number*(natural_number+1)/2;
printf("The Total Sum Of %d Natural Numbers Is: %d", natural_number, sum);
return 0;
}```

Output

``The Total Sum Of 10 Natural Numbers Is: 55``

Note: Due to the precedence of the operator in C, brackets are used in the formula surrounding (natural_number+1). Multiplication and division operations will be carried out before addition in C because they have a higher priority than addition and subtraction operations. We employ a bracket that takes precedence over other operators to stop this from happening.

Explanation
The code variable natural_number serves as an example of the sequence’s element count. The user provides this variable as input. The sum is obtained by changing the formula for the sum of natural numbers to reflect the number of elements in the sequence. The user is shown the output.

The program’s time complexity is O(1), or continuous time complexity.
The program’s space complexity is also O(1).

### Approach 2: C Program to Find the Sum of First N Natural Numbers Using For Loop

The sum of natural numbers can be calculated by iterating through the numbers in the natural number sequence and adding them together using a for loop.

Example
There are two methods to use the for loop. The for loop in the program below iterates from 1 to a natural integer,

```#include <stdio.h>
int main() {

int natural_number;
natural_number = 14;
int sum=0;
for(int i=1;i<=natural_number;i++){
sum=sum+i;
}
printf("The total sum of %d natural numbers is %d", natural_number, sum);
return 0;
}
```

The program below displays a for loop that iterates from the natural number to 1 (the first natural number in the sequence),

```#include <stdio.h>

int main() {
int natural_number;
natural_number = 14;
int sum=0;
// iterate from the maximum natural number to be summed to 1
for(int i=natural_number;i>0;i--){
// summation of natural numbers
sum=sum+i;
}
printf("The total sum of %d natural numbers is %d", natural_number, sum);
return 0;
}
```

Output

``The total sum of 14 natural numbers is 105``

Explanation
The user provides the highest possible number in the natural number series. Iterating from 1 to the greatest natural number or from the greatest natural number to 1 are both possible with a for loop. The total sum of natural numbers is obtained by adding the sum at each iteration.

Both programs will have an O(n) time complexity, where n is the number of iterations the for loop performs. Both programs’ space complexity will be O(1).

### Approach 3: C Program to Find the Sum of First N Natural Numbers Using Do While Loop

A do..while loop only checks for conditions from the second iteration of the loop’s run after running once without checking for the conditions it was given.

Example

```#include <stdio.h>

int main() {
// total number of natural numbers to be summed
int natural_number;
natural_number = 13;
int sum=0,i=1;
// do while loop
do
{
// Summation of natural numbers
sum = sum + i;
// increment i
i++;
} while( i <= natural_number); // condition
printf("The total sum of %d natural numbers is %d", natural_number, sum);
return 0;
}
```

Output

``The total sum of 13 natural numbers is 91``

Explanation
The do..while loop multiplies the input number by each number starting at one. The user sees the outcome displayed.
The program has an O(n) time complexity, where n is the total number of iterations in the do…while loop. The program’s O(1) space complexity.

### Approach 4: C Program to Find the Sum of First N Natural Numbers Using Recursion

A technique known as recursion involves repeatedly calling the same function. Finding the sum of natural numbers can be accomplished using recursion rather than loops.

Example

```#include <stdio.h>

int Sum(int natural_no)
{
if(natural_no != 0)
// recursive call to the same function
return natural_no + Sum(natural_no - 1);
// return 0 if 'natural_no' is 0
return 0;
}
int main() {
// total number of natural numbers to be summed
int natural_number;
natural_number = 12;
printf("The total sum of %d natural numbers is %d", natural_number, Sum(natural_number));

return 0;
}
```

Output

``The total sum of 12 natural numbers is 78``

Explanation
The input consists of the natural number. In a recursive function call, the same function is invoked with the parameter set to the value obtained by subtracting the number supplied as an argument in the previous function call. Only if the number decreases to zero will the recursive call terminate. At the conclusion of each function call, the output that the function returned is summed to obtain the sum of natural numbers.

The recursive natural number addition has an O(n) time complexity. A recursive function’s space complexity is influenced by how many function calls are made. The space complexity in the aforementioned example is O(n).

The functions will be called in the following order: Sum(12) –> Sum(11) –> Sum(10)…–> Sum(1).

The function returns zero once Sum(0) is achieved, and the output of each function is then added together backward to determine the sum,
Sum(0) –> Sum(1) –> Sum(2) …–> Sum(12), etc.

The return function and the accumulation are both executed in the same phase. When the function is Sum(0), the result is 0, and when the function is Sum(1), the result is 0+1, where 0 is the result of the Sum(0) function. To obtain the sum of n natural numbers, analogous accumulations are carried out for each succeeding function.

Conclusion
Writing a C program to find the sum of the first N natural numbers is an excellent way to practice fundamental programming skills. This task introduces beginners to the concepts of loops, user input, and basic arithmetic operations in C. Understanding how to calculate sums and handle iterative processes lays the groundwork for more complex programming challenges. As programmers become comfortable with these basic constructs, they can tackle more advanced topics with confidence.

## FAQ related to the C Program to Find the Sum of First N Natural Numbers

1. What is the formula to find the sum of the first N natural numbers?
The formula to find the sum of the first N natural numbers is:

``Sum = N X (N+1)/ 2``

2. How can I find the sum of the first N natural numbers using a loop in C?
You can use a for loop to iterate from 1 to N and add each number to a cumulative sum variable. Here’s a basic example:

``````#include

int main() {
int N, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &N);

for (int i = 1; i <= N; i++) {
sum += i;
}

printf("Sum of the first %d natural numbers is: %d\n", N, sum);
return 0;
}``````

3. How do I handle user input in a C program?
User input in a C program can be handled using the scanf function. For example, to read an integer input, you can use:

``````int N;
printf("Enter a positive integer: ");
scanf("%d", &N);``````

4. Can I use recursion to find the sum of the first N natural numbers?
Yes, you can use recursion to find the sum of the first N natural numbers. Here’s a simple example:

``````#include

int sumOfNaturalNumbers(int N) {
if (N == 0) {
return 0;
} else {
return N + sumOfNaturalNumbers(N - 1);
}
}

int main() {
int N;
printf("Enter a positive integer: ");
scanf("%d", &N);

printf("Sum of the first %d natural numbers is: %d\n", N, sumOfNaturalNumbers(N));
return 0;
}``````

5. What are natural numbers?
Natural numbers are a sequence of positive integers starting from 1. They are commonly used for counting and ordering.

6. How do I ensure the user inputs a positive integer?
To ensure the user inputs a positive integer, you can add a loop that repeatedly asks for input until a valid positive integer is provided:

``````#include

int main() {
int N;
do {
printf("Enter a positive integer: ");
scanf("%d", &N);
} while (N <= 0);

int sum = 0;
for (int i = 1; i <= N; i++) {
sum += i;
}

printf("Sum of the first %d natural numbers is: %d\n", N, sum);
return 0;
}``````