Easy to learn C language Chapter 5

Loop control

Learning content in this chapter:

① Goto statement and use goto statement to form a loop

②while statement

③do-while statement

④for statement

⑤ Loop nesting

⑥ Comparison of several cycles

⑦Break statement and continue statement

5.1 Overview            

In the program, all problems related to factorial, accumulation, sorting, etc. must be solved by loop, because a certain block in the program has to be executed several times.

C language to realize the loop statement: goto and if combination; while statement; do while statement; for statement.

5.2 Goto statement and use goto statement to form a loop function: unconditionally transfer to the statement pointed to by the statement label for execution.              

  General format:

            goto statement label;            

            ….…..

Label: statement;

Note: The statement label consists of letters, numbers and underscores. The naming rules are the same as variable names, and cannot start with numbers.

goto loop; (√) goto 100; (×) When used in conjunction with a loop statement, it can jump from inside the loop to outside the loop, but not from outside the loop to inside the loop. The direction of the goto statement can be forward or backward. It can form a loop when used in conjunction with an if statement.

The goto statement violates the principles of structured programming, so its use should be restricted.

Example uses if and goto statements to form a loop, ask

#include <stdio.h>
void main( )
{     int i,sum=0;
       i=1;
loop: if(i<=100)
      { 
           sum+=i;
	 i++;
	 goto loop;
      }    printf("%d",sum);
}

Example Input a group of data from the keyboard, end the input with 0, and sum the data.

#include <stdio.h>
void main()
{  	   
  int number,sum=0;
  read_loop: scanf("%d",&number);
	   if(!number)  goto print_sum;
	   sum+=number;
	   goto read_loop;
  print_sum: printf("The total sum is %d\n",sum);
}

while statement The while statement implements the "when type" loop structure. General form:

while(expression) loop body statement;

while(expression);

Example Use the while statement to form a loop, ask

#include <stdio.h>
void main( )
{     
    int i,sum=0;
    i=1;
    while(i<=100)
    {  
          sum=sum+i;
          i++;
    } 
    printf("%d",sum);
}

About the while loop statement:

  1. The while loop judges the expression first, and then executes the loop body.
  2. The body of the loop may not be executed once.
  3. If the loop body contains more than one statement, it should be enclosed in {}.
  4. The loop body should contain a statement that makes the loop tend to end;
  5. In the following cases, the conditional expression for exiting the while loop is not established (zero). A break and goto are encountered in the loop body
  6. Infinite loop              
  • while(1)                  
  • Loop body;

Example Use the while statement to display the square of 1~10

#include <stdio.h> 
void main()
{   int i=1;
    while(i<=10)
    {  
       printf("%d*%d=%d\n",i,i,i*i);
       i++;
    }
}

do-while statement

The do-while statement implements the "when type" loop structure. General form:

Function: execute the loop body first, and then judge the expression. If it is true, execute the loop body again, otherwise exit the loop. begging

Example Use the while statement to display the square of 1~10

#include <stdio.h> 
void main()
{   int i=1;
    while(i<=10)
    {  printf("%d*%d=%d\n",i,i,i*i);
       i++;
    }
}
  1. do-while loop, the loop body is executed at least once;
  2. While and do-while can solve the same problem, the two can be interchanged.
  3. When the expression after while is false at the beginning, the two loop results are different.

5.5 for statement             

The for statement is the most flexible and widely used loop statement in the C language and can completely replace the while and do-while statements. General form

General form: for (expression 1; expression 2; expression 3) loop body statement;

Common forms: for (assign initial value to loop variable; loop condition; loop variable increment) loop body statement;

Example Use the for statement to form a loop, ask

#include <stdio.h> 
void main( )
{     
  int i,sum=0;
  for(i=1;i<=100;i++)
      sum+=i;
  printf("%d",sum);
}

A few notes:

The expressions 1, 2, and 3 in the for statement are of any type and can be omitted, but the semicolon ";" cannot be omitted.

Infinite loop: for (;;) continues to execute the loop body, the loop does not terminate.

For statement can be converted into while structure

Several forms:

Expressions 1 and 3 can be expressions that have nothing to do with loops or comma expressions. for (s=0, i=1; i<=100; i++) s=s+i;

Expression 2 can be relational, logical, arithmetic, or character expression. When it is not 0, the loop body is executed, and when it is 0, the loop is exited.

#include <stdio.h>
main()
{  int  i,c;
   for(i=0;(c=getchar())!='\n';i+=c)
	printf("%d ",i+c);
}

Note: Loops can be nested within each other, but cannot cross each other.

5.8 break statement and continue statement

Break statement

Function: In the loop statement and switch statement, terminate and jump out of the loop body or switch body.

Description:

  1. Break can only terminate and jump out of the structure of the nearest layer.
  2. Break cannot be used in any other statements except loop statements and switch statements.

General form: break;

Example break Example: lowercase letters are converted to uppercase letters until non-alphabetic characters are entered

#include <stdio.h> 
void main()
{char  c;
  while(1)
    { c=getchar();
       if(c>='a' && c<='z') putchar(c-32);
       else
	if(c>=‘A' && c<=‘Z') putchar(c);
          else break;
    }
}

Continue statement

Features:

  1. End this loop, skip the statements that have not been executed in the loop body, and judge whether to execute the loop body next time.
  2. The continue statement is only used in loop statements.

The difference between break and continue statements

  1. The continue statement only ends this loop, and the break statement ends the entire loop.
  2. The continue statement is only used in while, do-while, and for loop statements, and the break statement can also be used in switch statements.

Example: Input the numbers between 100 and 200 that are not divisible by 3

#include <stdio.h> 
void main()
{ int i;
   for(i=100;i<=200;i++)
     { if(i%3= =0)
          continue;
       printf(“%d”,n);
     }
}

Example Find the number of positive numbers in the ten integers entered and their average value

#include <stdio.h> 
void main()
{    int i,num=0,a;
     float sum=0;
     for(i=0;i<10;i++)
     {  scanf("%d",&a);
	if(a<=0)  continue;
	num++;
	sum+=a;
     }
     printf("%d plus integer's sum :%6.0f\n",num,sum);
     printf("Mean value:%6.2f\n",sum/num);
}

For example, find the Fibonacci sequence: 1, 1, 2, 3, 5, 8... the first 40 numbers

#include <stdio.h>
#include <conio.h>
void main()
{ 
   long int f1,f2;
   int i;
   f1=1;  f2=1;
   for(i=1;i<=20;i++)
   { 
        printf("%12ld  %12ld  ",f1,f2);
        if(i%2==0)  printf("\n");
        f1=f1+f2;
        f2=f2+f1; 
   }
}

For example, judge whether m is a prime number.

#include <stdio.h>
#include <math.h>
void main()
{ 
   int m,i,k;
   scanf("%d",&m);
   k=sqrt(m);
   for(i=2;i<=k;i++)
     if(m%i==0)  break;
   if(i>k)  printf("%d is a prime number\n",m);
   else   printf("%d is not a prime number\n",m);
}

Example Find all prime numbers between 100 and 200.

#include <stdio.h>
#include <math.h>
void main()
{ 
   int m, k, i, n=0;
   for(m=101;m<=200;m=m+2)
     { k=sqrt(m);
        for(i=2;i<=k;i++)
          if(m%i==0)  break;
        if(i>=k+1) {printf("%d",m);n=n+1;}
        if(n%10==0) printf("\n");
     }
   printf("\n");
}

Example translation password.

Turn the text into a password according to a certain rule:        

Change the letter A to E, change the letter a to e, which becomes the fourth letter after it, and W will become A. Letters are converted according to the above rules, and non-letter characters remain unchanged. Enter a line of characters and output the corresponding password.

Analysis: Since characters and integers can be used universally,'A'->'E' corresponds to'A'->'A'+4. You can define a character variable c, c accept input, and c->c+4 . The special feature is that when between'W'-'Z' and'w'-'z', they need to correspond to'A'-'D' and'a'-'d', what should I do? One is to use the method in the book, and then reduce it back, that is, use c->c-26 to solve it.

