looping constructs
Learn looping constructs step by step with clear examples and exercises.
Why This Matters
Understanding looping constructs is crucial for any C programmer as they allow you to repeatedly execute a block of code until a certain condition is met. This is essential for tasks that require iterations, such as reading input, processing arrays, or performing calculations multiple times. In interviews and exams, you'll often encounter questions related to looping constructs due to their importance in solving complex problems.
Mastering looping constructs will help you write more efficient and readable code, making it easier for you to tackle larger projects and collaborate with other developers.
Prerequisites
Before diving into the core concept of looping constructs, it is essential that you have a good understanding of:
- Basic C syntax (variables, data types, operators)
- Control structures (if-else statements)
- Functions and function prototypes
- Array manipulation (accessing and modifying array elements)
Core Concept
In C programming, there are three main types of looping constructs: for, while, and do-while. Each has its unique use cases and syntax.
For Loop
The for loop is used when you know the number of iterations beforehand. It consists of an initializing statement, a condition, and an increment/decrement statement enclosed within curly braces.
for (initialization; condition; increment/decrement) {
// code to be executed
}
In the initialization section, you can declare and initialize one or more variables. The condition is a Boolean expression that determines whether the loop should continue executing. The increment/decrement section updates the variables before each iteration.
Example: Print numbers from 1 to 100 in increments of 5
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 100; i += 5) {
printf("%d\n", i);
}
return 0;
}
While Loop
The while loop continues to execute as long as the condition is true. It keeps checking the condition at the beginning of each iteration.
while (condition) {
// code to be executed
}
In a while loop, you should ensure that the condition eventually becomes false to avoid an infinite loop.
Example: Read user input until an empty line
#include <stdio.h>
int main() {
char input[100];
while (fgets(input, sizeof(input), stdin) != NULL && strlen(input) > 0) {
printf("You entered: %s", input);
// Clear the input buffer to avoid issues with newline characters
fflush(stdin);
}
return 0;
}
Do-While Loop
The do-while loop is similar to the while loop, but it checks the condition after executing the code block at least once. This ensures that the code inside the loop will run at least once.
do {
// code to be executed
} while (condition);
In a do-while loop, you should still ensure that the condition eventually becomes false to avoid an infinite loop.
Example: Read user input until an empty line (do-while version)
#include <stdio.h>
int main() {
char input[100];
do {
fgets(input, sizeof(input), stdin);
printf("You entered: %s", input);
// Clear the input buffer to avoid issues with newline characters
fflush(stdin);
} while (strlen(input) > 0);
return 0;
}
Worked Example
Example: Print Fibonacci sequence up to the 10th term using each looping construct
For Loop Version
#include <stdio.h>
int main() {
int a = 0, b = 1, nextTerm, i;
for (i = 1; i <= 10; ++i) {
printf("%d ", a);
nextTerm = a + b;
a = b;
b = nextTerm;
}
return 0;
}
While Loop Version
#include <stdio.h>
int main() {
int a = 0, b = 1, nextTerm, i = 1;
while (i <= 10) {
printf("%d ", a);
nextTerm = a + b;
a = b;
b = nextTerm;
++i;
}
return 0;
}
Do-While Loop Version
#include <stdio.h>
int main() {
int a = 0, b = 1, nextTerm, i = 1;
do {
printf("%d ", a);
nextTerm = a + b;
a = b;
b = nextTerm;
++i;
} while (i <= 10);
return 0;
}
Common Mistakes
- Forgetting to initialize the control variable or to increment/decrement it in a
forloop. - Using an infinite loop due to incorrect conditions in
whileanddo-whileloops. - Neglecting to check the condition in a
do-whileloop after executing the code block at least once. - Not handling edge cases, such as empty input or out-of-range indices when using loops with arrays.
- Failing to consider the order of operations within the increment/decrement section of a
forloop. - Misunderstanding the difference between pre-increment (++i) and post-increment (i++) in the increment/decrement section of a
forloop. - Using loops with uninitialized variables or variables that have not been properly declared.
- Forgetting to include necessary header files, such as
stdio.h, when using input/output functions likeprintf()andfgets(). - Not accounting for the termination condition in loops that process arrays, such as missing the last element or processing beyond the array's bounds.
- Incorrectly using looping constructs with pointer variables, leading to undefined behavior or memory leaks.
Practice Questions
- Write a program that prints the Fibonacci sequence up to the 20th term using each looping construct (for, while, do-while).
- Implement a program that calculates the sum of all odd numbers between 1 and 100 using each looping construct (for, while, do-while).
- Write a program that finds the largest prime number less than or equal to 100 using each looping construct (for, while, do-while).
- Create a program that reads a list of integers from the user and calculates their average using each looping construct (for, while, do-while).
- Implement a program that sorts an array of integers in ascending order using the bubble sort algorithm with each looping construct (for, while, do-while).
- Write a program that generates and prints all permutations of a given string using each looping construct (for, while, do-while).
- Implement a program that finds the greatest common divisor (GCD) of two numbers using each looping construct (for, while, do-while).
- Create a program that checks if a given number is prime using each looping construct (for, while, do-while).
- Write a program that generates and prints all possible combinations of k distinct elements chosen from a set of n unique elements using each looping construct (for, while, do-while).
- Implement a program that finds the smallest multiple of a given number that is greater than or equal to another number using each looping construct (for, while, do-while).
FAQ
Why use a for loop instead of a while loop?
The for loop is more concise and easier to read when you know the exact number of iterations beforehand. It also allows you to initialize and update variables within the loop declaration.
What's the difference between pre-increment (++i) and post-increment (i++) in a for loop?
Pre-increment increments the variable before using it in the expression, while post-increment increments the variable after using it in the expression. This can affect the order of operations within the loop.
How do I avoid an infinite loop in a while or do-while loop?
To avoid an infinite loop, ensure that the condition eventually becomes false by checking for termination conditions and handling edge cases appropriately.
Why is it important to clear the input buffer after reading user input using fgets()?
Clearing the input buffer helps prevent issues with newline characters when reading multiple lines of input from the user. The fflush(stdin) function clears the input buffer by discarding any remaining characters in the standard input stream.