Sum Array

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

//Function prototype
int sumArray(int);

const int 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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

//Function prototype
int sumArray(int[],int); // <- Your definition is wrong.

const int 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;

//Function prototype
int sumArray(int[],int);

const int 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.)
Last edited on
Topic archived. No new replies allowed.