C language savior (branch and loop statement--3)

content

1.1 if statement

Exercise 1.2: What is the output of the following code?

Exercise 1.3: Determine whether a number is odd (1 is true and 0 is false in C language)

Exercise 1.4: Printing odd numbers between 1 and 100

2.1: switch statement

 2.2 default clause

3.1 The loop statement while

Write a code, enter the password and confirm the password

4.1 for loop

5.1 do while loop (execute once first, then judge whether to loop)

Exercise 1: Calculate the factorial of n

Exercise 2: Add n factorial numbers (1!+2!+3!...)

Exercise 3: Find a specific number n in an ordered array (binary search)

Exercise 4: Write code that demonstrates multiple characters moving from ends to converge toward the middle

Exercise 5: Write a code implementation that simulates a user login scenario and can only log in three times. (Only three passwords are allowed to be entered. If the password is correct, it will prompt to log in successfully. If all three entries are incorrect, the program will exit.

Exercise 6: Number Guessing Game

Exercise 7: Write a shutdown program. As long as the program runs, the computer will shut down within 1 minute. If you enter: one key for three consecutive times, the shutdown will be canceled.


C is a (structured) programming language:

Among them, control statements (control statements are used to control the execution flow of the program to realize various structural modes of the program. They are composed of specific statement definers. There are nine control statements in C language.)

1. Conditional judgment statements are also called branch statements: if statement, switch statement;

⒉. Loop execution statement: do while statement, while statement, for statement;

3. Turn to statement: break statement, goto statement, continue statement, return statement.


1.1 if statement

#include <stdio.h>

int main()
{

 if(表达式)
    {
    语句列表1;
    }
  else  //不是if,就是else
    {
   语句列表2;
    }
   return 0;
}

if implements multi-branch

#include <stdio.h>
int main()
{
	int age = 0;
	scanf("%d", &age);

	if (age < 18)
	{
		printf("青少年\n");
		printf("好好学习\n");
	}
	else if (age >= 18 && age < 30)  //else if跟if一样判断
	{
		printf("青年\n");
	}
	else if (age >= 30 && age < 50)
	{
		printf("中年\n");
	}
	else if (age >= 50 && age < 80)
	{
		printf("中老年\n");
	}
	else if (age >= 80 && age < 100)
	{
		printf("老年\n");
	}
	else
	{
		printf("老寿星\n");
	}
	return 0;
}

Here is a recommended book: "High Quality C-C++ Programming", which helps to form a good code style


Exercise 1.2: What is the output of the following code?

int main()
{
	int a=0;
	int b = 2;
	if (a == 1)
	{
		if (b == 2)
			printf("hehe\n");
		else
			printf("haha\n");
	}
	return 0;
}

Explanation: There is no output, because else matches the latest if statement, a==1 is judged to be false, and the following judgment is not entered

Exercise 1.3: Determine whether a number is odd (1 is true and 0 is false in C language)

int main()
{
	int n = 0;
	scanf("%d", &n);
	//if (n % 2 != 0)    一种写法
	//if (n % 2 == 1)    一种写法
	//if(1 == n%2)       一种写法
	if(n%2)             //n%2的结果是1,c语言里面1为真,0为假
	{
		printf("奇数\n");
	}

	return 0;
}

Exercise 1.4: Printing odd numbers between 1 and 100

int main()
{   //第一种写法,更高效
	int i = 1;
	while (i <= 100)
	{
		printf("%d ", i);
		i=i+2;
	}


   //第二种写法
	//while (i <= 100)
	//{
	//	//对i进行判断,是奇数才打印
	//	if(i%2 == 1)
	//		printf("%d ", i);
	//	i++;
	//}
	return 0;
}

2.1: switch statement

switch (整形表达式)
{
	语句项;(case语句)
}

例如:
case (整型常量表达式):
      语句;



(I want to enter 1, which should print Monday, but what is the actual output?) 

int main()
{
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
		printf("星期1\n");
		
	case 2:
		printf("星期2\n");
		
	case 3:
		printf("星期3\n");
		
	case 4:
		printf("星期4\n");
		
	case 5:
		printf("星期5\n");
		
	case 6:
		printf("星期6\n");
		
	case 7:
		printf("星期天\n");
		
  return 0;
	}

Enter 1, but print Monday to Sunday, which is inconsistent with the result we want, because we are missing break

The break statement actually divides the statement into different branch parts, and the current loop stops when a break is encountered


 2.2 default clause

What if the value of the expression doesn't match the value of any of the case labels? The structure is that all statements are skipped. The program does not terminate and no error is reported, because this is not considered an error in C

What if you don't want to ignore the value of an expression that doesn't match all tags? You can add a default clause to the statement list, putting the following tags

default:

Write it anywhere a case tag can appear.

int main()
{
	int day = 0;
	scanf("%d", &day);//3
	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;
	}

	return 0;
}

