C language branches and loops (Part 1) – branch structure

Stick to your beliefs and break through yourself. Break the mold and pursue your dreams. Sometimes the height a person stands depends on the height of his dreams.

Table of Contents

1. if statement

1.1 if

1.2 else

1.3 points? Contains multiple statements

1.4 Nested if

1.5 The dangling else problem

2. Relational operators

3. Conditional operators

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

4.1 Logical negation operator

4.2 AND operator

4.3 OR operator

4.4 Exercise: Judgment of leap year

4.5 Short circuit

5. switch statement

5.1 Comparison between if statement and switch statement

5.2 break in switch statement

5.3 default in switch statement

5.4 The order of case and default in the switch statement

Text begins

C language is a structured programming language. The structures here refer to sequential structure, selection structure, and loop structure. C Language can realize these three structures. In fact, if we analyze it carefully, the things we see every day can be divided into these three structures or a combination of these three structures.

We can use if and switch to realize the division structure, and use for, while and do while to realize the loop structure.

Today let’s learn about the branch structure.

1. if statement

1.1 if

The syntax of the if statement is as follows:

0cd1c80f7a94401389b9933335060d7c.png

If the expression is true (true), the statement is executed; if the expression is not true (false), the statement is not executed.

In C language, 0 is false, and 0 means true. That is, if the result of the expression is 0, the statement will not be executed. If the result of the expression is not 0, the statement will not be executed. Execute?.

Example: Input an integer and determine whether it is an odd number

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

c73c32b624bb4690bd04007b9f3c640d.png if statement execution flow chart

1.2 else

If the number is not an odd number, it is an even number. If there is any integer, we need to clearly judge whether it is an odd number or an even number. How to express it?

This requires an if…else… statement. The syntax is as follows:

if (expression)
 Statement 1
else
 Statement 2

Example: Input an integer and determine whether it is an odd number. If it is an odd number, it will be printed as an odd number. Otherwise, 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;
}

The result is as follows:

9d44a90376d24fac9f05c4e53d7d16ae.png

1.3 points? Contains multiple statements

By default, only one statement is controlled in the if and else statements, such as:

#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;
}

In the above code, you will find that whether the input value is >=18 or less than 18, “You can fall in love” will be printed on the screen.

fe2a7d90212f4722b622f31d632f4012.pnga228c5dfce9c4f4cbd82902f62d66fa3.png

This is because the if statement can only control ? statements, which is printf(“Adult\\
“);. If the statement is true, then it will be printed. If the statement is false, it will not be printed. For printf(\ “You can fall in love\\
“); exists independently, and will be executed regardless of whether the condition of the if statement is true or false. So what should we do if we want the if statement to control two statements at the same time? Then you need to use ? {} to enclose the code, and else can also be followed by ? brackets. as follows:

