0
What are the values to i, x and y after completing the code segment?
int i = 0; int x = 0; int y; while (i<3){ x = x+5; i++; }
3 ответов
+ 4
Iteration 1 : x=5, i=1
Iteration 2 : x=10, i=2
Iteration 3 : x=15, i=3 (Loop stops)
+ 3
Let's see: We start with i = 0. The loop terminates when i >= 3. The value of i is incremented each time the loop is executed. So, the loop will execute 3 times.
Okay, so what are we doing with each loop iteration? Looks like we're adding 5 to x. We start with x = 0, and then increase the value of x by 5 every time the loop executes. It executes 3 times. Hmmm.
As for y, it never changes. It's not involved at all; it's not even initialized. So y is going to be some indeterminate value, assuming there's not more code to go with this.
You should be able to figure it out.
+ 2
entering the loop:
when i = 0, x = x + 5 = 5, i = 1
when i = 1, x = 10, i = 2
when i = 2, x = 15, i = 3
i is now 3, which is not less than 3, so loop terminates
x = 15
i = 3