Branch and loop statements of C Forum

Keywords: C

Hello, everyone. Today I'll take you to know the loop and branch statements in C language
(compiler: VS2019)


-------------

1, What is a sentence?

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

What the blogger will share with you this time is our control statement
Control statements are used to control the execution flow of the program to realize various structural modes of the program. They are composed of specific statement definer. There are nine control statements in C language.
It can be divided into the following three categories:

  1. Conditional judgment statements are also called branch statements: if statements and switch statements;
  2. Circular execution statements: do while statement, while statement and for statement;
  3. Turn statements: break statements, goto statements, continue statements, and return statements.

2, Branch statement (select structure)

2.1 if statement

Structure of if statement

1.if(expression)
      sentence;
2.if(expression)
      Statement 1;
  else
      Statement 2;
3.//Multi branch
  if(Expression 1)
      Statement 1;
  else if(Expression 2) //You can also directly if
      Statement 2;
  else
      Statement 3;    

give an example

//Code 1
#include <stdio.h>
int main()
{
 int age = 0;
    scanf("%d", &age);
    if(age<18)
   {
        printf("under age\n");
        //Single branch statements can omit {}
   }
}
//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 multi branch if statement
#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 if(age>=80 && age<100)
    {
        printf("God of Longevity\n");
    }
    else if(age>=100)
    {
        printf("Immortal\n");
    }        

When the condition holds and multiple statements need to be executed, these statements need to be placed in the code block
(a {} is a code block)

2.1.1 suspended else

Let's take a look at the result of 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;
}

You may think that the expression in the first if statement is judged to be false, so you will not enter the second if statement and directly jump to the else statement to print haha. That is, the final running result will print haha on the screen.

But the actual operation is

Nothing there?

This is because the else matching conforms to a principle: the else statement matches the nearest if, so after judging that the expression in the first if statement is false, return 0 directly; So nothing was printed

After change

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

After the change, we can clearly see the running results, which also reminds us to pay attention to the format style when typing the code to avoid confusion caused by similar situations.

2.2 switch statement

The switch statement is also a branch statement.
It is often used in the case of multiple branches.
If we want to print
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
The form of using if... else if... else if... else... Will be very complex and troublesome.
At this time, we can use the switch statement.

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

Combined with the above examples, we can better understand the grammatical form of switch statements.

switch(Integer expression)
{
      Statement item;
}

And what are statement items?

//Are some case statements:
//As follows:
case Integer constant expression:
    sentence;

And what is an integer constant expression?

Integer constant expression means that the operands in the expression are of integer type. The integer type here is not only int type, but also char, (unsigned) short, (unsigned) long and other types. The value of the operand in the integer constant expression has been determined at compile time.

Therefore, you only need to pay attention to which values are determined at compile time. This includes the following cases:

  1. Single character, such as' a ',' a '
  2. Single integer numbers and expressions composed of integer numbers, such as 123, 123 + 345
  3. enumeration constant
  4. There is a value returned by sizeof operation, such as sizeof(int)
  5. NULL pointer value
  6. Address constant, such as 0X12345678, and address constant plus an offset

2.2.1 break in switch statement

In the switch statement, we can't directly implement the branch. Only when we use it with break can we realize the real branch.
Take the code that just output the day of the week as an example:

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


Without a break statement, the output after entering 1 is Monday to Sunday, which is different from the expected Monday. This is the function of the break statement.
The actual effect of the break statement is to divide the statement list into different branch parts
(it will not stop until it encounters a break after completing the corresponding branch)

2.2.2 default clause

What happens when the value we enter does not match the value of all case tags?

In fact, it's nothing. As a result, all statements are skipped.
The program will not terminate or report an error, because this situation is not considered an error in C language. 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 write the following label default: Where any case label can appear. When switch
When the value of the 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.

#include <stdio.h>
int main()
{
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:printf("Today is Monday\n"); break;
	case 2:printf("Today is Tuesday\n"); break;
	case 3:printf("Today is Wednesday\n"); break;
	case 4:printf("Today is Thursday\n"); break;
	case 5:printf("Today is Friday\n"); break;
	case 6:printf("Today is Saturday\n"); break;
	case 7:printf("Today is Sunday\n"); break;
	default:printf("Output error, please re-enter\n");break;
	}
	return 0;
}

