C program to find sum of n natural numbers without using loops
Here we will learn a C program to find sum of n natural numbers without using loops. First we will read a number from user and store it in variable 'n'. Then we use the simple formula to find the sum of n natural numbers.
C program to find sum of n natural numbers without using loops |
The formula is :-
sum=n(n+1)/2
Example
Enter value of N: 5
Logic/formula:
sum = N*(N+1)/2 = 5(5+1)/2=5*6/2 = 15
Output:
sum = 15
Input:
Enter value of N: 10
Logic/formula:
sum = N*(N+1)/2 = 10(10+1)/2 =10*11/2 = 55
Output:
sum = 55
Algorithm:-
- Start
- Read n
- Apply formula
- Print the result
- Stop.
Program:-
Here in the program first we input the number n (that is the number upto which we need to find the sum of the natural numbers), then we apply the formula sum=n*(n+1) /2
and display the result
#include <stdio.h>
int main()
{
int n, sum;
printf("Enter n: ");
scanf("%d", &n);
sum=n*(n+1)/2;
printf("Sum = %d", sum);
return 0;
}
Output:-
Enter n: 5
Sum = 15
Enter n: 10
Sum = 55
0 Comments