当前位置:网站首页>Detailed explanation of C language P2 selection branch statement

Detailed explanation of C language P2 selection branch statement

2022-04-23 14:26:00 KissKernel


Why does circular structure appear , Because life is repeating the same thing day after day , There are similar things , But I can't go back to the beginning anyway . If you want to make new discoveries in every moment of your life , I'm afraid it's just a beautiful vision .
Why does the selection structure appear , Because every day we as like as two peas do not go through the same way. , for example , If it rains today , You have to bring an umbrella .

1. Branch statement

1.1 if sentence

if Basic syntax of statements

if( Judging expressions )// Take branch expression with non-zero result , Otherwise, execute branch 2 ;
{
    
     Branch one ;
}
{
    
     Branch two ;
}

The above is the case of single branch , Of course if Statement can also implement multiple branches as follows :

if( expression )
{
    
     Branch one ;
}
else if ( expression )
{
    
     Branch two ;
}
else
{
    
     Branch three ;
}

Of course, you can write more branches , But when there are many branches, we are used to it switch This statement will be introduced later .
Knowledge point 1: In the air else problem

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

What is the result of printing here ? The answer is “hehe”, So why not ?
there else Not with the first if combination ,else Only with the nearest if combination , This is hanging else problem .
Knowledge point 2:if and else It's actually a statement
The following procedure proves if and else It's actually a statement

#include<stdio.h>

int main()
{
    
    int n=0;
    scanf("%d",&n);
    if(n>0)
        if(n%2==0)
            printf(" The number is even \n");
        else
            printf(" The number is odd \n");
    else
        printf(" The number you entered is not positive ");   
    return 0;             

}

The above code is actually easy to misunderstand , Although there is indentation, it will make people misunderstand , Now let's improve ;

#include<stdio.h>

int main()
{
    
    int n=0;
    scanf("%d",&n);
    if(n>0)
    {
    
        if(n%2==0)
        {
    
            printf(" The number is even \n");
        }
        else
        {
    
            printf(" The number is odd \n");
        }
    }
    else
    {
    
        printf(" The number you entered is not positive "); 
    }
    return 0;
}

In this way, it seems that it is much clearer , In fact, the results of the above two codes are the same , It also shows that , stay c In language if And matching else Taken together as a statement .
Knowledge point 3: Short circuit evaluation problem
In the process of writing branch statements, we will certainly write judgment statements , So short circuit evaluation means :
When using logical and operators, for example :
expression 1&& expression 2
If the expression 1 Your judgment is false , Then the result of the whole expression is false , expression 2 You won't judge again . Of course , It's OK to use it at ordinary times , however
When the expression 2 by st++; There will be problems when this kind of self increasing statement , Because I skipped the expression 2, So the expression 2 The value of will not increase by itself .
The same logic or operator is the same :
expression 1 | | expression 2
If the expression 1 Judge as true , So the expression 2 You won't judge ;

1.2 switch sentence

switch Basic syntax of statements

#include<stdio.h>
int ch=0;
scanf("%d",&ch);

switch(ch)
{
    
    case 1:
    printf("hellow world");
    break;
    case 2:
    printf("hellow world");
    break;
    case 3:
    printf("hellow world");
    break;
    ......
}

among ch Must be an integer constant expression ,case The following must be constants ;
switch in break The role of
There is no break Of switch Statements do not implement multiple branches , Because when ch=1 The program jumps to case 1; Execute the following statement at this tag , encounter break, Jump out of switch sentence , If it were not so break Then continue case 2; Below the label , This is it. break The role of .
switch In the sentence default The role of
Let's write the above program completely :

#include<stdio.h>
int ch=0;
scanf("%d",&ch);

switch(ch)
{
    
    case 1:
    printf("hellow world");
    break;
    case 2:
    printf("hellow world");
    break;
    case 3:
    printf("hellow world");
    break;
    default :
    printf("input is error\n");
    break;
}

If we give ch Input 8, There is no case 8: This tag , Will execute default The code under the statement ;default Can be placed in switch Anywhere in the statement , It's best to put it at the end .


We have finished the above switch Statement and if When to use if When to use switch Well ?
In general , We go through Single expression When controlling program branching , Use switch The effect of the statement is better than if The effect of the statement is better .

2. Loop statement

2.1 while sentence

Let me introduce while Basic syntax , Let's take a look at an example ,
Enter an integer value , Value every number it decrements to zero .

#include<stdio.h>

int main()
{
    
    int n=0;
    scanf("%d",&n);
    while(n>=0)
    {
    
        printf("%d",n);
        n--;
    }
    return 0;
}

This is a very simple while loop , stay while Inside the curly braces is the loop body , After one execution, go up and judge n>=0 If set up , Continue to cycle , until n Less than 0;
Knowledge point 1:while In the loop break

#include<stdio.h>

int main()
{
    
    int n=0;
    scanf("%d",&n);
    while(n>=0)
    {
    
        printf("%d",n);
        n--;
        if(2==n)
        {
    
            break;
        }
    }
    return 0;
}

I modified the above code , If n be equal to 2 When you do it break This will jump directly out of the loop , therefore break The function of is to jump out of while( Pay attention to if while nesting ,break You can only jump one level )
Knowledge point 2:while Medium continue
A new keyword appears here ,continue, The old rule is to look at the code :

#include<stdio.h>
int main()
{
    
    int n=0;
    scanf("%d",&n);
    while(n>=0)
    {
    
        printf("%d",n);
        
        if(2==n)
        {
    
            continue;
        }
        n--;

    }
    return 0;
}

