Branch statement and loop statement (2)

3.3 do...while() loop

3.3.1 The syntax of the do statement:

do
loop statement;
while(expression);

3.3.2 Execution flowchart: 

 3.3.3 Features of the do statement

The loop is executed at least once, and the usage scenarios are limited, so it is not often used.
Print integers from 1-10:

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
	int i = 1;
	do
	{
		printf("%d\n", i);
		i++;
	} while (i < 10);
	return 0;
}

3.3.4 break and continue in do while loop

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
	int i = 1;
	do
	{
		if (5 == i)
			break;
		printf("%d\n", i);
		i++;
	} while (i <= 10);
	return 0;
}

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
	int i = 1;
	do
	{
		if (5 == i)
			continue;
		printf("%d ", i);
		i++;
	} while (i <= 10);
	return 0;
}

The break and continue in the do while loop are exactly the same as in the while loop.
Break is used to terminate the loop, and continue is to skip the code behind this loop and go directly to the judgment part

3.4 Exercises

1. Calculate the factorial of n.

The for loop generates 1-n numbers, uses ret to receive the cumulative multiplication, and prints ret after jumping out of the loop.

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
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;
		ret *= i;
	}
	printf("%d\n", ret);
	return 0;
}

2. Calculate 1!+2!+3!+…+10!

What needs to be noted here is that ret needs to be equal to 1 every time you enter the first for loop, and the previous factorial must be added up.

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
	int n = 0;
	//循环产生1~n的数字
	int i = 0;
	int ret = 1;
	int sum = 0;
	for (n = 1; n <= 10; n++)
	{
		ret = 1;
		for (i = 1; i <= n; i++)
		{
			ret *= i;
		}
		sum += ret;
	}
	printf("%d\n", sum);
	return 0;
}

3. Find a specific number n in an ordered array. (Explain binary search)

This is the general search method, traversing the array to find the number, but the efficiency is too low.

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int k = 0;
	scanf("%d", &k);//7
	//遍历
	int i = 0;
	int flag = 0;
	for (i = 0; i < 10; i++)
	{
		if (arr[i] == k)
		{
			printf("找到了,下标是:%d\n", i);
			flag = 1;
			break;
		}
	}
	if (flag == 0)
		printf("找不到\n");
	return 0;
}

This is the way of binary search. Half of the array elements are removed each time, which is efficient, but the array must be ordered .

sizeof(arr) is the total size of the array, sizeof(arr[0]) is the size of each element, the number of elements is obtained by dividing, left is the element with subscript 0, right is the last element, mid It is the middle element. If mid<k, then the element we are looking for must be on the right side of mid. At this time, we assign the subscript of the element mid+1 to left. If mid>k, then the element we are looking for is It must be on the left side of mid. At this time, we assign the subscript of the mid-1 element to right. If it's neither, you've found it.

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	//printf("%d\n", sizeof(arr));//40 - 数组的总大小,单位是字节
	//printf("%d\n", sizeof(arr[0]));
	//printf("%d\n", sizeof(arr)/sizeof(arr[0]));
	int sz = sizeof(arr) / sizeof(arr[0]);
	int k = 0;
	scanf("%d", &k);
	int left = 0;
	int right = sz-1;
	int flag = 0;
	while (left<=right)
	{
		int mid = (left + right) / 2;
		if (arr[mid] < k)
			left = mid + 1;
		else if (arr[mid] > k)
			right = mid - 1;
		else
		{
			printf("找到了,下标是:%d\n", mid);
			flag = 1;
			break;
		}
	}
	if (flag == 0)
		printf("找不到了\n");
	return 0;
}

4. Write code that demonstrates that multiple characters move from the ends and converge toward the middle.

In the while loop, we need to put the left and right elements of arr1 into the left and right sides of arr2, and print arr2 every time it is executed, then left++, right--, until left=right. strlen asks for the length of the string, including \0, so right needs to be -1.

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
	char arr1[] = "welcome to CHINA!!!!!!!";
	char arr2[] = "***********************";
	int left = 0;
	int right = strlen(arr2) - 1;
	while (left<=right)
	{
		arr2[left] = arr1[left];
		arr2[right] = arr1[right];
		printf("%s\n", arr2);
		Sleep(1000);
		system("cls");//清空屏幕
		left++;
		right--;
	}
	printf("%s\n", arr2);
	return 0;
}

