Comprehensive Application of Loop Structures in C Language (Detailed Case Studies)

๐Ÿง  1. Why Do Loop Comprehensive Exercises?

Loops are one of the most important logical structures in the C language. Whether you are creating a “multiplication table”, calculating average scores, or collecting sensor data and controlling device actions in IoT projectsโ€”loops are essential “automators”.

Today, we will bring loop logic to life through five detailed case studies.

๐ŸŒŸ Case 1: Upper Right Triangle Multiplication Table

๐Ÿ“‹ Case Description

The common multiplication table is in the lower left triangle, but sometimes we want it arranged in the upper right format for better data visualization. This requires mastering the double loop + controlling column numbers technique.

โœ… Complete Code

#include <stdio.h>
int main() {
    printf("=== Upper Right Triangle Multiplication Table ===\n");
    for (int i = 1; i <= 9; i++) {
        for (int j = i; j <= 9; j++) {
            printf("%dร—%d=%-2d ", i, j, i * j);
        }
        printf("\n");
    }
    return 0;
}

๐Ÿงฉ Sample Output

1ร—1=1  1ร—2=2  1ร—3=3  ... 1ร—9=9
2ร—2=4  2ร—3=6  ... 2ร—9=18
...
9ร—9=81

๐Ÿ’ฌ Thought Analysis

  • The outer loop controls the “rows” (from 1 to 9)
  • The inner loop controls the “columns”, starting from <span>i</span>
  • <span>%-2d</span> indicates left alignment, occupying 2 character widths for a neat table
  • <span>\n</span> controls line breaks

๐Ÿ“Œ Skill Summary:

  • Nested double loops
  • Coordinating inner and outer loop variables for output
  • Formatting output layout techniques

๐ŸŒŸ Case 2: Comparison of Accumulation and Multiplication

๐Ÿ“‹ Case Description

Input an integer n, calculate:

  • The accumulation sum from 1 to n (sum)
  • The product from 1 to n (product)

โœ… Complete Code

#include <stdio.h>
int main() {
    int n;
    long long sum = 0, product = 1;  // Note the type

    printf("Please enter a positive integer n:");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        sum += i;
        product *= i;
        printf("Iteration %d: sum=%lld, product=%lld\n", i, sum, product);
    }

    printf("Final results:\n");
    printf("Sum from 1 to %d = %lld\n", n, sum);
    printf("Product from 1 to %d = %lld\n", n, product);
    return 0;
}

๐Ÿงฉ Sample Output

Please enter a positive integer n: 5
Iteration 1: sum=1, product=1
Iteration 2: sum=3, product=2
Iteration 3: sum=6, product=6
Iteration 4: sum=10, product=24
Iteration 5: sum=15, product=120
Final results:
Sum from 1 to 5 = 15
Product from 1 to 5 = 120

๐Ÿ’ฌ Thought Analysis

  • <span>sum += i</span> means “add i each time”
  • <span>product *= i</span> means “multiply by i each time”
  • The loop executes n times to get the results
  • <span>long long</span> prevents integer overflow

๐Ÿ“Œ Skill Summary:

  • The difference between accumulation and multiplication
  • Choosing variable types (to prevent overflow)
  • Observing dynamic output in loops

๐ŸŒŸ Case 3: Fibonacci Sequence

๐Ÿ“‹ Case Description

Mathematical definition: Fโ‚=1, Fโ‚‚=1, Fโ‚™=Fโ‚™โ‚‹โ‚+Fโ‚™โ‚‹โ‚‚

This is a classic loop generation problem.

โœ… Complete Code

#include <stdio.h>
int main() {
    int n;
    printf("Please enter the number of terms n:");
    scanf("%d", &n);

    int a = 1, b = 1, c;
    printf("The first %d terms of the Fibonacci sequence are:\n", n);
    printf("%d %d ", a, b);

    for (int i = 3; i <= n; i++) {
        c = a + b;
        printf("%d ", c);
        a = b;
        b = c;
    }
    printf("\n");
    return 0;
}

๐Ÿงฉ Sample Output (n=10)

The first 10 terms of the Fibonacci sequence are:
1 1 2 3 5 8 13 21 34 55

๐Ÿ’ฌ Thought Analysis

  • <span>a</span> and <span>b</span> store the first two terms
  • Each loop generates a new term <span>c = a + b</span>
  • Rolling updates:<span>a=b</span>, <span>b=c</span>
  • The first two terms are printed separately