You can stop and think about the execution result of this code
If we type 5, So it prints 5 4 3 2 2 2 2 2······ Then it's a dead cycle , So here continue Is that , End this cycle and jump directly to the judgment part , That is to skip continue Later code , Because the adjustment part is skipped, it causes an endless loop , When actually writing code, you should pay attention to .

2.2 do while sentence

do while, seeing the name of a thing one thinks of its function , Come up and do it first , Anyway, let's start with a cycle , And then judge , If the conditions are met, continue , If you are not satisfied, it will end .
Look at the chestnuts first , Enter an integer to show whether it is odd or even , Then repeat .
Code up !

#include<stdio.h>

int main()
{
    
    int retry=0;
    do
    {
    
        int n=0;
        printf(" Please enter an integer :");
        scanf("%d",&n);
        if(n%2==0)
        {
    
            printf(" even numbers \n");
        }
        else
        {
    
            printf(" Odd number \n");
        }
        printf(" repeat :yes\1  no\0:);
        scanf("%d",&retry);
    }while(retry);
    return 0;
}

As above, execute it first , Then determine whether to continue to repeat . Others and while Similar, I won't repeat much .

2.3 for sentence

for Sentence syntax
Write a program output 0-12 Number between
Go straight to the code

#include<stdio.h>

int main()
{
    
    int n=0;
    for(n=0;n<=12;n++)
    {
    
        printf("%d ",n);
    }
    return 0;
}

Above is for Basic syntax ,n=0; For initialization statements ,n<=12 Is the judgment statement ,n++ To adjust the statement .
Knowledge point 1:for Statement break
Like while The cycle is the same ,for Inside the loop break Will jump out of the loop ;
Knowledge point 2:for Statement continue
Although the role and while Medium continue It's the same, but ,for In the loop continue, It doesn't jump directly to the judgment part of the program , Instead, it jumps to the adjustment part of the program , So subroutines don't appear like ,while The dead cycle in .
Knowledge point 3:for A variation of the cycle
stay for In circulation () The three expressions in can be omitted , If the second expression is omitted, that is, the judgment expression , That would be a dead circle , It is not recommended to omit


Attention should be paid to the use of circular statements , Try not to modify the control quantity of the loop inside the loop , Prevent circulation from getting out of control .

3.goto sentence

About goto, The following passage is me copy Of , Let's just have a look and understand ,goto It's easy to use
C The language provides a language that can be abused at will goto Statement and mark the label of jump .
In theory, goto Statements are not necessary , In practice, there is no goto Statements can also easily write code .
But on some occasions goto Statements are still useful , The most common use is to terminate the processing of structures nested in some depth
cheng .
for example : Jump out of two or more loops at a time .
Multilayer loops are used in this case break You can't achieve your goal . It can only exit from the innermost loop to the upper loop .
Code demonstration :

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

This is it. goto The most common scene , Jump out of multiple nested loops , You can save writing multiple break;


4. Exercises

practice 1
Write code , Demonstrate the movement of multiple characters from both ends , Converging in the middle

#include<stdio.h>
#include<string.h>
#include<Windows.h>
int main()
{
    
    char arr[] = {
     "***************" };
    char brr[] = {
     "hellow world!!!" };
    int sz = strlen(arr);
    int left = 0;
    int right = sz - 1;
    while (left <= right)
    {
    
        arr[left] = brr[left];
        arr[right] = brr[right];
        right--;
        left++;
        printf("%s\n", arr);
        Sleep(1000);

        system("cls");

    }
    printf("%s\n", arr);


    return 0;
}

practice 2
Dichotomy search ( Here is the simplest binary search , The details will be introduced later )

#include<stdio.h>

int main()
{
    
	int arr[] = {
     1,2,3,4,5,6,7,8,9,10 };
	int findnum = 8;
	int left = 0;
	int right = sizeof(arr) / sizeof(arr[0]);
	while (left <= right)
	{
    
		int mid = left + (right - left) / 2;
		if (arr[mid] < findnum)
		{
    
			left = mid + 1;
		}
		else if (arr[mid] > findnum)
		{
    
			right = mid - 1;
		}
		else
		{
    
			printf(" eureka , Subscript to be  %d ", mid);
			break;
		}
	}

	return 0;
}

practice 3
Guess the number game

#include<stdio.h>
#include<time.h>
void menu()
{
    
	printf("***********************\n");
	printf("****** 1 play ******\n");
	printf("****** 0 exit ******\n");
	printf("***********************\n");

}

void play()
{
    
	int ret = rand()%100;
	while (1)
	{
    
		printf(" Please start guessing numbers !\n");
		int sc = 0;
		scanf("%d", &sc);
		if (sc < ret)
		{
    
			printf(" Guess a little \n");
		}
		else if (sc > ret)
		{
    
			printf(" Guess the \n");
		}
		else
		{
    
			printf(" congratulations , Guessed it !!!\n");
			break;
		}

	}
}

int main()
{
    
	srand((unsigned int)time(NULL));
	int input = 0;

	do
	{
    
		menu();
		scanf("%d", &input);
		if (input == 1)
		{
    
			play();
		}
	} while (input);
	return 0;
}

practice 4
Shut down the applet , use goto Statements for

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    
	char arr[10] = {
     0 };
	system("shutdown -s -t 60");
again:
	printf(" Please enter that I am a pig , Otherwise your computer will be 60s Internal shutdown \n");
	printf(" Please enter :");
	scanf("%s", &arr);
	if (0==strcmp(arr," I am a pig "))
	{
    
		printf(" Cancel shutdown \n");
		system("shutdown -a");
	}
	else
	{
    
		goto again;
	}

	return 0;
}

版权声明
本文为[KissKernel]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231412251851.html