Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+14 votes
asked in CSC211_Winter2018 by (8 points)

2 Answers

+10 votes

I think you cannot use the same variable for the outer and inner loops. However, I think you can use i in the inner loops if it has some kind of connections to the inner variables.

For example:
for (int i = 1; i <= 5; i++) {

   for (int k = 1; k <= 6 - i; k++) {
        ....
  }

}

answered by (8 points)
+9 votes

You cannot use the same variable i for both outer and inner loop. If you use it, it can cause errors. However, I think you can use the same i for many inner loops that go in a sequence like below example because they are separate loops (you already close the other one).
For example:

for (int k = 1; k <= 5; k++) {
	for (int i = 1; i <= 3; i++) {
		System.out.print(i);
	}
	for (int i = 3; i >= 1; i--) {
		System.out.print(i);
	}
	System.out.println();
}
answered by (612 points)
edited by
+4

This is correct because it has to do with the “Scope” of the variable. Once the for loop ends the variable i no longer is defined and can be used again elsewhere with a different definition.

...