Introduction to C Language | Lesson 3: Detailed Explanation of Loop Statements

Introduction to C Language | Lesson 3: Detailed Explanation of Loop Statements

📝 This article is suitable for beginners with no background in C language. Through rich code examples and detailed comments, it will help you easily master the usage techniques of loop statements!

1. 🚀 Why Learn Loop Statements?

Imagine if you had to manually print the numbers from 1 to 100, how would you do it? Would you write 100 lines of <span>printf</span> statements? Of course not! This is where loop statements come into play.

Loop statements are the “repeaters” in programming, allowing the program to automatically repeat a segment of code, greatly improving programming efficiency. Just like a washing machine’s washing program, once the parameters are set, it can automatically repeat the washing action.

2. 🔄 Introduction to the Family of Loop Statements

The C language provides us with three siblings: <span>while</span>, <span>do-while</span>, and <span>for</span>. Each has its own characteristics and applicable scenarios, so let’s get to know them one by one!

3. 💡 while Loop: Check the Door Before Entering

(1) Basic Syntax

while(conditional expression)
{
    loop body statement;  // Repeat the code here when the condition is true
}

(2) Execution Flow

  1. 1. First, check if the conditional expression is true
  2. 2. If true, execute the loop body
  3. 3. After execution, return to step 1 to continue checking
  4. 4. Exit the loop when the condition is false

(3) Practical Example: Countdown Timer

#include <stdio.h>

int main()
{
    int countdown = 5;  // Start countdown from 5

    printf("Countdown begins:\n");
    while(countdown > 0)  // Continue looping while countdown is greater than 0
    {
        printf("%d...\n", countdown);
        countdown--;  // Decrease countdown by 1 each loop
    }
    printf("Time's up! 🎉\n");

    return 0;
}

Output:

Countdown begins:
5...
4...
3...
2...
1...
Time's up! 🎉

4. 🎯 In-Depth Understanding: The Difference Between i– and –i

This is a common point of confusion for beginners, let me explain with a simple example:

#include <stdio.h>

int main()
{
    int i = 5;
    int a, b;

    // Postfix decrement i--: use first, then decrement
    a = i--;  // Equivalent to: a = i; i = i - 1;
    printf("After using i--: a = %d, i = %d\n", a, b);  // a = 5, i = 4

    i = 5;  // Reset i's value

    // Prefix decrement --i: decrement first, then use
    b = --i;  // Equivalent to: i = i - 1; b = i;
    printf("After using --i: b = %d, i = %d\n", b, i);  // b = 4, i = 4

    return 0;
}

Memory Tips:

  • <span>i--</span>: The symbol is at the back, so “decrement later”
  • <span>--i</span>: The symbol is at the front, so “decrement first”

5. 🔁 Infinite Loop: The Never-Ending Motor

#include <stdio.h>

int main()
{
    int count = 0;

    while(1)  // The condition is always true, creating an infinite loop
    {
        printf("This is loop number %d\n", ++count);

        // Set an exit condition, otherwise the program will run forever
        if(count >= 5)
        {
            printf("Loop ended!\n");
            break;  // Exit the loop
        }
    }

    return 0;
}

Application Scenarios:

  • • Game main loop
  • • Server listening program
  • • Interactive menu system

6. 🎪 do-while Loop: Enter First, Then Check the Door

(1) Basic Syntax

do
{
    loop body statement;  // Will execute at least once regardless of the condition
} while(conditional expression);  // Note the semicolon here!

(2) Comparison of Characteristics

Loop Type Characteristics Applicable Scenarios
while Check first, then execute May not execute at all
do-while Execute first, then check Will execute at least once

(3) Practical Example: Input Validation System

#include <stdio.h>

int main()
{
    int password;
    int correct_password = 123456;

    printf("=== Password Validation System ===\n");

    do
    {
        printf("Please enter the password:");
        scanf("%d", &password);

        if(password != correct_password)
        {
            printf("Incorrect password, please try again! ❌\n");
        }

    } while(password != correct_password);  // Continue looping if the password is incorrect

    printf("Password correct, welcome to the system! ✅\n");

    return 0;
}

(4) Practical Example: Counting the Number of Digits

#include <stdio.h>

int main()
{
    int num, temp, digits = 0;

    printf("Please enter an integer:");
    scanf("%d", &num);

    temp = num;  // Save the original number

    // Use do-while to ensure at least one execution (handle the case of input 0)
    do
    {
        temp = temp / 10;  // Divide by 10 each time to remove the last digit
        digits++;          // Increase the digit count by 1
    } while(temp > 0);     // Continue while temp is greater than 0

    printf("The number %d has %d digits\n", num, digits);

    return 0;
}

