C language - branch and loop

Posted by PRSWeb on Fri, 04 Mar 2022 01:10:09 +0100

1, Foreword

C language is a structured programming language
1. Sequential structure
2. Select structure
3. Circulation structure
Life is nothing more than these three structures: some people follow the steps, some people face choices, and some people go back and forth
Focus on selection statements, circular statements and extended jump statements

2, What is a statement

//1. In C language, what is separated by a semicolon is a statement
int main()
{
	printf("hehe\n");
	return 0;
}

3, Branch statement

1.if

Syntax structure: (expression): if the expression is true, it will be executed; otherwise, it will not be executed; It has been said before that in C language, 0 means false and non-0 means true

if (expression)
Statement;

if (expression)
   statement 1;
else
   statement 2;

if (expression)
   statement 1;
else if (expression)
   statement 2;
else
   statement 3;

Look at the code:

#include<stdio.h>
int main()
{
	int age=20;
	if(age>=18)
		printf("adult\n");
	else
		printf("under age\n");
		printf("Can't fall in love\n");
	return 0;
}

result:

You can't fall in love when you're an adult
It shows that else has no power and can't talk about love. This is an independent statement



//After the protest of the majority of male compatriots (er... Now excluding minors), we decided to amend this sentence and look at the code:

#include<stdio.h>
int main()
{
	int age = 20;
	if (age >= 18)
		printf("adult\n");
	else
	{
		printf("under age\n");
		printf("Can't fall in love\n");
	}
	//if and else have multiple statements, {} must be used; Of course, a statement can also use {} or not
}

result:
1.

2.

Look at the code:

#include<stdio.h>
int main()
{
	int age = 60;
	if (age < 18)
		printf("juvenile\n");
	else if (18 <= age < 26)
		printf("youth\n");
	//Results: young people 
	//The world has changed - 60 year old youth (has China's aging problem been solved?)
	//Code logic:
	//If (60 < 18) - false, do not execute
	//Else if (18 < = 60 < 26) - 18 < = 68 is true and returns 1
	//Else if (1 < 26) - 1 < 26 is true
	//	printf("youth \ n");
	return 0;
}

//Don't believe rumors, don't spread rumors - since the 1990s, China's aging process has accelerated, and China can't solve the problem of aging in a short time... Er... Digress.
//Look at the code - multi branch

#include<stdio.h>
int main()
{
	int age = 60;
	if (age < 18)
		printf("juvenile\n");
	else if (age >= 18 && age <= 26)
		printf("youth\n");
	else if (age >= 26 && age < 40)
		printf("middle age\n");
	else if (age >= 40 && age < 60)
		printf("Prime of life\n");
	else if (age >= 60 && age <= 100)
		printf("old age\n");
	else
		printf("Old age never dies\n");
	//Logical operators are used here&&
	//&&If the same is true, the rest is false - 60 < 26 is false, and if one side is false, it is false
	//||The same false is false and the rest is true
	return 0;
}

Look at the code - hanging else

#include<stdio.h>
//Ask the implementation results?
int main()
{
	int a = 0;
	int b = 2;
	if (a == 1)
		if (b == 2)
			printf("hehe\n");
	else
		printf("haha\n");
	//Ideally: the first if and else are aligned. They are a pair. if(0==1) is false, execute else and print haha 
	//The result is no printing - I know it's not so simple - it's another pit
	//In fact, if and else have nothing to do with alignment, but else matches the nearest if
	//In fact, the compiler is very smart - when you write else, it will align and match its nearest if - note that when you don't use the platform to write code in the future (for example, Notepad), you should pay attention to the writing specification of the code
	return 0;
}

Here we should emphasize the importance of code specification, followed by code style;
Some students write code

What's more

The best compiler of x can't save you
About the code style, here is a book worth reading "high quality C/C + + program"

Easy to confuse
I
Observe 1 and 2 codes:

1:
if (condition)
{
  return x;
}
return y;
2:
if (condition)
{
  return x;
}
else
{
  return y;
}

#include<stdio.h>
int test1()
{
	if (1)
	{
		return 0;
	}
	return 1;
}
int test2()
{
	if (0)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}
int main()
{
	test1();
	test2();
	//The two pieces of code are essentially the same, but the writing form is different, and the resulting code style is also different
	return 0;
}

2, Observe 3 and 4 codes:

3:
if (condition)
{
  printf("hehe\n");
}
printf("haha\n");
4:
if (condition)
{
   printf("hehe\n");
}
else
{
  printf("haha\n");
}

#include<stdio.h>
void test3()
{
	if(1)
	{
		printf("hehe\n");
	}
	printf("haha\n");
}
void test4()
{
	if(1)
	{
		printf("hehe\n");
	}
	else
	{
		printf("haha\n");
	}
}
int main()
{
	test3();//hehe haha
	test4();//hehe
	//This is the difference caused by the form of code writing
	return 0;
}

