+ 3
Why does my arraySum code act the way it does? What's wrong?
#include <iostream> using namespace std; int main() { int arr[]={10,20,30,40,50}; int arraySum; for(int x = 0; x < 5;x++) { arraySum = arraySum + arr[x]; } cout << arraySum << endl; return 0; } Why is it when I omit explictly defining the arraySum it gives me an output of: 4232260 BUT when I do define arraySum = 0, it gives me the correct answer of 150? I've posted the code publicly on my page. Any help is pointing me in the right direction is appreciated. Thank you
4 Answers
+ 18
because when you declare a new variable (as you do)
int arraySum;
its value is not equal to 0.
it conatins a random value from memory that is != 0
(ex: it may be 235447 or any other value)
that's why when you try to add the value of the array it gives you wrong answer.
so, you need to set its value to 0 after declaring it.
int arraySum = 0;
then you add the value of the array.
+ 16
your are welcome..š
yes it differs from language to another language.
+ 3
You already answered your question. In c++ you have to define variable before working with it.
+ 1
Thank you Mohammad, that makes perfect sense. I didnāt know that it was randomly assigned. I learned Java before and with Java you didnāt have to explicitly define, at least I donāt think so