C program to find sum of n numbers - My CS Tutorial - My CS Tutorial

Breaking

Programming languages full tutorial and programs, exam papers, visual basic( Vb.net ), information of new technologies and more....

Monday, November 25, 2019

C program to find sum of n numbers - My CS Tutorial

In this tutorial we will learn how to write a program that find and print the sum of N numbers.

Explanation:



  1. First we initialized i,n, and sum which is declared as zero.
  2. A number is given by user (say 5).
  3. Now the logic is:sum=sum+i
    • sum=0+0=0
    • for next iteration i becomes '1' sosum=0+1=1
    • for next iteration i becomes '2' sosum=2+1=3
    • for next iteration i becomes '3' sosum=3+3=6
    • for next iteration i becomes '4' sosum=4+6=10
    • for next iteration i becomes '5' sosum=10+5=15
    • for next iteration i becomes '6' which is not less than or equal to 'n'(i.e 5 as we took a value for explanation) then the loop terminates and goes to the next line.
  4. Then the value of sum which is '15' will be printed.


C program code


#include<stdio.h>
#include<conio.h>
main()
{
  int i,n,sum=0;
  printf("\n Enter a number\n ");
  scanf("%d",&n);
  for(i=0;i<=n;i++)
  {
    sum=sum+i;
    printf("\n %d",i);
  }
  printf("\n Sum is=%d\n",sum);
  getch();
}



OUTPUT 1:





OUTPUT 2:






In first output,the value of input number is 5
After calculation
The value of sum is 15

In second output,the value of input number is 8
After calculation
The value of sum is 36


Please share this post and blog link with your friends.For more programs use this blog.
If you have any problem, please comment in comment box, subscribe this blog for notifications of new post on your email and follow this blog.



Created by-- HARSH CHAUHAN

No comments:

Post a Comment