How to understand C language branches and loop statements

1. Branch statement~

Branch statements are also called conditional judgment statements, which are divided into if statements and switch statements;

1.1 What is a branch statement: A branch statement is also called a selection structure

Simple example (hypothesis): If you study hard, you can get good grades and find a good job.

On the other hand, if you don’t study hard, you will only be able to bake sweet potatoes after graduation.

Those are two different options!

1.2 if statement

In C language: 0 is false and non-0 is true.

How to write this kind of sentence? Here is a brief introduction:

The syntax form of if statement:

If the expression becomes ? (is true), the statement will be executed. If the expression does not become ? (is false), the statement will not be executed. If the result of the expression is 0, the statement will not be executed. If the result of the expression is no 0, then the statement executes?.

eg: Enter an integer and determine whether it is an odd number.

#include<stdio.h>
int main()
{
  int n=0;
  scanf("%d", & amp;num);
  if(num%2==1)
    printf("%d is an odd number\\
",num);
  return 0;
}

1.3 else

If an integer is not an odd number, then it is an even number. If you want to determine whether any number is an odd number or an even number, and express them respectively, how should you operate?

The if…else… statement needs to be used here. The syntax is as follows:

if(expression)

Statement 1

else

Statement 2

eg1: Enter an integer and determine whether it is an odd number. If (if) is an odd number, it will be printed on the screen as an odd number, otherwise (else) it will be printed as an even number.

#include <stdio.h>
int main()
{
  int num = 0;
  scanf("%d", & amp;num);
if(num % 2 == 1)
    printf("%d is an odd number\\
", num);
else
    printf("%d is an even number\\
", num);
return 0;
}

2 Enter an age, if >= 18 years old, output: adult, otherwise, output: minor

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

1.4 Branch contains multiple statements

The if and else statements control the next line of statements by default. By slightly modifying the above code, you can get:

#include <stdio.h>
int main()
{
  int age = 0;
  scanf("%d", & amp;age);
  if(age >= 18)
      printf("Adult\\
");
      printf("You can fall in love\\
");
return 0;

When you enter the value, you will find that no matter what the value is, the content of the second printf will appear on the screen. This is because the if statement only controls the code on the next line of it, and other codes are not restricted.

How to resolve the above situation? {} is used here to enclose the code to be controlled.

In the same way, else can also be followed by braces to enclose the content.

The code is implemented as follows:

#include<stdio.h>
int main()
{
int age = 0;
scanf("%d", & amp;age);
if (age >= 18)//The content enclosed by {} can be called a program block or a compound statement
{
printf("Adult\\
");
printf("You can have a girlfriend\\
");

}
else //else uses ?{} to control multiple statements - this block is also called: program block, or compound statement
{
printf("Underage\\
");
printf("You can't fall in love early\\
");
}
return 0;
} 

1.5 Nested if

In the if else statement, else can be connected with another if statement to form multiple judgments.

For example: if you are required to input an integer, determine whether the input integer is 0, a positive number or a negative number. Please see the following code

#include <stdio.h>
int main()
{
    int num = 0;
    scanf("%d", & amp;num);
    if(num == 0)
        printf("The number entered? is 0\\
");
    else if(num > 0) //This if is equivalent to being nested in the els statement, forming a nested structure
        printf("The number entered? is a positive number\\
");
    else
        printf("The number entered? is a negative number\\
");
return 0;

The content after the second if statement in the above code is equivalent to being nested in the else above, which is a nested structure (nesting of if statements)

Input an integer, if it is a positive number, then determine whether it is an odd number or an even number, and output it; if it is not a positive number, output: a negative number.
e.g.:

#include <stdio.h>
int main()
{
  int num = 0;
        scanf("%d", & amp;num);
    if(num>0)
  {
    if(num%2 == 0)
        printf("even number\\
");
    else
        printf("odd number\\
");
  }
  else
  {
    printf("Negative number\\
");
  }
  return 0;
}

Nested if statements can complete complex logical judgments.

practise:

Enter the age of the person

If the age is <18 years old, print "Juvenile" If you are 18 years old or 44 years old, print "? Year" If you are 45 years old or 59 years old, print "Mid? Year" If you are 60 years old or 89 years old, print "?Year"

If you are over 90 years old, print “?Birthday Star”

Code:

 //? Method 1
#include <stdio.h>
int main()
{
    int age = 0;
    scanf("%d", & amp;age);
    if(age<18)
        printf("Youth\\
");
    else if(age<=44)
        printf("?Year\\
");
    else if(age<=59)
        printf("Middle? Year\\
");
    else if(age<=90)
        printf("?Year\\
");
    else
        printf("?birthday girl\\
");
    return 0;
}
//Method 2 Surround each statement with braces

#include <stdio.h>
int main()
{
    int age = 0;
        scanf("%d", & amp;age);
    if(age<18)
    {
        printf("Youth\\
");
    }
    else
    {
        if(age<=44)
        {
            printf("?Year\\
");
        }
    else
        {
            if(age<=59)
            {
                printf("Middle? Year\\
");
            }
            else
            {
                if(age<=90)
                    printf("?Year\\
");
                else
                    printf("?birthday girl\\
");
            }
        }
    }
return 0;
}

1.6 The dangling else problem

Usually when many people write nested if else statements, they cannot get the desired results when running the code. The main reason is that if and the corresponding else do not match correctly.

In the case of multiple if elses, else always matches the nearest if.

Use code as an example:

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

You can think about what is the result of running the program?

Should we first judge that a is 0 and not equal to 1, execute the else statement and print haha?

This is not the case

The result of running the code is that nothing is output.

why? This is the problem of dangling else. If there are multiple if and else, you can remember this rule. Else always matches the closest if. The above code layout allows else to match the first if statement, which makes us think that else matches the first if statement. When the if statement is incorrect, what we naturally think of is to execute the else statement and print it. haha, but in fact else is matched with the first if, so the subsequent if…else statement is nested in the first if statement. If the first if statement is not successful, the nesting If and else will have no chance to execute?, and ultimately nothing will be printed. What if the code is changed to the following? It will be easier to understand

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

To match else with the first if, modify the code with {}. Reasonable use of {} in complex code can enhance the readability of the code.

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

2. Relational operator

Expressions that are compared in C language are called “relational expressions”, and the operators they use are called “relational operators”. There are mainly the following six.

? > ? to operator

? < ?for operator

? >= ? equal to operator

? <= ? equal to operator

? == equality operator

? != inequality operator

e.g.:

1 a == b;

2 a != b;

3 a < b;

4 a > b;

5 a <= b;

6 a >= b;

Relational expressions usually return 0 or 1 to represent true or false.

In C language, 0 means false and non-0 means true.

Relational expressions are often used in if or while structures.

Note: 1. In C language = means assignment, and == is used to determine equality.

2. It is not suitable to use multiple operators together, as the desired results are usually not obtained.

i < j < k

In the above example, two operators are used consecutively. This is a legal expression and will not report an error, but it usually does not achieve the desired result, that is, it does not guarantee that the value of variable j is between i and k. Because relational operators are evaluated from left to right, the expression below is actually executed.

(i < j) < k

In the above equation, i < j returns 0 or 1, so the final value is 0 or 1 compared with the variable k. If you want to determine whether the value of variable j is between i and k, you should use the following writing method.

i < j & amp; & amp; j < k

For example: We input an age. If the age is between 18 and 36 years old, we output the year. If we write like this

#include <stdio.h>
int main()
{
    int age = 0;
        scanf("%d", & amp;age);
    if(18<=age<=36)
{
        printf("?Year\\
");
}
    return 0;
}

When the input value is 10, “Youth” is still printed.

This is because first comparing 18 with 10 stored in the age variable, the expression is false and the result is 0, and then comparing 0 with 36, it is true, so printing “Youth” can be done even when age=10. Printing “Youth”, there is a problem with the logic

The code should be modified as follows:

#include <stdio.h>
int main()
{
    int age = 0;
    scanf("%d", & amp;age);
    if(age>=18 & amp; & amp; age<=36)
{
        printf("?Year\\
");
}
    return 0;
}

At this point the problem is solved.

~~~~~Choose structure exercises:

Write a program to input three integers a, b, and c from the keyboard and output the largest one among them.
[Input form]
Enter only one line, enter 3 integers
[Output form]
Output only one line, output the maximum value among 3 numbers

#include<stdio.h>
int main()
{
  int a; int b; int c; int max;
  scanf("%d%d%d", & amp;a, & amp;b, & amp;c);
  if(a>b)
  {
      max=a; //First compare the two numbers and put the larger number in max

  }
  else
  {
      max=b;

  }
  if(c>max)
  {
      max=c; //If the maximum number in a and b is not as large as C, then the largest number is C
  }

  printf("max=%d\\
",max);

    return 0;
}

expand:

Write a program to input three integers and output them in order from large to small. Note: When testing this program, correct output results must be obtained from 6 sets of test data to prove that the program is correct. a b c a c b b a c b c a c b a c a b
[Input form]
Enter only one line and enter three integers.
[Output form]
The output is only one line, and the three integers are output in order from largest to smallest.

Analysis: To sort three numbers, suppose there are three numbers a, b, and c. If you want to sort the three numbers from large to small, compare the three numbers in pairs and exchange them. Compare a and b. If a is less than b, exchange the values. Then compare a with c. If a is less than c, exchange the values. At this time, a is the largest of the three numbers. At this time, b and c are Compare, if b is less than c, exchange, then the three numbers a, b, c will be arranged from large to small.

#include<stdio.h>
int main()
{
    int a;int b;int c;int k=0;
    scanf("%d%d%d", & amp;a, & amp;b, & amp;c);
    if(a<b)

    {
        k=b;
        b=a;
        a=k;

    }
     if(a<c)
    {
        k=c;
        c=a;
        a=k;

    }
     if(b<c)
      {

        k=c;
        c=b;
        b=k;
      }
        printf("%d>%d>%d",a,b,c);



   return 0;


}

3.Conditional operator

The conditional operator is also called the ternary operator and needs to accept three operands. The specific implementation is as follows:

The calculation logic of the conditional operator is: if exp1 is true, exp2 is calculated, and the calculation result is the result of the entire expression;

If exp1 is false, exp3 is evaluated and the result of the evaluation is the entire expression.

Use the ternary operator to easily optimize your code

Examples are as follows:

#include <stdio.h>
int main()
{
    int a = 0;
    int b = 0;
    scanf("%d %d", & amp;a, & amp;b);
    if (a > 5)
        b = 3;
    else
        b = -3;
    printf("%d\\
", b);
    return 0;
}
//After modifying the code using the ternary operator
#include <stdio.h>
int main()
{
    int a = 0;
    int b = 0;
    scanf("%d %d", & amp;a, & amp;b);
    b = a>5 ? 3:-3;
    printf("%d\\
", b);
    return 0;
}

Exercise: Use expressions to find the larger of two numbers

#include <stdio.h>
int main()
{
    int a = 0;
    int b = 0;
    scanf("%d %d", & amp;a, & amp;b);
    int num = a>b? a : b; //exp1? exp2; exp3
    printf("%d\\
", num);
    return 0;
}

4. Logical operators: & amp; & amp;, ||, !

Logical operators can connect statements into more complex statements

For example, suppose there are two logical propositions, namely “It is raining” and “I am in the house”. We can combine them into the complex proposition “It is raining, andandI am in the house” or “It’s notraining” or “Ifit’s raining,thenI’m in the house”. A new statement or proposition that is composed of two statements is called a complex statement or compound proposition.

? !: Logical negation operator (changes the true or false value of a single expression).

? & amp; & amp;: The AND operator, which means AND (the expressions on both sides are true, then it is true, otherwise it is false).

? ||: Or operator, which means or (if at least two expressions on both sides are true, then it is true, otherwise it is false).

4.1 Logical negation operator

logical inverse operation

eg: Define a variable flag to indicate true or false. If flag is false, to complete an operation, you can follow the following code:

#include <stdio.h>
int main()
{
    int flag = 0;
    if(!flag)
    {
        printf("do something\\
");
    }
    return 0;
}

If flag is true, then! flag is false, if flag is false, then! flag is true.

4.2 Logical AND Operator

Logical AND is expressed in the C language as & amp; & amp;, which can be understood as AND. & amp; & amp; is a binary operator. When used, there must be operands on both sides of the operator, such as a & amp; & amp;b. The expression on both sides of & amp; & amp; is true only if the expression on both sides is true. , if one of them is false, then the whole is false.

For example, how to use code to print spring when the input value is March-May?

Analysis, the entered value must meet two requirements (greater than 3 and less than 5)

#include<stdio.h>
int main
{
    int month = 0;
    scanf("%d", & amp;month);
    if(month >= 3 & amp; & amp; month <= 5)
    {
    printf("Spring\\
");
    }
    return 0;
}

4.3 Logical OR operator

logical or
a b a||b
Not 0 Not 0 1
Not 0 0 1
0 Not 0 1
0 0 0

|| is the logical OR operator, which means or. It is a binary operator like & amp; & amp;. When used, as long as one of the two expressions is true, the entire expression is true. If both expressions are false, the entire expression is false.

eg: When winter is in December, January or February, how can we use code to implement this?

#include<stdio.h>
int main
{
   int month = 0;
     scanf("%d", & amp;month);
   if(month == 12 || month==1 || month == 2)
    {
     printf("Winter\\
");
    }
   return 0;
}

4,4 small exercises: Judgment of leap years

Enter a year, and determine whether year is a leap year.

(ps: Leap year judgment rules, if it is divisible by 4 and not divisible by 100, it is a leap year; if it is divisible by 400, it is a leap year)

#include <stdio.h> //Method 1
int main()
{
    int year = 0;
    scanf("%d", & amp;year);
    if(year%4==0 & amp; & amp; year 0!=0)
        printf("It is a leap year\\
");
    else if(year@0==0)
        printf("It is a leap year\\
");
    return 0;
}
int main() //Method 2
{
    int year = 0;
    scanf("%d", & amp;year);
    if((year%4==0 & amp; & amp; year 0!=0) || (year@0==0))
        printf("It is a leap year\\
");
    return 0;
}

4.5 short circuit

There is a characteristic of logical operators in C language. It always evaluates the expression on the left first, and then evaluates the expression on the right. This order is determined.

If the expression on the left satisfies the conditions of the logical operator, the expression on the right is no longer evaluated. This situation is called a “short circuit”.

eg: if(month >= 3 & amp; & amp; month <= 5)

The left operand of & & in the expression is month >= 3, and the right operand is month <= 5. When the result of the left operand month >= 3 is 0, even if it is not judged that month <= 5 , the entire expression also evaluates to 0 (not spring). Therefore, for the & operator, when the result of the left operand is 0, the right operand will no longer be executed?.

As for what || is, let’s give an example:

if(month == 12 || month==1 || month == 2)

If month==12, then no matter whether month is equal to 1 or 2, the result of the entire expression is also 1 (winter). Therefore, when the result of the left operand of the || operator is not 0, the right operand needs to be executed.

This kind of operation in which the result of the entire expression can be known only based on the result of the left operand without calculating the right operand is called short-circuit evaluation.
Exercise: Read the code and calculate the output of the code

#include <stdio.h>
int main()
{
    int i = 0,a=0,b=2,c =3,d=4;
    i = a + + & amp; & amp; + + b & amp; & amp; d + + ;
    //i = a + + || + + b||d + + ;
    printf("a = %d\\
 b = %d\\
 c = %d\\
d = %d\\
", a, b, c, d);
    return 0;
}

5 switch statement

In addition to the if statement, C language also provides a switch statement to implement the split structure. The switch statement is a special form of if…else structure, which is suitable for situations where the judgment condition has multiple results. It changes the multiple else if to something easier and more readable

In the above code, the corresponding case analysis is performed according to different values of expression. If the corresponding value cannot be found, a default analysis is performed.

  • The expression after switch must be an integer expression
  • The value after case must be an integer constant expression

5.1 Comparison between if statement and switch statement

Exercise: Enter any integer value and calculate the remainder after dividing by 3

Complete with an if statement:

#include <stdio.h>
int main()
{
    int n = 0;
    scanf("%d", & amp;n);
    if(n%3 == 0)
        printf("divisible, remainder is 0\\
");
    else if(n%3 == 1)
        printf("The remainder is 1\\
");
    else
        printf("The remainder is 2\\
");
    return 0;
}

Complete with a switch statement:

#include <stdio.h>
int main()
{
    int n = 0;
    scanf("%d", & amp;n);
    switch(n%3)
    {
    case 0:
        printf("divisible, remainder is 0\\
");
        break;
    case 1:
        printf("The remainder is 1\\
");
        break;
    case 2:
        printf("The remainder is 2\\
");
        break;
}
    return 0;
}
  • There must be a space between case and the following number
  • After the code in each case statement is executed, a break will be added to jump out of the switch statement.

5.2 break in switch statement

The switch statement is usually used in conjunction with the break statement. So what is the role of the break statement? Let’s first remove the break statement in the above code and see the results.

#include <stdio.h>
int main()
{
    int n = 0;
    scanf("%d", & amp;n);
    switch(n%3)
    {
    case 0:
        printf("divisible, remainder is 0\\
");
    case 1:
        printf("The remainder is 1\\
");
    case 2:
        printf("The remainder is 2\\
");
    }
    return 0;
}

Test a set of values to see the results:

We found that when 13 is divided by 3, the remainder is 1, but the result of running the program is an extra line of “Remainder is 2”.

The reasons are as follows: The switch statement also has separate effects. Only using break in the switch statement can jump out of the switch statement. If there is no break statement after a certain case statement, the code will continue to execute, and other executions may be possible. The code in the case statement ends until it encounters a break statement or a switch statement. Just the code above executes the statement in case 2. Therefore, the break statement in the switch statement is very important and can achieve a real breaking effect. Of course, break is not required in every case statement. This depends on the actual situation.

practise:

Please enter a number from 1 to 7 and output the corresponding week in English. If the input is incorrect, “Error” is output. Weeks 1-7 correspond to: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.
[Input form]
Enter any integer.
[Output form]
If the input integer is between 0 and 6, the English corresponding to the week will be output, otherwise “Error” will be output.

#include<stdio.h>
   int main()
{ int x;
    scanf("%d", & amp;x);
    switch(x)
    {
        
        case 1:printf("Monday");break;
        case 2:printf("Tuesday");break;
        case 3:printf("Wednesday");break;
        case 4:printf("Thursday");break;
        case 5:printf("Friday");break;
        case 6:printf("Saturday");break;
        case 7:printf("Sunday");break;
        default:printf("Error\\
");
    }


    return 0;
}

If requirements change:

  • Input 1-5, the output is “working days”;
  • Enter 6-7 and output “rest day”

The reference code is as follows:

#include<stdio.h>
int main()
{
    int x;
    scanf("%d", & amp;x);
    switch(x)
    {
    
    case 1:printf("Monday");
    case 2:printf("Tuesday");
    case 3:printf("Wednesday");
    case 4:printf("Thursday");
    case 5:printf("working day\\
"); break;
    case 6:printf("Saturday");
    case 7:printf("rest day\\
"); break;
    default:printf("Error\\
");
    }


    return 0;
}

In the above exercise, we found that we should decide whether to use break in the code based on the actual situation, or where to use break, in order to correctly complete the actual requirements.

5.3 default in switcj statement

Default is mentioned in the above code. In the actual process of writing code, we may often encounter a situation, such as when the value in the expression after the switch cannot match the case statement in the code, or else No processing is required, otherwise you have to add a ?default? sentence to the switch statement.

switch behind When the result of expression is neither value1 nor value2, the ?default? statement will be executed.

5.4 The order of case and defult in the switch statement

Is there any required order between the case ? clause and the default ? clause in the switch statement? Can default only be placed at the end? In fact, there is no order requirement for case statements and default statements in the switch statement, as long as your order meets the actual requirements. But we usually put the default ? sentence at the end.

The branch statement (selection structure) content ends here, and we will continue to introduce the loop structure to you later!

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Algorithm skill tree Home page Overview 57427 people are learning the system