#include <stdio.h>
int main()
{
int age = 0;
scanf("%d", & amp;age);
if (age >= 18) //After if, use ?{} to control multiple statements - this block is also called: program block, or compound statement
{
printf("Adult\\
");
printf("Can we make friends\\
");
}
return 0;
}

#include <stdio.h>
int main()
{
int age = 0;
scanf("%d", & amp;age);
if (age >= 18) //After if, use ?{} to control multiple statements - this block is also called: program block, or compound statement
{
printf("Adult\\
");
printf("Can we make friends\\
");
}
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.4 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;
}

in this code

if (num > 0)
printf("The number entered? is a positive number\\
");
else
printf("The number entered? is a negative number\\
");

It is nested in the previous else statement, forming a nested if statement.

Another example:

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.

#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;
}

In the code above, the code for determining parity is also nested in the if statement, forming a nested if statement.

The above is the syntax of nested if statements. With nested if statements, more complex logical judgments can be completed.

1.5 Hanging else problem

If there are multiple ifs and elses, you can remember this rule: else always matches the closest if.

Let’s start with the next 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;
}

What is the result of running the program?

Many beginners come up to judge that a is 0 and not equal to 1, then execute the else sentence and print haha

But when you run the code, the output result is: nothing is output.

edd99c773d314d2384254ffceec20190.png

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 fails, 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 following if…else statement is nested in the first if statement. If the first if statement is not true, the nested if and else will have no chance to execute?, and nothing will be printed in the end.

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;
}

Or if we want else to indeed match the ?th if, we can modify the code like this:

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

As long as you bring appropriate brackets, the logic of the code will be clearer, so you should pay attention to the use of brackets when writing code in the future to make the code more readable.

2. Relational operators

Expressions that are compared in C language are called “relational expressions” (relational expression), and the operators used are called “relational operators”. There are mainly 6.

? > ? to operator

? < ?for operator

? >= ? equal to operator

? <= ? equal to operator

? == equality operator

? != inequality operator

Below are some examples.

2d4feca7cd564e7b85f2daefa2325c6f.png

Relational expressions usually return 0 or 1, indicating true or false.

In the C language, 0 represents false, and all zero values represent true. ?For example, 20 > 12 returns 1, 12 > 20 returns 0.

Relational expressions are often found in if or while structures.

if (x == 3) {
 printf("x is 3.\\
");
}

Note: The equality operator == and the assignment operator = are two different operators, so do not confuse them. Sometimes, you may not write the following code. It may work, but it is easy to produce unexpected results.

if (x = 3) ...

In the above example, the original intention is x == 3, but it cannot be written as x = 3. This expression assigns the value 3 to the variable x, and its return value is 3, so the if judgment is always true.

In order to prevent this kind of error, some programmers like to write variables on the right side of the equal sign.

if (3 == x) ...

In this case, if == is mistakenly written as =, the compiler will report an error.

/* Report error */
if (3 = x) ...

Another mistake to avoid is: Multiple relational operators should not be concatenated.

256a0fe60bdd44f1a1d07b7cd8597093.png

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.

3d637bb48a804f38a4a849faa799106c.png

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.

7f5ee132b3be44fc8eb5bf3ff81c9203.png

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 we lose ?10, we still output ?year, as shown below:

46536d59e11a4135a20026194f876d1b.png

This is because we first compare 18 with the 10? stored in age. The expression 18<=10 is false, and the result of 18<=age is 0. Then we compare 0 with 36?, and 0<=36 is true. So ?year is printed, so even when age is 10, ?year can be printed. There is a logical problem. How should this code be written?

9b73dba33c69413b8281829d89d92d3b.png

The above is what we need to master about operators. The rest is just a matter of understanding and using them according to the meaning of the words. There is no special attention.

3. Conditional operator

The conditional operator is also called the triple operator, which needs to accept three operands. The form is as follows:

7797f17283004681994a984f3c93770a.png

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

Exercise: Use conditional expressions to find the comparative value of two numbers.

#include <stdio.h>
int main()
{
int a = 0;
int b = 0;
scanf("%d %d", & amp;a, & amp;b);
int m = a > b ? a : b;
printf("%d\\
", m);

return 0;
}

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

Logical operators provide logical judgment functions and are useful for constructing more complex expressions. There are mainly three operators:

? !: 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, it is true, otherwise it is false).

Note: In C language, 0 means true and 0 means false.

4.1 Logical negation operator

1669e1a2734d4781b0772baba28bc420.png

For example, we have a variable called flag. If flag is false, what should we do? We can write the code like this:

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

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

So the meaning of the above code is that if the flag is false, the code in the if statement will be executed.

4.2 AND operator

e84604d3c2114e8a802130e491be24de.png

& amp; & amp; is the AND operator, which also means AND. & amp; & amp; is a double operator. The formula for using it is a & amp; & amp;b , & amp; & amp ; When the expressions on both sides are true, the entire expression is true. As long as one of them is false, the entire expression is false.

For example: If we say that the time is from 3 to 5, which is spring, how will it be reflected in the usage code?

int month = 0;
scanf("%d", & amp;month);
if (month >= 3 & amp; & amp; month <= 5)
{
printf("Spring\\
");
}

The meaning of this expression is that month must be equal to or equal to 3, and month must be equal to or equal to 5, and must be satisfied at the same time.

4.3 OR operator

cc78bfbeb6434742b798b3b08624b5fb.png

|| is the OR operator, which means or. || is also a double operator. The expression used is a || b. As long as one of the expressions on both sides of || is true, the entire expression It is true, and it is false only when the expressions on both sides are false. For example: We say that the month of the year is December or January or February is winter, so how do we use the code to reflect it?

int month = 0;
scanf("%d", & amp;month);
if (month == 12 || month == 1 || month == 2)
{
printf("Winter\\
");
}

4.4 Exercise: Judgment of leap years

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

Rules for judging leap years:

84c6792506e34cdbbc3e166d104509db.png

#include <stdio.h>
//Code 1
int main()
{
int year = 0;
scanf("%d", & amp;year);
if (year % 4 == 0 & amp; & amp; year % 100 != 0)
printf("It is a leap year\\
");
else if (year % 400 == 0)
printf("It is a leap year\\
");

return 0;
}
//Code 2
int main()
{
int year = 0;
scanf("%d", & amp;year);
if ((year % 4 == 0 & amp; & amp; year % 100 != 0) || (year % 400 == 0))
printf("It is a leap year\\
");

return 0;
}

4.5 Short circuit

C language logical operators have another characteristic. They always evaluate the expression on the left first, and then the expression on the right. This order is guaranteed.

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“.

The code as before?:

605e3b8b9ccd46bc8818b651a20adf55.png

In the expression, the left operand of & amp; & amp; is month >= 3, and the right operand is month = 3. When the result is 0, even if month <= 5 is not judged, the result of the entire expression is 0 (not spring).

Therefore, for the & operator, when the result of the left operand is 0, the right operand will no longer be executed?.

What about the || operator? Let’s combine the previous code:

9d3fc6de20834dc59ff137cfb6631cb6.png

If month == 12, then check whether month is equal to 1 or 2, and 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.

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 multiple else if statements into a simpler, more readable form.

switch (expression) {
case value1: statement
case value2: statement
default: statement
}

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.

Note:

? 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

If the ?if statement is completed, as follows:

#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;
}

If you rewrite the ?switch statement, it can look like this:

#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;
}

In the above code, the points we should pay attention to are:

1. There must be a space between case and the following number.

2. After the code execution in each case statement is completed, break needs to be added to jump out of the switch statement.

5.2 break in switch statement

In the code above, if we remove the break in the case statement, what will happen?

#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 the group and see the results below:

963075b1cd6443959f54b75513221472.png

We found that when 7 was divided by 3, the remainder was originally 1, but we found that the result of the program operation was “remainder is 2”.

Why is this?

The reason is that the switch statement also has separate effects. Only by using break in the switch statement can the switch statement be jumped out. If there is no break statement after a certain case statement, the code will continue to execute, and other cases may be executed. The code in the 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.

For example, this question:

4268c9f9c5594761b7b18fec772213be.png

code show as below:

#include <stdio.h>
int main()
{
int day = 0;
scanf("%d", & amp;day);

switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("?为?\\
");
break;
case 6:
case 7:
printf("Break?\\
");
break;
}
return 0;
}

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

5.3 default in switch statement

When using the switch statement, we may often encounter a situation. For example, when the value in the expression after the switch cannot match the case statement in the code, then either no processing will be done, or else no processing will be done. You have to add a ? default clause to the switch statement.

c57a51cd5b274cff8b82b828b1debf2d.png

When the result of expression after switch is neither value1 nor value2, the default clause will be executed. Just like the previous exercise of printing the week, if the input value of day is not a value from 1 to 7, if we want to prompt: input error, we can complete the code like this:

#include <stdio.h>
int main()
{
int day = 0;
scanf("%d", & amp;day);

switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("?为?\\
");
break;
case 6:
case 7:
printf("Break?\\
");
break;
default:
printf("Input? Error\\
");
break;
}
return 0;
}

5.4 The order of case and default 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.

However, we usually process the default clause last.

This concludes today’s study! ! !

syntaxbug.com © 2021 All Rights Reserved.