7. 🏃♂️ for Loop: The Most Elegant Counter

(1) Basic Syntax

for(initialization; loop condition; update operation)
{
    loop body statement;
}

(2) Execution Flow Diagram

Initialization → Check condition → Execute loop body → Update operation → Check condition → ...
   ↑                                    ↓
   └────────── Exit when condition is false ←──────────┘

(3) Practical Example: Multiplication Table

#include <stdio.h>

int main()
{
    printf("=== Multiplication Table ===\n");

    // Outer loop controls the rows (multiplicands)
    for(int i = 1; i <= 9; i++)
    {
        // Inner loop controls the columns (multipliers)
        for(int j = 1; j <= i; j++)
        {
            printf("%d×%d=%2d ", j, i, i*j);
        }
        printf("\n");  // New line after each row
    }

    return 0;
}

Output:

1×1= 1 
1×2= 2 2×2= 4 
1×3= 3 2×3= 6 3×3= 9 
...

(4) Practical Example: Sum from 1 to 100

#include <stdio.h>

int main()
{
    int sum = 0;  // Store the accumulated result

    // i starts from 1, adds 1 each time, until i is greater than 100
    for(int i = 1; i <= 100; i++)
    {
        sum += i;  // Equivalent to sum = sum + i
    }

    printf("The sum from 1 to 100 is: %d\n", sum);  // Output: 5050

    return 0;
}

8.🚪 break Statement: Emergency Exit

(1) Function Description

<span>break</span> acts like an “emergency exit” for loops; once executed, it immediately exits the current loop.

(2) Practical Example: Prime Number Checker

#include <stdio.h>

int main()
{
    int num, i;
    int is_prime = 1;  // Assume it is a prime number, 1 means true, 0 means false

    printf("Please enter an integer greater than 1:");
    scanf("%d", &num);

    // Check for factors from 2 to num-1
    for(i = 2; i < num; i++)
    {
        if(num % i == 0)  // If divisible by i
        {
            is_prime = 0;  // Not a prime number
            break;         // Exit once a factor is found to improve efficiency
        }
    }

    if(is_prime && num > 1)
        printf("%d is a prime number ✅\n", num);
    else
        printf("%d is not a prime number ❌\n", num);

    return 0;
}

(3) Practical Example: Guess the Number Game

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    srand(time(NULL));  // Initialize random seed
    int secret = rand() % 100 + 1;  // Generate a random number between 1-100
    int guess, attempts = 0;

    printf("=== Guess the Number Game ===\n");
    printf("I have thought of a number between 1-100, can you guess it?\n");

    while(1)  // Infinite loop
    {
        printf("Please enter your guess:");
        scanf("%d", &guess);
        attempts++;

        if(guess == secret)
        {
            printf("Congratulations! You guessed it right! 🎉\n");
            printf("You guessed it in %d attempts!\n", attempts);
            break;  // Exit the loop if guessed correctly
        }
        else if(guess < secret)
        {
            printf("Too low, try again! 📈\n");
        }
        else
        {
            printf("Too high, try again! 📉\n");
        }
    }

    return 0;
}

9. ⏭️ continue Statement: Skip This Time

(1) Function Description

<span>continue</span> acts like a “skip key” for loops, skipping the remaining part of the current loop and directly entering the next loop iteration.

(2) Practical Example: Odd and Even Number Separation

#include <stdio.h>

int main()
{
    printf("Odd numbers from 1 to 20 are:");

    for(int i = 1; i <= 20; i++)
    {
        if(i % 2 == 0)  // If it is an even number
        {
            continue;   // Skip this loop iteration, do not execute the following printf
        }

        printf("%d ", i);  // Only odd numbers will reach here
    }
    printf("\n");

    return 0;
}

Output:<span>1 3 5 7 9 11 13 15 17 19</span>

(3) Comparison of break vs continue

#include <stdio.h>

int main()
{
    printf("Effect of using continue:");
    for(int i = 1; i <= 5; i++)
    {
        if(i == 3)
            continue;  // Skip 3, continue with i=4,5
        printf("%d ", i);
    }
    printf("\n");  // Output: 1 2 4 5

    printf("Effect of using break:");
    for(int i = 1; i <= 5; i++)
    {
        if(i == 3)
            break;     // Exit the loop when reaching 3
        printf("%d ", i);
    }
    printf("\n");  // Output: 1 2

    return 0;
}

10.🎯 goto Statement: Time-Space Transporter

(1) Basic Syntax

label_name: statement
    ...
goto label_name;  // Jump directly to the label position

(2) Usage Example

#include <stdio.h>

int main()
{
    int choice;

menu:  // Define a label
    printf("\n=== Simple Calculator ===\n");
    printf("1. Addition\n");
    printf("2. Subtraction\n");
    printf("3. Exit\n");
    printf("Please choose:");
    scanf("%d", &choice);

    switch(choice)
    {
        case 1:
            printf("Performing addition operation...\n");
            goto menu;  // Jump back to the menu
        case 2:
            printf("Performing subtraction operation...\n");
            goto menu;  // Jump back to the menu
        case 3:
            printf("Thank you for using! Goodbye! 👋\n");
            break;
        default:
            printf("Invalid choice!\n");
            goto menu;  // Jump back to the menu
    }

    return 0;
}

(3) ⚠️ Usage Notes

  • Use with caution: goto can disrupt program structure and reduce readability
  • Alternative solutions: In most cases, can be replaced with while, for, or functions
  • Applicable scenarios: Error handling in multiple nested loops, breaking out of multiple loops

11.🎓 Loop Selection Guide

Scenario Recommended Loop Reason
Known exact number of times <span>for</span> Compact syntax, clear logic
Unknown number of times, check first <span>while</span> Strong flexibility, may not execute
At least execute once <span>do-while</span> Guarantees execution, suitable for validation
Need to exit early with <span>break</span> Improves efficiency, avoids unnecessary calculations
Skip certain situations with <span>continue</span> Code is concise, logic is clear

12.🚀 Comprehensive Exercise: Student Score Management System

Let’s use a comprehensive case to consolidate the knowledge learned:

#include <stdio.h>

int main()
{
    int choice;
    float score, sum = 0;
    int count = 0;
    float max_score = 0, min_score = 100;

    do
    {
        printf("\n=== Student Score Management System ===\n");
        printf("1. Enter Score\n");
        printf("2. View Statistics\n");
        printf("3. Exit System\n");
        printf("Please choose an operation:");
        scanf("%d", &choice);

        switch(choice)
        {
            case 1:  // Enter score
                printf("Please enter student score (0-100, input -1 to end):\n");
                while(1)
                {
                    scanf("%f", &score);
              
                    if(score == -1)  // Input -1 to exit entry
                        break;
              
                    if(score < 0 || score > 100)  // Score validation
                    {
                        printf("Invalid score! Please enter a number between 0-100:");
                        continue;  // Skip invalid input
                    }
              
                    // Statistics data
                    sum += score;
                    count++;
              
                    if(score > max_score) max_score = score;
                    if(score < min_score) min_score = score;
              
                    printf("Score entered successfully! Continue input (-1 to end):");
                }
                break;
          
            case 2:  // View statistics
                if(count == 0)
                {
                    printf("No score data available! ❌\n");
                }
                else
                {
                    printf("\n=== Statistics ===\n");
                    printf("Total number of students: %d\n", count);
                    printf("Average score: %.2f\n", sum / count);
                    printf("Highest score: %.2f\n", max_score);
                    printf("Lowest score: %.2f\n", min_score);
                }
                break;
          
            case 3:  // Exit system
                printf("Thank you for using the score management system! 👋\n");
                break;
          
            default:
                printf("Invalid choice! Please re-enter. ❌\n");
        }

    } while(choice != 3);  // Exit main loop when choice is 3

    return 0;
}

13.📝 Summary and Expansion

(1) Core Points Review

  1. 1. while Loop: Check first, then execute, suitable for unknown times
  2. 2. do-while Loop: Execute first, then check, at least executes once
  3. 3. for Loop: Suitable for known times, compact syntax
  4. 4. break: Exit the loop
  5. 5. continue: Skip this loop iteration
  6. 6. goto: Unconditional jump (use with caution)

(2) 🔥 Advanced Techniques

  • Nested Loops: Implement complex logic (e.g., matrix operations)
  • Loop Optimization: Reduce unnecessary calculations
  • Boundary Conditions: Pay attention to the start and end conditions of loops
  • Preventing Infinite Loops: Ensure loops have correct exit conditions

(3) 💡 Practical Suggestions

  1. 1. Practice More: Familiarize yourself with syntax through extensive programming practice
  2. 2. Debugging Skills: Learn to use debuggers to observe loop execution processes
  3. 3. Code Standards: Maintain good indentation and commenting habits
  4. 4. Performance Awareness: Consider the time complexity of loops

14. 🎯 Next Preview

In the next lesson, we will learn Lesson 4: Number Systems and Codes and Basic Types, to understand how data is represented in computers and the application of basic data types. This knowledge is the foundation for understanding program operation mechanisms and subsequent learning of more complex content!

If you like this article, don’t forget to like 👍, bookmark ⭐, and share 📤 it!

If you have any questions, feel free to discuss in the comments section, let’s improve together! 💪

Leave a Comment