当前位置:网站首页>[C language foundation] 04 judgment and circulation

[C language foundation] 04 judgment and circulation

2022-07-06 10:44:00 One reed to sail FP

One 、 Judge

1、if sentence

// form 1: Single execution statement 
if ( Judging expressions )               //")" No semicolon after 
    Execute statement 

// form 2: Multiple execution statements ( Compound statement )
if( Judging expressions ) {
    
	 Execute statement 1
	 Execute statement 2
	...
}                            //"}" There must be no semicolon after 
  • Calculate the relationship between two values , Called relational operators . The following table shows the common relational operators

2、 Relational operator

Operator significance
== equal
!= It's not equal
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
  • There are only two results of relational operation : Integers 1( The result is true ) And integer 0( The result is false ).
  • All relational operators have a lower priority than arithmetic operators , But higher than the assignment operator . To determine whether they are equal == and != The priority of is lower than others , Continuous relational operations operate from left to right .

3、if - else sentence

// form 1: Single execution statement 
if ( Judging expressions )  Execute statement  else  Execute statement 

// form 2: Multiple execution statements ( Compound statement )
if ( Judging expressions ) {
    
	 Execute statement 1
	 Execute statement 2
	...
	} 
else {
    
	  Execute statement 1
	  Execute statement 2
	 ...
	 }

4、if Nesting of statements

if ( Judging expressions 1) {
    
	 Execute statement 
	} if ( Judging expressions 2) {
    
	  	    Execute statement 
	  	   } 
	  else {
    
	   	   Execute statement 
	      }
  • else And the nearest one if matching ;
  • Indent format cannot be in time else The match of ;

Suggest :

  1. stay if and else Always add {}, Even if there is only one execution statement .
  2. A match if and else Position alignment .

5、if Cascade of statements

if ( Judging expressions 1)
	 Execute statement 
else if ( Judging expressions 2)
	 Execute statement 
...
else if ( Judging expressions )
	 Execute statement 
else
	 Execute statement 

6、if Common errors in statements

1、 When executing a compound statement , Forget the parentheses {} .

  • countermeasures : Always in if and else I'll put curly braces after it .

2、if Add a semicolon after . namely :

if ( Judging expressions );    
	   sentence 
// The upper and lower codes are equivalent 
if ( Judging expressions )
	  ;
	   sentence 

3、 Misuse == and =

  • if Only required () The value in is zero ( To judge as false ) Or nonzero ( Judge as true )

4、 Code style.

  • stay if and else Then you must add braces {} Form statement blocks ;
  • In braces {} The statement inside is indented by tab The location of .

7、 Multiple branches switch-case

Format :

switch ( Control expression ) {
                // Control expressions can only be integer values 
	case  Constant expression  :  sentence        // Here " Constant expression " It can be a constant , It can also be a constant calculation expression , for example "2" or "1+1" All possible  
	...
	case  Constant expression  :  sentence 
	default :  sentence 
}

give an example :

switch(type) {
    
	case 1: 
		printf("type = 1");
		break;             // Jump out of judgment 
	case 2:                //"type" Meet the corresponding value , Jump directly to the corresponding case Statement place , Instead of judging from the top to the bottom from the beginning .
		printf("type = 2");
		break;            // Jump out of judgment 
	case 3: 
		printf("type = 3");
		break;            // Jump out of judgment 
	default:              // Other situations 
		printf("type= Other values ");
}

Particular attention : case It only indicates the starting position of the program after judgment , It's just “ entrance ”, Instead of dividing the program into segments . If there is no break Then we will not continue to judge , No matter later case What is the value of the , The program is still executed sequentially . For example, the following procedure :

//  This procedure ,type=1 and type=2 The output is the same , because case 1: There is no break. if case 2 There is no break, Will continue to execute case 3 The following statement . Until I met break or "}" end .
switch(type) {
    
	case 1:
	case 2:
		 sentence 
		break;
	case 3:
		 sentence 
		break;
	default:
		 sentence 
}

Two 、 loop

1、while loop

while Sentence format :

while( Loop judgment expression ) {
    
	 Loop statement 
}

while Cycle flow chart : Please add a picture description

  • The circulatory body should have the opportunity to change the conditions of circulatory judgment , Otherwise, it will become an endless circle .
  • while Cycle means , Keep repeating the sentences inside the loop .
  • while Determine whether to continue the loop before the loop is executed , So it's possible that the loop hasn't been executed .( And do-while Different )
  • The condition is the condition for the cycle to continue .

2、do-while loop

do-while Circular format :

do {
    
	 Loop statement 
} while( Return the loop condition );   // There must be a semicolon here  ( You can think of braces {} Bring your own semicolon )

do-while Cycle flow chart :
 Please add a picture description

  • do-while The cycle will enter the cycle at least once ( And while Different )

Tips:

  1. Note the start and end values of the loop ;
  2. To simulate running a large number of cycles , It can simulate fewer cycles , And then infer ;
  3. Remember to save the original value before calculating , It may be useful later .
  • Decomposition of integers ( How to get the number on each bit of an integer ):
  1. Integers %10, Get single digits ;
  2. Integers /10, Get ten digits ;
  3. Yes 2 Result %10, Get hundreds of digits
  4. ... And so on .
  • ** Find the inverse ordinal number
  • :**
int x, digit;         //digit Is the last digit 
scanf("%d",&x);            // Read the original number 

do {
     
	digit = x%10;           // Get the last digit 
	printf("%d",digit);     // Output the last digit 
	//ret = ret*10 + digit;
	x /= 10;                // Remove the last digit from the original number 
	}while(x!=0);

