In the following C program, what is wrong with the while loop? int main() { int i = 1; while () { printf("%d", i++); if (i > 10) break; } return 0; }

Difficulty: Easy

Correct Answer: The while loop has an empty condition, which is a syntax error; a valid expression must appear inside the parentheses

Explanation:


Introduction / Context:
This question is about the correct syntax of the while loop in C. It highlights that while requires a condition expression inside its parentheses, even if the intention is to loop forever.


Given Data / Assumptions:

  • The program declares an integer i and initializes it to 1.
  • The while statement is written as while ().
  • Inside the loop, the program prints i and increments it, exiting when i becomes greater than 10.


Concept / Approach:
In C, the syntax of a while loop is while (expression) statement;. The expression must be present and must be something that the compiler can evaluate as true or false (nonzero or zero). An empty pair of parentheses is not valid syntax. If a programmer wants an infinite loop, they usually write while (1) or while (true) in C with appropriate definitions.


Step-by-Step Solution:
Step 1: Inspect the while line. It is written as while ().Step 2: The grammar for C requires an expression between the parentheses.Step 3: Because no expression is present, the compiler cannot parse this as a valid while loop.Step 4: The compiler will emit a syntax error pointing at the while statement.


Verification / Alternative check:
If you attempt to compile this program, the compiler will reject it and indicate an error near while (). If you change the line to while (1) and keep the break condition, the loop runs and prints numbers from 1 to 10, demonstrating what the programmer may have intended.


Why Other Options Are Wrong:
Option B is incorrect because break is allowed inside while loops.Option C is false; using i++ inside printf is allowed, though it must be used carefully in more complex expressions.Option D is incorrect because nesting if inside while is perfectly legal and common.


Common Pitfalls:
Some beginners think they can leave the while condition empty to indicate an infinite loop, similar to for(;;) syntax. However, while does not allow an empty condition; an explicit expression such as 1 is required.


Final Answer:
The issue is that The while loop has an empty condition, which is a syntax error; a valid expression must appear inside the parentheses.

More Questions from Programming

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion