0

How can I obtain a value from inside a for loop?
I declared the variable in the method and not inside the loop. When I use the same variable in an if statement in the same method however, I get a message saying that the variable has not been initialized. I want to use the value of the variable that has ibeen initialized inside the for loop in my if statement. I dont want to however, put the if statement inside the for loop.
Any suggestions?
Thanks!!!!!!!!

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by kvass
0

Lets say you are using an integer as a counting variable:

int x;
for (x=0;x<10;x++){}
//remainder of your code here

If you want to access the value of x later the for-loop may not have been evaluated if the condition was Never met, so x would be lacking a value, potentially causing issues later in the code. To avoid this, simply initialize the variable outside the loop and modify it inside the loop as required:

int x = 0;
for (x=0;x<10;x++){}
//remainder of your code here
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.