1 basic cycle structure
- The cycle structure generally consists of two parts:
- Cycle condition: determines whether to enter or exit the cycle. When satisfied, enter the next cycle, otherwise exit the cycle.
- Loop body: the operation performed for each round of loop, usually consisting of a sequence of statements.
- Three cycle structures
- while statement
- do... while statement
- for statement
1.1 while statement
while() loop
while: Loop control variable initialization while(Cycle termination condition) { Circulatory body Cyclic control variable increment }
Cycle execution steps:
- First, initialize the loop control variable (before while);
- Second, judge the cycle termination condition. If the judgment result is true, enter the third step; If false, the loop body is not executed;
- Third, execute the loop body;
- Fourth, execute the increment of loop control variable and go to step 2;
- example
int main() { int i = 1, sum = 0; while (i <= 100) { sum += i; i += 1; } printf("The result is%d\n", sum); return 0; }
- matters needing attention:
- And variables, the initial value is 0! If sum does not have an initial value of 0, it will be randomly assigned to sum.
- When there is more than one statement in the loop body, it is enclosed in curly braces.
- There must be a statement to change the value of "loop condition expression" in the loop body (such as i + +)
1.2 do... while loop
do while: Loop control variable initialization do { Circulatory body Cyclic control variable increment }while (Cycle termination condition);
- Cycle execution steps:
- First, initialize the loop control variable (before do while);
- Second, execute the loop body;
- Third, execute cyclic control variable increment;
- Fourth, judge the cycle termination condition. If the judgment result is true, return to step 2; If false, exit the cycle directly;
- matters needing attention:
Pay special attention to do... While(), that is, the semicolon after while() cannot be less
In general, when using the while() statement and do... while() statement to deal with the same problem, if the loop body and conditional expression of both statements are the same, their results are the same. However, when the conditional expression after while is 0 at the beginning (that is, the expression does not hold), the results of the two loops are different.
1.3 for statement
for Cycle: for (Loop control variable initialization; Cycle termination condition; Cyclic control variable increment) { Circulatory body }
- Cycle execution steps:
- First, initialize the loop control variable first;
- Second, execute the loop termination condition. If the judgment result is true, enter the third step; if it is false, the loop terminates and exits;
- Third, execute the loop body;
- Fourth, execute the increment of loop control variable and go to step 2;
- Examples
#include <stdio.h> int main(void) { int S = 0, i, n; printf("Please enter n Value of:"); scanf("%d", &n); for ( i = 1; i < n; i++) { S += i; } printf("S=%d\n", S); }
About omission:
- Expression 1 omitted: expression 1 is placed before the for loop
i=1;
for( ; i<=100 ;i++)
- Omitting expression 2: it is equivalent to that the loop termination condition is always true. Unless there is a break in the loop body, it is easy to die
for(i=1; ;i++) S=S+i;
- Omit expression 3: expression 3 is used as an embedded statement
for(i=1; i<=100 😉
{
S=S+i;
i++;
}
- Expressions 1 and 3 are omitted:
- All three expressions can be omitted:
- Other operations appear in expressions 1 and 3
Note: except for the loop termination conditions, the other two parts of the for loop () can be omitted, but in the standard for loop, the initialization and increment of the loop control variables should be placed in (), and the loop control variables should never be changed in the loop body;
1.4 comma expression
The value of each expression is calculated from left to right, and the value of the last expression is taken as the value of the whole comma expression.
2 selection of cycle
- Counter Controlled Loop
- Number of cycles known - for
- Condition Controlled Loop
- Loop conditions are known - while, do... While
- The three kinds of sentences can replace each other, but who can use them more conveniently
2.1 cycle of counting control
- Factorial
Cycle number determination n - > select for cycle
#include <stdio.h> int main() { int i,n; double M = 1; /*Because of factorial, M is defined as double precision, and the integer is not large enough*/ printf("Please enter n Value of:\n"); scanf("%d", &n); for( i = 1;i <= n;i++) { M = M * i; } printf("%d! = %f\n", n, M); return 0; }
- Sum of factorials
- Fibonacci sequence
#include <stdio.h> int main() { int f1 = 1, f2 = 1, f , i, k=0; /*The value of the first two items is fixed to 1*/ printf("%d\t %d\t", f1, f2); /*The first two items of the output sequence*/ k = k+2; /*It is unnecessary to set k as a counter. 2 items have been output*/ for( i = 3;i <= 30;i++) /*Calculate items 3 to 30*/ { f = f1 + f2; /*Each term is equal to the sum of the first two terms*/ printf("%d\t", f); /*Output the currently calculated item f */ k++; /*Another term is output, k increases by 1 */ if ( k%5 == 0) /*If the current output item is a multiple of 5*/ printf("\n"); /*Output newline*/ f1 = f2; /*f1 Take the value of the previous f2*/ f2 = f; /* f2 Take the value of the previous f */ } printf("\n"); /*After the sequence is output, the newline character is output*/ return 0; }
2.2 cycle of condition control
- A rectangular board is 56 cm long and 40 cm wide. If it is cut into several squares of the same size, the side length will be the whole centimeter and there is no residue. What is the maximum side length of the cut square?
- Exhaustive algorithm (the maximum side length of the cut square is the maximum common divisor of the length and width of the board)
int main(void) { int x, y, z; printf("Please enter the width and length of the rectangle:\n"); scanf("%d %d", &x, &y); if (x <= y) z = x; else z = y; while (!(x % z == 0 && y % z == 0)) { /*When x and y cannot be divided by z at the same time, the loop body is executed*/ z--; } printf("The maximum side length of the square is:%d centimeter\n", z); return 0; }
- Rolling phase division
surface | x | y | r(x%y) | Judgment condition (x%y!= 0) |
---|---|---|---|---|
for the first time | 56 | 40 | 16 | establish |
The second time | 40 | 16 | 8 | establish |
third time | 16 | 8 | 0 | Not established (terminated) |
Principle:
1. Enter x, y;
2. Compare the sizes of X and y so that x > = y.
3. Judge whether the remainder r of x divided by Y is 0. If R is 0, y is the maximum common divisor of x and Y. turn to step 5, otherwise turn to step 4;
4. Make x = y, y = r; turn to step 3;
5. Output y;
#include <stdio.h> int main(void) { int x, y, r, t; printf("Please enter the width and length of the rectangle:\n"); scanf("%d %d", &x, &y); if (x < y) /*When x < y, exchange the values of X, y*/ { t = x; x = y; y = t; } while ((r = x % y) != 0) /*When the remainder is not 0, the loop body is executed*/ { x = y; y = r; } printf("The maximum side length of the square is:%d centimeter\n", y); return 0; }
5. (polynomial summation) use Gregory formula π 4 = 1 1 − 1 3 + 1 5 − 1 7 + . . . \frac{\pi}{4}=\frac{1}{1}-\frac{1}{3}+\frac{1}{5}-\frac{1}{7}+... 4 π = 11 − 31 + 51 − 71 +..., solution π \pi The approximate value of π until the absolute value of a term is found to be less than 1 0 − 6 10^{-6} 10 − 6.
- [condition]: stop accumulation when the absolute value of the last addend | term | > = 1e-6 is met
#include <stdio.h> #include <math.h> int main(void) { double pi = 0, denominator = 1, flag = 1, term; term = 1 / denominator; while (fabs(term) >= 1e-6) /* Judgment | term | ≥ 1e-6 */ { pi = pi + term; /*Add current item to pi*/ denominator = denominator + 2; flag = -flag; /*The symbol of the next item is opposite to the current item*/ term = flag / denominator; /*Calculate the value of the next item*/ } pi = pi * 4; printf("pi = %10.8f\n", pi); /*Approximate value of output*/ return 0; }
3 process control statement
-
break statement
- break;
- End the entire cycle immediately
- Execute the statements below the loop structure
- It is usually used in conjunction with if statements and switch statements.
-
continue Statement
- continue;
- Only end this cycle
- Ignore the remaining statements in the loop body and directly judge whether to continue the next loop.
- Output the first of the three digits that can be divided by 9 and the first digit is 5
#include <stdio.h> int main() { int i; for ( i = 100; i < 1000; i++) { if (i%9==0 && i%10==5) { printf("%d\n", i); break; //Jump out of the for loop instead of if } } return 0; }
- Outputs a number between 50 and 100 that cannot be divided by 6.
#include <stdio.h> int main(void) { int i; for (i = 50; i <= 100; i++) { if (i % 6 == 0) continue; //End current cycle printf(" %d \t", i); } printf(" \n"); return 0; }
4 topic
- greatest common divisor
- Narcissistic number
- prime number