C Loop Control Structures šŸŽÆ

beginner
19 min

C Loop Control Structures šŸŽÆ

Welcome to our deep dive into C Loop Control Structures! Let's embark on this exciting journey together, learning one of the most fundamental aspects of C programming. This guide is designed for both beginners and intermediates, so let's get started!

What are Loop Control Structures? šŸ“

In C programming, loop control structures allow you to repeatedly execute a block of code. They are essential for writing efficient and practical programs.

Understanding Loops: while, do-while, and for šŸ’”

C offers three main types of loops: while, do-while, and for. Let's explore each one!

while Loop

A while loop checks the condition at the top of the loop and executes the loop body if the condition is true.

c
while (condition) { // code to be executed }

šŸ’” Pro Tip: Make sure the condition eventually becomes false to avoid an infinite loop.

do-while Loop

A do-while loop is similar to the while loop, but the loop body is executed at least once before checking the condition.

c
do { // code to be executed } while (condition);

for Loop

The for loop is a convenient way to execute a loop for a specific number of iterations.

c
for (initialization; condition; increment/decrement) { // code to be executed }
  • initialization: used to initialize the control variable (usually an integer)
  • condition: checks if the control variable meets the condition to continue the loop
  • increment/decrement: increases or decreases the control variable by a specific amount after each iteration

Practical Examples šŸ“

Let's see some practical examples of these loop structures!

Example 1: while Loop

c
#include <stdio.h> int main() { int i = 1; while (i <= 10) { printf("Iteration %d\n", i); i++; } return 0; }

Output:

Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 Iteration 6 Iteration 7 Iteration 8 Iteration 9 Iteration 10

Example 2: do-while Loop

c
#include <stdio.h> int main() { int i = 1; do { printf("Iteration %d\n", i); i++; } while (i <= 10 && i % 2 != 0); // prints even numbers only return 0; }

Output:

Iteration 2 Iteration 4 Iteration 6 Iteration 8

Example 3: for Loop

c
#include <stdio.h> int main() { for (int i = 1; i <= 10; i++) { printf("Iteration %d\n", i); } return 0; }

Output:

Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 Iteration 6 Iteraction 7 Iteraction 8 Iteraction 9 Iteraction 10

Quiz šŸ“

:::quiz Question: What is the output of the following code?

c
#include <stdio.h> int main() { int i = 1; while (i <= 10) { printf("Iteration %d\n", i); i += 2; // increment by 2 instead of 1 } return 0; }

A: Iteration 1, Iteration 3, Iteration 5, Iteration 7, Iteration 9 B: Iteration 1, Iteration 3, Iteration 5, Iteration 7, Iteration 9, Iteration 11 C: Iteration 1, Iteration 3, Iteration 5

Correct: A Explanation: The loop increments i by 2, so it stops at 9.