Branching and Looping of Control Statements

1. What is a control statement

Control statements are used to control the execution flow of the program to realize the sequence structure, selection structure and loop structure of the program, and they are composed of specific statement definers.

There are nine kinds of control statements in C language, which can be divided into the following three categories:

(1) Branch statement: if statement, switch statement
(2) Loop execution statement: do while statement, while statement, for statement;

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

2. Branch statement

2.1 if statement

The if statement is used to determine whether the given condition is met, and perform subsequent operations according to the result of the determination. There are three basic forms of if statement, which are single-branch if statement, double-branch if statement and multi-branch if statement.

The basic form of a single-branch if statement is:

if(表达式)
    语句;

Execution process: If the expression is true, the statement is executed; otherwise, it is not executed.

Code example:

int main()
{
	int age = 0;
	scanf("%d", &age);
	if (age < 18)  //当只有单个语句时,可以不加大括号
		printf("未成年\n");
	return 0;
}

The basic form of a double-branch if statement is:

if(表达式)
    语句1;
else
    语句2;

Execution process: If the expression is true, execute statement 1; otherwise, execute statement 2.

Code example:

int main()
{
	int age = 0;
	scanf("%d", &age);
	if (age < 18)
		printf("未成年\n");
	else
		printf("成年\n");
	return 0;
}

The basic form of a multi-branch if statement is:

if(表达式1)
    语句1;
else if(表达式2)
    语句2;
else if(表达式3)
    语句3;
...

else if(表达式n)
    语句n;
else
    语句n+1;

Execution process: if expression 1 is true, execute statement 1; if expression 2 is true, execute statement 2; and so on. If all expressions are false, statement n+1 is executed.

Code example:

int main()
{
	int score = 0;
	scanf("%d", &score);
	if (score < 60)
		printf("不及格\n");
	else if (score >= 60 && score < 70)
		printf("及格\n");
	else if (score >= 70 && score < 85)
		printf("良好\n");
	else
		printf("优秀\n");
	return 0;
}

Note that the else always matches the closest if. The following code may output "haha" at first glance, but the actual output is empty because the else matches the nearest if.

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

Adding appropriate { } can make the code logic clearer. So when writing code, you must develop good habits to enhance the readability of the code.

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

2.2 switch statement

A switch statement allows testing for a variable to be equal to multiple values, each value is called a case .

The basic form of a switch statement is:

switch(表达式)
{
    case 常量表达式1:
        语句1;
        break;
    case 常量表达式2:
        语句2;
        break;
    case 常量表达式3:
        语句3;
        break;
        ...
    default:
        语句n;
        break;
}

Execution process: first calculate the value of the expression, and then compare it with the constant expression one by one. When the value of the expression is equal to the value of a constant expression, execute the following statement, and then jump out of the switch case statement; if the value of the expression is not equal to the value of all constant expressions, execute the statement after default.

Note: (1) The expression behind the switch must be an integer expression;

(2) The case is followed by an integer constant expression, and the character type can be used, because the character is stored in the memory as an ASCII code value;

(3) The constant expressions after the case cannot be the same;

(4) There are multiple statements allowed after the case, which can be enclosed without { };

(5) The order of case and default can be changed;

(6) Only one default clause can appear in each switch statement, and the default clause can be omitted.

Code example:

int main()
{
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
		printf("星期一\n");
		break;
	case 2:
		printf("星期二\n");
		break; 
	case 3:
		printf("星期三\n");
		break;
	case 4:
		printf("星期四\n");
		break;
	case 5:
		printf("星期五\n");
		break;
	case 6:
		printf("星期六\n");
		break;
	case 7:
		printf("星期日\n");
		break;
	default:
		break;
	}
	return 0;
}

When the switch statement is in the following form, the output results are the same when the case values ​​are 1, 2, 3, 4, and 5, and the output results are the same when the case values ​​are 6 and 7.

int main()
{
	int day = 0;
	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:
		break;
	}
	return 0;
}

Switch statements can also be nested. In the following code, the output is m = 5, n = 3.

n = 1, enter the case 1 statement, at this time m = 3, but did not encounter a break, so continue to execute the following case statement; enter the case 2 statement, n = 2; enter the case 3 statement, a switch is nested at this time statement, n is 2, enter the case 2 statement, m = 4, n = 3, the break here is to jump out of the nested switch statement, and the outer switch statement will continue; enter the case 4 statement, m = 5, n = 3, break jumps out of the swtich statement.

int main()
{
	int n = 1;
	int m = 2;
	switch (n)
	{
	case 1:m++;
	case 2:n++;
	case 3:
		switch (n)
		{
		case 1:n++;
		case 2:
			m++;n++;
			break;
		}
	case 4:
		m++;
		break;
	default:
		break;
	}
	printf("m = %d, n = %d\n", m, n);
	return 0;
}

3. Loop statement

3.1 do while statement

The basic form of a do while loop is:

do
{
    循环体语句;
}
while(表达式);

Execution process: first execute the loop body statement, and then judge whether the expression is true, if it is true, continue the loop; if it is false, jump out of the loop.

3.2while statement

The basic form of the while loop is:

while(表达式)
{
    循环体语句;
}

Execution process: first judge the expression, if it is true, then execute the loop body statement; if it is false, then jump out of the loop.

Code example: print the numbers from 0 to 9.

