Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a 'for' loop inside of a 'for' loop use the same counter variable name?

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++)   {   } } 
like image 940
Uclydde Avatar asked Jul 26 '18 23:07

Uclydde


People also ask

Can nested for loops use the same variable?

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.

Can you do a for loop inside of a for loop?

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.

What are counter variables in for 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.

Can a for loop have multiple loop variables?

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.


1 Answers

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.

like image 94
Eric Postpischil Avatar answered Oct 12 '22 12:10

Eric Postpischil