C Language Loop Structures (Part 2): Detailed Explanation of while and do-while Loops

πŸ” C Language Loop Structures (Part 2): Detailed Explanation of while and do-while Loops

Author: IoT Smart Academy

πŸ’‘ 1. Why do we need while?

Sometimes we do not know how many times a loop should execute, for example:

  • The user keeps entering data until they input 0 to end
  • Repeatedly entering a password until it is correct
  • The sensor continuously samples until a threshold is triggered

In this case, <span>for</span> loops are inconvenient because the number of iterations is unknown. βœ… while loops are more flexible!

🧱 2. Basic Syntax of while

while (condition) {
    loop statements;
}

πŸ“Œ Execution Logic:

Check β†’ True β†’ Execute β†’ Check again β†’ Execute again β†’ … β†’ False β†’ End

βœ… Example 1: Output numbers from 1 to 5

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

Output:

1 2 3 4 5

πŸ“ Note:

  • Remember to update the variable <span>i++</span>
  • Otherwise, the condition will always be true β†’ infinite loop!

βœ… Example 2: Calculate the sum from 1 to 100

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

Output:

Total sum: 5050

βœ… Example 3: Password verification program (Typical application)

#include <stdio.h>
#include <string.h>

int main() {
    char password[20];
    while (1) {
        printf("Please enter the password:");
        scanf("%s", password);
        if (strcmp(password, "iot2025") == 0) {
            printf("Login successful!\n");
            break;
        } else {
            printf("Incorrect password, please try again.\n");
        }
    }
    return 0;
}

πŸ“ Features:

  • Infinite loop <span>while(1)</span>
  • Combined with <span>break</span> to achieve β€œuntil correct”

🧩 3. do-while Loop (Executes at least once)

do {
    loop statements;
} while (condition);

πŸ“Œ Execution Order:

Execute first β†’ Check β†’ If satisfied, continue β†’ Otherwise, exit

βœ… Example 1: Basic structure

#include <stdio.h>
int main() {
    int i = 1;
    do {
        printf("%d ", i);
        i++;
    } while (i <= 5);
    return 0;
}

Output:

1 2 3 4 5

Similar to while, but executes at least once βœ…

βœ… Example 2: Input numbers until 0 is entered

#include <stdio.h>
int main() {
    int n;
    do {
        printf("Please enter a number (input 0 to end):");
        scanf("%d", &n);
        if (n != 0)
            printf("You entered: %d\n", n);
    } while (n != 0);
    printf("Program ended.\n");
    return 0;
}

πŸ“Œ Suitable for β€œdo first, then check” situations.

βœ… Example 3: Average score input (Dynamic loop)

#include <stdio.h>
int main() {
    int count = 0;
    float score, sum = 0;
    do {
        printf("Input score (negative number to end):");
        scanf("%f", &score);
        if (score >= 0) {
            sum += score;
            count++;
        }
    } while (score >= 0);

    if (count > 0)
        printf("Average score: %.2f\n", sum / count);
    else
        printf("No valid scores entered.\n");

    return 0;
}

πŸ“ while is a typical application for unknown iterations.

βš™οΈ 4. Summary of Loop Control

Control Statement Function Example
<span>break</span> Immediately exit the entire loop Exit after correct password
<span>continue</span> Skip the current loop, proceed to the next Skip negative inputs
<span>while(1)</span> Infinite loop Commonly used in main menus, control programs

🚫 5. Common Errors Summary

Error Type Example Description
Infinite Loop <span>while(1){}</span> Condition always true with no break
Condition Not Updated <span>i</span> not incremented Condition always true
Logical Error <span>do…while(i>5)</span> Ends immediately after one execution

🧠 6. Classroom Exercises (Analysis part to be published tomorrow)

πŸ“ Exercise 1

Use a while loop to calculate the factorial of 1~n (n!)

Input: 5 Output: 120

πŸ“ Exercise 2

Use do-while to input several positive numbers and output the maximum value. Input a negative number to end.

πŸ“ Exercise 3 (Challenge)

Write a number guessing game:

  • The system sets a random number between 1 and 100
  • The user keeps inputting until they guess correctly
  • Each time, prompt β€œtoo high” or β€œtoo low”

Hint: <span>#include <stdlib.h></span>, <span>rand()</span>, <span>srand(time(0))</span>

βœ… 7. Summary

Loop Type Characteristics Scenario
<span>for</span> Known number of iterations Accumulation, traversal
<span>while</span> Unknown number of iterations, check first Dynamic loops, real-time input
<span>do-while</span> Executes at least once Menu loops, input validation

πŸ”œ Next Article Preview

πŸ’₯ Comprehensive Applications of C Language Loops

  • Upper right triangle of multiplication table
  • Fibonacci sequence
  • Comparison of accumulation and multiplication
  • Random number exercises
  • Comprehensive case of break + continue

πŸ“š IoT Smart Academy

One article a day, programming is not difficult. From C language basics to IoT project practice, let’s learn together!πŸ’ͺ

Leave a Comment