int main()
{
	int i = 0;
	while (i < 10)
	{
		printf("%d ", i);
		i++;
	}
	return 0;
}

break and continue in while loop:

break permanently terminates the loop; continue terminates this loop and proceeds to the next loop. Let's observe the difference between break and continue through the code.
Code 1:

int main()
{
	int i = 0;
	while (i < 10)
	{
		if (i == 5)
			break;
		printf("%d ", i);
		i++;
	}
	return 0;
}

Code 2:

int main()
{
	int i = 0;
	while (i < 10)
	{
		if (i == 5)
			continue;
		printf("%d ", i);
		i++;
	}
	return 0;
}

In code 1, when i=5, the loop is terminated directly, and the running result is 0 1 2 3 4.

In code 2, when i=5, skip the statement after this loop and enter the next loop, the value of i has not changed, so it is trapped in an infinite loop.

3.3 for statement

The basic form of a for loop is:

for(初始化表达式;条件表达式;更新表达式)
{
    循环体语句;
}

Execution process: first solve the initialization expression, and then solve the conditional expression, if it is true, execute the loop body statement, and then execute the update expression; if it is false, jump out of the loop.

Note: (1) The three expressions in the for loop can be omitted, but ";" cannot be omitted;

(2) The initialization expression and update expression can be a simple expression or a comma expression;

(3) The conditional expression is generally a relational expression or a logical expression, and it can also be a numerical expression or a character expression;

(4) A for loop can have multiple loop control variables.

Code example:

int main()
{
	int i = 0;
	int k = 0;
	for (i = 0, k = 0; k = 0; i++, k++)
		k++;
	return 0;
}

This code loops 0 times. First, the conditional expression "k=0" is assigned instead of judged. Secondly, the value of the expression is 0, and 0 is false, so the loop will not enter once.

break and continue in for loop:

break and continue have the same effect in a for loop as in a while loop, but the results are somewhat different when used.

Code 1:

int main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		if (i == 5)
			break;
		printf("%d ", i);
	}
	return 0;
}

Code 2:

int main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		if (i == 5)
			continue;
		printf("%d ", i);
	}
	return 0;
}

The execution result of code 1 is 0 1 2 3 4, and the execution result of code 2 is 0 1 2 3 4 6 7 8 9. It can be seen that when using break, when i=5 directly terminates the loop, when using continue, when i=5 skips the current loop, and executes the update expression to enter the next loop.

4. goto statement

The basic form of the goto statement is:

goto 语句标号;

...

语句标号:
    语句;

Execution process: unconditionally jump to the statement label, and then execute the following code.

Note: (1) The statement label can be composed of letters, numbers and underscores, and the first character must be a letter or an underscore;

(2) The goto statement can be used to jump out of the deep loop, but it will also make the code structure level blurred and difficult to read, so the goto statement should be used reasonably.

5. Practice

1. Calculate n!

int main()
{
	int n = 0;
	scanf("%d", &n);
	int mul = 1;
	for (int i = 1; i <= n; i++)
	{
		mul *= i;
	}
	printf("mul = %d\n", mul);
	return 0;
}

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

method one:

int main()
{
	int sum = 0;
	for (int i = 1; i <= 10; i++)
	{
		int mul = 1;
		for (int j = 1; j <= i; j++)
		{
			mul *= j;
		}
		sum += mul;
	}
	printf("sum = %d\n", sum);
	return 0;
}

Method 2 (optimization):

int main()
{
	int mul = 1;
	int sum = 0;
	for (int i = 1; i <= 10; i++)
	{
		mul *= i;
		sum += mul;
	}
	printf("sum = %d\n", sum);
	return 0;
}

3. Find in half

int main()
{
	int arr[] = { 0,1,2,3,4,5,6,7,8,9 };
	int len = sizeof(arr) / sizeof(arr[0]);
	int left = 0;
	int right = len - 1;
	int k =7;
	int flag = 0;
	while (left <= right)
	{
		//int mid = (right + left) / 2;    
		//当left和right过大时,二者的和可能会超出整型所能表示的最大范围,发生越界
		//所以采用下面这种方式
		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);
			flag = 1;
			break;
		}
	}
	if (flag == 0)
		printf("没找到!\n");
	return 0;
}

4. Realize that multiple characters move from both ends and converge toward the middle

#include <stdio.h>
#include <string.h>
#include <Windows.h>
int main()
{
	char arr1[] = "hello world!";
	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);
		Sleep(1000);  //停止1000毫秒
		system("cls");  //清屏
		left++;
		right--;
	}
	printf("%s\n", arr2);
	return 0;
}

5. Guess the number game (1~100)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
	printf("********************\n");
	printf("******1.0 start*****\n");
	printf("******0.0  exit*****\n");
	printf("********************\n");
}

void game()
{
	//设置随机数
	int ret = rand() % 100 + 1;
	//猜数字
	int input = 0;
	while (1)
	{
		printf("请输入->");
		scanf("%d", &input);
		if (input < ret)
		{
			printf("猜小了\n");
		}
		else if (input > ret)
		{
			printf("猜大了\n");
		}
		else
		{
			printf("猜对了!\n");
			break;
		}
	}
}

int main()
{
	int input = 0;
	//随机数生成器
	srand((unsigned)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;
}

Guess you like

Origin blog.csdn.net/minLi_/article/details/131600533