Branch and loop

C language is a structured programming language

1. Sequential structure
2. Select structure
3. Cyclic structure
 These three structures are the three structures existing in life.

Sequential structure is the downward execution of sentence by sentence

Select structure -- > branch statement

  • if
  • switch

Loop structure -- > loop statement

  • while
  • do while
  • for

Branch statement

if
// Type I
if (condition){
	sentence;
}

// Type II
if (condition){
    sentence;
}else{
    sentence;
}

// Category III
if (condition)
    sentence;
else if(condition)
    sentence;
else
    sentence;
// If more statements are executed, {}

You can nest {} to represent a code block - for readability, it is generally recommended to add {}

Suspended else

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

The result is empty; Else's proximity principle, so (a==1) incorrect code ends. The suspended else and (b==2) are a group.

switch ---- often used for multi branch
switch(Integer expression){
        Statement item;
}
//Statement items are case statements
case integral constant expression :sentence;

int main(){
    int nowDay=0;
    scanf("%d",&nowDay);
    switch(nowDay){  // nowDay must be an integer constant. Expressions such as float 1.0 are not allowed
        case 1:    // case must also be followed by integer constant expression. float 1.0 and other expressions are not allowed
            printf("It's Monday\n");
            break;
        case 2:
            printf("It's Tuesday\n");
            break;
        case 3:
            printf("It's Wednesday\n");
            break;
        case 4:
            printf("It's Thursday\n");
            break;
        case 5:
            printf("It's Friday\n");
            break;
        case 6:
            printf("It's Saturday\n");
            break;
        case 7:
            printf("It's Sunday\n");
            break;
    }
}

int main(){
    int nowDay=0;
    scanf("%d",&nowDay);
    switch(nowDay){  
        case 1:    
        case 2:
        case 3:
        case 4:
        case 5:
            printf("It's a working day\n");
            break;
        case 6:
        case 7:
            printf("It's a rest day\n");
            break;  // The good habit of programming is best added, and the plasticity will be very good
        default:   //When all conditions are not met, the execution can be written anywhere in the switch
            printf("Input error\n");
            break;
    }
}

Case just enters and leaves, which is managed by break. Add a break statement after the last case statement.

default is optional. If it exists, it is generally illegal.

As long as there is no break in the switch statement, it will be executed downward.

Circular statement

while
while(The expression is true){
    Execute statement;
}
//You can use break when you want to jump out

episode

int main(){
    int ch = 0;
    while((ch=getchar()) != EOF){  //getchar() gets the value in the keyboard and enters the function
        putchar(ch);			//putchar() prints the value on the display and outputs the function
    }							//EOF is the end of file - > - 1
    return 0;
}

break

End the loop and terminate all the contents of the loop.

continue

This cycle ends and goes directly to the next cycle. That is, the code after continue in this loop is no longer executed, but directly jumps to the judgment part of the while statement. Judgment of the entrance to the next cycle.

for
// When using while, if the amount of code is large, the whole is messy
 Initialization content
    ...
while(Conditional judgment){
    Execute statement
        ...
    Adjustment statement
        ...
}
// The for loop was born
for(Expression 1;Expression 2;Expression 3){
    Circular statement;
}
Expression 1 is the initialization part, which is used to initialize the loop variable, and expression 2 is the condition judgment part, which is used to judge when the loop terminates. Expression 3 is the adjustment part, which is used to adjust the loop conditions.

for recycling recommendations

Loop variables cannot be modified within the for loop to prevent the for loop from losing control. Can be written in expression 3.

It is suggested that the value of the loop control variable of the for statement should be written as "closed before open interval".

Changes in the for loop

All three expressions of the for loop can be omitted, but if the judgment part is omitted, it will always be true.

do while
do{
    Circular statement;
}while(expression);

Features: first execute a circular statement.

practice
  1. Calculate the factorial of n
int main(){
    int n;
    int res=1;//Factorial
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        res = res*i;
    }
    printf("res = %d",res);
}
  1. Calculate 1+ 2!+ 3!+…+ 10!
