SET OF PROGRAMS

This blog provided "C" programs for beginners. Providing c programs for students.enjoy this blog.this blog include many c programs for engineering students, IT engineering students and programmers this blog is very useful.this blog post daily 1-5 programs for you.this programs use full for devlop games devlops application and much more. This blog programs useful for projects because all programs post with explanations.

Search Bar

Ads Here

Saturday, 5 May 2018

C program of Sum of N numbers

C program of Sum of N number's
#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);
}
Output:
Enter a number
10
55
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.

No comments:

Post a Comment