(C language path ----- p1: branch and loop)

In reality, the order of things can be summarized into three types

In c language, the running sequence of programs is also divided into several types. One is running from top to bottom, the other is branch structure, and the other is loop structure. The more common one in c language than in real life is goto statement

Next, we will introduce how to use branch statements, loop statements and goto statements to control the sequence of program operation

Branch statement: 1.if statement

                  2.switch statement

Loop statement: 1.while loop

                  2.for loop

                  3.do while loop

goto statement:

1, Branch statement

The first is the if statement of the branch statement:

#include <stdio.h>

//if statements can be divided into single branch statements, double branch statements and multi branch statements


int main()
{
int age = 0;
scanf("%d",&age);//Enter age

//Single branch
if(age<18)
{
   printf("under age\n");
}

//Double branch
if(age<18)
{
   printf("under age\n");
}
else
{
   printf("Adult\n");
}

//Multi branch
if ((age > 0) && (age < 18))
{
    printf("under age\n");
}
else if ((age >= 18) && (age < 40))
{
	printf("Young adults\n");
}
else if ((age >= 40) && (age < 60))
{
	printf("middle age\n");
}
else if ((age >= 60) && (age < 80))
{
	printf("old age\n");
}
else
{
	printf("God of Longevity\n");
}

return 0;
}

Next is the switch statement
 

#include <stdio.h>

int main()
{
int day = 0;
scanf("%d", &day);

//Entering 1 to 5 will output weekday, while entering 6 and 7 will output weeken. Entering other numbers will prompt you to re-enter
//In the switch statement, if there is no break interrupt, the program will continue to go on, so add a break statement as appropriate
//The default clause indicates that the input day is a value other than 1-7, and the program will execute the instructions under the default clause
//The order of default clause and case clause can be disordered, but generally in order. The default clause is generally placed on the last line of the switch statement
switch (day)
{
   case 1:
   case 2:
   case 3:
   case 4:
   case 5:
      printf("weekday\n");
      break;
   case 6:
   case 7:
      printf("weekend\n");
      break;
   default:
      printf("Input error, please enter 1_7 Number between\n");
      break;
}









return 0;
}

2, Circular statement

while statement

int i = 0;
while(i<10)
{
    printf("%d ",i);

    if(5==i)//If i is equal to 5, jump out of the cycle and print 1 2 3 4 6 7 8 9 
    {
        break; 
    }
  
    if(5==i)//If i is equal to 5, end the current cycle and go directly to the judgment section to print 1 2 3 4_ Dead cycle
    {
        continue; 
    }

    i++;

}

for statement

① Grammar

for(Expression 1; Expression 2; Expression 3)
{

Code snippet;
...

}

Expression 1: initialization part, used to initialize loop variables

Expression 2: condition judgment part, which is used to judge when the loop terminates

Expression 3: adjustment part, which is used to adjust the loop condition

Practical problem: print 1 ~ 10 on the screen

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

What are the advantages of a for loop over a while loop?

The initialization part, condition judgment part and adjustment part of the while loop are written separately, which is not centralized and convenient. The three most important parts of a loop are these three parts. The while loop needs to modify these three parts. If there is a large amount of code in the loop body, it will be very difficult. The for loop puts these three parts together, which is very convenient for modification.

The for loop is slightly better, and the for loop is more efficient

② break and continue in the for loop

The break of the for loop is the same as that of continue and while. Its functions are to terminate the loop and skip the current loop to judge directly. However, there are some subtle differences between the continue of the for loop and the while loop

int i = 0;
while(i<10)
{
    printf("%d ",i);

    if(5==i)//If i is equal to 5, end the current cycle and go directly to the judgment section to print 1 2 3 4_ Dead cycle
    {
        continue; 
    }

    i++;

}

int i = 0;
for(i=1; i<=10; i++)
{    
    if(5 == i)
    {
        continue;
    }
    
    printf("%d ",i);    //Print 1 2 3 4 6 7 8 9 10
}

In this example, both loops use the same judgment condition and continue, but produce two different results. The reason is that the continue of the while loop skips the change of the loop condition, while the continue of the for loop does not skip this part

③ Loop control variable for loop

1. Try not to change the loop control variable in the loop body to prevent the loop from losing control

2. The cycle control variable shall be written as close to the left and open to the right as possible, as follows:

for(i=0; i<10; i++)

In this way, we can see at a glance that the number of cycles of this for loop is 10, but if we change to:

for(i=0; i<=9; i++)

In this way, the number of cycles can't be seen at a glance, and I don't understand the meaning of this 9

  do while statement

  grammar

do
{
...
    Code snippet;
...
}while(expression);

The code is executed at least once. The usage scenario is limited and is not very common

3, goto statement

C language provides goto statements that can be abused at will and goto statements that mark jump.

Theoretically, goto statement is unnecessary, because goto statement can change the running order of the program, and this function can be realized by circular statement. Abusing goto statement will disrupt the running order of the program and make the program difficult to maintain. Many programmers use goto statement to avoid thinking and lazy in thinking, which is wrong.

However, the goto statement is not good for nothing. When the loop is embedded many times, you can use the goto statement if you want to jump out of the loop immediately. Jumping out of a multi-layer embedded loop with break is like going down the stairs, while the goto statement directly jumps down, which saves a lot of effort and has little impact on the running sequence of the program.

while()
{
    ...
    while
    {
        ...
        while
        {
            ...
            if(disaster)
            {
                goto quit;
            }
        }    
    }
}
quit:
...

4, Combined application of branch loop goto

① Gets each digit of a binary number

int main()
{
	int a = 0;
	scanf("%d", &a);

	int i = 32;
	for (i = 31; i >= 0; i--)
	{
		printf("%d", (a >> i) & 1);
	}

	return 0;
}

② Inverts an n-digit decimal number

int main()
{
	int a = 0;
	scanf("%d", &a);

	do
	{
		printf("%d", a % 10);	
	} while (a /= 10);

	return 0;
}

③ Empty buffer with loop and getchar

//Please input a password
char arr[20] = "";
scanf("%s",arr);

//Please confirm
char a ='\0';
scanf("%c",&a);

char ch = '\0';

//Empty buffer with loop
while((ch = getchar()) != '\n')
{
    ;
}

//Determine whether the confirmation is successful or failed
if(a == 'Y')
{
    printf("Confirmation successful\n");
}
else if(a == 'N')
{
    printf("Confirmation failed\n");
}
else
{
    printf("Please enter again\n");
}

Keywords: C Back-end

Added by mikkex on Mon, 01 Nov 2021 05:35:38 +0200