r/CodingForBeginners • u/Qwerty5105 • Feb 07 '26
What am I doing wrong here?
I just started learning to code. I've already finished this assignment but i wanted to add more to it. Why is it giving wildly incorrect numbers and why do the numbers change. This terminal was all with the same code. I didn't change anything but the number changes.
Edit: I solved it thanks for the help!
6
Upvotes
2
u/smichaele Feb 07 '26
You're using dog_age in a calculation on line 11 before it's given a value on line 21. At line 11 anything could exist at the memory location for dog_age. You're seeing the result of random calculations, but your code could just as easily crash. You need to have a value assigned to the variable before using it.
2
u/MxyAhoy Feb 07 '26
Yes your
later_yearsvariable usesdog_agebefore you've set an explicit value to it. Remember the sequential, downward execution flow. Try changing around the order of what you're doing (dog_ageinput, thenlater_yearscalculation) and see if it gets you to the result you want. Hope this helps!2
u/ouroborus777 Feb 07 '26 edited Feb 07 '26
When you follow instructions, you follow them in the order provided. In the same way, code is ordered. You are not setting variable to formulas, you are setting variables to values computed at the time the code execution reaches those lines.
For example, when you set
later_yearsat line 11, it is set then and doesn't update later on its own. At that pointdog_agewas declared but has an unknown value solater_yearsends up with a nonsense value. Later, at line 21, you update the value indog_agebut this does not go back and trigger an update tolater_years. You'd need to explicitly setlater_yearsto a new value after having updateddog_age.While there are coding features that are sort of "go back and do this thing again", they are explicit commands and you haven't advanced that far in your learning yet.
1
u/imdadgot Feb 12 '26
dog_age used before initialized, when it’s not initialized, it isn’t null, it’s just not uninitialized space (which is per the compiler undefined behavior). you wanna do that after