It's because you don't initialize total
. When a local variable is declared, it's value is undefined, and adding something to an undefined value leads to undefined behavior.
In reality, the value of an uninitialized local variable is whatever is in the memory location now occupied by the variable, and will be seemingly random.
You also have the problem that you don't actually add all entries in the array, only the one at index j
, which is also an uninitialized variable, leading you to fetch a value from a random location (and most likely from beyond the limits of the array).
You don't actually need the array, just three variables: The loop counter i
, the total
(which you should initialize to zero) and a general value
integer used in the input statement.
Then you do e.g.
int total = 0;
for (int i = 0; i < 5; ++i)
{
std::cout << "Enter a number: ";
int value;
std::cin >> value;
total += value;
}
std::cout << "Total is " << total << '\n';
Note: You don't need to initialize the value
variable in my example, because it's not read, only written to (and therefore initialized) in the input statement.