C Program to find Sum of first ‘n’ Natural numbers
|In this C programming example, We will see the program that calculates the sum of first ‘n’ natural numbers. Also, we will discuss the execution of the program.
1. Introduction
Helpful topics to understand the implementation of this program better are:
- Natural numbers: These numbers are counting numbers; positive integers beginning with 1 and increasing by 1 forever. eg:1,2,3,4….
- Using loops in C.
- Header files in C.
1.1. Sum of ‘N’ Natural numbers using loops
Let’s implement a simple c program to find the sum of first n natural numbers using loops. In this example, we will use a while
loop, but it can easily be replaced by any other loop.
#include <stdio.h> void sumOfNaturalNumber_UsingLoop(long number) { long counter = 1, sum = 0; while (counter <= number) { sum = sum + counter; counter++; } printf("Sum of Natural Numbers from 1 to %ld is : %ld\n", number, sum); } int main() { long number; printf("Enter the number :\n"); scanf("%ld", &number); sumOfNaturalNumber_UsingLoop(number); return 0; }
Output Enter the number : 10 Sum of Natural Numbers from 1 to 10 is : 55
2. Understanding the Program
counter
is the iterating element that goes from1
tonumber
in the while loop.- In every iteration, the sum is incremented by the value of the counter.
- At last, print the required sum of first n natural numbers.
3. Sum of ‘N’ Natural numbers using formula
The time complexity for the example implemented above is O(n), but we can use a simple mathematical formula to find the sum of first n natural numbers in O(1) time complexity.
So the formula to find the sum of first n natural numbers is (n * (n +1))/2
.
So let’s replace the method using loops by the new˘efficient method that uses the formula.
void sumOfNaturalNumber_UsingFormula(long number) { long sum = (number * (number + 1)) / 2; printf("Sum of Natural Numbers from 1 to %ld is : %ld\n", number, sum); }
3. Conclusion
In this C Programming example, we have discussed, how to find the sum of first ‘n’ natural numbers and a glimpse over its implementation.
Helpful Links
Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.
Also for the example C programs please refer to C Programming Examples.
All examples are hosted on Github.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?