Algorithm
- Get n to loop through upto number
- Initialize
sum = 0
; - Loop throw from 1 to n
- Inside loop, increment sum with 1 count
- Print the sum
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <stdio.h>
int main()
{
int number, count, sum = 0;
printf("Enter the value of n (upto calculate) : ");
scanf("%d", &number);
for(count = 1; count < = number; count++)
{
sum = sum + count; // or sum += count;
}
printf("First %d natural numbers sum : %d", number, sum);
return 0;
}
Copy The Code &
Try With Live Editor
Input
Enter the value of n (upto calculate) : 20
Output
First 20 natural numbers sum : 210
Demonstration
It's knowned also sum of first n numbers.
Just follow the algorithm to understand the concept. It's simple.
Just a basic for loop and inside that loop, increment the sum
with count
.