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?
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.
#include <iostream>
// using namespace std;
int add_array_easy( int* my_array, unsignedint size )
{
// int my_array[size];
int sum = 0 ; // initialize
for(unsignedint i = 0; i < size; i++)
{
my_array[i] = i + 1;
}
/*
if(size == 0)
{
sum = 0;
}
else
*/
{
for(unsignedint i = 0; i < size; i++)
{
sum += my_array[i];
}
}
return sum;
}
int main()
{
constint N = 7 ;
int a[N] ;
std::cout << "Easy sum is: " << add_array_easy( a, N ) << '\n' ;
}