3, Observe 5 and 6 Codes:

5:
int num = 1;
if (num ==5)
{
  printf ("hehe\n");
}
6:
int num == 1;
if (5 == num)
{
  printf ("hehe\n");
}

First look at an error code:

#include<stdio.h>
int main()
{
	int num = 3;
	if (num = 5)//I don't want to output "hehe" - because I wrote one less =; num is assigned a value of 5, which is true - and the compiler does not report an error - this kind of code error is difficult to find in the process of writing code in the future (the output result is inconsistent with the expectation - runtime error)
	{
		printf("hehe\n");
	}
	return 0;
}

After optimization:

#include<stdio.h>
int main()
{
	int num = 3;
	if (5 == num)//When writing such expressions in the future, try to write the numbers on the left; Because if you write one less = - 5=num - err: the left operand must be an lvalue (syntax error) 
	{
		printf("hehe\n");
	}
	return 0;
}

5. The function of 6 code is the same, but after the analysis of the above two codes, 6 code is more standardized

Small trial ox knife
Judge whether a number is odd

int main()
{
	int num = 15;
	if (num % 2 == 1)
	{
		printf("Odd number\n");
	}
	return 0;
}

2.switch

It is often used in multi branch scenarios

switch (integer expression)
{
    statement item;
}
Statement item:
case integer constant expression:
    statement;
case integer constant expression:
    statement;
... ...

For example:
Input 1, output Monday
Input 2, output Tuesday
Input 3, output Wednesday
... ...
If you use if... else if... Else, the form of if is too complex
Look at the code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
	int day = 0;
	//Enter a number from the keyboard into the day variable
	scanf("%d", &day);
	//Put the value of day into the expression (only integer) - the value of day will match the case tag below and execute the statement under the tag
	switch (day)
	{
	case 1:
		printf("Monday\n");
	case 2:
		printf("Tuesday\n");
	case 3:
		printf("Wednesday\n");
	case 4:
		printf("Thursday\n");
	case 5:
		printf("Friday\n");
	case 6:
		printf("Saturday\n");
	case 7:
		printf("Sunday\n");
	}
	//It is found that if we input 3 - the content after Wednesday will also be output; Input 4 - the content after Thursday will also be output; Obviously, this is not the result we want
	return 0;
}

After correction:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
		printf("Monday\n");
		break;
	case 2:
		printf("Tuesday\n");
		break;
	case 3:
		printf("Wednesday\n");
		break;
	case 4:
		printf("Thursday\n");
		break;
	case 5:
		printf("Friday\n");
		break;
	case 6:
		printf("Saturday\n");
		break;
	case 7:
		printf("Sunday\n");
		break;
	}
	//Note: 1 Switch (integer expression)  
	//2.case integer constant expression:  
	//3. Characters can be used as expressions because they have corresponding ASCII code values 
	//4. The integer constant expression in case cannot be the same as the value in other cases
	return 0;
}

Is thinking break a must in a switch statement?
If 1-5 are working days; 6-7 are rest days

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		printf("weekdays\n");
		break;
	case 6:
	case 7:
		printf("Rest Day\n");
		break;
	}
	//Obviously, break is added as needed
	//Do you need to add break in the last label- It won't affect if you don't add it, but if you have a good habit of programming, you'd better add it - to prevent it from overlapping with the previous label if you want to add a new case label later
	return 0;
}

default clause:
Take the working day code for example. Enter a 9 or exclude a number between 1 and 7 - there are many such numbers (wrong numbers) - we can't list them one by one - then you can use the default clause

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		printf("weekdays\n");
		break;
	case 6:
	case 7:
		printf("Rest Day\n");
		break;
	default:
		printf("Input error\n");
		break;
	}
	//Note: 1 The switch does not specify the case tag order or default order, as long as it is logical
	//2. There can only be one default clause
	return 0;
}

Small trial ox knife

#include<stdio.h>
nt main()
{
	int n = 1;
	int m = 2;
	switch (n)
	{
	case 1:
		m++;
	case 2:
		n++;
	case 3:
		switch (n)//switch allows nested use
		{
		case 1:
			n++;
		case 2:
			m++;
			n++;
			break;//This break may be the reason why you miss the correct answer - use break in nested switch statements, and break jumps out of your own switch statement
		}
		m++;
		break;
	default:
		break;
	}
	printf("m=%d,n=%d\n", m, n);//m=5,n=3
	return 0;
}

4, Circular statement

1.while

While (expression)
{
   circular statement;
}

Look at the code: print 1-10 on the screen

