Part 3 of Learning C in Details: Branches and Loops

Article directory

  • 1.If and switch statements implement branching
    • 1.1if statement
      • 1.1.1 Grammatical form of if statement
      • 1.1.2 Examples of using nested if
      • 1.1.3 The hanging else problem
    • 1.2 Operators
    • 1.3switch statement
  • 2.Three types of loop statements: while, for, do…while
    • 2.1while loop
    • 2.2for loop
    • 2.3do-while loop
  • 3.break and continue statements
    • Take break and continue in the while loop as an example
  • 4.goto statement

1.if and switch statements implement branching

1.1if statement

1.1.1 Grammatical form of if statement

if(expression)
   {<!-- -->Statement 1
   ...
   }//Use {} after if to control multiple statements - this block is also called: program block, or compound statement
  else if
   Statement 2
   ...
  else
   Statement 3

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

1.1.2 Examples of using nested if

practise:
1. Enter a person’s age
2. If the age is <18, print Juvenile’
3If you are between 18 and 44 years old, print ‘youth’
4If you are between 45 and 59 years old, print middle-aged’
5If the age is between 60 and 89 years old, print elderly’
6If you are over 90 years old, print 老生星’

#include<stdio.h>
int main()
{<!-- -->
int age = 0;
scanf("%d", & amp;age);
if (age < 18)
printf("Youth\
");
else
{<!-- -->
if (age < 45)
printf("Youth\
");
else {<!-- -->
if (age < 60)
printf("middle-aged and elderly\
");
else {<!-- -->
if (age <= 90)
printf("elderly\
");
else
printf("Old birthday star\
");
}
}
}
return 0;//It is easier to understand with braces
}

1.1.3 hanging else problem

If there are multiple if and else, you can remember a rule: else always matches the closest if

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

The above code layout aligns else with the first if statement, which makes us think that else matches the first if. When the if statement is not established, the subsequent else statement will naturally be executed and print haha
But in fact, else matches the second if statement, so that the subsequent if…else statement escapes in the first if statement. If the first if statement does not hold, nested if and else will have no chance to execute, and nothing will be printed in the end.

1.2 Operator

Relational operators: >, <, >=, <=, ==, !=
Conditional operator: exp1 ? exp2 : exp3
Logical operators: & amp; & amp;, ||, !
Logical negation operator: If flag is true, !flag is false, if flag is false, !flag is true.
Exercise: Determining leap years:
1. It is a leap year if it is divisible by 4 and not divisible by 100.
2. If it is evenly divisible by 400, it is a leap year.

#include<stdio.h>
int main()
{<!-- -->
int year = 0;
scanf("%d", & amp;year);
if ((year % 4 == 0 & amp; & amp; year % 100 != 0) || year % 400 == 0)
printf("It's a leap year");
return 0;
}

**Short-circuit evaluation:** An 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.

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

1.3switch statement

· The expression after switch must be an integer expression
· The value after case must be an integer constant expression, and there must be a space between case and the following number.
· After the code in each case statement is executed, a break needs to be added to jump out of the switch statement.

switch (expression) {<!-- -->
case value1:statement
case value2:statement
default:statement//When the value in the expression cannot match the case statement
}

Exercise: Print out the corresponding days
1. Enter 1-5, the output is “working days”
2. Enter 6-7 and output “rest day”

#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("working day\
");
break;
case 6:
case 7:
printf("rest day\
");
break;
}
return 0;
}//According to the actual situation, determine whether break needs to be used in the code, or where to use break, in order to correctly complete the actual requirements.

2. Three loop statements of while, for, do…while

2.1while loop

Grammar form:

while (expression)
 {<!-- --> Statement 1;
 ...}//Braces make the loop body contain more statements


Exercise: Enter an integer and print each digit of the integer in reverse order
1.To get the lowest digit of n, you can use n operation, and the remainder is the lowest digit, such as: 1234 gets 4
2.If you want to remove the lowest bit of n and find the penultimate digit, you can use n=n/10 operation to remove the lowest bit, for example: n = 1234/10 to get 123, 123 phase Compared with 1234, the lowest digit is removed, and 123 gets the penultimate digit 3.
3. Loop through steps 1 and 2, and get all the bits before n becomes 0.