3、for loop

Format :

for ( expression 1;  expression 2;  expression 3) {
    
	 sentence 
}
// expression 1—— initial ( turn ) Conditions 
// expression 2—— The cycle continues ( Repeat the loop body ) Conditions 
// expression 3—— The last step before the end of each cycle 

above for sentence Equivalent to The following statement :

 expression 1;
while( expression 2){
    
	 sentence 
	 expression 3;
}
  • for Cyclic 3 Expressions can omit one of them .

Tips:3 Seed circulation

  • If there's a fixed number of times , use for loop ;
  • If necessary 1 Time , use do-while loop ;
  • In other cases while loop .

3、 ... and 、 Cycle control

1、 Cycle control

  • break: Out of the loop
    ( Jump out of this cycle completely , Including the current round and the number of subsequent rounds )
  • continue: End the cycle ahead of time
    ( Skip the remaining statements , Go straight to the next round ).

Program examples :

// Program for judging prime numbers 
int x,i;
scanf("%d", &x);
int isPrime = 1;
for(i=2;i<x;i++){
    
	if(x%i == 0){
    
		isPrime = 0;
		break;   // As long as existence can be 1 Divide by numbers other than itself , End cycle 
	}
}
if(isPrime == 1) printf(" Prime number ");
else printf(" Not primes ");

2、 Multiple cycles

(1) A nested loop

  • In each cycle , The variables that control the loop should be different , Otherwise, an error will be reported .

Program examples :

// Program for judging prime numbers 
int x;
for(x=1;x<=100;x++){
    
	int i;
	int isPrime = 1;
	for(i=2;i<x;i++){
    
		if(x%i == 0){
    
			isPrime = 0;
			break;   // As long as existence can be 1 Divide by numbers other than itself , End cycle 
		}
	}
	if(isPrime == 1) printf("%d ",x);
}

(2) Jump out of nested loop

  • break and continue Can only operate on the layer where it is located , When loop nesting exists , The cycle of other layers where it is not located still needs to continue , Will not be skipped .
  • The most appropriate way to jump out of multiple nesting is goto sentence . In other cases, try not to use , Otherwise, the structure of the program will be destroyed , It leads to poor readability .

Method 1 : The relay break

Program examples :

// use 1 horn 、2 Angular sum 5 Horn money , Find a solution 
int x;
int one; two; five;
int exit = 0;  // Judge break Whether to relay variables 
scanf("%d", &x);
for(one = 1;one<=x*10;one++){
    
	for(two = 1;two<=x*10/2;two++){
    
		for(five = 1;five<=x*10/5;five++){
    
			printf("%d Yuan is equal to %d individual 1 horn +%d individual 2 horn +%d individual 5 horn ",x,one,two,five);
			exit = 1;    // If found, change the relay variable 
			break;
		}
		if(exit) break;  // Judge whether to relay 
	}
	if(exit) break;  // Judge whether to relay 
}

Method 2 :goto sentence

The basic structure :

【 Label statement 】 identifier : sentence // Pay attention to the colons
【goto sentence 】 goto identifier ;

Program examples :

for(one = 1;one<=x*10;one++){
    
	for(two = 1;two<=x*10/2;two++){
    
		for(five = 1;five<=x*10/5;five++){
    
			printf("%d Yuan is equal to %d individual 1 horn +%d individual 2 horn +%d individual 5 horn ",x,one,two,five);
			goto out;  //out For the label that jumps out 
		}
	}
}
out:  // Jump out of position , Pay attention to the end of the colon 

3、 Recycling

(1) front n Sum of terms

Program examples :

// seek f(n) = 1-1/2+1/3-1/4+...+1/n
int i,n;
int sign = 1;    // Replace the sign 
double sum=0.;
scanf("%d",&n);
for(i=1;i<=n;i++){
    
	sum += sign*1./i;
	sign = -sign;   // Alternate polarity 
}
printf("f(%d) = %f\n",n,sum);

(2) Integer decomposition

// Integer decomposition : For example, the input 10340, Output 1 0 3 4 0
int x;
scanf("%d",&x);

int mask = 1;  //mask Storage 10 Multiple 
int t = x;
// For different digits x, Find the same number of digits mask. For example, the input 100342,mask=100000
while(t>9){
    
	t /= 10;
	mask *= 10;
}
printf("x=%d, mask = %d", x, mask);
do{
    
	int d = x / mask;
	printf("%d",d);
	if(mask>9){
          //mask The judgment condition of this statement , Instead of x
		printf(" ");
	}
	x %= mask;
	mask /= 10;
}while(mask>0);  //mask The judgment condition of this cycle , Instead of x

(3) Find the greatest common divisor

  1. Enumeration :
int a,b,i;

for(i=1; i<a&&i<b; i++){
    
	if(a%i==0 && b%i==0) ret = i;
}
printf("%d and %d The greatest common divisor of is %d", a,b,ret);

2. division

Ideas :

  • If b be equal to 0, End of calculation ,a Is the greatest common divisor ;
  • otherwise , Calculation a And b The remainder of , Give Way a be equal to b, and b Equal to the remainder ;
  • Back to step one .

Demo code :

// Find the greatest common divisor by division 
int a,b,ret;
scanf("%d %d",&a,&b);
while(b!=0){
    
	ret = a%b;
	a = b;
	b = ret;
}
printf(" The greatest common divisor is %d",a);
原网站

版权声明
本文为[One reed to sail FP]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131657276427.html