Challenge your understanding of how loops and conditional statements work together in programming. This quiz features realistic programming scenarios to test your ability to predict outcomes when loops and conditions are combined.
Given the code: 'for (int i = 1; i u003C= 10; i++) { if (i % 2 == 0) count++; }', what will be the value of 'count' after the loop ends?
Explanation: The loop iterates from 1 to 10, and 'count' is increased only when 'i' is even. There are five even numbers between 1 and 10 inclusive (2, 4, 6, 8, 10). Option '10' incorrectly assumes every iteration is counted, '4' misses one even number, and '6' overcounts. Option '5' is correct since that's the exact count of even numbers.
Consider the code: 'for (int i = 0; i u003C 10; i++) { if (i == 4) break; }'. How many times does the loop body execute?
Explanation: The loop starts at 0 and runs until i is less than 10. When i reaches 4, the condition 'i == 4' is true, and 'break' ends the loop. Thus, the loop executes for i equals 0, 1, 2, and 3—four times in total. Option '5' assumes the loop runs until i equals 4, but the break prevents that. '9' and '10' ignore the early exit.
If you have the code 'sum = 0; for (int i = 1; i u003C= 5; i++) { if (i == 3) continue; sum += i; }', what is the final value of 'sum'?
Explanation: The loop iterates from 1 to 5 and adds each number to 'sum' except when i is 3 because 'continue' skips that iteration. So, sum becomes 1+2+4+5=12. Option '15' assumes every number is added, '11' mistakenly excludes two values, and '10' is not the result of excluding just 3. '12' is correct based on the logic.
In a script with 'for (int i = 1; i u003C= 3; i++) { for (int j = 1; j u003C= 3; j++) { if (j u003E i) print(j); } }', how many numbers are printed?
Explanation: For each i value, inner loop prints j only when j u003E i. So for i=1, print j=2,3 (2 prints); for i=2, print j=3 (1 print); for i=3, no j satisfies ju003Ei. Thus, there are 2+1=3 prints in total. The other options overcount by misunderstanding the conditional or loop boundaries.
For this code: 'for (int n = 1; n u003C= 100; n++) { if (n % 13 == 0) { found = n; break; } }', what will be the value stored in 'found' after execution?
Explanation: The loop searches from 1 upwards for the first 'n' divisible by 13. The first such number is 13, so 'found' will be set to 13. Option '1' ignores the condition, '12' is not divisible by 13, and '100' is the loop’s upper limit but not the first result. '13' is correct because it's the smallest integer in the range meeting the criteria.