The problem in your program is with the scope of your sum variable(s)
. Note that in its present form your program has two instances of the sum variable
.
One of the sum
variables is inside your for loop.
for(int i=0, sum=0; i < n; i++)
{
sum = sum + elements[i];
}
Inside the for loop it has a local scope
, meaning that the sum variable exists only for the duration of the for loop. Outside the for loop it does not exist!
Whereas, in this line of your code cout << " float n is " << float(n) << " float sum is "<< float(sum) << endl;
the sum variable that you are trying to output is the one declared at the beginning of your program as int sum;
which is also the second instance
of the sum variable
and it has not been initialized or assigned a value.
This is what your problem is.
How can the compiler cast your int sum
into a float sum
and output it onto the screen when it has no value assigned to it?
The program works fine as you say for yourself when sum
is initialized outside the for loop. This is because in this case the sum
variable used is the one declared at the top (after int n
). This version of the sum
variable has a global scope
for the duration of the whole code body, and when you output it in the end the compiler recognizes the sum as having been initialized to zero
and incremented inside the for loop.
So the output is the sum of all the numbers inside the array elements[i]
.
Remember that the lifetime or scope of a local variable is just within
a procedure or a code block whereas the scope of a global variable is
throughout the program, meaning it is recognized wherever it is used
or referenced.
Hope this helps!