Saturday, August 23, 2025

C Programming Viva Questions on Loops with Model Answers

Viva Questions on Loops with Model Answers


1. What is a loop in C programming? Why do we use it?

Answer:
A loop is a control structure in C that repeatedly executes a block of code until a specified condition is true. We use loops to avoid writing repetitive code and to perform iterative tasks efficiently.

2. Explain the difference between while, do…while, and for loops in C.

Answer:
  • while loop: Condition is checked first, then the body executes. (Entry-controlled loop)
  • do…while loop: Body executes first, then condition is checked. (Exit-controlled loop, runs at least once)
  • for loop: Used when initialization, condition, and increment/decrement are all in one line. Best for fixed iterations.
3. What happens if the loop condition is never satisfied in a while loop?

Answer:
If the condition is false at the beginning, the while loop body will never execute even once.

4. Can a for loop run infinitely? Give an example.

Answer:
Yes. If the loop condition is always true or missing, the loop runs infinitely.
Example:
for(;;) {
   printf("Infinite loop\n");
}

5. What is the difference between break and continue statements inside loops?

Answer:
•   break: Immediately exits the loop and transfers control outside.
•   continue: Skips the current iteration and jumps to the next iteration of the loop.

6. What is an infinite loop? Write a simple example in C.
Answer:
An infinite loop is a loop that never terminates because the condition always remains true.
Example:
while(1) {
   printf("Hello\n");
}

7. How is the initialization, condition, and increment part of a for loop optional? Give an example.
Answer:
All three parts in a for loop are optional. If omitted, they must be handled inside the loop body.
Example:
int i = 1;
for(; ; ) {
   if(i > 5) break;
   printf("%d ", i);
   i++;
}

8. What is the output of the following code?
int i = 1;
while(i <= 5){
    printf("%d ", i);
    i++;
}
Answer:
Output:
1 2 3 4 5

9. Write a C program to print numbers from 1 to 10 using a do…while loop.
Answer:
#include <stdio.h>
int main() {
    int i = 1;
    do {
        printf("%d ", i);
        i++;
    } while(i <= 10);
    return 0;
}

10. Explain nested loops with an example (e.g., printing a multiplication table).
Answer:
A nested loop is a loop inside another loop.

Example-Multiplication table:
for(int i = 1; i <= 3; i++) {
    for(int j = 1; j <= 3; j++) {
        printf("%d ", i * j);
    }
    printf("\n");
}
Output:
1 2 3  
2 4 6  
3 6 9

 < Back to Question Bank >


No comments:

Post a Comment