#include <stdio.h>
void main()
{
   char c;
   while((c=getchar())!='\n')
      { if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
           { c=c+4;
	  if(c> 'Z'&&c<= 'Z'+4||c>'z') c=c-26;
           }
         printf("%c",c);
      }
    printf(“\n");
}

chapter summary:

  1. Using programming language to realize structured algorithm is structured programming.
  2. The structured algorithm only contains three control structures: sequence, branch and loop.
  3. The control statements that implement the above three structures in C language are sequential statements, branch statements and loop statements.
  4. When using if/if else statements, you should pay attention to the match between else and the latest if not matched by else.
  5. The? Operator is equivalent to a short form of if/else statement that assigns a value to the same variable according to different situations.
  6. The switch statement implements multiple selections. When applying it, note that its conditional expression value is an integer or character type, and each branch ends with a break statement.
  7. While and do while statements should be used to pay attention to the latter to execute the loop body at least once.
  8. Pay attention to the function and execution order of each expression in its control structure when applying for loop. for(expression1;expression2;expression3)→expression 1 is the initial execution, only executed once; expression 2 is executed next to determine whether to exit the loop, if the loop is executed, then execute expression 3 , Make some changes to the loop condition, and then go to expression 2 for judgment...
  9. Pay attention to the difference between break and continue, break ends the loop, and continue ends the loop.

Featured practice questions:

1. In C language, the loop formed by the do-while statement can only be exited with the break statement. (Can exit naturally)

A.    Right B. Wrong

2. The loop body of the for, while and do while loop structures is the first statement immediately after it (including compound statements).

A. Right B. Wrong

3. From i=-1;while(i<10) i+=2;i++; we can see that the loop body of this while loop is executed 6 times.

A. Right B. Wrong

Analysis: 1: i = 1 2: i = 3 3: i = 5 4: i = 7 5: i = 9 6: i = 11 i = 12 (attention range)

4. The expression after while can only be a logical or relational expression. 【Note: while(1)】

A. for    B. wrong

5 . Known : int = T 0; the while (T =. 1) {   ...   } , then the following statements is correct ______ . 

   A. The value of the loop expression is 0                     B. The value of the loop expression is 1   

C. Loop expression is illegal D. None of the above statements are correct

6. The running result of the following program segment is ______. 

i=0; do printf("%d,",i); while(i++); printf("%d\n",i);

   A.0,0           B . 0, 1 C.1,1 D. program enters an infinite loop

7. If the input data during program execution is 2473<Enter>, the output result of the following program is ______.

#include <stdio.h>

void main()

{ 
    int cs;

    while((cs=getchar())!='\n')

    {
        switch(cs-'2')

        {  
            case 0:

            case 1: putchar(cs+4);

            case 2: putchar(cs+4); break;

            case 3: putchar(cs+3);

            default: putchar(cs+2); 
         } 

    }

}

     A.668977         B.668966         C.6677877     D.6688766

8. The output of the following program is ______.

#include "stdio.h"

void main()

{ 
    int a,i;a=0;

    for(i=1;i<5;i++) //1 2 3 4

    switch(i)

    {  

         case 0: case 3:a+=2;

         case 1: case 2:a+=3;

         default:a+=5 ;

        //(1 ,2,3,4): 3+5+3+5+3+5+2+5=24+7=31

    }

    printf("%d\n",a);    

}

 A.31     B.13             C.10             D.20

9. The running result of the following program is ______.

#include <stdio.h> 
void main() 
{ 
    int i; 
    for(i='a';i<'f';i++,i++)//'a' 'c' 'e'
        printf("%c",i-'a'+'A'); //i+32
    //ACE
    printf("\n");
}

A.ACE                B.BDF             C.ABD                 D.CDE

10. The output of the following program after running is ______.

#include <stdio.h>
void main() 
{ 
    int k=5,n=0; 
    do 
    {
        switch(k) 
        { 
         case 1: case 3:n+=1;k--;break; 
         default:n=0;k--; 
         case 2: case 4:n+=2;k--;break; 
        } 
        printf("%d",n); 
    }while(k>0 && n<5);  
} 

A.235     B.0235     C.02356     D.2356

Analysis:

//k=5 n=0 k=4 (when the default is not out of the loop, printf will not be executed)

//k=4 n=2 k=3

//k=3 n=3 k=2

//k=2 n=5 k=1

11. The output of the following program is _______. 

#include <stdio.h>

void main()

{ 
   int x=8;

   for(  ;  x>0;  x--)

   { 
        if(x%3) 
        {
            printf("%d,",x--);  
            continue;
        }

       printf("%d,",--x); 
   }   
}

A.7,4,2,         B.8,7,5,2,          C.9,7,6,4,          D.8,5,4,2,

12 The following is not be a statement or group of statements constitute the infinite loop is _______ .

A.n=0; do{++n;}while(n<=0);                B.n=0; while(1){n++;} //永远为真

C.n=10; while(n); {n--;}                     D.for(n=0,i=1; ;i++) n+=i;

解析:
/* 循环的题目 注意while();这种语句如果while(n)后面跟;而且n不等于0,则永远为真
A.
#include <stdio.h> 
void main() 
{ 
    int n=0; 
    do{
        ++n;//1 
    }
    while(n<=0);    //一直加到溢出,就跳出循环
    printf("一直加到溢出,就跳出循环");
}


B.
n=10; while(n); //死循环
{n--;}   

D.
for(n=0,i=1; ;i++) 
    n+=i;
//没有终止条件,死循环

D.
n=0; while(1){n++;} //永远为真
 */

13. The running result of the following program is _______.

//注意作用域
#include "stdio.h" 
void main()
{  
    int k=0,m=0,i,j;
    for(i=0;i<2;i++) 
    { 
        for(j=0;j<3;j++) 
            k++;
        k-=j; 
    } 
    m=i+j;//2+3=5
    printf("k=%d,m=%d",k,m);  
}

A.k=0,m=3        B.k=0,m=5         C.k=1,m=3      D.k=1,m=5

14. The running result of the following program is _______. 

a=1;b=2; c=2; while(a<b<c) { t=a;a=b;b=t;c--;}

printf("%d,%d,%d",a,b,c);

A.1,2,0       B.2,1,0     C.1,2,1              D.2,1,1

//Pay attention to whether the loop is satisfied, if satisfied, continue, if not satisfied, jump out of the loop

//1<2=1 1<2=1 a=2 b=1 c=1

//2<1=0 0<2=1 a=1 b=2 c=0

15 . The following description is correct _______.  

A. The break statement can only be used in the body of the switch statement

The function of the B.continue statement is to make the execution flow of the program jump out of all loops that contain it

C. The break statement can only be used in the loop body and the switch statement body

D. Using break statement and continue statement in the loop body has the same effect

16. The output of the following program after running is _______.

#include "stdio.h" 
void main()
{ 
    int k=5,n=0;
    do 
    { 
        switch(k)//k=5
        { 
            case 1: case 3: n+=1; break;
            default: n=0;k--; //default结束之后如果还有语句不会跳出循环
            case 2: case 4: n+=2;k--;break; 
        }
        printf("%d", n);
    }while(k>0&&n<5); 
}

A.2345      B.0235     C.02356     D.2356

Analysis:

//k=5 n=0 k=4

//k=4 n=2 k=3 printf 2

//k=3 n=3 printf 3

//k=3 n=4 printf 4

//k=3 n=5 printf 5

17. Enter 1234567890<Enter> when executing the following program, and the while loop body will execute _______ times.

#include "stdio.h"

void main()

{ char ch; while((ch=getchar())=='0') printf("#"); }

A.10              B.0              C.2       D.l

Analysis:

//important!!!!
#include "stdio.h" 
void main()
{ 
	char ch; 
	//1234567890<回车>
	//只有输入0,才会执行循环
	while((ch=getchar())=='0') //因为输入的1234567890<回车>的第一个被拿出来的'1'不等于'0',所以条件为假,循环不可以执行,然后会执行0次
		printf("#"); 
	printf("*************************************\n");
}

18. The output result after the following program is executed is ________.

#include "stdio.h" 
void main()
 { 
    int i;
    for(i=1;i<=40;i++)
    { 
        if(i++%5==0)//5 10 15 20 25 30 35 40
            if(++i%8==0)//7 12 17 22 27 32 37 42  //32  
                printf("%d",i); 
    }
        printf("\n"); 
}

A.5             B.24            C.32             D.40

19. There are the following programs, if input from the keyboard when running: 18,11<Enter>, the program output result is _______.

#include "stdio.h"

void main()

{  int a,b;

   printf("Enter a,b:");scanf("%d,%d",&a,&b);

   while(a!=b)

   {  while(a>b) a-=b;

      while(b>a) b-=a;  }

      printf("%3d%3d\n",a,b); }

A.1  1      B.1  2        C.1  3         D.1  4

Analysis:

#include "stdio.h" 
void main()
{  
    int a,b;
    printf("Enter a,b:");//18 11
    scanf("%d,%d",&a,&b);
    while(a!=b)
    {  
        while(a>b) //1  7>4 3>1 2>1
            a-=b;//a=18-11=7 7>11不大于 跳出循环 a=3 a=2 a=1
        while(b>a) //11>7 4>3 
            b-=a;  //b=11-7=4 a=7 b=1
	}
    printf("%3d%3d\n",a,b); //a=1 b=1
}

20. The output result after running the following program is _______.

#include "stdio.h" 
void main()
{ 
    int i,j,x=0;
    for(i=0;i<2;i++)//0 1
    { 
        x++;
        for(j=0;j<=3;j++)
        { 
            if(j%2)// 注意这个式子:当 j取 1,3 if(j%2)为真,取0,2的时候if(j%2)为假
                continue;
            x++; 
        }
        x++;   
    }
    printf("x=%d\n",x); 
}
  1. x=4               B.x=8           C.x=6             D.x=12

//x=1 j=0 x=2 j=1 j=2 x=3 j=3 x=4

//x=5 j=0 x=6 j=1 j=2 x=7 j=3 x=8

21. The output of the following program is _______.

#include "stdio.h" 
void main()
{  
    int k=5,n=0;
    while(k>0)
    { 
        switch(k)
        { 
            default : break;
            case 1 : n+=k;
            case 2 :
            case 3 : n+=k;  
        }
        k--;  
        printf("%d\n",k);
    }
    printf("%d\n",n);
}

A.3               B.4              C.5                D. 6

//k=4 k=3

//k=3 n=0+3=3

//k=2 n=3+2=5

//k=1 n=5+1+1=7

//k=0   n=7

22. The output result after the following program is executed is _______.

#include "stdio.h" 
void main()
{  
    int x=0,y=5,z=3;
    while(z-->0&&++x<5)  
        y=y-1;
    printf("%d,%d,%d\n",x,y,z); 
}

A.3,2,0      B.3,2,-1            C.4,3,-1        D.5,-2,-5

Analysis:

//z=3>0 z=2 x=1<5 y=4
//z=2>0 z=1 x=2<5 y=3
//z=1>0 z=0 x=3<5 y=2
//z=0>0 不成立 z=-1  important!!!!
//x=3 y=2 z=-1

23. The output result after the following program is executed is _______.

#include "stdio.h"

void main()

{  int i,n=0;

   for(i=2;i<5;i++)

     { do{ if(i%3) continue; n++; }while(!i);

       n++;   }

   printf("n=%d\n",n);  }

A.n=5      B.n=2   C.n=3   D.n=4

Analysis:

#include <stdio.h>
int main( )
{ 
	int i,n=0;
	for(i=2;i<5;i++)//2 3 4 
	{
		 do
		 {
			if(i%3) //为真 2 4 为假 3
				continue;// i%3与i%3!=0等效  
				//break;
			n++;
		 } while(!i);//!i  i!=0
		n++;
		//printf("n=%d\n",n);
	}
	printf("n=%d\n",n);
}

//continue执行到i%3为真的时候,然后它不会继续执行n++;语句,重新进行do...while()循环,但是此时while(!i)为假,所以跳出循环
//break执行到i%3为真的时候,然后它不会继续执行n++;语句,直接跳出do...while();循环

24. The function of the following program is to output the pyramid chart in the following form. What should be filled in underline is _______.

                         *

                        ***

                      *****

                     *******

#include "stdio.h"

void main( )

{  int i,j;

   for(i=1;i<=4;i++)

    {  for(j=1;j<=4-i;j++) printf(" ");

       for(j=1;j<=_______;j++) printf("*");

       printf("\n"); }  

}

A.i         B.2*i-1     C.2*i+1   D.i+2

Analysis:

//                        *       i=1 , n1=1 , n2=3 n1=2*i-1
//                       ***      i=2 , n1=3 , n2=2 n1=2*i-1
//                      *****     i=3 , n1=5 , n2=1 n1=2*i-1
//                     *******    i=4 , n1=7 , n2=0 n1=2*i-1



//思路整理
/*
for(i=0;i<=4;i++)
	for(j=1;j<=4-i;j++)
		printf("");
	for(j=1;j<=2*i-1;j++)
		printf("*");
*/

//程序设计
#include "stdio.h" 
void main( )
{  
   int i,j;
   for(i=1;i<=4;i++)//i控制行数
    {  
        for(j=1;j<=4-i;j++)   //j控制空格个数 个数规律为:3 2 1 0 满足 j=4-i
            printf(" ");
        for(j=1;j<=2*i-1;j++) //j控制*的个数 个数规律为:1 3 5 7 满足 j=2*i-1
            printf("*");
        printf("\n"); 
    }  
}

The notes in this article are from the PPT of C program design by Tan Haoqiang, I love learning haha!

If you think the writing is good, please like it~

Guess you like

Origin blog.csdn.net/weixin_41987016/article/details/105822965