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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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: } |
Output
Recent Comments