Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+14 votes
asked in CSC211_Winter2018 by (1 point)

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 (1 point)
+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 (1 point)
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.

...