Note: switch allows nested use

3.1 The loop statement while

When the condition is met, the statement after the if statement is executed, otherwise it is not executed. But this statement will only be executed once.

while statement to loop

 while(表达式)
  {
   循环语句;  //再返回表达式判断
  }
int main()
{
	
	int  i = 1;
	while (i<=10)
	{
		if (5 == i)
			continue;

		printf("%d ", i);
		i++;
	}

	return 0;
}

The code is in an infinite loop, continue means to skip the code after this loop continue

In the while loop, break is to end the loop directly after this loop, and permanently terminate the loop


Usage of getchar

char a = getchar();   X错误的写法

//getchar读取一个字符,但是却不能放到char类型数据里面,是因为getchar读取失败后会返回EOF
//EOF就是-1,char类型存不下-1

int a = getchar();   √正确的写法

//如果读取到一个字符,此时返回的便是该字符的ASICC码值

Write a code, enter the password and confirm the password

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

	printf("请确认密码(Y/N):>");
	int ch = getchar();
	if ('Y' == ch)
		printf("确认成功\n");
	else
		printf("确认失败\n");
	return 0;
}

The result is this, the confirmation fails without even YES input

Explanation: scanf and getchar take data from the buffer, wait for the keyboard to input data, enter 123456 carriage return on the keyboard (the carriage return is parsed as \n), scanf takes away the data before \n (123456), at this time the buffer There is also \n this data, getchar goes to the buffer to get it, and finds that there is another \n, take it away and judge, and the confirmation fails

Then we need to clear the buffer

int main()
{
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s", password);
	int tmp = 0;
	while ((tmp = getchar()) != '\n')//利用getchar把缓冲区字符读取掉不使用,到\n前全清理
	{
		;//继续读
	}

	printf("请确认密码(Y/N):>");
	int ch = getchar();
	if ('Y' == ch)
		printf("确认成功\n");
	else
		printf("确认失败\n");
	return 0;
}


4.1 for loop

for(表达式1;表达式2;表达式3)

表达式1为初始化部分,用于初始化循环变量的。

表达式2为条件判断部分,用于判断循环时候终止。

表达式3为调整部分.用干循环条件的调整.


int main()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	for (i = 0; i <=9; i++)
	{
		printf("%d ", arr[i]);
	}

	return 0;
}

 The continue of the for loop (skip the code behind the continue of this loop, come to the adjustment part, and then judge)

int main()
{
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
		if (5 == i)
			continue;

		printf("%d ", i);
	}

	return 0;
}

 Exercise: How many times does the following code loop

 Explanation: infinite loop, the judgment part of expression 2 is an =, which means assignment, and assign k to 0


5.1 do while loop (execute once first, then judge whether to loop)

do 
   循环语句;

while(表达式)
int main()
{
	int i = 1;
	do
	{
		printf("%d ", i);
		i++;

		if (i == 5)
			continue;
	} while (i<=10);

	return 0;
}

Exercise 1: Calculate the factorial of n

int main()
{
	int n = 0;
	//输入
	scanf("%d", &n);//
	//产生1~n的数字
	int i = 0;
	int ret = 1;
	for (i = 1; i <= n; i++)
	{
		ret = ret * i;
	}

	printf("%d\n", ret);

	return 0;
}

Exercise 2: Add n factorial numbers (1!+2!+3!...)

int main()
{
	int n = 0;
	//产生1~n的数字
	int i = 0;
	int ret = 1;
	int sum = 0;
	//1!+2!+3! = 1+2+6 = 9
	for (n = 1; n <= 10; n++)
	{
		ret = ret * n;
		sum = sum + ret;
	}

	printf("%d\n", sum);//9

	return 0;
}

Exercise 3: Find a specific number n in an ordered array (binary search)

int main()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int k = 7;//要查找的数字
	//查找k   //40        /   4
	int sz = sizeof(arr) / sizeof(arr[0]);//计算数组长度,sizeof求的是字节

	int left = 0;//左下标
	int right = sz-1;//右下标 //数组下标第一个从0开始,减一后才是最右边元素下标

	while (left<=right)
	{
		//int mid = (left + right) / 2;//中间元素的下标
		int mid = left + (right - left) / 2;//优化平均值求法

		if (arr[mid] < k)
		{
			left = mid + 1;
		}
		else if (arr[mid] > k)
		{
			right = mid - 1;
		}
		else
		{
			printf("找到了,下标是:%d\n", mid);
			break;
		}
	}
	//
	if (left > right)
	{
		printf("找不到了\n");
	}
	return 0;
}

Median value = half of right divided by 2 plus left (optimized average method)

