๐ง 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 ๐