#include<stdio.h>
//Hard core output
int main01()
{
	printf("1 2 3 4 5 6 7 8 9 10");//If you want to print 1-100 or more - that's too much trouble
	return 0;
}
//Cyclic output
int main02()
{
	//The start of the cycle is 1 and the end is 10
	int i = 1;//Initialization part
	while (i <= 10)//Judgment part
	{
		printf("%d ", i);
		i++;//Adjustment part
	}
	//Any change in one of the three parts will affect the cycle
	return 0;
} 

break and continue in a while loop

#include<stdio.h>
int main01()
{
	int i = 1;
	while (i <= 10)
	{
		if (5 == i)
		{
			break;
		}
		printf("%d ", i);
		i++;
	}
	//The result is 1 2 3 4 - once the condition break is met, it will permanently jump out of the loop
	return 0;
}
int main02()
{
	int i = 1;
	while (i <= 10)
	{
		if (5 == i)
		{
			continue;
		}
		printf("%d ", i);
		i++;
	}
	//The result is 1 2 3 4- The function of dead loop - continue is to skip the code behind this loop continue and directly go to the while loop judgment part to judge the entry of the next loop
	//The reason for the dead loop here is that once 5 = = 5 is established, the following code will be skipped (i + + skipped) and back to while (i < = 10) 
	return 0;
}

getchar and putchar

int main01()
{
	//getchar can read a character from the keyboard - its return value is a character (the corresponding ASCII code value); EOF is returned if an error is encountered while reading or the file ends
	//putchar can output one character
	//EOF - end of file - end of file flag - right click to go to the definition of EOF and find that the value of EOF is - 1 
	int ch = getchar();
	printf("%c\n", ch);
	putchar(ch);
	//It is found that no matter how many characters it inputs, it can only output one
	return 0;
}
//The use of loops enables putchar to output multiple characters
int main02()
{
	int ch = 0;
	while ((ch = getchar()) != EOF)
	{
		putchar(ch);
	}
	//In fact, getchar is not read directly from the keyboard, but in the buffer between getchar and the keyboard
	//When "A enter" is entered - there are actually two characters in the buffer - 'A','\n'
	//CTRL+Z - getchar will finish reading
	return 0;
}

The application scenario of getchar:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main01()
{
	char password[20] = { 0 };
	printf("Please input a password:>");
	//For an array, the array name itself is an address - so you don't have to&
	scanf("%s", &password);//123456\n
	printf("Please confirm the password(Y/N):>");
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("Confirmation successful\n");
	}
	else
	{
		printf("Confirmation failed\n");
	}
	//It was found that after entering the password and pressing enter - the program did not wait for us to confirm the password - the direct confirmation failed
	//We all know that scanf and getchar read data in the input buffer
	//When we enter 123456\n, scanf will only read data except \ n; At this time, there is still one in the input buffer. \ n getchar takes it away as soon as it sees the content in the input buffer; ' \n'=='Y' is false, execute else
	return 0;
}
//After correction:
int main02()
{
	char password[20] = { 0 };
	printf("Please input a password:>");
	scanf("%s", &password);//123456 abcdef\n
	printf("Please confirm the password(Y/N):>");
	getchar();//Clear buffer - remove \ n
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("Confirmation successful\n");
	}
	else
	{
		printf("Confirmation failed\n");
	}
	//Here, when we enter 123456 abcdef\n, we find that it can't stop again
	//scanf only reads the characters in front of the space, and there are still many characters left in the buffer
	return 0;
}
//Correction after correction:
int main03()
{
	char password[20] = { 0 };
	printf("Please input a password:>");
	scanf("%s", &password);//123456 abcdef\n
	printf("Please confirm the password(Y/N):>");
	int temp = 0;
	while ((temp = getchar()) != '\n')//Use a loop to clean up multiple characters in the buffer
	{
		;
	}
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("Confirmation successful\n");
	}
	else
	{
		printf("Confirmation failed\n");
	}
	return 0;
}

Look at the code: what is the result

#include<stdio.h>
int main()
{
	int ch = 0;
	while ((ch = getchar()) != EOF)
	{
		if (ch<'0' || ch>'9')//If it is a non numeric character, execute continue to skip this cycle and judge again; Otherwise output
		{
			continue;
		}
		else
		{
			putchar(ch);
		}
	}
	//The function of this program is to print only numbers
	return 0;
}

2.for

for (expression; expression; expression)
{
╭ circular statement;
}


Having learned the while loop, why learn the for loop? Or what are the defects of the while loop?

