Can I use the same counter variable for a for
loop inside of a for
loop?
Or will the variables affect each other? Should the following code use a different variable for the second loop, such as j
, or is i
fine?
for(int i = 0; i < 10; i++) { for(int i = 0; i < 10; i++) { } }
In Python variables have function-wide scope which means that if two variables have the same name in the same scope, they are in fact one variable. Consequently, nested loops in which the target variables have the same name in fact share a single variable.
Note: It is possible to use one type of loop inside the body of another loop. For example, we can put a for loop inside the while loop.
A counter variable in Java is a special type of variable which is used in the loop to count the repetitions or to know about in which repetition we are in. In simple words, a counter variable is a variable that keeps track of the number of times a specific piece of code is executed.
Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.
You may use the same name (identifier). It will be a different object. They will not affect each other. Inside the inner loop, there is no way to refer to the object used in the outer loop (unless you make special provisions for that, as by providing a pointer to it).
This is generally bad style, is prone to confusion, and should be avoided.
The objects are different only if the inner one is defined separately, as with the int i
you have shown. If the same name is used without defining a new object, the loops will use the same object and will interfere with each other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With