← Back to Index
Research & Engineering Archive

LPC 4. Repetition

By Jingnan Huang · January 20, 2025 · 1300 Words

Last Edit: 1/20/25

Loops帮助程序节省空间,提高编写效率并减少错误,常见的Loop存在两种,while loop和for loop

4.1 While Loop
#

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

4.1.2 Infinite Loops
#

4.2 Do-while Loop
#

do {
  <statements>;
} while (<condition>);

4.2.2 Do-While vs. while
#

#include <stdio.h>
int main(void) {
  int num;
  do {
    printf("Please enter a number between 1 
and 10 (inclusive): ");
    scanf("%d", &num);
  } while (num < 1 || num > 10);
  printf("The number entered is %d.\n", num);
  return 0;
}

For loops
#

for 循环的本质是为了解决重复执行一定次数的任务的问题,尤其是在已知迭代次数或需要遍历某个范围或集合的场景下

4.3.1 Forming for loop
#

for (<initialization>;<condition>;<increment>) {
  <statements>;
}
<other statements>;
#include <stdio.h>
int main(void) {
  for (int i = 1; i <= 10; i++) {
    printf("%d ", i);
  }
  return 0;
}

4.3.2 Scope of the loop variable
#

#include <stdio.h>
int main(void) {
  for (int i = 1; i <= 10; i++) {  // declare & 
initialize the loop variable inside the loop
    printf("%d ", i);
  }
    
  printf("\nWe exited the loop with i = %d \n", i);
  return 0;
}

4.3.3 Variations in for loop
#


#include <stdio.h>  
int main(void) {
  for (int i = 1, j = 7; i <= 10; printf("7 * %d = %d\n", i, j), i += 1, j += 7);
  return 0;
}
#include <stdio.h>  
int main(void) {
  for (int i = 1, j = 7; i <= 10;)
    printf("7 * %d = %d\n", i, j);
    i += 1;
    j += 7;
    
return 0;
}

4.4 Nested Loop
#

Loop中套Loop,复杂度变成多项式复杂度

4.4.1 Print 2D pattern
#

*
**
***
****
*****
#include <stdio.h>
int main(void) {
    for (int line = 1; line <= 5; line += 1) {  // 外层循环控制行数
        for (int star = 1; star <= line; star += 1) {  // 内层循环控制每行星号的数量
            printf("*");
        }
        printf("\n");  // 每行结束后换行
    }
    return 0;
}

4.4.2 Tweak a little
#

    *
   **
  ***
 ****
*****
#include <stdio.h>
int main(void) {
  int n = 0;
  printf("Enter the number of rows:");
  scanf("%d", &n);
  for (int row = 1; row <= n; row += 1) {
    for (int col = 1; col <= n; col += 1) {
      if (col <= n - row) {
        printf(" ");
      } else {
        printf("*");
      }
    }
    printf("\n");
  }
  return 0;
}

4.5 Debugging for loops
#

Enter the number of rows: **5**
    *
   ***
  *****
 *******
*********
#include <stdio.h>
int main(void) {
  int n = 0;
  printf("Enter the number of rows: ");
  scanf("%d", &n);
  for (int row = 1; row <= n; row += 1) {
    for (int col = 1; col < n; col += 1) {
      if (col <= n - row) {
        printf(" ");
      } else if (col >= n - row || col <= n - 1 
+ row) {
        printf("*");
      }
    }
    printf("\n");
  }
  return 0;
}