#include<stdio.h>
int main01()
{
	int i = 1;//Initialization part
	//...
	//...
	while (i <= 10)//judge
	{
		printf("%d ", i);
	}
	//...
	//...
	i++;//adjustment
	//When more and more code is written in the future, these three parts may be far apart, resulting in inconvenient changes or reading
	return 0;
}
//The for loop avoids this problem well - it puts initialization, judgment and adjustment in a bracket
//For (expression; expression; expression)
//For (initialization; judgment; adjustment)
//Look at the code: use the for loop to print 1-10
int main02()
{
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
		printf("%d ", i);
	}
	return 0;
}

break and continue in the for loop

#include<stdio.h>
int main01()
{
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
		if (5 == i)
			break;
		printf("%d ", i);//1 2 3 4
	}
	//If 5 = = 5 is true, terminate the for loop
	return 0;
}
int main02()
{
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
		if (5 == i)
			continue;
		printf("%d ", i);//1 2 3 4 6 7 8 9 10
	}
	//The adjustment part i + + is not skipped here, so there will be no dead loop; The continue in the while loop is likely to skip the adjustment part, resulting in an endless loop
	return 0;
}

Suggestions and notes on using for loop
1. Do not modify the loop variable in the for loop to prevent the for loop from losing control

#include<stdio.h>
int main()
{
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
		printf("%d ", i);
		i = 5;// -err: the cause of the dead cycle
	}
	return 0;
}

2. It is suggested that the value of the loop control variable of the for statement should be "closed before open interval"

#include<stdio.h>
int main()
{
	int arr[10] = { 0 };
	int i = 0;
	//It is not recommended to write as for (I = 0; I < = 9; I + +) - pre closed and post closed interval - not that this writing is wrong - but that the readability is relatively poor
	for (i = 0; i < 10; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

3. Definition initialization in for loop

#include<stdio.h>
int main()
{
	//Here i is defined inside the for loop
	for (int i = 0; i < 10; i++)
	{
		printf("%d ", i);
	}
	//It is found that there is no problem running in VS2017. In fact, this writing method is C + + syntax. Although it can run, it may cause cross platform problems on other platforms
	return 0;
}

Some other forms of the for loop
1.

#includ<stdio.h>
int main()	
{
	//The initialization, judgment and adjustment of the for loop can be omitted, and the syntax is supported - but not recommended
	//Omission of judgment part - constant to true - dead cycle
	for (;;)
	{
		printf("hehe\n");
	}
	return 0;
}

Let's look at the code first: how many "hehe" are output

#include<stdio.h>
int main01()
{
	int i = 0;
	int j = 0;
	for (i = 0; i < 3; i++)
	{
		for (j = 0; j < 3; j++)
		{
			printf("hehe\n");//Print 9 "hehe" in total
		}
	}
	return 0;
}
//Take the above code for example: because i and j have been defined, i=0 and j=0 in the for loop are omitted?
int main02()
{
	int i = 0;
	int j = 0;
	for (; i < 3; i++)
	{
		for (; j < 3; j++)
		{
			printf("hehe\n");//Print 3 "hehe" in total
		}
	}
	//Here, when i=0, after 3 "hehe" are output in the inner loop; i=1. At this time, j=3 here is not reinitialized to 0
	return 0;
}
#include<stdio.h>
int main()
{
	int x, y;
	for (x = 0, y = 0; x < 2 && y < 5; ++x, y++)
	{
		printf("hehe\n");//Output 2 "hehe"
	}
	return 0;
}

Try the ox knife - how many times does it cycle

int main()
{
	int i = 0;
	int k = 0;
	for (i = 0, k = 0; k = 0; i++, k++)
	{
		k++;
	}
	//Because k=0 is false, it will not enter the loop
	return 0;
}

3.do while

do
{
   statement;
}While (expression);


This sentence is very personalized. I prefer to cut first and then play - execute first and then judge
Print 1-10

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

break and continue in do... while loop

#include<stdio.h>
int main01()
{
	int i = 1;
	do
	{
		if (5 == i)
			break;
		printf("%d ", i);//1 2 3 4
		i++;
	} while (i <= 10);
	
	return 0;
}
int main02()
{
	int i = 1;
	do
	{
		if (5 == i)
			continue;
		printf("%d ", i);//1 2 3 4... Dead cycle
		i++;
	} while (i <= 10);
	//When 5 = = 5 is true, it will skip the adjustment part i + + to the judgment part
	return 0;
}

Characteristics of do... while loop: the loop is executed at least once, and the use scenarios are limited, so it is not often used

5, Jump statement

1.goto

c language provides goto statements that can be abused at will and labels that mark jump; Theoretically, goto statement is unnecessary, but it is useful in some situations (but it is not recommended)

int main()
{
	flag:
	printf("hehe\n");
	printf("haha\n");
	goto flag;
	//The result is an endless loop - goto defines flag here; Every time it comes to the goto statement, it will jump to the place matching the flag
	return 0;
}

Topics: C