Adsense 728 * 15

Search

Custom Search

Calculate Sum of N Numbers in C, C++

Write a program in C, C++ to calculate  sum of n numbers using iterative approach.

If you are familiar with the concept of loop in programming then you can easily solve this problem. In one of my programming i have explained how to find sum of n natural numbers using recursion.

Suppose if user has entered number 10. So we have to calculate the sum of first 10 numbers. Sum of 10 numbers is 55.

Program to Calculate Sum of Digits of a Number.

Logic to Calculate the Sum of n Numbers


1. Use for loop to calculate the sum.

  for(i=1;i<=num;i++){

      sum +=i;
  }

 
Program to Count Number of Words in a Sentence by Taking Input from User.

2. You can also calculate the sum of n numbers, using mathematical formula n(n+1)/2.

    So if number is 10 then sum of number is 10 * 5 = 55


C,C++ Interview Questions.

 Program to Calculate the Sum of n Numbers

In this approach we calculate the sum of n numbers using mathematical formula (Sum of n numbers).

#include <stdio.h>

void main()
{

    int n,sum;

    printf("Enter the value of n");
    scanf("%d",&n);

    sum = (n*(n+1))/2;

    printf("The sum of n number is %d",sum);

}

Calculate Sum of n Numbers using For Loop


#include <stdio.h>

int main(void) {
 
 
    int n,sum=0,i;

    printf("Enter the value of n");
    scanf("%d",&n);
    
    /* Iterate from 1 to n . */

    for(i=1;i<=n;i++) {
     
     sum = sum + i;
    }
    
    printf("The sum of n number is %d",sum);
    
    return 0;
}


Sum of n Odd Numbers.

Output:

Enter the value of n : 10

The sum of n number is : 55

No comments:

Post a Comment