SO Im supposed to write a program that uses arrays to calculate the sum and display it. I keep getting the error that says the sum has to be initialized.
Any idea what Im not seeing ?
Thanks.
#include <iostream>
usingnamespace std;
//Function prototype
int sumArray(int);
constint NUM_ELEMENTS = 5;
int main()
{
int sum;
int number[NUM_ELEMENTS];
cout << "Enter the number\n";
for (int index = 0; index < NUM_ELEMENTS; index++)
{
cout << "Index #" << (index+1) << ": ";
cin >> number[index];
}
cout << "The sum is: " << sum << endl;
return 0;
}
int sumArray( int array[], int number)
{
int sum;
if (number < 0)
{
sum = 0;
}
else
{
sum = array[0] + sumArray(array + 1, number - 1);
}
return sum;
}
#include <iostream>
usingnamespace std;
//Function prototype
int sumArray(int[],int); // <- Your definition is wrong.
constint NUM_ELEMENTS = 5;
int main()
{
int sum = 0;
int number[NUM_ELEMENTS];
cout << "Enter the number\n";
for (int index = 0; index < NUM_ELEMENTS; index++)
{
cout << "Index #" << (index+1) << ": ";
cin >> number[index];
}
cout << "The sum is: " << sum << endl;
return 0;
}
int sumArray( int array[], int number)
{
int sum = 0;
if (number < 0)
{
sum = 0;
}
else
{
sum = array[0] + sumArray(array + 1, number - 1);
}
return sum;
}
Index #1: 4
Index #2: 7
Index #3: 2
Index #4: 8
Index #5: 3
The sum is: 134519194
is the output of your program.
Reason for the strange output:
In C++, variables are NOT initialized to 0 when they are created. As a result, they contain random values which were already there in the place in memory. That is why you need to add =0; after every variable declaration.
#include <iostream>
usingnamespace std;
//Function prototype
int sumArray(int[],int);
constint NUM_ELEMENTS = 5;
int main()
{
int sum = 0;
int number[NUM_ELEMENTS];
cout << "Enter the number\n";
for (int index = 0; index < NUM_ELEMENTS; index++)
{
cout << "Index #" << (index+1) << ": ";
cin >> number[index];
}
sum = sumArray(number,NUM_ELEMENTS - 1);
cout << "The sum is: " << sum << endl;
return 0;
}
int sumArray( int array[], int number)
{
int sum = 0;
if (number < 0)
{
sum = 0;
}
else
{
sum = array[number] + sumArray(array, number - 1);
}
return sum;
}
Here is the more-or-less corrected code. Also your Recursion is wrong(I think.)