C language notes: loop statement

content

1.while loop

1.1 Syntax

1.2 break and continue in while statement

1.2.1 The role of break in the while loop:

1.2.2 The role of continue in the while loop:

2.for loop

2.1 Syntax

2.1 break and continue in for loop

2.2 The loop control variable of the for statement

2.3 Some variants of for loops

3. do...while loop

3.1 Syntax

3.2 Features of the do statement

3.3 break and continue in do while loop

Supplement: How to use the goto statement

Exercise questions:

Exercise 1: Calculate the factorial of n

Exercise 2: Calculate 1!+2!+3!+...+10!

Exercise 3: Find a specific number n in an ordered array. (binary search)

Exercise 4*: Write code that demonstrates multiple characters moving from ends to converge toward the middle.

Exercise 5: Write code to simulate the user login scenario, and can only log in three times. (Only three passwords are allowed to be entered. If the password is correct, it will prompt that the login is successful. If the password is entered incorrectly three times, the program will be exited.

Exercise 6***: Number guessing game - 1. The computer randomly generates a number 2. The player guesses the number (the return value can only be a big guess, a small guess, and a correct guess) until the guess is correct


1.while loop

1.1 Syntax

while(expression) loop statement;

The flow of while statement execution:

1.2 break and continue in while statement

1.2.1 The role of break in the while loop:

As long as break is encountered in the loop, all subsequent loops are stopped and the loop is terminated directly.

The break in while is used to permanently terminate the loop.

#include <stdio.h>
int main()
{
     int i = 1;
     while(i<=10)
     {
         if(i == 5)
             break;
         printf("%d ", i);
         i = i+1;
     }
     return 0;  //1 2 3 4 当i == 5时循环结束
}

1.2.2 The role of continue in the while loop:

continue is used to terminate this loop, that is, the code after continue in this loop will not be executed, but jump directly to the judgment part of the while statement. The entry judgment of the next cycle is performed .

Such as:

#include <stdio.h>
int main()
{
     int i = 1;
     while(i<=10)
     {
         if(i == 5)
             continue;
         printf("%d ", i);
         i = i+1;
     }
     return 0;  //1 2 3 4 但陷入死循环,因为i始终等于5
}

Exercise 1:

//代码什么意思?
//代码1
#include <stdio.h>
int main()
{
    int ch = 0;        //此处用的int需要重视下方的解释
    while ((ch = getchar()) != EOF)  
        putchar(ch);
    return 0;
}//输入字符则打印字符,直到键盘输入 Ctrl Z 结束循环

Notes: getchar( ): Get a character (corresponding ASCII code value) from the keyboard, int getchar(void);

           Note: The character obtained by getchar is actually the obtained ASCII code value , and EOF is essentially -1, where ch may be equal to EOF (-1), and the char type cannot store -1, so it is defined here with int ch

           putchar( ): prints a character to the screen

           EOF - end of file: the sign of the end of the file (Note: the above code is not to enter "EOF" to end the loop but to enter Ctrl Z )

*Exercise 2 (key attention): Analyze why the following code does not work as expected, and learn how to clear the buffer

#include <stdio.h>
int main()
{
    int ch = 0;
	char password[20] = {0};

	printf("请输入密码:>");
	scanf("%s", password);

	printf("请确认(Y/N):>");
	ch = getchar();

	if('Y' == ch)
	{
		printf("确认成功\n");
	}
	else
	{
		printf("放弃确认\n");
	}

	return 0;
}

The results are as follows:

Analysis : The scanf function and the getchar function are both functions to obtain data from the keyboard (not directly). In fact, there is an input buffer between the function and the keyboard . When the program executes this function, the function will check whether there is data in the input buffer. If there is, it will be taken away directly . If not, the keyboard input data will be required to enter the input buffer, and the function will take out the data.

When the user enters 123+Enter (\n) on the keyboard, "123\n" enters the input buffer, when the scanf function takes the data, only "123" is taken away , and '\ n' remains in the input buffer area , when the program executes to ch == getchar( ), getchar will not wait for user input but directly take "\n" in the buffer , because of '\n'! ='Y', so the above result is caused.

How to modify the code?

Preliminary method: Before the program executes to ch == getchar( ), use a getchar to remove the '\n' in the input buffer

#include <stdio.h>
int main()
{
    int ch = 0;
	char password[20] = {0};

	printf("请输入密码:>");
	scanf("%s", password);
    //处理\n
    getchar();

	printf("请确认(Y/N):>");
	ch = getchar();

	if('Y' == ch)
	{
		printf("确认成功\n");
	}
	else
	{
		printf("放弃确认\n");
	}

	return 0;
}

But the actual situation may be far more complicated than the above example, for example, when entering "123456 abcdef", an error will occur.

The reason for the error is: when scanf reads the string to the space, it thinks it is over, only 123456 is taken away, and the remaining "abcdef" is still in the buffer, how to deal with it?

The answer is as follows:

#include <stdio.h>
int main()
{
    int ch = 0;
	char password[20] = {0};

	printf("请输入密码:>");
	scanf("%s", password);

    //处理缓冲区多余的字符
    while(getchar() != '\n')
    {
        ;                     //当getchar()没有读取到'\n'时,该循环会让getchar()不停的读取
    }
	printf("请确认(Y/N):>");
	ch = getchar();

	if('Y' == ch)
	{
		printf("确认成功\n");
	}
	else
	{
		printf("放弃确认\n");
	}

	return 0;
}

*Exercise 3:

#include <stdio.h>
int main()
{
    int ch = 0;
 while ((ch = getchar()) != EOF)
 {
     if (ch < '0' || ch > '9')
        continue;
     putchar(ch);
 }
 return 0;
}
//这个代码的作用是:只打印数字字符,跳过其他字符的

2.for loop

2.1 Syntax

for(expression1; expression2; expression3) loop statement;

Expression 1 Expression 1 is the initialization part, which is used to initialize the loop variable.

Expression 2 Expression 2 is the conditional judgment part, which is used to judge the termination of the loop.

Expression 3 Expression 3 is an adjustment part for adjustment of loop conditions.

Now let's compare the for loop and the while loop:

int i = 0;
//实现相同的功能,使用while
i=1;                       //初始化部分
while(i<=10)               //判断部分
{
 printf("hehe\n");
 i = i+1;                  //调整部分
}

//实现相同的功能,使用for
for(i=1; i<=10; i++)
{
 printf("hehe\n");
}

 It can be found that there are still three necessary conditions for the loop in the while loop, but due to the style problem, the three parts are likely to deviate far away, so the search and modification are not concentrated and convenient enough.

Therefore, the style of for loop is better, and the frequency of for loop is also the highest .

2.1 break and continue in for loop

Break and continue can also appear in for loops, and their meanings are the same as in while loops.

But there are still some differences:

//代码1
#include <stdio.h>
int main()
{
     int i = 0;
     for(i=1; i<=10; i++)
     {
         if(i == 5)
         break;
         printf("%d ",i);
     }
     return 0;                 //1 2 3 4 
}
//代码2
#include <stdio.h>
int main()
{
     int i = 0;
     for(i=1; i<=10; i++)
         {
         if(i == 5)
         continue;
         printf("%d ",i);      //1 2 3 4 6 7 8 9 10
         }
     return 0;
}

2.2 The loop control variable of the for statement

Good programming habits :

1. The loop variable cannot be modified in the body of the for loop to prevent the for loop from losing control.

2. It is recommended that the value of the loop control variable of the for statement be written in the "front closed and then open interval " writing method.

int i = 0;
//前闭后开的写法
for(i=0; i<10; i++)
{}
//两边都是闭区间
for(i=0; i<=9; i++)
{}

2.3 Some variants of for loops

#include <stdio.h>
int main()
{
     //代码1
     for(;;)
     {
         printf("hehe\n");
     }
    //for循环中的初始化部分,判断部分,调整部分是可以省略的,但是不建议初学时省略,容易导致问
    
    //代码2
    int i = 0;
    int j = 0;
    //这里打印多少个hehe?                             //100
    for(i=0; i<10; i++)
   {
        for(j=0; j<10; j++)
       {
           printf("hehe\n");
       }
   }
    
    //代码3
    int i = 0;
    int j = 0;
    //如果省略掉初始化部分,这里打印多少个hehe?         //10
    for(; i<10; i++)
    {
        for(; j<10; j++)
       {
           printf("hehe\n");
       }
    }
    
    //代码4-使用多余一个变量控制循环
    int x, y;
    for (x = 0, y = 0; x<2 && y<5; ++x, y++)
   {
        printf("hehe\n");
   }
 return 0;
}

 Interview questions:

//请问循环要循环多少次?  0次
#include <stdio.h>
int main()
{
 int i = 0;
 int k = 0;
 for(i =0,k=0; k=0; i++,k++)
        k++;
 return 0;
}

When the judgment statement is k = 0, 0 is assigned to k, the result of the expression is 0 , and 0 is false, so the loop is not executed

3. do...while loop

3.1 Syntax

do

        loop statement;

while(expression);

3.2 Features of the do statement

The loop is executed at least once, and the usage scenarios are limited, so it is not used very often.

3.3 break and continue in do while loop

#include <stdio.h>
int main()
{
     int i = 1;
    
     do
     {
            if(5 == i)
                break;
            printf("%d\n", i);
            i++;
     }while(i <= 10);
    
     return 0;
}                                   // 1 2 3 4 程序结束
#include <stdio.h>
int main()
{
     int i = 1;
    
     do
     {
            if(5 == i)
                continue;
            printf("%d\n", i);
            i++;
     }while(i <= 10);
    
     return 0;                     // 1 2 3 4 程序未结束,陷入死循环
}

Supplement: How to use the goto statement

The C language provides goto statements and labels that mark jumps that can be abused at will.

Theoretically, the goto statement is unnecessary. In practice, it is easy to write code without the goto statement.

The goto statement is easy to mess up the logic of the code

But in some cases the goto statement is still useful, the most common usage is to terminate the processing of the program in some deeply nested structures.

For example: jump out of two or more layers of loops at a time.

The use of break in this case of multi-layer loop will not achieve the purpose. It can only exit from the innermost loop to the previous loop.

The scenarios where the goto statement is really suitable are as follows:

for(...)
    for(...)
   {
        for(...)
       {
            if(disaster)
                goto error;
       }
   }
error:
 if(disaster)
         // 处理错误情况

Such as: a shutdown procedure

With the goto statement:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
    char input[10] = {0};
    system("shutdown -s -t 60");
again:
    printf("电脑将在1分钟内关机,如果输入:我是猪,就取消关机!\n请输入:>");
    scanf("%s", input);
    if(0 == strcmp(input, "我是猪"))
   {
        system("shutdown -a");
   }
    else
   {
        goto again;
   }
    return 0;
}
//shutdown -a 取消关机
//shutdown -s -t 时间(秒) 设置关机倒计时
//system需要<stdlib.h>,strcmp需要头文件<string.h>

