A while loop in C is a control flow statement used to execute a block of code repeatedly as long as a specified condition remains true. The condition is checked before each iteration, and if the condition is false initially, the loop is skipped entirely.
Syntax:
while (condition) {
// Code to execute as long as the condition is true
}
Explanation:
condition: A boolean expression that is checked before each iteration. If it is true, the loop continues; if false, the loop terminates.
Example: Print the value from 1 to 5
#include <stdio.h>
int main() {
int number = 1; // Initialize the number variable
// While loop that runs until number is less than or equal to 5
while (number <= 5)
{
printf("%d\n",number); // Prints the current value of number
number++; // Increment count after each iteration
}
return 0;
}
Output:
2
3
4
5
C While loop – Interview Questions
Q 1: What is a while loop in C?
Q 2: Is while an entry-controlled loop?
Q 3: When should we use a while loop?
Q 4: Can a while loop run infinitely?
Q 5: Can a while loop have multiple statements?
C While loop – Objective Questions (MCQs)
Q1. What is the correct syntax of a while loop in C?
Q2. The condition of a while loop is checked:
Q3. What happens if the condition in a while loop is false initially?
Q4. What is the output of this code?
int i = 1;
while (i <= 3) {
printf("%d ", i);
i++;
}
Q5. What can make a while loop run infinitely?