Contact Learn C
Copy

Program 7:Sum of N numbers

Program 7:

#include<stdio.h>
main()
{
  int i,n,sum=0;
  printf("Enter a number\n");
  scanf("%d",&n);
  for(i=0;i<=n;i++)
  {
    sum=sum+i;
  }
  printf("%d\n",sum);
}
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' so sum=0+1=1
    • for next iteration i becomes '2' so sum=2+1=3
    • for next iteration i becomes '3' so sum=3+3=6
    • for next iteration i becomes '4' so sum=4+6=10
    • for next iteration i becomes '5' so sum=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.
Algorithm:-

1.Assign sum as 0
2.Read n
3.Assign i as 0
4.Repeat steps until i<=n
   4.1)  sum=sum+i
   4.2)  i=i+1
5.Print Sum
6.Stop

FlowChart:

Sum of N numbers FlowChart


Output:

Sum of N numbers

 
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide