Basic usage of C language while, do while, for loop and two algorithms (recursion, exhaustive)

Basic usage of C language loop control statement

The basic idea of ​​using loop statements:

  1. For loops called count control whose loop times are known in advance , a for loop is generally used;
  2. For loops called conditional control whose loop times are unknown in advance , the while or do while loop statement is generally used;
  3. For a loop statement including another loop statement is called a nested loop ;

One, while statement

  1. General form:
    assign initial value; assign initial value; assign initial value;
    while (loop control expression)
    { loop body statement; }

  2. flow chart:
    while

The loop control expression is judged before executing the loop body statement:

  1. The execution process of the while statement

The loop control expression is judged before the execution of the loop body statement;
if the value of the expression is 0 at the beginning, the statement will not be executed once;
a. Calculate the value of the loop control expression;
b. If the loop control expression If the value of the formula is true, execute the statement of the loop body and return to the step;
c. If the value of the loop control expression is false, skip the loop, and then execute the following statement;

Example 1. Output all odd numbers between 1-100;

#include <stdio.h>
void main()
{
    
    
	int i=1;//记得赋初始值;
	while(i <= 100)
	{
    
    
		if(i%2 != 0)//判断奇偶;(i%2==0)输出偶数;
		{
    
    
			printf("%5d",i);
		}
		i++;
	}
}
  1. Infinite loop (to give an example)
#include <stdio.h>
void main()
{
    
    
	int i=1;
	while(i <= 100);//这里加上分号就很有可能变成死循环
	{
    
    
		if(i%2 != 0)
		{
    
    
			printf("%5d",i);
		}
		i++;
	}
}

Two, do...while statement

  1. The general form
    do
    { loop body statement; } while (loop control expression);


while(); followed by a semicolon

  1. flow chart
    do...while

The loop body statement is executed first, and then the expression judgment is performed;

  1. The execution process of the do...while statement:

a. Calculate the loop body statement;
b. Calculate the value of the loop control expression;
c. If the value of the loop control expression is true, return to the step;
d. If the value of the loop control expression is false, skip the loop, Then execute the following statement;
because it is executed first, and then the true or false of the expression is judged, the statement in the loop body is executed at least once;

  1. The difference between while and do...while:
(1)#include <stdio.h>              (2)#include <stdio.h>
void main()                        void main()                           
{
    
                                      {
    
        
	int i=11;                       int i=11;
	while(i<=10)                    do
	{
    
                                  {
    
    
		printf("i = %d\n",i);          printf("i = %d\n",i);
		i++;                           i++;
	}                               }
	                                while(i<=10);
}                                  }
没有任何输出                        输出:i=11

Program (1) is executed after judgment first, so when the condition is not met at the beginning, the loop is not executed once, so there is no output;
program (2) is executed first and then judged, and it has been executed once The judgment is performed again, so the loop is executed at least once, and the output i=11.

Example 2: A number quiz game between 1-100 (when the random value is fixed)

#include <stdio.h>
#include <stdlib.h>
void main()
{
    
    
	int person,machine;//用户猜的数,系统随机数
	int i = 0;  //猜的次数
	printf("输入一个1-100之间的数:");
	machine = rand()%100+1;
	do{
    
         
		    scanf("%d",&person);
			if(person>machine)
			{
    
    
				printf("这个数大了!\n");
			}
			else if(person<machine)
			{
    
    
				printf("这个数小了!\n");
			}
			else
			{
    
    
				printf("你猜对了!\n");
			}
			i++;
	  }
	while(person!=machine);
	printf("您一共猜了%d次\n",i);
}

The rand() function generates an integer between 0-32767; you need to include the header file stdlib.h when using it;
rand()%b ==> [0, b-1] between;
rand()%b+a ==> [a,a+b-1] between;

Three, for statement

  1. General form:
    for (initialization expression; loop control expression; loop variable increment)
    { loop statement; }

The expression separator semicolon in the for statement, there are only two, and cannot be omitted;

It can also be expressed in other forms:

初始化表达式                           初始化表达式 
 for(  ;循环控制表达式;循环变量增量)     for( ;循环控制表达式; )
    {
    
                                          {
    
    
       循环语句;                              循环语句;  
                                              循环变量增量;
    }                                     }
 当循环控制表达式省略时,则表示循环条件永真,不做处理的话,可能会导致死循环;
  1. flow chart:
    for

  2. The execution process of the for statement:
    a. Start with the initialization expression;
    b. Execute the loop control expression, if its value is true (not 0), execute the statement in the loop, and then execute the loop variable increment statement;
    c. If it is If the value is false (0), the loop is ended and the statement outside the loop is executed;

Example 3: (Algorithm 1: Exhaustive method) Han Xin's problem of
ordering soldiers Han Xin has a team of soldiers. He wants to know how many people there are, so he asks the soldiers to queue up to report the number: According to the number from 1 to 5, the number reported by the last soldier is 1; Press from 1 to 6, the number reported by the last soldier is 5; press from 1 to 7 to report the number, and the number reported by the last soldier is 4; finally press from 1 to 11 to report the number, the last The number reported by a soldier was 10. How many soldiers does Han Xin have at least by programming?

Exhaustive method: start from 1 until the above condition is satisfied i, i is the desired value;

Solution one:

#include <stdio.h>
void main()
{
    
    
	int i;
	for(i=1; ;i++)
	{
    
    
		if(i%5==1 && i%6==5 && i%7==4 && i%11==10)
		{
    
    
			printf("%d\n",i);
			break;
		}
	}
}

Use an infinite loop to find the first value that satisfies the condition, and then jump out of the loop;

Solution 2: (For conditional control loops with unknown number of loops, generally use while or do while statements)

#include <stdio.h>
void main()
{
    
    
	int i = 0;
	do
	{
    
    
		i++;
	}
	while(!(i%5==1 && i%6==5 && i%7==4 && i%11==10));
	printf("%d\n",i);
}

Algorithm 2: Recursive method: The value of the next item is calculated on the premise of the previous item.
Find the first 40 numbers in the Fibonacci sequence. This number sequence has the following characteristics: the first and second numbers are 1, 1. Starting from the third number, the number is the sum of the previous two numbers.

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

Four, goto statement and if statement form a loop

  1. Generally, goto statements and if statements are not used to form a loop;

**Example: **Calculate the sum of 1+2+…+100

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

Guess you like

Origin blog.csdn.net/weixin_46623617/article/details/105384715