Sunday, 1 September 2013

Write a c program to find out the sum of series 1 + 2 + …. + n.



Write a c program to find out the sum of series 1 + 2 + ….  + n.

Mathematical Formula:
Sum of the series 1 + 2 + 3 + … + n = n (n+1)/2

#include<stdio.h>
int main(){

    int n,i;
    int sum=0;

    printf("Enter the n i.e. max values of series: ");
    scanf("%d",&n);

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

    printf("Sum of the series: ");

    for(i =1;i <= n;i++){
         if (i!=n)
             printf("%d + ",i);
         else
             printf("%d = %d ",i,sum);
         }
   
    return 0;
}

Sample output:
Enter the n i.e. max values of series: 5
Sum of the series: 1 + 2 + 3 + 4 + 5 = 15

0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved