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.


+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++) {
	for (int i = 3; i >= 1; i--) {
answered by (1.1k points)
edited by

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.