“From today onwards, study hard and make progress every day”
Repetition is the best method for memory; spend one minute each day to remember the basics of C language.
“Series of 100 Essential Knowledge Points for C Language Beginners“
31. Tips for Using Nested Loops: Applications of Multiple Loops
1. Basic Concept of Nested Loops
A nested loop refers to a complete loop structure contained within another loop body, forming multiple layers of loops:
for (initialization; condition; iteration) { // Outer loop
for (initialization; condition; iteration) { // Inner loop
// Loop body code
}
}
2. Typical Applications
1. Processing Two-Dimensional Arrays
int matrix[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
for (int i = 0; i < 3; i++) { // Row loop
for (int j = 0; j < 3; j++) { // Column loop
printf("%d ", matrix[i][j]);
}
printf("\n");
}
2. Matrix Operations
// Matrix multiplication
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
int sum = 0;
for (int k = 0; k < colsA; k++) {
sum += A[i][k] * B[k][j];
}
C[i][j] = sum;
}
}
3. Tips for Using Nested Loops
1. Use Different Loop Variables
for (int i = 0; i < 5; i++) { // Outer loop uses i
for (int j = 0; j < 3; j++) { // Inner loop uses j
printf("%d-%d ", i, j);
}
}
2. Control the Depth of Nesting
// It is recommended to limit to a maximum of 3 levels of nesting
for (int i...) {
for (int j...) {
for (int k...) {
// If more than 3 levels, consider refactoring
}
}
}
3. Exit Nested Loops Early
int found = 0;
for (int i = 0; i < n && !found; i++) {
for (int j = 0; j < m && !found; j++) {
if (arr[i][j] == target) {
found = 1;
break;
}
}
}
Some students have contacted me, wanting to have a study exchange group. I hesitated to create one before due to concerns about advertisements, but I think having a group would indeed be convenient, so I will create one this time to try it out.
If you need it, please join quickly; the validity period is 7 days.

———- End ———-
[Special Statement: All articles in this public account are original or authorized by the author. Some content and images are sourced from the internet. Please feel free to consume them. The views are for learning reference only, and if there are any errors, please forgive me]


“If you like C, please give a thumbs up”
Click the bottom right corner to view
“