6.1 Overview (goto loop statement)
Loop structure is mainly used to solve operations that need to be repeated. For example: sum several numbers, iterate to find the root, sort, find, and so on.
When designing a loop structure, you should look for patterns in repetitive operations, including code snippets for repetitive execution and conditions for repetitive execution.
-
Common loop structure statements: while statement, do...while statement, for statement, goto statement (not generally recommended)
-
The goto statement, together with the if statement, can also form a circular structure. The goto statement is also known as an unconditional transfer statement
-
The general format of the goto statement is as follows:
goto Statement label; . . . Label: Statement . . .
-
The semantics of a goto statement is to change the flow of the program to execute the statement identified by the statement label
Example: Construct a loop with goto statements to calculate the sum of integers from 1 to 100
#include <stdio.h> void main() { int i=1,sum=0; loop:sum=sum+i; i++; if(i<=100) goto loop; printf("The sum of 1 to 100 is:%d\n",sum); }
6.2 while Loop Statement
A loop composed of while statements is called an equivalent loop. When the loop condition is satisfied, the loop body statement is executed.
-
The general form of a while statement:
while(Expression) Loop statement; /*Expression is a cyclic condition*/
-
The while statement is characterized by judging the expression before executing the loop body statement
Example: Count the number of characters entered in a line from the keyboard
#include <stdio.h> void main() { int n=0; printf("Enter a string:\n"); while(getchar()!='\n') /*Continue the loop as long as the character entered from the keyboard is not a line break*/ n++; printf("%d",n); }
- In C, when the enter key is pressed, two characters'\r'and'\n' are generated, and the standard input function receives'\n'
-
An expression in a while statement can be any legal expression, typically a relational or logical expression, that continues the loop as long as the value of the expression is true (not 0)
-
If the loop body contains more than one statement, it must be enclosed in curly brackets {} to form a compound statement
-
Selecting a loop condition must avoid an endless loop, the loop condition must change from true to false, and the loop body statement can be empty
6.3 do...while loop statement
do...while loops are called until-type loops; Execute the loop body statement first, then judge the expression until it is false in while, jump out of the loop
-
do...while loops typically take the form of:
do Loop body statement; while(Expression); /*There is a semicolon at the end of the sentence!*/
-
do...while statement is executed by executing a loop body statement once, then discriminating the value of the expression. If the expression value is true, the loop continues until the expression value is false and the loop jumps out.
Example: Find integer i, which satisfies 1+2+...+ (i+1)<100 and 1+2+...+i>=100
#include <stdio.h> void main() { int i=0,sum=0; do { i++; sum=sum+i; }while(sum<100); printf("The integer is:%d\n",i); }
- The while and do...while statements are similar, but do...while statements execute the loop body statement before judging, at least once; A while statement is a decision before choosing whether to execute a loop body statement
Example: Any input of a positive integer, the number of bits reversed order output, such as input 1234, output 4321
Analysis: You can find the digits that have no place by balancing the positive integers you enter. The first time you take the balance, you get the digits that have no place, then divide by 10, and then you get the 10 digits of the original positive integer by balancing the 10 digits
- while Loop
#include <stdio.h> void main() { int a,b; printf("Enter a positive integer:"); scanf("%d",&a); while(a!=0) { b=a%10; printf("%d",b); a=a/10; } }
- do...while loop
#include <stdio.h> void main() { int a,b; printf("Enter a positive integer:"); scanf("%d",&a); do { b=a%10; printf("%d",b); a=a/10; }while(a!=0); }
- If the title requires a non-negative integer to be entered and there is no output when 0 is entered using the while loop, you need to add a case where the input is 0 before the while loop
6.4 for loop statement
for loops apply not only to cases where the number of loops is known, but also to cases where the number of loops is unknown.
-
The general form of a for loop is:
for(Expression 1;Expression 2;Expression 3) Loop body statement;
- Expression 1 is usually used to assign values to certain variables before entering a loop. Generally, it is an assignment expression. The entire loop is executed only once and can be placed in front of the for loop
- Expression 2 is usually a cyclic condition used to control whether a loop is executed or not, usually a relational or logical expression. The missing expression 2 system defaults to 1, which leads to an infinite loop
- Expression 3 is used to modify the value of a loop control variable when a loop repeats, generally an assignment expression. You can put it inside a for loop to make loop body statements
- These three expressions can be any legal expression
- If a loop statement consists of more than one statement, it must be enclosed in curly brackets
-
for loop execution process:
- Evaluates the value of expression 1 and goes directly into expression 2 without expression 1
- Calculates the value of expression 2, executes the loop body statement once if the value is true, jumps out of the for loop directly for fake and executes subsequent statements
- Execute Loop Body Statement
- Evaluate the value of expression 3 and go back to step two to execute expression 2, or directly to step two to execute expression 2 without expression 3
-
Throughout the for loop, expression 1 executes only once, expression 2 and 3 may execute more than once, loop body may execute more than once, or none at a time
-
All three expressions in the for loop can be omitted, but the semicolon cannot be omitted
Example: Output all displayable characters on screen against their ASCII codes
ASCII codes are displayable characters from 32 (space) to 126 ('~')
#include <stdio.h> void main() { char c; for(c=32;c<=126;c++) printf("%c %d\n",c,c); }
6.5 break and continue statements
Both break and continue statements are jump statements that control the flow direction of the program
6.5.1 break statement
- In addition to being used in switch statements, break statements can also be used in loop statements to jump out of the loop and execute subsequent statements
- When a break statement is used in a loop statement, it is usually used in conjunction with an if statement to end the loop ahead of time
- Break statements can only be used in looping and switching statements, but when a break occurs within a switch statement in a loop body, it simply jumps out of the switch statement and does not terminate the loop
Example: Calculate the area of a circle when r=1 to r=10, and terminate when the area is greater than 100
#include <stdio.h> #define PI 3.1415926 void main() { int r; float area; for(r=1;r<=10;r++) { area=PI*r*r; if(area>100) break; printf("r=%d area is: %.2f\n",r,area); } }
6.5.2 continue statement
-
The continue statement can only be used within a loop, in the general form of: continue;
-
The semantics of a continue statement is to end the loop, stop executing the statement after the continue statement in the loop body, and move to the judgment and execution of the next loop condition.
-
The continue statement should also be used in conjunction with the if statement to end the cycle.
-
In while and do...while statements, the continue statement causes the process to jump directly to the judgment part of the loop control condition; In the for statement, when a continue is encountered, the rest of the loop body is skipped and expression 3 in the for statement is evaluated
Example: Output a number within 100 that can be divided by 7
#include <stdio.h> void main() { int a; for(a=1;a<=100;a++) { if(a%7!=0) continue; printf("%d ",a); } } not applicable continue Statements can also: #include <stdio.h> void main() { int a; for(a=1;a<=100;a++) { if(a%7==0) printf("%d ",a); } }
Nesting of 6.6 loops
Cycle nesting refers to the complete inclusion of another or several cyclic structures within a cycle.
- While, do...while, for loops can nest with each other
- Nested cannot cross, need to include completely
- Loop control variables for internal and external loops cannot have duplicate names
- Different or different loops can be nested in multiple layers
- Note the initial value setting of the inner loop and the number and extent of executions of the inner loop body
Example: Demonstrate the execution of a nested loop
#include <stdio.h> void main() { int i,j; for(i=0;i<3;i++) { printf("i=%d",i); for(j=0;j<4;j++) printf("j=%-4d",j); printf("\n"); } }
6.7 Examples of Loop Structure Programming
6.7.1 Accumulation and Multiplication Algorithms
Example: At 8 × 8 board 64 cells, the first grid put a bean, the second two beans, the third four in turn cumulative, full of 64 cells, design algorithm to find how many beans, how many cubic meters? 1 cubic meter of beans is about 1.42e8 grains.
Analysis: The first grid contains 1, the second two, the third four, and so on. The second grid contains 2(i-1) beans. The total number of beans is 20+21+22+23+...263.
#include <stdio.h> void main() { double sum,t; /*t Is an accumulator, the initial value is usually 1; sum is an accumulator, the initial value is sometimes 0, sometimes the first number to add up; i is a counter, The initial value is 1, which is the exponent of 2^1*/ int i; for(t=1,sum=1,i=1;<=63;++) { t=t*2; sum=sum+t; } printf("The total number of beans is:%e\n",sum); printf("The folded volume is:%e Cubic metre\n",sum/1.42e8); }
6.7.2 Enumeration, Enumeration Algorithms
Example: 100 yuan, 5 yuan for rooster, 3 yuan for hen, 1 yuan for three pups. If you buy 100 yuan for 100 chickens, how many chickens and chickens each?
Analysis: cock i, hen j, chick k, i+j+k=100;5i+3j+k/3=100; If you buy 100 all cocks, you can buy 20, so the range of I is 020; If you buy all hens, you can buy up to 33, leaving one piece, so the range of J is 033; The range of K can be determined by I and j
#include <stdio.h> void main() { int i,j,k; int m=100/5,n=100/3; for(i=0;i<=m;i++) { for(j=0;j<=n;j++) { k=100-i-j; if(i*5+j*3+k/3 == 100&&k%3 == 0) printf("i=%d,j=%d,k=%d\n",i,j,k); } } }
6.7.3 Recursive algorithm (using previously known data to infer later unknown data)
Example: Output the first 40 items of the Fibonacci number column, four items per row, Fibonacci number column: 1, 1, 2, 3, 5, 8, 13..., the first and second items are all 1, the latter items are the sum of the first two items
Analysis: General term expression: f1=1 (n=1)
f2=1 (n=2)
fn=fn-1+fn-2 (n>=3)
#include <stdio.h> void main() { long f1,f2; int i; f1=f2=1; for(i=1;i<=20;i++) { printf("%12ld %12ld",f1,f2); if(i%2==0) printf("\n"); f1=f1+f2; f2=f1+f2; } } Operation: initial f1=f2=1 ①: i=1,i=1<=20;Enter Loop Output Right Align Left 12 Spaces f1=1,f2=1;i=1,1%2 Not equal to 0,Do not output line breaks;f1=2,f2=3 ②: here i after i++obtain i=2<=20;Enter Loop Output Right Align Left 12 Spaces f1=2,f2=3;i=2,2%2 Equal to 0,Output Line Break;f1=5,f2=8 ③: here i after i++obtain i=3<=20;Enter Loop Output Right Align Left 12 Spaces f1=5,f2=8;i=3,3%2 Not equal to 0,Do not output line breaks;f1=13,f2=21 ④: here i after i++obtain i=4<=20;Enter Loop Output Right Align Left 12 Spaces f1=13,f2=21;i=4,4%2 Equal to 0,Output Line Break;f1=34,f2=55 . . . ⑤: here i after i++obtain i=19<=20;Enter Loop Output Right Align Left 12 Spaces f1=24157817,f2=39088169;i=19,19%2 Not equal to 0,Do not output line breaks;f1=63245986,f2=102334155 ⑥: here i after i++obtain i=20<=20;Enter Loop Output Right Align Left 12 Spaces f1=63245986,f2=102334155;i=20,20%2 Equal to 0,Output Line Break;f1=165580141,f2=267914296 ⑦: here i after i++obtain i=21,i<=20 False, jump out of the loop, end the program
6.7.4 Calculate x^y
Y is an integer variable and y>=0
#include <stdio.h> void main() { float x,z; int y; printf("input x and y: \n"); scanf("%f,%d",&x,&y); for(z=1;y>0;y--) z*=x; printf("z=%f",z); } Operation: input x=4,y=5; ①: z=1,y=5>0;Enter the loop to get z=z*x by z=1*4 ②: z=1*4,here y after y--obtain y=4>0;Enter the loop to get z=z*x by z=1*4*4 ③: z=1*4*4,here y after y--obtain y=3>0;Enter the loop to get z=z*x by z=1*4*4*4 ④: z=1*4*4*4,here y after y--obtain y=2>0;Enter the loop to get z=z*x by z=1*4*4*4*4 ⑤: z=1*4*4*4*4,here y after y--obtain y=1>0;Enter the loop to get z=z*x by z=1*4*4*4*4*4 ⑥: here y after y--obtain y=0,Jump out of loop output z=1*4*4*4*4*4=4^5
6.7.5 Output all prime numbers between 3 and 100
To determine whether an integer m is a prime number, just divide m by every integer between 2 and m-1. If it cannot be divided by an integer, m is a prime number.
#include <stdio.h> void main() { int i,j; for(i=3;i<=100;i++) { for(j=2;j<=i-1;j++) if(i%j == 0) break; if(j == i) printf("%3d",i); } } Operation: ①: i=3<=100; Enter inner loop: 1.j=2<=2;here i=3,j=2,3%2=1!=0;Get into j++,here j=3 2.j=3>2;End inner loop here j=i=3,output i=3;Get into i++,here i=4 ②: i=4<=100; Enter inner loop: 1.j=2<=3;here i=4,j=2,4%2=0;Get into break;End inner loop here j=2,i=4;No Output i;Get into i++,here i=5 . . .
6.7.6 Proves that a positive integer cube can be written as the sum of a series of consecutive odd numbers
#include <stdio.h> void main() { long int n,i,k,j,sum; print("input n="); scanf("%ld",&n); k=n*n*n; for(i=1;i<k/2;i+=2) { for(j=i,sum=0;sum<k;j+=2) sum+=j; if(sum==k) printf("%ld*%ld*%ld=%ld=form%ldto%ld\n",n,n,n,sum,i,j-2); } } Operation: input n=5,be k=125 ①: i=1<k/2=62 Enter inner loop: 1.j=i=1,sum=0<125;be sum=sum+j=1;Get into j+=2 have to j=3 2.sum=1<125;be sum=sum+j=1+3=4;Get into j+=2 have to j=5 3.sum=4<125;be sum=sum+j=4+5=9;Get into j+=2 have to j=7 4.sum=9<125;be sum=sum+j=9+7=16;Get into j+=2 have to j=9 5.sum=16<125;be sum=sum+j=16+9=25;Get into j+=2 have to j=11 6.sum=25<125;be sum=sum+j=25+11=36;Get into j+=2 have to j=13 7.sum=36<125;be sum=sum+j=36+13=49;Get into j+=2 have to j=15 8.sum=49<125;be sum=sum+j=49+15=64;Get into j+=2 have to j=17 9.sum=64<125;be sum=sum+j=64+17=81;Get into j+=2 have to j=19 10.sum=81<125;be sum=sum+j=81+19=100;Get into j+=2 have to j=21 11.sum=100<125;be sum=sum+j=100+21=121;Get into j+=2 have to j=23 12.sum=121<125;be sum=sum+j=121+23=144;Get into j+=2 have to j=25 13.sum=144>125;Do not enter the inner loop, enter if Sentence, sum=144!=k=125;Get into i+=2,i=3 ②: i=3<k/2=62 Enter inner loop: 1.j=i=3,sum=0<125;be sum=sum+j=3;Get into j+=2 have to j=5 2.sum=3<125;be sum=sum+j=3+5=8;Get into j+=2 have to j=7 3.sum=8<125;be sum=sum+j=8+7=15;Get into j+=2 have to j=9 4.sum=15<125;be sum=sum+j=15+9=24;Get into j+=2 have to j=11 5.sum=24<125;be sum=sum+j=24+11=35;Get into j+=2 have to j=13 6.sum=35<125;be sum=sum+j=35+13=48;Get into j+=2 have to j=15 7.sum=48<125;be sum=sum+j=48+15=63;Get into j+=2 have to j=17 8.sum=63<125;be sum=sum+j=63+17=80;Get into j+=2 have to j=19 9.sum=80<125;be sum=sum+j=80+19=99;Get into j+=2 have to j=21 10.sum=99<125;be sum=sum+j=99+21=120;Get into j+=2 have to j=23 11.sum=120<125;be sum=sum+j=120+23=143;Get into j+=2 have to j=25 12.sum=143>125;Do not enter the inner loop, enter if Sentence, sum=143!=k=125;Get into i+=2,i=5 ③: i=5<k/2=62 Enter inner loop: 1.j=i=5,sum=0<125;be sum=sum+j=5;Get into j+=2 have to j=7 2.sum=5<125;be sum=sum+j=5+7=12;Get into j+=2 have to j=9 3.sum=12<125;be sum=sum+j=12+9=21;Get into j+=2 have to j=11 4.sum=21<125;be sum=sum+j=21+11=32;Get into j+=2 have to j=13 5.sum=32<125;be sum=sum+j=32+13=45;Get into j+=2 have to j=15 6.sum=45<125;be sum=sum+j=45+15=60;Get into j+=2 have to j=17 7.sum=60<125;be sum=sum+j=60+17=77;Get into j+=2 have to j=19 8.sum=77<125;be sum=sum+j=77+19=96;Get into j+=2 have to j=21 9.sum=96<125;be sum=sum+j=96+21=117;Get into j+=2 have to j=23 10.sum=117<125;be sum=sum+j=117+23=140;Get into j+=2 have to j=25 11.sum=140>125;Do not enter the inner loop, enter if Sentence, sum=140!=k=125;Get into i+=2,i=7 ④: i=7<k/2=62 Enter inner loop: 1.j=i=7,sum=0<125;be sum=sum+j=7;Get into j+=2 have to j=9 2.sum=7<125;be sum=sum+j=7+9=16;Get into j+=2 have to j=11 3.sum=16<125;be sum=sum+j=16+11=27;Get into j+=2 have to j=13 4.sum=27<125;be sum=sum+j=27+13=40;Get into j+=2 have to j=15 5.sum=40<125;be sum=sum+j=40+15=55;Get into j+=2 have to j=17 6.sum=55<125;be sum=sum+j=55+17=72;Get into j+=2 have to j=19 7.sum=72<125;be sum=sum+j=72+19=91;Get into j+=2 have to j=21 8.sum=91<125;be sum=sum+j=91+21=112;Get into j+=2 have to j=23 9.sum=112<125;be sum=sum+j=112+23=135;Get into j+=2 have to j=25 10.sum=135>125;Do not enter the inner loop, enter if Sentence, sum=135!=k=125;Get into i+=2,i=9 ⑤: i=9<k/2=62 Enter inner loop: 1.j=i=9,sum=0<125;be sum=sum+j=9;Get into j+=2 have to j=11 2.sum=9<125;be sum=sum+j=9+11=20;Get into j+=2 have to j=13 3.sum=20<125;be sum=sum+j=20+13=33;Get into j+=2 have to j=15 4.sum=33<125;be sum=sum+j=33+15=48;Get into j+=2 have to j=17 5.sum=48<125;be sum=sum+j=48+17=65;Get into j+=2 have to j=19 6.sum=65<125;be sum=sum+j=65+19=84;Get into j+=2 have to j=21 7.sum=84<125;be sum=sum+j=84+21=105;Get into j+=2 have to j=23 8.sum=105<125;be sum=sum+j=105+23=128;Get into j+=2 have to j=25 9.sum=128>125;Do not enter the inner loop, enter if Sentence, sum=128!=k=125;Get into i+=2,i=11 ⑥: i=11<k/2=62 Enter inner loop: 1.j=i=11,sum=0<125;be sum=sum+j=11;Get into j+=2 have to j=13 2.sum=11<125;be sum=sum+j=11+13=24;Get into j+=2 have to j=15 3.sum=24<125;be sum=sum+j=24+15=39;Get into j+=2 have to j=17 4.sum=39<125;be sum=sum+j=39+17=56;Get into j+=2 have to j=19 5.sum=56<125;be sum=sum+j=56+19=75;Get into j+=2 have to j=21 6.sum=75<125;be sum=sum+j=75+21=96;Get into j+=2 have to j=23 7.sum=96<125;be sum=sum+j=96+23=119;Get into j+=2 have to j=25 8.sum=119<125;be sum=sum+j=119+25=144;Get into j+=2 have to j=27 10.sum=144>125;Do not enter the inner loop, enter if Sentence, sum=144!=k=125;Get into i+=2,i=13 . . .
6.7.7 Read the scores of 10 students in 4 courses in sequence, calculate the average score of each student and output
#include <stdio.h> void main() { int n,k,score,sum; float ave; for(n=1;n<=10;n++) { sum=0; for(k=1;k<=4;k++) { scanf("%d",&score); sum+=score; } ave=sum/4.0; printf("NO.%d:%f\n",n,ave); } }
6.7.8 Three digits, the cube of each digit and the number equal to it, called the number of daffodils, print out the number of all daffodils
#include <stdio.h> void main() { int i,j,k,sum; for(i=1;i<=9;i++) for(j=0;j<=9;j++) for(k=0;k<=9;k++) { sum=100*i+10*j+k; if(sum==i*i*i+j*j*j+k*k*k) printf("%d ",sum); } }
6.7.9 calculates and outputs the sum of the ten largest natural numbers within n divisible by 11 or 19. Output 2646 if n value is 300
#include <stdio.h> void main() { int sum=0,mix=1,n; scanf("%d",&n); while((n>=2)&&(mix<=10)) { if((n%11==0)||(n%19==0)) { sum=sum+n; mix++; } n--; } printf("%d\n",sum); }
6.7.10 Counts the number of digits with a value of 0 in an unsigned integer, and finds the maximum number value for each digit
Example: 10080, there are 3 numbers with a value of 0, the largest number is 8
#include <stdio.h> void main() { unsigned m; int n=0,max=0,t; scanf("%d",&m); do { t=m%10; if(t==0) n++; if(max<t) max=t; m=m/10; }while(m); printf("\n The result is that the largest number is%d 0 Yes%d individual\n",max,n); }
6.7.11 Fractional Sum
Find 1-1/2+1/3-1/4+...+1/99-1/100
#include <math.h> void main() { int s; /*s Is a molecule and needs to determine the positive and negative*/ float n,t,sum; /*n As denominator, need to add up; t is the specific value of each item; Sum is the sum*/ t=1; sum=0; n=1; s=1.0; while(n<=100) { sum=sum+t; n=n+1; s=-s; t=s/n; } printf("sum=%10.6f\n",sum); }
Factorial of 6.7.121~10
Find the factorial of 1 to 10 and show it on the screen separately
#include <stdio.h> void main() { int i; long int n=1; for(i=1;i<=10;i++) { n=n*i; printf("%d ",n); } }
6.7.13 Isosceles triangle with n*
#include <stdio.h> void main() { int n,i,j; scanf("%d",&n); for(i=0;i<=n;i++) { for(j=1;j<=n+i-1;j++) if(j<=n-i) printf(" "); else printf("*") printf("\n"); } } Operation: Enter 7; be n=7 ①: i=0<=7; Enter inner loop: 1.j=1<=7+0-1=6;j=1<7-0=7,Output space
6.7.14 Find the number of completions within 1,000
A number is exactly equal to the sum of its factors and is called a perfect number. Completion 6 equals 1+2+3,
#include <stdio.h> void main() { int m,s,i; /*s Is the sum of the factors; m is the number of completions to verify; i is a factor*/ for(m=2;m<1000;m++) { s=0; for(i=1;i<m;i++) if((m%i)==0) s=s+i; if(s==m) { printf("%d its factors are ",m); for(i=1;i<m;i++) if((m%i)==0) printf("%d ",i); printf("\n"); } } }
6.7.15 Targeting
Eight beats 53 rings, all hits 10 rings, 7 rings and 5 rings, ask how many rings each hit
#include <stdio.h> void main() { int h10,h7,h5; for(h10=1;h10<=4;h10++) for(h7=1;h7<=6;h7++) for(h5=1;h5<=8;h5++) if(h10+h7+h5==8&h10*10+h7*7+h5*5==53) printf("h10=%d,h7=%d,h5=%d",h10,h7,h5); }
6.7.16 Monkey Eating Peaches
The monkey picked a heap of peaches the first day, ate half of them, ate one more without any effort; The next day he ate half of the peaches left yesterday and ate one more without any effort. Each day afterwards, I ate one more from the previous day. When you eat again on day 10, you will have one left. How many peaches were picked on the first day?
Analysis: On the ninth day, I ate half of the peach left on the eighth day plus one, and then there was one peach left
Reverse thinking, backward #include <stdio.h> void main() { int day,x1,x2; /*day For the day; x2 The peaches left over from the tenth day were initially eaten on the ninth day. x1 is the peach left over from the ninth day after the eighth day*/ day=9; x2=1; while(day>0) { x1=(x2+1)*2; x2=x1; day--; } printf("Pick peach for the first day%d individual\n",x1); } Method 2 #include <stdio.h> void main() { }
6.7.17 Use Newton's iteration method to find the root of equation 2x3-4x2+3x-6=0 near 1.5
6.7.18 Enter two positive integers m and n to find their maximum and minimum common multiples
Divide by rolling until b is 0
#include <stdio.h> void main() { int p,r,n,m,temp; printf("Enter two positive integers:"); scanf("%d,%d",&n,&m); if(n<m) { temp=n; n=m; m=temp; } p=n*m; while(m!=0) { r=n%m; n=m; m=r; } printf("The greatest common divisor is:"); printf("The minimum common multiple is:"); }