Without the goto statement:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
    char input[10] = {0};
    system("shutdown -s -t 60");
    while(1)
    {
        printf("电脑将在1分钟内关机,如果输入:我是猪,就取消关机!\n请输入:>");
        scanf("%s", input);
    
    
    if(0 == strcmp(input, "我是猪"))
       {
        system("shutdown -a");
        break;
       }
    }
    return 0;
}

Exercise questions:

Exercise 1: Calculate the factorial of n

#include <stdio.h>
int main()
{
     int n = 0;
	 int i = 1;
	 int ret = 1;
	 
	 scanf("%d", &n);
	 
	 for (i = 1;i <= n; i++)
	 {
		 ret *= i;
	 }
	 printf("%d\n", ret); 
}

Exercise 2: Calculate 1!+2!+3!+...+10!

Code one:

#include <stdio.h>
int main()
{
     int j = 1;
	 int i = 1;
	 int ret = 1;
	 int sum = 0;
	 
	 for (j = 1;j <= 10; j++)
	 {
        ret = 1;    //最关键的一步,每次内层循环结束让ret回到初始值1
		for (i = 1;i <= j; i++)
		{
			 ret *= i;
		}
		sum += ret;
	 }

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

*Optimized code:

#include <stdio.h>
int main()
{
     int j = 1;
	 int ret = 1;
	 int sum = 0;
	 
	 for (j = 1;j <= 10; j++)
	 {
			 ret *= j;
		     sum += ret;
	 }

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

Exercise 3: Find a specific number n in an ordered array. (binary search)

//实现在主函数内:
int main()
{
 int arr[] = {1,2,3,4,5,6,7,8,9,10};
 int left = 0;
 int right = sizeof(arr)/sizeof(arr[0])-1;  //重点
 int key = 7;
 int mid = 0;
 while(left<=right)
 {
     mid = (left+right)/2;
     if(arr[mid]>key)
     {
         right = mid-1;
     }
     else if(arr[mid] < key)
     {
         left = mid+1;
     }
     else
         break;
 }
 if(left <= right)
     printf("找到了,下标是%d\n", mid);
 else
     printf("找不到\n");
}

Exercise 4*: Write code that demonstrates multiple characters moving from ends to converge toward the middle.

#include <stdio.h>
int main()
{
    char arr1[] = "welcome to bit!!!!!";
    char arr2[] = "###################";
    int left = 0;
    int right = strlen(arr1)-1;   //strlen()用于计算字符串长度
    
    while(left<=right)
    {   
        arr2[left] = arr1[left];
        arr2[right] = arr1[right];
        printf("%s\n", arr2);
        Sleep(1000);             //停顿1000ms
        system("cls");           //清空屏幕 需要头文件#include <windows.h>
        left++;
        right--;
    }
    printf("%s\n", arr2);
    return 0;
}

Exercise 5: Write code to simulate the user login scenario, and can only log in three times. (Only three passwords are allowed to be entered. If the password is correct, it will prompt that the login is successful. If the password is entered incorrectly three times, the program will be exited.

#include <stdio.h>
#include <string.h>
int main()
{
	int i = 0;
	//假设正确密码是"123456"
	char password[20] = {0};
	for(i = 0; i < 3; i++)
	{
		printf("请输入密码:>");
		scanf("%s", password);
		//判断密码的正确性 - 比较2个字符串的大小关系
		//strcmp - 用于比较字符串的大小关系,库函数,所需要的头文件是:string.h
		if(strcmp(password,"123456")==0)
		{
			printf("密码正确\n");
			break;
		}
		else
		{
			printf("密码错误,请重新输入\n");
		}
	}
    if(3 == i)
    {
        printf("三次密码错误,退出程序\n");
    }
	return 0;
}

Note : The strcmp function, short for string compare, compares two strings and returns an integer based on the result of the comparison. The basic form is strcmp(str1, str2), if str1=str2, it returns zero; if str1str2, it returns a positive number. For library functions, the required header file is: string.h

Exercise 6***: Number guessing game - 1. The computer randomly generates a number 2. The player guesses the number (the return value can only be a big guess, a small guess, and a correct guess) until the guess is correct

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void game()
{
	//1.生成随机数 1-100之间的随机数 所以让rand()对100取模再+1

	//C语言中有一个生成随机数的函数 - rand() (但每一轮生成的随机数是相同的) 
	//需要头文件<stdlib.h>
	//调用rand()前,需要使用srand()设置一个随机的起点
	//()内为时刻发生变化的数字 - 电脑上的时间一直在变化 =》时间戳=》time函数
	//time 获取系统时间,需要头文件<time.h> 此处想使用向time函数中传入一个空指针即可

	int guess = 0;
	int ret = rand()%100+1;
	printf("%d\n", ret);
	    
	//2.猜数字
	while(1)
	{
		printf("请猜数字:>");
		scanf("%d",&guess);
		if (guess > ret)
		{
			printf("猜大了\n");
		}
		else if (guess < ret)
		{
			printf("猜小了\n");
		}
		else
		{
			printf("恭喜你,猜对了!\n");
			break;
		}
	}
}

void menu()
{
 printf("**********************************\n");
 printf("*********** 1.play     **********\n");
 printf("*********** 0.exit     **********\n");
 printf("**********************************\n");
}

int main()
{
	int input = 0;
	srand((unsigned int)time(NULL)); 
	do
	{
		//1.打印一个菜单
		menu();
		printf("请选择:>");
		scanf("%d", &input);
		switch (input)
		{
			case 1:
				//游戏的逻辑
				game(); //猜数字游戏的代码
				break;
			case 0:
				printf("退出游戏\n");
				break;
			default:
				printf("选择错误,重新选择!\n");
				break;
		}
	}while(input);
	return 0;
}

Notes: 1. In order to execute the first game, choose do while loop

           2. The function of generating random numbers - rand() requires the header file <stdlib.h> int rand(void) but the random numbers generated in each round are the same, so before calling rand(), you need to use srand() to set a The random starting point srand() is also the library function needs the header file <stdlib.h>  void srand(unsigned int seed)   I want to put the number that changes at the moment in the parentheses - the time on the computer keeps changing = "timestamp =" The function of the time() function is to obtain the system time, the header file <time.h> is required, and I won't go into details. Here, I want to pass a null pointer to the time function.

           3. Put srand((unsigned int)time(NULL)); into the main function

           4. In order to generate a random number between 1-100, let rand() take the modulo of 100 and then +1
 

Guess you like

Origin blog.csdn.net/m0_62934529/article/details/123158560