1.for循环
#include <stdio.h>
int main(void)
{
int i = 0;
int sum = 0;
for (i = 1; i <= 100; i++)
{
sum += i;
}
printf("sum = %d\n", sum);
return 0;
}
2.循环因子
3.练习:猜数字游戏
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int n = 0;
int num = rand() % 100;
while (1)
{
printf("请输入一个数:");
scanf("%d", &n);
if (n > num)
{
printf("猜大了\n");
}
else if (n < num)
{
printf("猜小了\n");
}
else
{
printf("猜对了\n");
break;
}
}
return 0;
}
4.嵌套循环
5.练习:模拟电子表打印
#include <stdio.h>
#include <Windows.h>
int main(void)
{
int i, j, k;
for (i = 0; i < 24; i++)
{
for (j = 0; j < 60; j++)
{
for (k = 0; k < 60; k++)
{
printf("%02d:%02d:%02d\n", i, j, k);
Sleep(1000);
system("cls");
}
}
}
return 0;
}
6.练习:打印9*9乘法表
#include <stdio.h>
int main(void)
{
int i, j;
for (i = 1; i <= 9; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d*%d=%d\t", j, i, j * i);
}
printf("\n");
}
return 0;
}
7.思考题
int main(void)
{
int i, j;
for (i = 9; i >= 1; i--)
{
for (j = 1; j <= i; j++)
{
printf("%d*%d=%d\t", j, i, j * i);
}
putchar('\n');
}
return 0;
}
8.跳转语句
#include <stdio.h>
int main(void)
{
for (int i = 0; i < 5; i++)
{
if (i == 3)
{
continue;
}
printf("i = %d\n", i);
printf("=======1=======\n");
printf("=======2=======\n");
printf("=======3=======\n");
printf("=======4=======\n");
printf("=======5=======\n");
}
return 0;
}
9.数组
#include <stdio.h>
int main(void)
{
int a = 10, b = 20, c = 30;
int arr[5] = { 1,2,3,4,5 };
printf("&arr[0] = %x\n", &arr[0]);//&arr[0] = 137fb24
printf("&arr[1] = %p\n", &arr[1]);//&arr[1] = 0137FB28
printf("&arr[2] = %p\n", &arr[2]);//&arr[2] = 0137FB2C
printf("&arr[3] = %p\n", &arr[3]);//&arr[3] = 0137FB30
printf("&arr[4] = %x\n", &arr[4]);//&arr[4] = 137fb34
printf("&a = %p\n", &a);//&a = 0137FB58
printf("&b = %p\n", &b);//&b = 0137FB4C
printf("&c = %p\n", &c);//&c = 0137FB40
return 0;
}
{
int arr[5] = { 1,2,3,4,5 };
printf("数组大小:%u\n", sizeof(arr));
printf("数组元素大小:%u\n", sizeof(arr[0]));
printf("数组元素个数:%u\n", sizeof(arr)/sizeof(arr[0]));
return 0;
}
10.数组初始化
11.练习:数组元素逆序
#include <stdio.h>
int main(void)
{
int arr[] = { 1,6,8,0,4,3,9,2 };
int len = sizeof(arr) / sizeof(arr[0]);
int i = 0;
int j = len - 1;
int temp = 0;
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
while (i < j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
12.冒泡排序
#include <stdio.h>
int main(void)
{
int arr[] = { 12,32,14,62,27,8,89 };
int n = sizeof(arr) / sizeof(arr[0]);
int i = 0;
int j = 0;
int temp = 0;
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}