Hello, aspiring C programmers!
After mastering conditional statements, it’s now time that we dive into iteration – a fundamental aspect of programming in C. In this tutorial, we will explore the for, while, and do-while loops in C. These basic loops are essential in various coding scenarios because these help us to execute a block of code repeatedly or simply put, on a loop.
Understanding Loops in C
Loops are invaluable when you need to execute the same code multiple times, either with varying values or until a specific condition is met. In C, we primarily utilize three types of loops:
for Loop: This loop executes a block of code a specific number of times.
for (initialization; condition; increment/decrement) {
// code to be executed
}
while Loop: It runs a block of code as long as a specified condition is True.
while (condition) {
// code to be executed
}
do-while Loop: Similar to the while loop, but this loop executes the block of code once before checking if the condition is True. It then repeats the loop as long as the condition holds.
do {
// code to be executed
} while (condition);
Writing Programs Using Different Loops
Let’s explore examples of each type of loop in C:
Example using a for loop: Displaying the multiplication table of 5 up to 10 multiplications.
#include
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d x 5 = %d\n", i, i * 5);
}
return 0;
}
Example using a while loop: Printing the first five even numbers.
#include
int main() {
int i = 2;
while (i <= 10) {
printf("%d\n", i);
i += 2;
}
return 0;
}
Example using a do-while loop: Prompting the user for a number until they provide a value greater than 100.
#include
int main() {
int number;
do {
printf("Enter a number: ");
scanf("%d", &number);
} while (number <= 100);
return 0;
}
Exercise
Your task is to create a C program that implements different types of loops:
- Using the for loop, display the squares of numbers from 1 to 5.
- With the while loop, print the first five odd numbers.
- Employ the do-while loop to ask the user to enter a positive number until they provide one.
This exercise will enhance your understanding of looping structures in C.
Conclusion
Congratulations on successfully navigating through loops, a pivotal concept in C programming! Mastering these constructs allows you to efficiently handle repetitive tasks in your applications. As we progress, we’ll delve deeper into these principles. Keep your enthusiasm high and keep coding!