d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Question About Code, For Loop
Add Reply New Topic New Poll
Member
Posts: 31,293
Joined: Mar 25 2009
Gold: 0.00
Jan 12 2019 08:57pm
Code
int[] myIntArray = new int[10];

for(int i=0; i < 10; i++) {
myIntArray[i] = i*10;
}



for(int i=0; i<10; i++) {
System.out.println("Element " + i + ", value is " + myIntArray[i]);
}








I'm not sure how it's printing out the value of i*10 in second for loop... as they are in seperate scopes..... So it should just be printing out value of i:0,1,2,3,4,5,6,7,8,9.

As they are seperate for loops, in seperate scopes.... YET, it's still printing value of i*10 for some reason, which i don't understand.


For example, if i put a System.out.println(i);, in between the for loops it doesn't work, cuz it's out of scope....
Therefor the 2nd for loop shouldn't get value of i*10
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Jan 12 2019 08:59pm
Quote
as they are in seperate scopes


define "they". what is in separate scope? the array is in scope of the entire function.
Member
Posts: 31,293
Joined: Mar 25 2009
Gold: 0.00
Jan 12 2019 09:06pm
Quote (carteblanche @ Jan 12 2019 10:59pm)
define "they". whatis in separate scope? the array is in scope of the entire function.


I mean, each for loop is a seperate scope yes?
if that's the case, then the 2nd for loop shouldn't be printing value of i*10... it should only be printing value of i.....
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Jan 12 2019 09:42pm
Quote (ferf @ Jan 12 2019 10:06pm)
I mean, each for loop is a seperate scope yes?


variables declared inside different for loops have different scope, yes. but we just said the array is declared outside of the loop so it shares scope. and you're talking about the array.
Member
Posts: 31,293
Joined: Mar 25 2009
Gold: 0.00
Jan 12 2019 09:49pm
Quote (carteblanche @ Jan 12 2019 11:42pm)
variables declared inside different for loops have different scope, yes. but we just said the array is declared outside of the loop so it shares scope. and you're talking about the array.


Gotchya thanks, makes sense
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll