Branch and loop statements of initial C language

Branch and loop statements

Branch statement

  • if
  • switch

Circular statement

  • while
  • for
  • do while

goto statement

1. What is a statement

C statements can be divided into the following five categories:

  1. Expression statement
  2. Function call statement
  3. Control statement
  4. Compound statement
  5. Empty statement

Control statements are used to control the execution process of the program to realize various structural modes of the program. They are composed of specific statement definer. There are nine kinds of control statements in C language.

  • It can be divided into the following three categories:

    1. Conditional judgment statements are also called branch statements:

      if statement and switch statement;

    2. Circular execution statement:

      do while statement, while statement and for statement;

    3. Steering statement:

      break statement, goto statement, continue statement, return statement.

2. Branch statement (select structure)

If you study hard and get a good offer in school, you will reach the peak of your life. If you don't study, graduation equals unemployment. Go home and sell sweet potatoes. This is the choice! five

2.1 if statement

What is the grammatical structure of the if statement?

Syntax structure:
    
if(expression)
    sentence;

if(expression)
    Statement 1;
else
    Statement 2;

//Multi branch   

if(Expression 1)
    Statement 1;
else if(Expression 2)
    Statement 2;
else
    Statement 3;

Example:

//Code 1

#include <stdio.h>
int main()
{
 int age = 0;
    scanf("%d", &age);
    if(age<18)
   {
        printf("under age\n");
   }
}

//Code 2

#include <stdio.h>
int main()
{
 int age = 0;
    scanf("%d", &age);
    if(age<18)
   {
        printf("under age\n");
   }
    else
   {
        printf("adult\n");
   }
}

//Code 3

#include <stdio.h>
int main()
{
 int age = 0;
    
    scanf("%d", &age);
    
    if(age<18)
   {
        printf("juvenile\n");
   }
    else if(age>=18 && age<30)
   {
        printf("youth\n");
   }
    else if(age>=30 && age<50)
   {
          printf("middle age\n");
   }
    else if(age>=50 && age<80)
   {
        printf("old age\n");
   }
    else
   {
        printf("God of Longevity\n");
   }
    
}

Explanation:

  • If the result of the expression is true, the statement executes. How to express true and false in C language?

0 means false and non-0 means true.

  • If the condition holds and multiple statements are executed, how should code blocks be used?
#include <stdio.h>
int main()
{
    if(expression)
   {
        Statement list 1;
   }
    else
   {
        Statement list 2;
   }
    return 0;
}
  • The pair {} here is a code block.

2.1.1 suspended else

When you write this Code:

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

Explanation: else is combined with the nearest if.

Correction:

//Proper use of {} can make the logic of the code clearer.
//Code style is important
#include <stdio.h>
int main()
{
    int a = 0;
    int b = 2;
    if(a == 1)
   {
        if(b == 2)
       {
            printf("hehe\n");
       }
   }
    else
   {
         printf("haha\n");
   }       
    return 0;
}

Else matching: else is the if matching that l is closest to him.

2.1.2 comparison of if writing forms

//Code 1

if (condition) 
{
    return x;
}
return y;


//Code 2

if(condition)
{
    return x;
}
else
{
      return y;
}

//Code 3

int num = 1;
if(num == 5)
{
    printf("hehe\n");
}

//Code 4

int num = 1;
if(5 == num)
{
    printf("hehe\n");
}

**Explanation: * * code 2 and code 4 are better, with clearer logic and less error prone.

  • Both if and else can control only one statement by default.
  • If you want to express multiple statements, you'd better use code to quickly {statement}.
  • else matches the nearest if.

2.1.3 practice

  1. . judge whether a number is odd
  2. Output odd number between 1-100

2.2 switch statement

The switch statement is also a branch statement.

It is often used in the case of multiple branches.

For example:

Input 1, output Monday

Input 2, output Tuesday

Input 3, output Wednesday

Input 4, output Thursday

Input 5, output Friday

Input 6, output Saturday

Input 7, output Sunday

  • If... Else if... Else if... The form of else if is too complex, then we have to have different grammatical forms. This is the switch statement.
  • Statement items must be integer constant expressions.
  • Case 1: not case 1.0:
switch(Integer expression)
{
    Statement item;
}
  • What are statement items?

    case expressions one by one

//Are some case statements:
//As follows:

case Integer constant expression:
    sentence;

2.2.1 break in switch statement

In the switch statement, we can't directly implement the branch. The real branch can be realized only when it is used with break.

For example:

#include <stdio.h>
int main()
{
    int day = 0;
    switch(day)
   {
        case 1: 
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;    
        case 4:
            printf("Thursday\n");
            break;    
        case 5:
            printf("Friday\n");
            break;
        case 6:
            printf("Saturday\n");
            break;
        case 7:
            printf("Sunday\n");    
            break;
   }
    return 0;
}

Sometimes our needs change:

  1. Input 1-5 and output "weekday";
  2. Input 6-7 and output "weekend"

So our code should be implemented in this way:

#include <stdio.h>
//switch code demonstration
int main()
{
    int day = 0;
    switch(day)
   {
        case 1: 
        case 2:
        case 3:
        case 4:
        case 5:
            printf("weekday\n");
            break;
        case 6:
        case 7:
            printf("weekend\n");
            break;
   }
    return 0;
}
  • break statement

    The practical effect is to divide the statement list into different branch parts.
    Permanently jump out of the loop

  • Good programming habits

Add a break statement after the last case statement.

(this is written to avoid forgetting to add a break statement after the last previous case statement.).

2.2.2 default clause

What if the expressed value does not match the value of all case tags?

In fact, it's nothing. The structure is that all statements are skipped.

The program will not terminate or report an error, because this situation is not considered an error in C.

But what if you don't want to ignore the values of expressions that don't match all tags?

You can add a default clause to the statement list and put the following tag

default:

  • Write where any case tag can appear.

  • When the value of the switch expression does not match the value of all case tags, the statement after the default clause will be executed.

  • Therefore, only one default clause can appear in each switch statement.

  • However, it can appear anywhere in the statement list, and the statement flow executes the default clause like a case tag.

  • Good programming habits

    It's a good habit to put a default clause in each switch statement. You can even add a break after it.

2.2.3 practice

#include <stdio.h>
int main()
{
    int n = 1;
    int m = 2;
    switch (n)
   {
    case 1:
            m++;
    case 2:
            n++;
    case 3:
            switch (n)
           {//switch allows nested use
             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. Circular statement

  • while
  • for
  • do while

3.1 while cycle

We have mastered the if statement:

if(condition)
     sentence;
  • When the conditions are met, the statement after the if statement is executed, otherwise it is not executed.

  • But this statement will be executed only once.

  • Because we find that many practical examples in life are: we need to complete the same thing many times.

    So what do we do?

  • C language introduces us: while statement, which can realize loop.

//while syntax structure
while(expression)
 Circular statement;

Example:

Print numbers 1-10 on the screen.

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

The above code has helped me understand the basic syntax of the while statement. Let's learn more:

3.1.1 break and continue in while statement

  • break introduction
//break code instance
#include <stdio.h>
int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			break;
        printf("%d ", i);
        i = i+1;
 }
 return 0;
}
  • What is the result of the code output here?

1 2 3 4

1 2 3 4 5

1 2 3 4 5 6 7 8 9 10

1 2 3 4 6 7 8 9 10

Summary:

The role of break in the while loop:

In fact, as long as you encounter a break in the cycle, stop all the later cycles and directly terminate the cycle.

So: break in while is used to permanently terminate the loop.

continue introduction

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

What is the result of the code output here?

1 2 3 4

1 2 3 4 5

1 2 3 4 5 6 7 8 9 10

1 2 3 4 6 7 8 9 10

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

What is the result of the code output here?

1 2 3 4

1 2 3 4 5

1 2 3 4 5 6 7 8 9 10

1 2 3 4 6 7 8 9 10

2 3 4 6 7 8 9 10

Summary:

The function of continue in the while loop is:

Continue is used to terminate this cycle, that is, the code behind continue in this cycle will not be executed, but directly jump to the judgment part of the while statement. Determine the inlet of the next cycle.

  • break is a permanent stop cycle

  • Look at a few more codes:

//What does code mean?
//Code 1
#include <stdio.h>
int main()
{
    int ch = 0;
    while ((ch = getchar()) != EOF)
        putchar(ch);
    return 0;
}
The code here can be used to clean up the buffer with appropriate modifications.
//Code 2
#include <stdio.h>
int main()
{
    char ch = '\0';
    while ((ch = getchar()) != EOF)
    {
        if (ch < '0' || ch > '9')
            continue;
        putchar(ch);
    }
    return 0;
}
//The function of this code is to print only numeric characters and skip other characters

3.2 for loop

We already know the while loop, but why do we need a for loop? First, let's look at the syntax of the for loop:

3.2.1 grammar

for(Expression 1; Expression 2; Expression 3)
 Circular statement;
  • Expression 1 is the initialization part, which is used to initialize the of loop variables.
  • Expression 2 expression 2 is a condition judgment part, which is used to judge the termination of the cycle.
  • Expression 3 is the adjustment part, which is used to adjust the loop conditions.

Practical problems:

Use the for loop to print numbers 1-10 on the screen.

#include <stdio.h>
int main()
{
	int i = 0;
	//for(i=1 / * initialization * /; i < = 10 / * judgment part * /; i + + / * adjustment part * /)
	for (i = 1; i <= 10; i++)
	{
		printf("%d ", i);
	}
	return 0;
}

Now let's compare the for loop with the while loop.

int i = 0;
//To achieve the same function, use while
i = 1;//Initialization part
while (i <= 10)//Judgment part
{
	printf("hehe\n");
	i = i + 1;//Adjustment part
}
//To achieve the same function, use while
for (i = 1; i <= 10; i++)
{
	printf("hehe\n");
}

It can be found that there are still three necessary conditions for the loop in the while loop.

However, due to the problem of style, the three parts are likely to deviate far.

It is not convenient to find and modify in a centralized way.

Therefore, the style of for loop is better; The for loop is also used the most frequently.

3.2.2 break and continue in for loop

We found that break and continue can also appear in the for loop, and their meaning is the same as that in the while loop. But there are some differences:

//Code 1

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

//Code 2

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

3.2.3 loop control variable of for statement

Recommendations:

  1. Do not modify the loop variable in the for loop body to prevent the for loop from losing control.
  2. It is suggested that the value of the loop control variable of the for statement should be written as "closed before open interval".
int i = 0;

//The writing method of front closing and back opening
for (i = 0; i < 10; i++)
{
    
}

//Both sides are closed intervals
for (i = 0; i <= 9; i++)
{
    
}

3.2.4 deformation of some for cycles

#include <stdio.h>
int main()
{
    //Code 1
    for (;;)
    {
        printf("hehe\n");
    }
    //The initialization part, judgment part and adjustment part of the for loop can be omitted, but it is not recommended to omit them at the beginning of learning, which is easy to cause questions
    Question.

        //Code 2
        int i = 0;
    int j = 0;
    //How many hehe are printed here?
    for (i = 0; i < 10; i++)
    {
        for (j = 0; j < 10; j++)
        {
            printf("hehe\n");
        }
    }

    //Code 3
    int i = 0;
    int j = 0;
    //If the initialization part is omitted, how many hehe are printed here?
    for (; i < 10; i++)
    {
        for (; j < 10; j++)
        {
            printf("hehe\n");
        }
    }

    //Code 4 - use more than one variable to control the loop
    int x, y;
    for (x = 0, y = 0; x < 2 && y < 5; ++x, y++)
    {
        printf("hehe\n");
    }
    return 0;
}

The rest of the content will be updated this week. That's all for today's sharing. If you think my sharing is helpful to you, please praise and support it.

Tags: C

Posted by sridsam on Thu, 14 Apr 2022 17:42:18 +0930