iOS学习03C语言循环结构

1、while循环

  while (循环条件) {
        循环体;

  }

1         // 1.定义循环变量
2         int time = 1;
3         // 2.循环条件
4         while (time <= 3) {
5             // 3.循环体
6             printf("%d
",time);
7             // 4.循环增量
8             time++;
9         }

  练习:打印1-100之间所有的数

1         int number = 1;
2         while (number <= 100) {
3             printf("%-4d", number);
4             number++;
5         }

2、do...while循环

    do {
        循环体
    } while (循环条件);

1         int a = 1;
2         do {
3             a++;
4         } while (a > 10);
5         printf("a = %d
", a);

3、for循环

  for(定义循环变量 ; 循环条件;循环增量){...}

  练习:用for循环打印出1~100之间既不是7的倍数并且也不包含7的数。

1         for (int i = 1; i <= 100; i++) {
2             if (i % 7 != 0 && i % 10 != 7 && i / 10 != 7) {
3                 printf("%-4d", i);
4             }
5         }

4、循环嵌套

  打印:

  1
  1 2
  1 2 3
  1 2 3 4
  1 2 3 4 5

1         // 控制行数
2         for (int i = 1; i <= 5; i++) {
3             // 每一行要打印的内容
4             for (int j = 1; j <= i; j++) {
5                 printf("%d ", j);
6             }
7             printf("
");
8         }

  打印乘法口诀表

1     for (int i = 1; i <= 9; i++) { 
2         // 控制打印的方格
3         for (int j = 1; j <= i; j++) {  
4             printf("%dx%d=%d ", j, i, j*i);
5         }
6         printf("
");
7     }

5、for循环和while的区别

   for:循环通常用于知道循环次数的情况下使用(常用)
     while:不明确循环次数,知道循环结束的标识

6、break,continue

  break:在switch...case中,结束当前的case分支
    在循环中,遇到break,break后面的语句不再执行结束整个循环
  continue:在循环中遇到continue,后面的语句不再执行结束本次循环

  练习:打印1-20之间所有的数,如果是7,不打印,如果是17,17和后面的数不再打印

 1     int a = 0;
 2     while (a < 20) {
 3         a++;
 4         if (a == 7) {
 5             continue;
 6         }
 7         if (a == 17) {
 8             break;
 9         }
10         printf("%d ", a);
11     }

7、随机数

  arc4random()

  原理: 余数 < 除数

  取对应区间随机数公式

    [0, n] arc4random() % (n + 1)
    [a, b] arc4random() % (b - a + 1)+a

  练习:用while打印10个随机数(范围为10~30),求最大值和最小值。

 1     int number = 1;
 2     int max = 0;
 3     int min = 30;
 4     while (number <= 10) {
 5         // 打印随机数(范围为10~30)
 6         int random = arc4random() % 21 + 10;
 7         printf("%4d", random);
 8         if (max < random) {
 9             max = random;
10         }
11         if (min > random) {
12             min = random;
13         }
14 
15         number++;
16     }
17     printf("max = %d
", max);
18     printf("min = %d
", min);
原文地址:https://www.cnblogs.com/gfxxbk/p/5254985.html