Monday, 24 March 2014
0
C Program 1: To Print The Sum of First Five Natural Numbers Using Arrays
Aim: To print the sum of first five natural numbers using arrays
Theory: For achieving the desired result, we need to put first five natural numbers in form of array. So, we use a for loop so as to enter the first give natural numbers in an array and then calculate their sum.
The code for the following would be:
Theory: For achieving the desired result, we need to put first five natural numbers in form of array. So, we use a for loop so as to enter the first give natural numbers in an array and then calculate their sum.
The code for the following would be:
//to print the sum of first 5 natural numbers
#include<stdio.h>
#include<conio.h>
int main()
{
int i,a[10], sum=0;
for (i=0; i<=4; i++)
{
a[i]=i;
printf("%d\n", a[i]);
sum=sum+a[i];
}
printf("The sum is %d", sum);
getch();
return 0;
}
Note that we would initialize the variable for storing the sum to 0. If we don't do that, the sum would initially have a garbage value which would give wrong output.
The first statement
Thus, at the end we get the desired output.
The first statement
a[i]=i;
would allow us to store first five natural numbers in the array form. Then using the next statement, we printed all the first five natural numbers and then we calculate their sum using the statement sum=sum+a[i];
Thus, at the end we get the desired output.
Subscribe to:
Post Comments (Atom)
0 Responses to “C Program 1: To Print The Sum of First Five Natural Numbers Using Arrays”
Post a Comment