Which of the following is the correct syntax for a for loop in C++?
A
for (int i = 0; i < 10; i++)
C
loop (int i = 0; i < 10; i++)
D
foreach (int i = 0; i < 10; i++)
Analysis & Theory
The correct syntax for a C++ for loop is: for (initialization; condition; increment).
What will the following code print?
for (int i = 0; i < 3; i++) {
cout << i << ' ';
}
Analysis & Theory
The loop starts at 0 and runs while i < 3, printing: 0 1 2.
Which part of a C++ for loop is optional?
Analysis & Theory
In C++, all three parts of the for loop (initialization, condition, and increment) are optional.
How many times will the loop execute?
for (int i = 10; i > 0; i -= 2) { }
Analysis & Theory
The loop starts at 10 and decreases by 2 until i > 0, so it runs 5 times: 10, 8, 6, 4, 2.
Which of the following will cause an infinite loop?
A
for (int i = 0; i < 5; i++)
C
for (int i = 0; i < 5; i += 2)
D
for (int i = 5; i > 0; i--)
Analysis & Theory
for (;;) has no condition and no increment, so it creates an infinite loop.
Which keyword can be used to exit a loop early?
Analysis & Theory
The 'break' statement immediately exits the loop.
What does the 'continue' statement do in a for loop?
B
Skips the remaining code and continues to the next iteration
D
Restarts the loop from the beginning
Analysis & Theory
'continue' skips the rest of the loop body and moves to the next iteration.
Can a for loop have multiple initialization expressions?
B
No, only one is allowed
Analysis & Theory
You can initialize multiple variables using commas, e.g., for (int i = 0, j = 5; i < j; i++, j--).
Which of the following prints even numbers from 0 to 10?
A
for (int i = 0; i <= 10; i += 2) cout << i;
B
for (int i = 2; i < 10; i++) cout << i;
C
for (int i = 0; i <= 10; i++) cout << i % 2;
D
for (int i = 1; i <= 10; i += 2) cout << i;
Analysis & Theory
i += 2 increments i by 2, starting from 0, thus printing even numbers.
Which of the following loops is equivalent to a for loop?
C
while loop with initialization and increment outside
Analysis & Theory
A while loop can mimic a for loop if initialization and increment are handled outside the loop.