Tuesday 12 February 2013

Sum of First n natural numbers using C

This program illustrates the more practical example of application of C-loops discussed in previous lession. This program calculates the sum of first n natural numbers. Complete source code and output of program is given here..
Source Code
1: // summation of first n natural numbers
2: #include<stdio.h>
3: 
4: int main(){
5:     int i, sum = 0; //for storing sum, initially must be zero
6:     int n;
7:     printf("Enter the number: ");
8:     scanf("%d",&n);
9: 
10:     for(i = 0; i <=n; i++){
11:         sum = sum + i;
12:     }
13: 
14:     printf("The sum of first %d natural number is %d\n\n", n,sum);
15:     return 0;
16: }
17: 

Output

sumofnumbers

No comments:

Post a Comment

Comment