"C Language Elementary" Chapter 3 - Branch Statements and Loop Statements

foreword

After nearly half a month of end-of-term review, Xiaoyang, I finally came to add a new chapter to the C language elementary column: branch statements and loop statements in C language~ Before
touching our main learning content today, we must first know the sentences The definition and classification of sentences!


sentence

statement definition

A statement in C language is an instruction or a line of code and ends with a semicolon.

Classification of sentences

  • expression statement
  • function call statement
  • empty statement
  • compound statement
  • Control Statements
    The branch statements and loop statements we learned today are all control statements, and the C language has three types of control statements:
  1. Branch statement: ifstatement, switchstatement
  2. Loop statements: do whilestatement, whilestatement, forstatement
  3. Turn to statement: breakstatement, gotostatement, continuestatement, returnstatement

branch statement

A branch statement means a choice statement:
If you study hard, you can find a good offer. If you don't study hard, go home and sell sweet potatoes. There are statements and statements
in branch statements .ifswitch

if statement

  1. Grammatical structure one:
if (表达式)
	语句;
  1. Grammatical structure two:
if (表达式)
	语句1else(表达式)
	语句2
  1. grammatical structure three;
if (表达式)
	语句1else if(表达式)
	语句2else
	语句3;

In C language, 0 is false and non-zero is false. If the expression in parentheses after if is true, the statement is executed, otherwise it is false, and the statement is not executed.

usage example

#include<stdio.h>
int main()
{
    
    
	int age = 0;
	scanf("%d", &age);
	if (age >= 18)
	{
    
    
		printf("成年\n");
	}
	else if (age < 18 && age>12)
	{
    
    
		printf("青少年\n");
	}
	else
	{
    
    
		printf("小朋友\n");
	}
	return 0;
}

dangling else

An if, else, else if can only be followed by one statement. If you want to follow multiple statements, you need to use curly braces { } (code block) to include multiple statements (to form a compound statement). If {} is not used when writing multiple statements, a dangling esle will appear.
Example:
Question : What is the result of the following code execution?

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
    
    
	int a = 0;
	int b = 2;
	if (a == 1)
		if (b == 2)  
			printf("lala\n");
	else
		printf("hehe\n");
	return 0;
}

Answer : No output content
ii
Reason : The grammar stipulates that else matches its nearest if, and the first if condition is false, the following statement will not be executed.

为了避免这类bug的出现,我们应该多使用{},莫要偷懒。

switch statement

The switch statement is also a branch statement, often used in multi-branch situations.

Grammatical structures

#include <stdio.h>
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;
	defaule:
		printf("该天不存在\n");
	}
	return 0;
}

constitute:

  • switch: The content in () behind the switch is an integer expression
  • case: If the value of the expression is this possible value, then execute: the following statement
  • break: When we finish executing a situation and don’t want to continue executing, we need to use break to jump out of the switch
  • default: If none of the above cases match the possible values, execute the default statement, and there is only one default statement in the switch statement

Flexible use

#include <stdio.h>
{
    
    
    int day = 0;
    switch(day)
   {
    
    
        case 1case 2:
        case 3:
        case 4:
        case 5:
            printf("工作日\n");
            break;
        case 6:
        case 7:
            printf("休息日\n");
            break;
   }
    return 0;
}

If multiple case statements execute the same content, you can omit multiple identical case statements. You only need to add the content to be executed and break to the last case statement that executes the same content.


loop statement

The definition of a loop statement is to do one thing repeatedly, which is repeated execution in the language

while loop

Grammatical structures

while(表达式)
{
    
    
	语句;
}

This code means that the condition to enter the loop is true and enter the loop. If the expression is true, the statement is executed, and if the expression is false, the statement is not executed.

usage example

Print the numbers from 0 to 9

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

insert image description here

do while loop

Grammatical structures

do
	语句;
while(表达式);

do whileLoops are very similar to whileloops, with one difference:

  • whileThe statement judges the expression first, and then executes the loop statement;
  • do whileThe statement executes the loop statement first, and then evaluates the expression.

usage example

Problem: Print the numbers 0-9 on the screen

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

insert image description here

for loop

Grammatical structures

for(表达式1; 表达式2; 表达式3)
{
    
    
	...//循环语句;
}

Three necessary conditions for a loop:

  1. Expression 1 is the initialization part, which is used to initialize the loop variable;
  2. Expression 2 is the condition judgment part, which is used to judge the termination of the loop (== "logic" judgment, if the condition is judged as a relational expression, then compare the size, if the condition is judged as an expression, then compare the expression The final value is compared with 0 for false and non-zero for true)
  3. Expression 3 is an adjustment part, which is used to control loop traversal.

The for loop is actually a bit different from the while loop. Let's compare and compare the similarities between these two statements:

  1. The loop variable of the while loop is defined outside {}, and the for loop can be defined outside {} or inside ()
  2. The judgment condition of the while loop is in (), and the judgment condition of the for loop is expression 2
  3. The while loop controls the loop variable in {}, and the for loop is in expression 3

usage example

print numbers 0-9

#include <stdio.h>
int main()
{
    
    
 int i = 0;
 for(i=0; i<10; i++{
    
    
 	printf("%d ", i);
 }
 return 0;
}

break与continue

break

breakFunction: Permanently terminate the loop, as long as a break is encountered in the loop, all subsequent loops will be stopped until the loop is terminated.

usage example

Print the numbers 0-9, add a break statement, and observe the effect

#include<stdio.h>
int main()
{
    
    
    int i = 0;
    while (i<10)
    {
    
    
        if (i == 5)
        {
    
    
            break;
        }

        printf("%d ", i);
        i = i + 1;
    }
    return 0;
}

insert image description here

continue

continueFunction: Terminate this cycle (skip the current cycle where continue is located), that is, the code part after continue in this cycle will not be executed, and directly jump to the judgment part for judgment, and enter the entry of the next cycle body.

usage example

Print the numbers 0-9, not 5

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

insert image description here

goto statement

The c language provides goto statements that can be used at will and labels that mark jumps.
Function: It can be used to jump out of deep loop nesting 深层循环(jump out of one or more layers of loops), while break can only jump out 一层循环.

usage example

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

As above, no matter how many layers are nested in the program, as long as gotoa statement is encountered, it will jump to gotothe marked statement label~


Well, this is the end of the knowledge points shared by Xiaoyang today, and the basic knowledge of C language will continue to be updated~

Guess you like

Origin blog.csdn.net/hsjsiwkwm/article/details/131309499