๐Ÿ“Œ Skill Summary:

  • Recursive sequence model
  • Rolling updates of loop variables
  • Logical accumulation thinking in for loops

๐ŸŒŸ Case 4: Number Guessing Game (while + break)

๐Ÿ“‹ Case Description

  • The system randomly generates a number between 1 and 100
  • The user continuously inputs guesses
  • The program prompts “too high” or “too low” until guessed correctly

โœ… Complete Code

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

int main() {
    srand(time(0));  // Random seed
    int target = rand() % 100 + 1;
    int guess, count = 0;

    printf("๐ŸŽฎ Number Guessing Game Starts! (Range 1~100)\n");

    while (1) {
        printf("Please enter your guess:");
        scanf("%d", &guess);
        count++;

        if (guess == target) {
            printf("โœ… Congratulations! You guessed it right! Total attempts: %d.\n", count);
            break;
        } else if (guess > target) {
            printf("Too high!\n");
        } else {
            printf("Too low!\n");
        }
    }

    printf("Game over, the answer is: %d\n", target);
    return 0;
}

๐Ÿงฉ Sample Output

๐ŸŽฎ Number Guessing Game Starts! (Range 1~100)
Please enter your guess: 50
Too high!
Please enter your guess: 30
Too low!
Please enter your guess: 40
โœ… Congratulations! You guessed it right! Total attempts: 3.
Game over, the answer is: 40

๐Ÿ’ฌ Thought Analysis

  • Infinite loop <span>while(1)</span>
  • Use <span>break</span> to end the game
  • <span>rand() % 100 + 1</span> generates a random number
  • <span>srand(time(0))</span> ensures different results each time

๐Ÿ“Œ Skill Summary:

  • Comprehensive application of loops + conditional judgments + random functions
  • Practical project models (e.g., sensor threshold detection)

๐ŸŒŸ Case 5: Sensor Sampling Simulation (do-while + continue)

๐Ÿ“‹ Case Description

Simulate IoT device sampling: Continuously input sensor values, filter out abnormal (negative) data, and end input with -1 while calculating the average value.

โœ… Complete Code

#include <stdio.h>

int main() {
    float data, sum = 0;
    int count = 0;

    do {
        printf("Please enter the %dth sampling value (input -1 to end):", count + 1);
        scanf("%f", &data);

        if (data < 0 && data != -1) {
            printf("โš ๏ธ Invalid data (negative value), skipping!\n");
            continue;
        }

        if (data != -1) {
            sum += data;
            count++;
        }

    } while (data != -1);

    if (count > 0)
        printf("Valid samples: %d, average: %.2f\n", count, sum / count);
    else
        printf("No valid data collected.\n");

    return 0;
}

๐Ÿงฉ Sample Output

Please enter the 1st sampling value (input -1 to end): 10
Please enter the 2nd sampling value (input -1 to end): -5
โš ๏ธ Invalid data (negative value), skipping!
Please enter the 3rd sampling value (input -1 to end): 20
Please enter the 4th sampling value (input -1 to end): -1
Valid samples: 2, average: 15.00

๐Ÿ’ฌ Thought Analysis

  • <span>do-while</span> ensures at least one execution
  • Negative value detection and filtering <span>continue</span>
  • Average calculation requires a counter <span>count</span>
  • Typical IoT loop sampling model

๐Ÿงฎ 6. Overview of Loop Structures

Type Judgment Position At Least One Execution Applicable Scenarios
for Judged first No Known number of iterations
while Judged first No Condition-driven
do-while Judged last โœ… Yes Tasks that must execute at least once

๐Ÿ“Œ Mnemonic:

for controls iterations, while controls conditions, do-while executes at least once.

โœ… 7. Summary

You have now learned:

  • Multi-layer loops (e.g., multiplication table)
  • Dynamic data processing and input control
  • Combining random numbers and conditional judgments
  • Flexible use of break and continue
  • Simulating practical IoT scenarios

๐ŸŽฏ Mastering loops leads to automated thinking!

๐Ÿ”œ Next Article Preview

๐Ÿ“˜ Introduction to Arrays in C Languageโ€”Storing Multiple Data at Once!

  • Array definition and initialization
  • Using for loops to traverse arrays
  • Statistics and average calculation of scores
  • Finding maximum and minimum values in arrays

๐Ÿ“š IoT Smart Learning Platform

A learning platform designed specifically for higher vocational IoT majors. One article a day, bridging basic programming and practical applications ๐Ÿš€

Leave a Comment