# C实训（二）

### 练习与注意事项：

1.while循环

``````//控制台100次输出
int count = 1;
while (count<=100) {
printf("%d\n",count);
count++;
}
``````

2.控制台n次打印

``````     int count = 1;
int n;
printf("请输入打印次数：");
scanf("%d",&n);
while (count <= n) {
printf("%d\n",count);
count++;
}
``````
``````     int n = 0;
printf("请输入打印次数:");
scanf("%d",&n);
while (n >= 1) {
printf("%d\n",n);
n--;
}
``````

3.随机数提示:arc4random() % (最大值 - 最小值 + 1) + 最小值

``````//获取0-99的随机数
//int random = arc4random() % 100;
//n-m
//arc4random() % (m - n + 1) + n
``````

4.小明抽奖问题（两种方法）

`````` // 1️⃣while
int r = 0;
int count = 1;
r = arc4random() % (9999 - 1 + 1) + 1;
while (r != 8888) {
r = arc4random() % (9999 - 1 + 1) + 1;
count++;
printf("random:%d\n",r);
}
printf("共抽奖%d次，花费%d元",count,2 * count);
``````
``````//2️⃣do...while
int random = 0;
int count = 0;
do {
random = arc4random() %(9999 - 1 + 1) + 1;
count++;
} while (random != 8888);
printf("共购买%d次，花费%d元",count,2 * count);
``````

5.for循环

``````     for (int i = 0; i <= 9; i++) {
printf("%d",i);
}
``````
``````//上面的for循环与这个while循环功能相同
int i = 0;
while (i < 10) {
printf("%d",i);
i++;
}
``````

6.用for循环打印1-100之间的偶数

``````     int o = 0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
printf("偶数为：%d\n",i);
o += i;
}
}
``````

7.求1-100的整数和

``````     int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
printf("整数和为：%d\n",sum);
``````

8.求1-100的偶数和

``````     int sum1 = 0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
sum1 += i;
}
}
printf("偶数和为：%d\n",sum1);
``````

9.for循环

``````     for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
printf("i=%d,j=%d\n",i,j);
}
}
``````

10.用for循环进行图形绘制

``````//用for循环进行图形绘制
for (int i = 1; i <= 5; i++) {
for (int j = 1; j < i + 1; j++) {
printf("%d",j);
}
printf("\n");
}
``````

11.九九乘法表

``````for (int i = 1; i < 10; i++) {
for (int j = 1; j <= i; j++) {
printf("%d*%d=%d\t",i,j,i*j);
}
printf("\n");
}
``````

12.判断一个人数是不是质数（只能被1和它本身整除的数是质数）

``````   int num = 81;
//默认num是质数
BOOL flag = YES;

for (int i = 1; i <= num; i++) {
if (num % i == 0 && i != 1 && i != num) {
flag = NO;
break;
}
}
if (flag) {
printf("%d是质数\n",num);
} else {
printf("%d不是质数\n",num);
}
``````

### 知识点：

1.循环：

• while循环：
``````while(条件表达式) {
语句
}
``````
• do...while循环：
``````   do{
语句
} while {
条件表达式
}
``````
• for循环：
`````` for(循环变量初始化；循环条件；循环变量增量) {
循环体
}
``````

2.break&continue

``````break:结束本次循环,跳出循环体执行循环后面的语句
continue:跳过当次循环中剩下的语句，执行下一次循环
``````