C program to find sum of n natural numbers without using loops

 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.

sum of n natural numbers formula
C program to find sum of n natural numbers without using loops

The formula is :-

sum=n(n+1)/2

Example 

 Input:
 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:-

  1. Start 
  2. Read n
  3. Apply formula 
  4. Print the result 
  5. 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 

Post a Comment

0 Comments