I tried to write a simple code to calculate an array elements' sum. every thing looks normal but the function return the sum value wrongly (it always multiply it by two). Although if I want just print the value, it works fine. this is the code:
#include <iostream>
using namespace std;
void getElements(int[],int);
int sumOfElements(int[],int);
int number;
int sum=0;
int main()
{
int a[10];
getElements(a,5);
sumOfElements(a,5);
cout<<"The sum is "<<sumOfElements(a,5)<<endl;
return 0;
}
//Getting array's elements
void getElements(int numbers[],int size_)
{
for (int i=0; i<size_; i++)
{
cout<<"numbers["<<i<<"]: ";
cin>>number;
numbers[i]=number;
}
cout<<'\n';
}
//Calculation the sum of array's elements
int sumOfElements(int numbers[],int size_)
{
for(int i=0;i<size_;i++)
{
sum+=numbers[i];
}
cout<<sum<<endl;
return sum;
}
any idea? thank you in advance!
sumOfElementsmodifies the global variablesum... and you callsumOfElementstwice. so... yeah...you're gonna have a double sum. Probably should have declaredsumlocal tosumOfElements.int numberintogetElementsandint sumintosumOfElements. Then inmain, you can capture the return value ofsumOfElementsand print it out, or print out the return value directly as you have done. After that change, you can callsumOfElements10 times if you want and it will always return the same, correct sum "automatically". Furthermore, calling it without capturing its return value would essentially be a noop.