Summation of Array Elements using C++ Programming

Recommended Article:

Read this article to understand first that ..

Explanation of Program code:

First of all you have to do is that go for adding library files for input and output streams. cin and cout are the input and output streams respectively.Then now you have to write code for summation of array elements, now where should you write this, for this the necessary function for every c++ program , the main function you have to include.Return statement is necessary to tell the compiler that there are no other statements to execute at the end of program but inside the curly braces of main function.

#include<iostream>
int main()
{
return 0;
}

Now if you know about arrays, then define array.Let i define array of type integer and array size is six which means that maximum six elements you can define in the array.As in my program i am asking the user to define six elements , for this for loop is there. In order to access the elements of array, use array index. The index for first elements in array is zero or we can say that it starts from zero and then onward.

For the summation you need another variable which is responsible to store the summation result , because of integer data type for array , the data type for sum variable is also integer type.Sum variable assigned a value a zero because if it has already sum value by default then it just replaced by a zero value.


Program code:
#include<iostream>
using namespace std;
int main()
{
int arr[6] , sum = 0;
cout<<"Enter any six numbers one by one"<<endl;
for(int i = 0 ; i < 6 ; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<endl<<endl;
cout<<sum << " is the sum of array elements you entered";
         
return 0;
}

Output:
Enter any six number one by one
2
3
4
5
6
7

27 is the sum of array elements you entered

No comments:

Post a Comment

Please disable your ad blocker to support this website.

Our website relies on revenue from ads to keep providing free content.