Hi, my code seems to stop running(I get a process error and it prompts me to shut down the program) after the first for loop.
Could someone help me pinpoint my problem? Also, would there be a way to increment years once in a second for loop instead of me creating 3 for loops? Like maybe nesting them or something along those lines?
You're overstepping the boundaries of months. There're a few thing wrong with your code.
1) The <= operator in each of the for loops should be <. Every index is offset by one. For example, 0 (first), 1(second), etc. By using the <= operator, you attempt to access the 12th element of months, which doesn't exist.
2) You never reset month. After the first for loop has finished, month contains 12. Then, within your second for loop, you increment month again. Again, month is incremented another 12 times. Since you never reset month, you're writing to unknown memory. The index range of months is 0 -to- 11.
To fix this code, you need to do the following:
- After each for loop, reset month to 0.
- Change each comparison statement within each for loop with: x < 12;
No they will still exist in that function, with the exception of the variable created in a for() statement. There's not really any point on declaring a variable inside a loop though
An object (variable, or whatever floats your boat) declared within the scope[1] of a function or loop construct is local. Allow me to elaborate further with this code segment:
Wouldn't it re-initialize every time it loops though? Like, it'll initialize the variable the first time, then it will redo it, or it will try to make another variable of the same name? I am just confused how it is working underneath the code I guess
Wouldn't it re-initialize every time it loops though?
That is the exact reason you would want to use it in a loop like that - you will find that sometimes you want a value that resets with each loop iteration, and this is the way to do it.
I still don't think your understanding what im trying to say. Lemme break it down, I might be explaining weirdly. Ok so let's say we have a for loop:
for (int x = 0, x < 5, x++) //this is NOT the variable I am talking about
{
double y = 0.0; //this IS the variable I am talking about
other statements...
}
Now "double y = 0.0" will be read each time this loop passes correct?
So let's think this through a couple loops...
First pass:
initialize variable double y with value 0.0
other statements....
Second pass:
Now here, will it reinitialize double y back at 0.0, or does it just ignore this after the first time through?
other statements...
That is my question. I hope that better explains what I am getting at
It at the end of each iteration it deletes it, then at the beginning it makes a new one. Compiler optimizations may change this but the behavior you get from it will always be that of it being reinitialized.