Summary

1) The basic structure of program execution includes: sequence structure, cycle structure and selection structure

2) IF is suitable for complex logic judgment, “by slice” judgment; Switch is suitable for judging discrete values, judging by multiple branches

3) var in switch applies only to integer values (discrete variables or values)

4) In a switch statement, a break should be added to each case (unless otherwise required). If the case is not broken, the execution will continue from the current case to the next break, even if the var does not meet the following case conditions.

5) Three elements of circular structure:

  • Initialize the loop variable
  • Changes loop variables in the body of the loop
  • Determine cycle conditions

If there is no integer between [2,x] that can divide x (x % I == 0), then x is prime

1. Choose structure

1.1 the if… else …

  • The if statement is used to select the statement to execute according to the condition
  • The else cannot stand alone and always matches the nearest if
  • The else statement can be followed by other if statements
if(condition1)
{
    // statement1
}
else if(condition2)
{
    // statement2    
}
else
{
    // statement3
}

1.2 the switch… case …

  • Switch is a more compact multi-branch selection structure
  • Switch input var can only be an integer value!
  • Note the use of break
  • Multiple cases can be merged together to execute the same statement

2. Cyclic structure

The main structure of loop is while loop, for loop, do while loop. In a loop, you can break out of the loop using the break keyword; Use continue to terminate this loop and enter the next loop immediately.

2.1 the do… while

  • Do is the beginning of the loop and while is the end of the loop
  • do… while(); You can view it as a statement, so you end it with a semicolon
  • do… The while executes the body of the loop at least once

2.2 while

The three elements of the circular structure:

  • Initialize the loop variable
  • Changes loop variables in the body of the loop
  • Determine cycle conditions

2.3 the for

The for loop is a more concise loop structure:

int i = 0;
int sum = 0;
for(i=0; i<=100; i++)
{
    sum += i;
}

2.4 Use a loop to determine if a number is prime

The definition of a prime number x: x is only divisible by 1 and x: The number between [2,x] does not have any integers that can divide x (x % I == 0), then x is prime

bool isPrimeNumber(int x)
{
    bool ret = true;
    int i = 0;
    
    for(i=2; i<x; i++)
    {
        if(x % i == 0)
        {
            ret = false;
            break;
        }
    }
    
    return ret;
}

This paper is summarized from the “C Language Introduction Course” by Tang Zuolin, teacher of “Ditai Software College”. If there are mistakes or omissions, please correct.