Loops

Lesson 2.6: Looping Statements


Loops are a powerful tool in programming, allowing you to repeat a block of code multiple times. This lesson will introduce you to the three main looping structures in C: for, while, and do-while.


1. The for Loop


Purpose: Ideal when you know the exact number of iterations in advance.

Syntax:

C

for (initialization; condition; update) {

    // Code to be executed in each iteration

}

Explanation:


Initialization: Sets the initial value of a loop control variable (often called a counter).

Condition: Specifies the condition that must be true for the loop to continue.

Update: Modifies the loop control variable after each iteration (typically incrementing or decrementing).

Example:


C

for (int i = 0; i < 5; i++) {  // Execute 5 times (i = 0, 1, 2, 3, 4)

    printf("Iteration %d\n", i);

}


2. The while Loop


Purpose: Great for situations where the number of iterations is unknown and depends on a condition.

Syntax:

C

while (condition) {

    // Code to be executed as long as the condition is true

}

Example:

C

int number = 1;

while (number <= 10) {

    printf("%d ", number);

    number++; 

}

3. The do-while Loop


Purpose: Similar to the while loop, but the code block is guaranteed to execute at least once, even if the condition is initially false.

Syntax:

C

do {

    // Code to be executed at least once

} while (condition); 


Example:

C

int num;

do {

    printf("Enter a positive number: ");

    scanf("%d", &num); // Read the number from the user

} while (num <= 0); 


printf("You entered: %d\n", num);


Choosing the Right Loop


for: When you know the exact number of repetitions.

while: When you need to repeat until a condition becomes false, and you don't know how many times it'll take.

do-while: When you want the loop to execute at least once, even if the condition is initially false.

Nested Loops


You can place one loop inside another to create nested loops. This is useful for tasks like iterating through a multidimensional array.


C

for (int i = 0; i < 3; i++) {

    for (int j = 0; j < 2; j++) {

        printf("(%d, %d)\n", i, j); // Prints (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)

    }

}

Important Considerations


Infinite Loops: Be careful not to create loops with conditions that never become false, as this will lead to an infinite loop (a program that never ends).

Loop Control Statements: You can use break to exit a loop prematurely or continue to skip to the next iteration.

Let me know if you'd like more examples or specific use cases for loops!

Course Syllabus