Exercise 4: Write code that demonstrates multiple characters moving from ends to converge toward the middle

#include <string.h>
#include <windows.h>
#include <stdlib.h>

int main()
{

	char arr1[] = "welcome to bit!!!!!!";
	char arr2[] = "####################";
	
	int left = 0;
	
	int right = strlen(arr1) - 1;strlen求的是数组\0之前的长度,用sizeof求则要-2
    //int right = sizeof(arr1) / sizeof(arr1[0]) - 2;

	while (left<=right)
	{
		arr2[left] = arr1[left];//交换元素
		arr2[right] = arr1[right];
		printf("%s\n", arr2);
		Sleep(1000);//单位是毫秒,意味1s后再执行
		system("cls");//执行系统命令,cls是清理屏幕显示
		left++;
		right--;
	}
	printf("%s\n", arr2);

	return 0;
}

Exercise 5: Write a code implementation that simulates a user login scenario and can only log in three times. (Only three passwords are allowed to be entered. If the password is correct, it will prompt to log in successfully. If all three entries are incorrect, the program will exit.

The comparison of two strings cannot use == and should use strcmp

The first string is greater than the second string, return >0

The first string is equal to the second string is equal, return 0

The first string is less than the second string, return <0


int main()
{
	int i = 0;
	char password[20] = { 0 };
	//假设正确的密码是"abcdef"
	for (i = 0; i < 3; i++)//三次机会
	{
		printf("请输入密码:>");
		scanf("%s", password);
		if (strcmp(password, "abcdef") == 0)
		{
			printf("密码正确\n");
			break;//跳出循环,程序结束
		}
		else
		{
			printf("密码错误,重新输入\n");
		}
	}
	//1,2
	if (i == 3)
	{
		printf("三次密码均输入错误,退出程序\n");
	}
	return 0;
}

Exercise 6: Number Guessing Game

 The game needs to generate random numbers, and the C language provides the rand library function

 

 

 When you write the main body and then write a game function that generates random numbers, you will find that the two random numbers are generated the same.

#include <string.h>
void menu()
{
	printf("*******************\n");
	printf("****** 1.play *****\n");
	printf("****** 0.exit *****\n");
	printf("*******************\n");
}


void game()
{
   int ret=rand();
   printf("%d\n",ret);

}



int main()
{
	int input = 0;
	do
	{
		menu();
		printf("请选择:>");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误,重新选择!\n");
			break;
		}
	} while (input);

	return 0;
}

 Before calling the rand function, you need to call the srand function to set the random number generation

The time on the computer has been changing (timestamp), we can pass the time on the computer to srand

 

 C language provides a function time that returns a timestamp


void game()
{
   srand((unsigned int)time(NULL));//time强制类型转换unsigned int类型,也满足srand类型
   int ret=rand();                 //不需要用指针储存,直接传空指针
   printf("%d\n",ret);

}

The random number is still not random enough, because we frequently call srand to set the starting point

It only needs to be run once when the program is called

 


To generate numbers between 1-100

void game()
{
	int guess = 0;
	// 生成一个随机数
	int ret = rand()%100+1;//任何数字%100结果是0-99,加1变成1-100
	//printf("%d\n", ret);
	
	

final code output

#include <string.h>
void menu()
{
	printf("*******************\n");
	printf("****** 1.play *****\n");
	printf("****** 0.exit *****\n");
	printf("*******************\n");
}

void game()
{
	int guess = 0;
	//1. 生成一个随机数
	int ret = rand()%100+1;//1-100
	//printf("%d\n", ret);
	//2. 猜数字
	
	while (1)
	{
		printf("猜数字:>\n");
		scanf("%d", &guess);
		if (guess < ret)
		{
			printf("猜小了\n");
		}
		else if (guess > ret)
		{
			printf("猜大了\n");
		}
		else
		{
			printf("恭喜你,猜对了\n");
			break;
		}
	}
}

int main()
{
	int input = 0;
	srand((unsigned int)time(NULL));

	do
	{
		menu();
		printf("请选择:>");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误,重新选择!\n");
			break;
		}
	} while (input);

	return 0;
}


Exercise 7: Write a shutdown program. As long as the program runs, the computer will shut down within 1 minute. If you enter: one key for three consecutive times, the shutdown will be canceled.

#include <stdlib.h>
#include <string.h>

int main()
{
	char input[20] = { 0 };

	system("shutdown -s -t 60");//system是一个库函数,是用来执行系统命令的

	while (1)
	{
		printf("请注意,你的电脑在1分钟内关机,如果输入:一键三连,就取消关机\n");
		scanf("%s", input);
		//判断
		if (strcmp(input, "一键三连") == 0)
		{
			system("shutdown -a");//取消关机
			break;
		}
	}

	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_63543274/article/details/123227601