if ,While,for和do......while

158 阅读1分钟

image.png
else和最近的if匹配

image.png

image.png Switch

image.png

image.png

输出1-100之间的奇数

#include <stdio.h>

int main()
{
	//输出1-100之间的奇数
	int a = 0;
	for (a = 1; a <= 100; a++)
	{
		if (a % 2 != 0)
		{
			printf("1到100之间的奇数有:%d\n", a);
		}
		
		
	}
	system("pause");
	return 0;
	
}

1-5工作日 6-7休息日

#define  _CRT_SECURE_NO_WARNINGS 1;
#include <stdio.h>

int main()
{
	//1-5工作日  6-7休息日
	int day;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		printf("工作日\n");
		break;
	case 6:
	case 7:
		printf("休息日\n");
		break;
	default:
		printf("输入错误\n");
		break;
	}
	system("pause");
	return 0;
	
}

image.png

循环语句

在While循环中,break用于永久终止循环

#define  _CRT_SECURE_NO_WARNINGS 1;
#include <stdio.h>

//在While循环中,break用于永久终止循环
int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			break;
		printf("%d", i);
		i++;
	}
	system("pause");
	return 0;
	
}

image.png 在While循环中,continue作用是跳过本次循环continue后面的代码,直接到判断语句,看是否进行下一次循环

#define  _CRT_SECURE_NO_WARNINGS 1;
#include <stdio.h>

//在While循环中,continue作用是跳过本次循环continue后面的代码,直接到判断语句
int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			continue;
		printf("%d", i);
		i++;
	}
	system("pause");
	return 0;
	
}

image.png

image.png

#define  _CRT_SECURE_NO_WARNINGS 1;
#include <stdio.h>


int main()
{
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s", password);
	printf("请确认密码(Y/N):>");

	//清理缓冲去区   
	//getchar();//处理'\n'
	//清理缓冲区的中多个字符
	int tmp = 0;
	while ((tmp = getchar()) != '\n')
	{
		;
	}
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("确认成功\n");
	}
	else
	{
		printf("确认失败\n");
	}
	system("pause");
	return 0;
	
}

image.png

for循环

image.png

do....while

image.png

image.png

image.png

计算n的阶乘

#define  _CRT_SECURE_NO_WARNINGS 1;
#include <stdio.h>

//计算n的阶乘
int main()
{
	int i, n ,sum=1;
	scanf("%d", &n);
	for (i = 1; i <= n; i++)
	{
		sum = sum*i;
		printf("%d\n",sum);
	}
	system("pause");
	return 0;
	
}

image.png

image.png

#define  _CRT_SECURE_NO_WARNINGS 1;
#include <stdio.h>
#include <string.h>

int main()
{
	//多个字符从俩端移动
	char arr1[] = "welcome to bit!!!";
	char arr2[] = "#################";
	int left=0;
	int right = strlen(arr1) - 1;
	while (left <= right)
	{
		arr2[left] = arr1[left];
		arr2[right] = arr1[right];
		printf("%s\n", arr2);
		left++;
		right--;
	}
	system("pause");
	return 0;
	
}

image.png

image.png 比大小

#define  _CRT_SECURE_NO_WARNINGS 1;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main()
{
	int guess = 0;

	int num = 0;
	num = rand() % 100;
	while (1)
	{
		printf("请你输入想要猜的数字:");
		scanf("%d", &guess);
		if (guess > num)
		{
			printf("猜大了\n");
		}
		else if (guess < num)
		{
			printf("猜小了\n");
		}
		else
		{
			printf("猜对了\n");
			break;
		}
	}
	system("pause");
	return 0;
}