5. Write code to simulate the user login scenario, and can only log in three times. (It is only allowed to enter the password three times. If the password is correct, it will prompt to log in. If it is entered incorrectly three times, it will exit the program.

The for loop limits the number of times, if judges whether the input password is equal to 123456, if it is equal, break jumps out of the loop, if the password is wrong, enter the loop again, if the number reaches 4 times, then exit the program. The strcmp function is to compare the size of the string, the header file string.h, if strcmp=0, then password=123456.

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
	int i = 0;
	char password[20] = {0};
	for (i = 0; i < 3; i++)
	{
		printf("请输入密码:>");
		scanf("%s", password);
		if (strcmp(password, "123456") == 0)
		{
			printf("登录成功\n");
			break;
		}
		else
		{
			printf("密码错误\n");
		}
	}
	if (i == 3)
		printf("三次密码错误,退出程序\n");
	return 0;
}

3.5 Guess the number game implementation

1. Generate the game menu 1. play (enter the game) 0. exit (exit the game)
2. Use loop statements to build the game framework so that players can play multiple games until they guess correctly.
3. Design the specific idea of ​​the game, make the system generate a random number, let the player input a number, then compare the two numbers, and gradually lock the target according to the feedback information of the system.

Using a do--while() loop, the player makes multiple guesses. Use the switch statement to control whether to play the game or to exit the game. 

Sometimes a program needs a random number within a specified range. To limit the range of random numbers to integers between 1 and a certain maximum max, you can use the following formula:
number = rand() % max + 1;
For example, to generate a random number of 1-10 to represent the number of dice , you can use the following statement:
dice = rand() % 100+1;

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void game()
{
	int guess = 0;
	int ret = rand() % 100 + 1;
	while (1)
	{
		printf("请猜数字:\n");
		scanf("%d", &guess);
		if (guess > ret)
			printf("猜大了\n");
		else if (guess < ret)
			printf("猜小了\n");
		else
		{
			printf("恭喜你,猜对了\n");
			break;
		}
	}
}
void menu()
{
	printf("**************************\n");
	printf("******   1.play   ********\n");
	printf("******   0.exit   ********\n");
	printf("**************************\n");
}
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;
}

4. goto statement

The C language provides goto statements that can be abused at will and labels that mark jumps.
Theoretically, the goto statement is not necessary, and in practice, the code can be easily written without the goto statement.
However, the goto statement is still useful in some occasions. The most common usage is to terminate the processing of the program in some deeply nested structures
.
For example: Jump out of two or more layers of loops at a time.
The use of break in this case of multi-layer loop cannot achieve the purpose. It can only exit from the innermost loop to the previous loop.

The scenarios where the goto language is really suitable are as follows:

for (...)
for (...)
{
	for (...)
	{
		if (disaster)
			goto error;
	}
}
…
error :
if (disaster)

The following is an example of using the goto statement, and then replacing the goto statement with a loop implementation:
a shutdown program

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
	char input[10] = { 0 };
	system("shutdown -s -t 60");
again:
	printf("电脑将在1分钟内关机,如果输入:我是猪,就取消关机!\n请输入:>");
	scanf("%s", input);
	if (0 == strcmp(input, "我是猪"))
	{
		system("shutdown -a");
	}
	else
	{
		goto again;
	}
	return 0;
}

And if the goto statement is not applicable, you can use a loop:
 

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
	char input[10] = { 0 };
	system("shutdown -s -t 60");
	while (1)
	{
		printf("电脑将在1分钟内关机,如果输入:我是猪,就取消关机!\n请输入:>");
		scanf("%s", input);
		if (0 == strcmp(input, "我是猪"))
		{
			system("shutdown -a");
			break;
		}
	}
	return 0;
}

Today's sharing is over here! Thank you veterans for reading. We will explain functions in the next article. See you next time.

Guess you like

Origin blog.csdn.net/2301_79035870/article/details/132257032