1. What is the basic syntax of a for loop in C#?
Answer:
Explanation:
A for loop in C# typically includes initialization, a condition, and an iteration expression.
2. Which part of a for loop is executed only once?
Answer:
Explanation:
The initialization statement of a for loop is executed only once at the beginning of the loop.
3. What will be the output of the following code?
for (int i = 0; i < 3; i++) { Console.WriteLine(i); }
Answer:
Explanation:
The loop starts with i = 0 and runs while i < 3, so it prints 0, 1, and 2.
4. Which part of the for loop is optional?
Answer:
Explanation:
All three parts of the for loop—initialization, condition, and iteration—are optional. Omitting the condition results in an infinite loop.
5. How can you exit a for loop prematurely in C#?
Answer:
Explanation:
The break statement is used to exit a for loop before its normal termination.
6. What is the purpose of the continue statement in a for loop in C#?
Answer:
Explanation:
The continue statement skips the rest of the code in the current iteration and proceeds with the next iteration of the loop.
7. What happens if you omit the iteration expression in a for loop?
Answer:
Explanation:
Omitting the iteration expression can lead to an infinite loop if the condition never becomes false.
8. Which type of loop is most appropriate for iterating over an array in C#?
Answer:
Explanation:
A for loop is often the most appropriate choice for iterating over an array due to its structure that easily accommodates an index variable.
9. In a for loop, is it possible to have multiple initialization statements?
Answer:
Explanation:
Multiple initialization statements can be included in a for loop, separated by commas.
10. Can the condition in a for loop be a complex expression?
Answer:
Explanation:
The condition in a for loop can be any expression that evaluates to a boolean value, including complex expressions.
11. What is the scope of a variable declared in the initialization section of a for loop?
Answer:
Explanation:
Variables declared in the initialization section of a for loop are local to the loop and cannot be accessed outside of it.
12. How many times does the body of a for loop execute if its condition is never true?
Answer:
Explanation:
If the condition of a for loop is never true, the body of the loop does not execute at all.
13. What is the correct syntax for a for loop with no body in C#?
Answer:
Explanation:
A for loop with no body can be written with a semicolon after the iteration expression.
14. Can you declare a variable of a different type in the iteration part of a for loop?
Answer:
Explanation:
Variables declared in the iteration part of a for loop must be of the same type as those in the initialization part, or else a compile-time error will occur.
15. Is it possible to nest for loops in C#?
Answer:
Explanation:
In C#, for loops can be nested within each other to any depth, allowing for complex iteration patterns.