int main(){
    int sum = 0;
    //Control 10 times and
    for(int n=1;n<=3;n++){
        //The factorial should res start at 0 each time
        int res=1;//Factorial
        for(int i=1;i<=n;i++){
            res = res*i;
        }
        sum+=res;
    }
    printf("sum = %d",sum);
}
  1. Find a specific number N in an ordered array. Write int binsearch(int x,int v[],int n); Function: find X in the array of v [0] < = v [1] < = v [2] < =... < = v [n-1].
//It can be traversed, but there is no progress. The binary search is used here
int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int find = 7;
    int sz = sizeof(arr) / sizeof(arr[0]);
    int left = 0;			//Left subscript
    int right = sz - 1;		//Right subscript
    while (left <= right) {      //Conditions for binary search
        int mid = (left + right) / 2;
        if (arr[mid] > find) {
            right = mid - 1;
        } else if (arr[mid] < find) {
            left = mid + 1;
        } else {
            printf("Yes, the subscript is:%d", mid);
            break;    
        }
    }
    if (left>right){     // If this is the case because it doesn't jump out
        printf("I can't find it!\n");
    }
    return 0;
}
  1. Write code to demonstrate that multiple characters move from both ends and converge to the middle.
//Print hello for example
//#####
//h###o
//he#lo
//hello
#include <string.h>
#include <windows.h>
#include <stdlib.h>

int main() {
    char arr1[] = "hello world!";   //Later, it can be changed to keyboard input
    char arr2[] = "************";   //Later, you can calculate the length of arr1 and generate such a string
    int left = 0;
    int right = sizeof(arr1) / sizeof(arr1[0]) - 2;  // Because the length is obtained and there is an end flag of "\ 0", 2 should be subtracted here
    // int right = strlen(arr1)-1;    // Use the function to get the length. At this time, you only need - 1
    while (left <= right) {
        arr2[left] = arr1[left];
        arr2[right] = arr1[right];
        printf("%s \n", arr2);
        Sleep(500);    //Take a second off
        system("cls");       //#include <stdlib. h> Function in, execute the system command "cls"
        left++;
        right--;
    }
    return 0;
}
  1. Write code to simulate the login scenario, and you 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 to log in. If the password is wrong three times, you will exit the program)
#include <string.h>
int main() {
    int i = 3;
    char password[20] = {0};
    for (i = 0; i < 3; i++) {
        printf("Please input a password:");
        scanf("%s", password);
        if (strcmp(password, "123456") == 0) {   
            //The double equal sign cannot be used to compare the equality of two strings. The library function - strcmp should be used. If it is the same, the return value is 0
            //If the left is greater than the right, the number greater than 0 is returned, and the number less than 0 is returned, which is equal to 0
            printf("Login succeeded\n");
            break;
        } else{
            printf("Wrong password!\n");
        }
    }
    if (i == 3) {
        printf("Incorrect password input for three times, exit the program");
    }
    return 0;

goto Statement

int main(){
    printf("hhh");
    goto A;
    printf("hhh123");
    A:
    printf("xxx");
    return 0;
}

goto statements are generally used to jump out of deep loops

A shutdown program

#include <stdlib.h>
#include <string.h>

int main() {
    char input[20] = {0};
    //shutdown -s -t 60
    //system() - a function that executes system commands
    system("shutdown -s -t 60");    //Need #include < stdlib h>
    again:
    printf("Please note that your computer will shut down in 1 minute. Enter here\"I'm a pig.\"I can cancel the shutdown\nplease input:");
    scanf("%s", input);
    //C language can not be equal directly, so it needs the help of function
    if (strcmp(input, "I'm a pig.")) {//Expected #include < string h>
        system("shutdown -a");
    } else {
        goto again;
    }
    return 0;
}
//May not be applicable to goto implementation
int main() {
    char input[20] = {0};
    //shutdown -s -t 60
    //system() - a function that executes system commands
    system("shutdown -s -t 60");   
    while (1) {
        printf("Please note that your computer will shut down in 1 minute. Enter here\"I'm a pig.\"I can cancel the shutdown\nplease input:");
        scanf("%s", input);
        if (strcmp(input, "I'm a pig.")) {
            system("shutdown -a");
            break;
        }
    }
    return 0;
}

Keywords: C Back-end

Added by Transmission94 on Mon, 27 Dec 2021 19:37:50 +0200