How do...while loop works? (C Programming)
Learn How do...while loop works? (C Programming) step by step with clear examples and exercises.
Why This Matters
Understanding while and do-while loops in C programming is crucial for writing efficient and effective programs. These control structures allow you to repeat a block of code until a specified condition is met, which is essential for solving real-world problems, preparing for interviews, and debugging common errors in your C programs.
Prerequisites
Before diving into the details of while and do-while loops, it's important to have a good understanding of the following concepts:
- Variables and data types
- Basic arithmetic operations
- Control structures (if-else statements)
- Functions and function prototypes
- Arrays in C programming
- Understanding pointers (optional but recommended for more complex programs)
Core Concept
While Loop
The while loop repeatedly executes a block of code as long as the condition within the parentheses is true. The syntax for a while loop is:
while (condition) {
// Code to be executed
}
Here's an example that prints numbers from 1 to 5 using a while loop:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
In this example, the loop continues executing as long as i is less than or equal to 5. After each iteration, the value of i is incremented by 1.
Do-While Loop
The do-while loop also repeatedly executes a block of code but first executes the code at least once before checking the condition. The syntax for a do-while loop is:
do {
// Code to be executed
} while (condition);
Here's an example that prints numbers from 1 to 5 using a do-while loop:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
In this example, the loop first executes and prints the number 1 before checking if i is less than or equal to 5. After each iteration, the value of i is incremented by 1, and the condition is checked again. This ensures that the code inside the do-while loop will always execute at least once.
Advantages and Disadvantages
The main difference between while and do-while loops lies in when they check their conditions:
- A
whileloop checks its condition before executing the code, which can cause the loop to not execute if the initial condition is false. - A
do-whileloop checks its condition after executing the code at least once, ensuring that the code inside the loop will always be executed at least once.
Nested Loops
You can use multiple loops within other loops in C programming. This is known as nesting loops. Nesting loops allows you to iterate through multiple dimensions of data structures such as arrays and matrices. Here's an example that prints a multiplication table for the numbers 1 to 10:
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 10; i++) {
printf("\n%d * ", i);
for (j = 1; j <= 10; j++) {
printf("%d ", i * j);
}
}
return 0;
}
In this example, an outer for loop iterates through the numbers from 1 to 10. For each iteration of the outer loop, an inner for loop is used to print the multiplication table for that number.
Worked Example
Let's write a program that reads numbers from the user until they enter a negative number. We'll use both while and do-while loops to demonstrate their differences:
#include <stdio.h>
int main() {
int num;
printf("Enter numbers (negative number to quit):\n");
// While loop example
while (1) {
scanf("%d", &num);
if (num < 0) break;
printf("You entered: %d\n", num);
}
printf("\nWhile loop example finished.\n");
// Do-while loop example
do {
printf("Enter a number (negative number to quit): ");
scanf("%d", &num);
} while (num >= 0);
printf("\nDo-while loop example finished.\n");
return 0;
}
In this example, both loops read numbers from the user and print them. However, the while loop starts by checking the condition and might not execute any code if the first input is a negative number. On the other hand, the do-while loop executes at least once before checking the condition, so it will always prompt for an input.
Common Mistakes
- Forgetting to initialize variables: Always initialize your loop variables before using them in the condition.
- Incorrectly setting the condition: Make sure that the condition checks the correct variable and uses the appropriate comparison operator (e.g.,
!=instead of=). - Forgetting to increment or decrement loop variables: Don't forget to update loop variables after each iteration to eventually satisfy the condition and exit the loop.
- Using a
whileloop when ado-whileloop is more appropriate (or vice versa): Choose the appropriate loop based on whether you want to check the condition before executing the code or after executing it at least once. - Forgetting to handle edge cases: Always consider what happens when the loop condition becomes false, such as an empty array or a loop that never terminates.
- Neglecting to validate user input: When reading user input, always validate the input to ensure it meets certain criteria (e.g., within a specific range).
Common Mistakes - Subheadings
- Initialization Errors
- Condition Errors
- Variable Update Errors
- Loop Type Selection
- Edge Case Handling
- User Input Validation
Practice Questions
- Write a program that calculates and prints the sum of all numbers from 1 to 100 using a
whileloop. - Write a program that finds the smallest prime number greater than 50 using a
do-whileloop. - Write a program that reads user input until they enter "quit" (case-insensitive) using a
whileloop and validates the input. - Write a program that counts and prints the number of vowels in a given string using a
do-whileloop. - Write a program that finds the largest prime number less than or equal to 100 using both a
whileloop and ado-whileloop. - Write a program that generates and prints Fibonacci sequence up to the nth term, where n is user-defined using a
whileloop. - Write a program that sorts an array of integers in ascending order using a
do-whileloop and bubble sort algorithm. - Write a program that finds the factorial of a given number using both a
whileloop and ado-whileloop. - Write a program that generates and prints all permutations of a string using a
whileloop and recursion. - Write a program that checks if a given year is a leap year using a
whileloop.
FAQ
What happens if I use an infinite loop with a while or do-while loop?
An infinite loop is a loop that never ends because its condition remains true. To exit an infinite loop, you can forcefully terminate the program (Ctrl+C on Linux/macOS or pressing the "End" key on Windows).
Can I use both a while and do-while loop in the same program?
Yes, you can use both loops in the same program as needed. However, it's generally recommended to use one type of loop for clarity and readability.
What's the difference between a while and do-while loop in terms of performance?
In most cases, there is no significant performance difference between while and do-while loops because they have similar efficiency. However, the do-while loop might be slightly faster due to its guaranteed first execution before checking the condition.
How can I break out of a nested loop?
To break out of a nested loop, you can use multiple break statements or a single break statement with a label on the outer loop.
What is the purpose of the semicolon (;) at the end of the while and do-while loop's condition?
The semicolon is not part of the loop condition itself but rather a part of C syntax that separates statements. In the context of loops, it is required to separate the loop condition from the code block that follows.