Elementary C Language - Branch and Loop Statements (Part 2)

"Flowers will bloom along the way, and so will the road in the future." Today we will continue to learn more about branch statements and loop statements together.

3. Loop statement

3.2 getchar() and putchar() statements

Here we give a program to confirm the password:

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
    
    
	char password[20];
	printf("请输入密码:");
	scanf("%s", password);//输入字符数组不需要&
	printf("请确认(Y/N): ");
	int ch = getchar();
	if ('Y' == ch)
		printf("密码正确!\n");
	else
		printf("密码错误!\n");
	return 0;
}

insert image description here
By running, we found that an error was reported here. The reason is that what we input from the keyboard is actually 123456\n. When getchar() reads, it will automatically read \n, so the result is wrong. Here we can use another one gerchar()to Clear the \n of the buffer , the detailed code is as follows:

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
    
    
	char password[20];
	printf("请输入密码:");
	scanf("%s", password);//输入字符数组不需要&
	getchar();//清理缓冲区
	printf("请确认(Y/N): ");
	int ch = getchar();
	if ('Y' == ch)
		printf("密码正确!\n");
	else
		printf("密码错误!\n");
	return 0;
}

insert image description here
insert image description here
We found that this way there is no problem! But what if there is a space in the middle of the password we entered? Can the above method still solve the problem?
insert image description here
We can find out, or report an error, why is this? When the scanf function reads a string, it will stop reading if it encounters a space! scanfIt will read information from the buffer. At the beginning, the buffer is empty. At this time, I input 123456 abc\n on the screen, and scanf will stop reading when it encounters a space, so it only reads 123456. The first one getchar()will read a space, then the second one getchar()will read a backwards, then this is definitely not enough, because there are still characters behind, so the result will be wrong. At this time, we need to use a loop to help us solve it this problem.

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
    
    
	char password[20];
	printf("请输入密码:");
	scanf("%s", password);//输入字符数组不需要&
	int ch = 0;
	while (getchar() != '\n')
	{
    
    
		;//该循环语句的目的就是让它一直读取到\n前面的字符
	}
	printf("请确认(Y/N): ");
	ch = getchar();
	if ('Y' == ch)
		printf("密码正确!\n");
	else
		printf("密码错误!\n");
	return 0;
}

insert image description here

3.3 for loop

We learned earlier while循环, here we look at the for loop again.

3.3.1 Grammar

//表达式1为初始条件,用于初始化循环变量的。
//表达式2为条件判断部分,用于判断循环时候终止。
//表达式3为调整部分,用于循环条件的调整。
for(表达式1;表达式2;表达式3)`
    循环语句;

Here, we use for循环also to try to print out the numbers from 1 to 10:

//for循环
#include <stdio.h>
int main()
{
    
    
	int i;
	for (i = 1; i <= 10; i++)
	{
    
    
		printf("%d ", i);
	}
	return 0;
}

insert image description here
Let's take a look at for循环the execution process in the form of a flow chart:
insert image description here
Here, let's use while循环the above functions to make a comparison:

#include <stdio.h>
int i = 1;//初始化部分
int main()
{
    
    
	while (i <= 10)//判断部分
	{
    
    
		printf("%d ", i);
		i++;//调整部分
	}
	return 0;
}

It can be found while循环that there are still three necessary conditions for the cycle, but due to the style problem, the three parts are likely to deviate far away. In this case, the search and modification are not concentrated and convenient enough. Therefore, for循环your style is better, and for循环your usage frequency is also the highest.

3.3.2 break and continue in for loop

We have learned about the functions of breakand continuestatements in while循环, so in for循环, do they have the same meaning? Next, let's take a look at the following piece of code, let's see what is the result of its operation?

//for循环中的break和continue
#include <stdio.h>
int main()
{
    
    
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
    
    
		if (i == 5)
			continue;
		printf("%d ", i);
	}
	return 0;
}

insert image description here
We can see that the numbers 1~4, 6~10 are printed on the screen, and 5 is missing. We found that when we i=5encountered it, comtinuethe statement after the current round of loop was skipped, but the adjustment statement was not skipped. If you encounter it in , you will skip the following code and go directly to the adjustment part of the loop, which is still somewhat different from that in . for循环continuecontinuewhile循环continueHere, let's take a look at the break in the kankanfor loop:

#include <stdio.h>
int main()
{
    
    
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
    
    
		if (i == 5)
			break;
		printf("%d ", i);
	}
	return 0;
}

insert image description here
breakIn for循环is also directly terminating the loop, as long as it is encountered break, it will end directly, which is the same as in the loop while.for

Here is for语句a suggestion for the loop control variable:

  1. The loop variable cannot be modified for循环internally to prevent for循环loss of control.
  2. The value of the suggested for语句loop control variable is written in the form of "closed before and opened after".

3.3.3 Some for loop variants

The three parts of initialization, judgment and adjustment can be omitted, but if the judgment part is omitted, it means that the judgment part is always true.

Here are some examples to help you understand:

#include <stdio.h>
int main()
{
    
    
	for (;;)
	{
    
    
		printf("6 ");
	}
	return 0;
}

By running, we can find that the judgment code is always true, entering an infinite loop, and the screen keeps printing 6.

insert image description here

Next, let's look at the following two examples:

#include <stdio.h>
int main()
{
    
    
	int i = 0;
	int j = 0;
	int count = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		for (j = 0; j < 10; j++)
		{
    
    
			printf("haha ");
			count++;//计数的作用
		}
	}
	printf("count = %d ", count);
	return 0;
}

insert image description here
We can find that 100 hahas are printed on the screen, so what happens when we omit the initialization?

#include <stdio.h>
int main()
{
    
    
	int i = 0;
	int j = 0;
	int count = 0;
	for (; i < 10; i++)
	{
    
    
		for (; j < 10; j++)
		{
    
    
			printf("haha ");
			count++;//计数
		}
	}
	printf("count = %d ", count);
	return 0;
}

insert image description here
By running, we found that only 10 hahas are printed on the screen at this time. Although the initialization can be deleted, we should not clear it at will, otherwise, the meaning of the expression will change. Let's look at another example together, let's see how many times this code loops?

//示例
#include <stdio.h>
int main()
{
    
    
	int i = 0;
	int j = 0;
	for (i = 0, j = 0; j = 0; i++,j++)
		j++;
	return 0;
}

There may be students whose first reaction is 1 time. If your idea is also 0, then it is wrong. What we need to pay attention to is the for循环second expression j = 0. Here =is the assignment operator, rather than judging whether j is equal to 0 or not. j=0 (assigned to 0 is false), then the expression is false, the cycle is 0 times, and all programs will not be executed.
insert image description here

Alright, that’s all for today. Welcome to follow, like and comment!

Guess you like

Origin blog.csdn.net/qq_73121173/article/details/131872187