This time, when we enter a value that does not match the value of the case tag
"Output error, please re-enter" will be printed on the screen
At this time, some people may wonder whether the break after the default clause is necessary?
As mentioned above, the default clause can appear anywhere in the statement list.
When we remove the break after default and put it in the first row.

We found that after entering a mismatched value, it didn't end until we finished printing "today is Monday"

Summary: that is to say, if we put the default clause on the last line of the statement item, we can omit break. However, if we want to put the default clause in another position, we should pay attention to adding break after it to avoid errors.

2.2.3 small exercises

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

n=1 m=2 - > enter the switch statement n=1 execute case 1 - > m = 3 no break execute case 2 - > n = 2 m = 3 no break enter case 3 - > execute case 2 m=4 n=3 break jump out of the second switch statement no break - > execute case 4 m=5 n=3 jump out of the print result in case of a break.

That is, the final result is m = 5, n = 3

3, Circular statement

3.1 while loop

We have learned about the if statement. When the conditions are met, the statement after the if statement will be executed, otherwise it will not be 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.

Execution process of while statement:

(Note: the number of times to enter the loop condition in the while statement is more than the number of times to enter the loop body)

Example: print 1 ~ 10 numbers on the screen

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

From the above code, we can get the basic syntax of the while statement

while(expression)
      sentence;
The expression is a loop condition and the statement is a loop body.

3.1.2 function of break and continue in while statement

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


We can see that when i=5, we jump out of the loop directly
Summary:
The role of break in the while loop:
When a break is encountered in a loop, all subsequent loops are stopped and the loop is terminated directly.
So: break in while is used to permanently terminate the loop
Next, we will replace break with continue
continue example 1

You can see that the final result is 1 2 3 4, but it is still not over, and the process becomes an endless loop

When i=5, the continue statement directly skips the remaining executed statements and returns to the next cycle condition determination. Because i is still equal to 5 and meets the condition determination of the if statement, the continue statement enters the dead cycle again.

continue example 2

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

Observe the result of example 2. When i=5, skip the remaining unexecuted statements, re-enter the loop determination condition, and print from 6 to 10.

Summary:
The function of continue statement is to skip the remaining unexecuted statements in the body of this cycle and immediately determine the next cycle condition. It can be understood as only ending this cycle.
Note: the continue statement does not terminate the entire loop.

3.2 for loop

for(Expression 1; Expression 2; Expression 3)
    Circular statement;

Expression 1 is the initialization part, which is used to initialize the of the loop variable.
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.
Example

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

Loop flow chart of for statement:

Let's compare the difference between the while loop and the for loop.

#include <stdio.h>
int main()
{
    int i = 1;
   //Initialization part
  while(i<=10)//Judgment part
  {
   printf("%d ",i);
   i = i+1;//Adjustment part
  }
  printf("\n");
  //Achieve the same function, for
  for(i=1; i<=10; i++)
  {
  printf("%d",i);
  }
}

It can be found that when some functions are implemented, there are still three necessary conditions for the loop in the while loop, but it is obvious that using the for statement is more concise and more convenient to modify and find. This is why the for loop is used most frequently in the loop.

3.2.1 break and continue functions in the 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;
}

Recommendations:

  1. Loop variables cannot be modified 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 in "closed before open interval".
int i = 0;
//Front closed and back open
for(i=0; i<10; i++)
{}
//Both sides are closed intervals
for(i=0; i<=9; i++)
{}

3.2.2 some variants of the for loop

#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 problems. If the judgment part in the middle is omitted, it means that the judgment is always true, which constitutes a dead cycle.
//Code 2
    int i = 0;
    int j = 0;
    int count=0;
    //How many hehe are printed here?
    for(i=0; i<10; i++)
   {
        for(j=0; j<10; j++)
       {
         printf("hehe\n");
       }
       printf("Total print%d second",count);//Check the printing times with count
   }
   

