Summing Elements in an array?

I'm just trying to sum the elements in an array but I keep getting impossibly huge numbers and can't see the problem. Here's what I'm working with. Thoughts?

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
#include <iostream>
using namespace std;

int add_array_easy(unsigned int size)
{
	int my_array[size];
	int sum;
	
	for(unsigned int i = 0; i < size; i++)
	{
		my_array[i] = i + 1;
	}
	
	if(size == 0)
	{
		sum = 0;
	}
	
	else
	{
		for(unsigned int i = 0; i < size; i++)
		{
			sum += my_array[i];
		}
	}
	return sum;
}

int main()
{
	cout << "Easy sum is: " << add_array_easy(7) << endl;
}
In C++, the only thing a variable declaration does is allocate space for that variable.
The numbers inside these variables are still junk until they are assigned a number.

line 23: junk + 2 being assigned to junk is still junk :)
You initialized each array element inside your first for loop, but you never initialized sum.

Last edited on
This is not standard C++ (though it compiles cleanly with certain compilers that, by default, do not conform to C++):
1
2
3
int add_array_easy(unsigned int size)
{
	int my_array[size];

The number of elements in an array must be a constant integral expression (value known at compile-time).

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
#include <iostream>
// using namespace std;

int add_array_easy( int* my_array, unsigned int size )
{
	// int my_array[size];
	int sum = 0 ; // initialize

	for(unsigned int i = 0; i < size; i++)
	{
		my_array[i] = i + 1;
	}

	/*
	if(size == 0)
	{
		sum = 0;
	}

    else
    */
	{
		for(unsigned int i = 0; i < size; i++)
		{
			sum += my_array[i];
		}
	}
	return sum;
}

int main()
{
    const int N = 7 ;
    int a[N] ;
    std::cout << "Easy sum is: " << add_array_easy( a, N ) << '\n' ;
}
Topic archived. No new replies allowed.