+ 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

21st Feb 2018, 1:14 AM
Winson Dieu
Winson Dieu - avatar
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.
21st Feb 2018, 3:16 AM
Mohammad Dakdouk
Mohammad Dakdouk - avatar
+ 16
your are welcome..šŸ˜€ yes it differs from language to another language.
21st Feb 2018, 6:24 AM
Mohammad Dakdouk
Mohammad Dakdouk - avatar
+ 3
You already answered your question. In c++ you have to define variable before working with it.
21st Feb 2018, 2:55 AM
Š“ŠµŠ¾Ń€Š³ŠøŠ¹ Š’Š°Š²ŠøŠ»Š¾Š²
Š“ŠµŠ¾Ń€Š³ŠøŠ¹ Š’Š°Š²ŠøŠ»Š¾Š² - avatar
+ 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
21st Feb 2018, 3:55 AM
Winson Dieu
Winson Dieu - avatar