#include<stdio.h>
int main()
{<!-- -->
int n = 0;
scanf("%d", & amp;n);
while(n)
{<!-- -->
printf("%d", n % 10);//Use to get the last digit
n /= 10;//Use /10 to remove the last digit
}
return 0;
}

2.2for loop

The for loop is the most commonly used among the three types of loops. The syntax of the for loop is as follows:

for(expression1;expression2;expression3)

Expression 1 is used to initialize loop variables
Expression 2 is used to determine the loop end condition
Expression 3 is used to adjust loop variables
The three expressions of initialization, judgment and loop in the for loop can be omitted, but if the judgment part is omitted, it will always be true

Note: For and while have three parts: initialization, judgment and adjustment in the process of implementing the loop. However, the three parts of the for loop are very concentrated, which facilitates the maintenance of the code. If there is a lot of code, The three parts of the while loop are relatively scattered, so the for loop is better in form.
Exercise: Calculate the sum of numbers that are multiples of 3 between 1 and 100

#include<stdio.h>
int main()
{<!-- -->
int i = 0;
int sum = 0;
for (i = 3; i <= 100; i + = 3)
{<!-- -->
sum + = i;
}
printf("%d\
", sum);
return 0;
}

2.3do-while loop

Among the loop statements, the do…while statement is the least used, and its syntax is as follows:

do
{<!-- --> statement;}
while (expression)

Both while and for loops are judged first, then enter the loop when the condition is met, execute the loop statement, and jump out of the loop if the condition is not met.
The do…while loop first directly enters the loop body, executes the loop statement, and then executes the judgment expression after the while. If the expression is true, it will proceed to the next time. If the expression is false, the loop will not continue.
So the do…while statement is executed at least once in the loop, which is really a special thing about the do…while loop

Exercise: Enter a positive integer and calculate the number of digits in this integer

#include<stdio.h>
int main()
{<!-- -->
int n = 0;
scanf("%d", & amp;n);
int cnt = 0;
do
{<!-- -->
cnt + + ;
n /= 10;
} while (n);//Note that this place requires one;
printf("%d\
", cnt);
return 0;
}

3.break and continue statements

During the execution of the loop, if certain conditions occur, the loop needs to be terminated early. This is a very common phenomenon. The C language provides two keywords, break and continue, which should be used in loops.
· break is used to permanently terminate the loop. As long as break is executed, it will jump out of the loop and continue execution.
The function of ·continue is to skip the code after continue in this loop, which is different in the for loop and the while loop.

Take break and continue in the while loop as an example

break in while loop

#include<stdio.h>
int main()
{<!-- -->
int i = 1;
while (i <= 10)
{<!-- -->
if (i == 5)
break;//The function of break is to skip the loop, executed when i=5, and the loop terminates
printf("%d", i);
i = i + 1;
}
return 0;
}//The result is 1234

continue in while loop

#include<stdio.h>
int main()
{<!-- -->
int i = 1;
while (i <= 10)
{<!-- -->
if (i == 5)
continue;//When i equals 5, execute continue, directly skip the continue code, and go to the loop judgment point
//Because i=i + 1 is skipped here, i is always 5, and the program falls into an infinite loop.
printf("%d", i);
i + = 1;
}
return 0;
}//The result is still 1234

Note: The break and continue in the for loop are actually the same as the break in the while loop. The break in the for loop is also used to terminate the loop. No matter how many times the loop needs to loop, as long as the break is executed, the The fight will be completely terminated.
The functions of break and continue in the do…while statement are almost identical to those in the while loop.

4.goto statement

C language provides a very special syntax, which is the goto statement and jump label.
The goto statement can jump to the set label within the same function.

#include<stdio.h>
int main()
{<!-- -->
printf("hehe\
");
goto next; //This is a semicolon
printf("haha\
");

next:
printf("Skip the printing of haha\
");
return 0;
}

If the goto statement is used improperly, it will cause random jumps within the function and disrupt the execution flow of the program. Therefore, it is recommended not to use it as much as possible;
But the goto statement is not useless. In multi-layer loop code, if you want to jump out quickly, it is very convenient to use the goto statement.