After running, 100 lines hehe, count=100 are printed on the screen, so after entering the first for loop, the nested for loop is used as the loop body of the first for loop, so a total of 100 times are printed.

  //Code 3
  	int i = 0;
	int j = 0;
	int count = 0;
	//If the initialization part is omitted, how many hehe are printed here?
	for (; i < 10; i++)
	{
		for (; j < 10; j++)
		{
			printf("hehe\n");
			count++;
		}
	}
	printf("The number of times to print is%d", count);

3.3 do... while loop

do
 Circular statement;
while(expression);

Loop flow chart of do... while

Characteristics of do... while loop: the loop is executed at least once
Example

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

3.3.1 break and continue in do... while loop

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

3.4 goto statement

C language provides goto statements that can be abused at will and labels that mark jump.
In theory, goto statement is not necessary. In practice, it is easy to write code without goto statement.
However, goto statements are still useful in some situations. The most common usage is to terminate the processing process of the program's deeply nested structure.
For example: jump out of two or more layers of loops at a time.
In the case of multi-layer loops, it is not possible to use break. It can only exit from the innermost loop to the upper loop.
goto language is really suitable for the following scenarios:

for(...)
    for(...)
   {
        for(...)
       {
            if(disaster)
                goto error;
       }
   }
    ...
error:
 if(disaster)
         // Handling error conditions

4, Practice

1. Judge whether a number is odd

#include <stdio.h>
int main()
{
	int n = 0;
	printf("Please enter:>");
	scanf("%d", &n);
	if (n % 2 == 1)

	{
		printf("%d It's an odd number\n", n);
	}
	else
	{
		printf("%d It's an even number\n", n);
	}
	return 0;
}

2. Output an odd number between 1 and 100

//Output odd numbers between 1 and 100
#include <stdio.h>

int main()
{
	int i = 0;
	for (i = 1; i <= 100; i++)
	{
		if (i % 2 == 1)
		{
			printf("%d ", i);
		}
	}
	return 0;
}

3. Input two integers and operators, and output the operation result after operation

//Input two integers and operators, and output the operation result after operation
#include <stdio.h>
int main()
{
	int a = 0;
	int b = 0;
	char c = 0;
	scanf("%d%c%d", &a, &c, &b);
	switch (c)
	{
	case '+':printf("%d\n", a + b); break;
	case '-':printf("%d\n", a - b); break;
	case '*':printf("%d\n", a * b); break;
	case '/':
		if (b == 0)
			printf("Divisor cannot be 0");
		else
			printf("%f", a * 1.0 / b);
		break;
	case '%':printf("%d\n", a % b); break;
	default:printf("Output error\n"); break;
	}
	return 0;
}

4. Calculate the factorial of n

#include <stdio.h>
int main()
{
	int n = 0;
	int i = 0;
	int ret = 1;//Create a variable to produce a cumulative effect
	scanf("%d", &n);
	for (i = 1; i <= n; i++)
	{
			ret = ret * i;
	}
	printf("%d\n",ret);
	return 0;
}

5. Calculate 1+ 2!+ 3!+……+ 10!

//Sum of factorials
#include <stdio.h>
int main()
{
	int n = 0;
	int i = 0;
	int ret = 1;//Create a variable to produce a cumulative effect
	int sum = 0;
	for (n = 1; n <= 10; n++)
	{
		ret = 1;
		for (i = 1; i <= n; i++)
		{
			ret = ret * i;
		}
		sum += ret;
	}
	printf("%d\n", sum);
	return 0;
}

6. Write code to simulate the user login scenario, and can only log in three times. (you are only allowed to enter the password three times. If the password is correct, you will be prompted that the login is successful. If you enter the wrong password three times, you will exit the program.)

#include <stdio.h>
#include <string.h>
int main()
{
	int i = 0;
	char password[20] = "";
	//Suppose the password is 123456
	for (i = 0; i < 3; i++)
	{
		printf("Please input a password:>");
		scanf("%s", password);//password is the array name and does not require an address
		if (strcmp(password, "123456") == 0)//Compare whether two strings are equal. Cannot = =. Use the function strcmp
		{
			printf("Login succeeded\n");
			break;
		}
		else
		{
			printf("Password error\n");
		}
	}
	if (i == 3)
	{
		printf("The password has been wrong for more than three times, and the login failed\n");
	}
	return 0;
}

Posted by datoshway on Mon, 22 Nov 2021 22:15:35 -0800