CS101 Unit 5: End of unit assessment Q10 Variable Shadowing?

Hi. I’ve been practicing the end of unit problems for preparation towards the final exam, and having attempted unit 5 assessment the 2nd time I felt I came across a variable shadowing problem in the last question. A local variable was declared twice in the same scope, and my understanding is that the program won’t compile for that reason.

Please correct me if I’m wrong because I’d like to get a good grasp on scoping. Thank you.

Bumping this thread! I took a look with a browser console and online IDE but don’t know enough to say for sure. For anyone who wants to check the Java code themselves, click below…

U5 question 10
int x = 5, y = 3;
while ( x > 0 ) {
    if ( y > 1 ) {
        int x = 1;
        y -= x * y;
    }
    else {
        y += x;
    }
    x = x – 1;
}
Answer and explanation

a. x = 0, y = 0

The inner x is not available outside of the compound statement in which it is declared. The outer x decreases by 1 in each iteration. The value of y alternates between 0 and x as the loop proceeds, ending at 0.

1 Like