Jun 3, 2020

C program to print sum of 1 to n natural numbers

Ex: Write a C program to print sum of 1 to n natural numbers. C program to print sum of 1 to n natural numbers. How to write a C program to print sum of 1 to n natural numbers.


Input from user:

Enter the limit: 10


Expected output:

Sum is 55





Step by step logic of the given program:


1.  First declare three intiger variable's no(accept limit), i(use in for loop) and sum(store addition of n natural numbers).

2. Accept limit from user.

3. Use for loop to get 1 to n natural numbers.
 for(i=1;i<=no;++i)


4. Add natural numbers one by one and store this in variable sum (sum=sum+i)

5. Print sum out of the for loop to print sum of all natural numbers.






Program:


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

int no,i,sum=0;


printf("Enter the limit:");
scanf("%d",&no);

for(i=1;i<=no;++i)
{
  sum=sum+i;
}
printf("\nsum is %d",sum);

return 0;
}



Above prgram shows the following output:






Share This:    Facebook Twitter

0 comments:

Post a Comment

If you have any doubts, please discuss here...