c language is a structured programming language~
Sequential structure branch structure / selection structure cyclic structure
Everything in life is a combination of these three structures
1. What is a statement?
- Expression statement
- Function call statement
- Control statement
- Compound statement
- Empty statement
c=a+b;//Expression statement printf("%d\n", strlen("China"));//Function call statement if//switch control statement ; //Empty statement
Control statements are used to control the execution flow of the program to realize various structural modes of the program. They are composed of specific statement definer. There are nine control statements in C language
- Conditional judgment statements are also called branch statements: if statements and switch statements;
- Circular execution statements: do while statement, while statement and for statement;
- Turn statements: break statements, goto statements, continue statements, and return statements.
2. Branch statement
if statement
if statement
- If (expression)
sentence;
What is true and what is false
c language stipulates that 0 is false and non-0 is true - If (expression)
Statement 1;
else
Statement 2; - If (expression 1)
Statement 1;
Else if (expression 2)
Statement 2;
else
Statement 3;
int main() { int age = 0; scanf("%d", &age); /*if (age >= 18) { printf("Adult \ n ""); }*/ /*if (age >= 18) { printf("Adult \ n ""); } else { printf("Minors "); }*/ if (age < 18) { printf("juvenile\n"); } else if(age>=18&&age<40) { printf("youth\n"); } else if (age >= 40 && age < 60) { printf("Prime of life\n"); } else if (age >= 60 && age < 90) { printf("old age\n"); } else { printf("God of Longevity\n"); } }
if(18<=age<40)
18 < = 12 is false 0
0 is less than 40
There are errors in the operation logic. The syntax is correct and the logic does not meet the requirements
If the condition holds, you should use code blocks to execute multiple statements.
int main()
{
If (expression)
{
Statement list 1;
}
else
{
Statement list 2;
}
return 0;
}
Code specification problem
//About suspended else #include <stdio.h> int main() { int a = 0; int b = 2; if(a == 1) if(b == 2) printf("hehe\n"); else printf("haha\n"); return 0; }
What is the output?
Nothing is output. The first if doesn't go in
else is paired with the nearest if, which has nothing to do with how to align
//Proper use of {} can make the logic of the code clearer. //Code style is important #include <stdio.h> int main() { int a = 0; int b = 2; if(a == 1) { if(b == 2) { printf("hehe\n"); } } else { printf("haha\n"); } return 0; }
Particularly bad code style
#include <stdio.h> int main() { int a = 0; int b = 2; if (a == 1) if (b == 2) printf("hehe\n"); else printf("haha\n"); return 0; }
if writing form comparison
//Code 1 if (condition) { return x; } return y;
Poor code, poor readability
//Equivalent to code 2 if(condition) { return x; } else { return y; }
//Code 3 int num = 1; if(num == 5) { printf("hehe\n"); } //num==5 is easy to write as num=5
Put it another way
//Code 4 int num = 1; if(5 == num) { printf("hehe\n"); } //If you write wrong, 5=a compilation will not pass //5==a is equivalent to a==5
Write code similar to 5==a
practice
Odd number of outputs 1-100
//FA Yi int main() { int i = 0; while (i <= 100) { if (i % 2 == 1) { printf("%d ",i); } i++; } return 0; }
//Method II int main() { int i = 1; while (i <= 100) { printf("%d ", i); i += 2; } return 0; } //Very efficient
switch
It is better to convert multi branch statements into switch case s
#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; } return 0; }
switch must be followed by an integer expression
If float day=0;
The compilation will not pass
case must be followed by * * integer constant expression**
case 1.0 error reporting
switch() expression in parentheses
The expression in parentheses of switch() statement must be an integer, which should correspond to the value in case
Character type. Only character constants can be used. For example, 'a', 'b', '6' \ r 'is actually an integer
Brin type - true, false, actually 0, 1
enum type can also be used because it simulates 0,1,2,3
Can be char,long,int, but not float
#include <stdio.h> //switch code demonstration int main() { int day = 0; scanf("%d", &day); switch (day) { case 1: case 2: case 3: case 4: case 5: printf("weekday\n"); break; case 6: case 7: printf("weekend\n"); break; } return 0; }
The actual effect of the break statement is to divide the statement list into different branch parts
The real branch depends on break
default
When the value of the switch expression does not match the value of all case tags, the statement after the default clause will be executed.
Therefore, only one default clause can appear in each switch statement.
Make good use of default to prompt the user to enter the wrong value
default: printf("Please enter 1-7 Value of\n"); break;
defualt is placed in random order
Good programming habits. break is added after default
practice
#include <stdio.h> int 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; //Jump out of case3 } case 4: m++; break; default: break; } printf("m = %d, n = %d\n", m, n); return 0; }
Output 5 3
break can only jump out of one layer
3. Circular statement
while
#include <stdio.h> int main() { while (1) { printf("ha-ha"); } return 0; } //Dead cycle printing
ctrl+c can terminate the loop
While (expression)
Loop statement;
break/continue
#include <stdio.h> int main() { int i = 1; while (i <= 10) { if (5 == i) continue; printf("%d ", i); i++; } return 0; }
The result is 1 2 3 4
When i=5, the code after continue and the opportunity of i + + are skipped
Then judge again, i is equal to 5, and the following statements have been skipped,
Therefore, only 1 2 3 4 is printed
The break in while is used to permanently terminate the loop.
Continue is used to terminate this cycle, that is, the code behind continue in this cycle will not be executed, but directly jump to the judgment part of the while statement. Determine the inlet of the next cycle
getchar/putchar
Read a character from a stream (getc, getwc), or get a character from stdin (getchar, getwchar).
stdin standard input, obtained from the keyboard
int getchar( void );
The return type is int
Return ValueEach of these functions returns the character read. To indicate an read error or end-of-file condition, getc and getchar return EOF
//When getchar fails to read, EOF is returned, i.e. - 1
putchar - output one character
Writes a character to a stream (putc, putwc) or to stdout (putchar, putwchar).
stdout standard output – screen
int putchar( int c );
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> //getchar //EOF //Go to the definition and find that EOF is - 1 //#define EOF (-1) int main() { //Why use int to receive the characters obtained? //'a'-97, the character is essentially ASCII //When getchar fails to read, EOF is returned, i.e. - 1 //-1 is an integer and requires 4 bytes to store //So if you use char ch, it's not appropriate int ch = getchar(); //printf("%c\n", ch); putchar(ch); return 0; }
int main() { int ch = 0; while ((ch = getchar()) != EOF) { putchar(ch); } return 0; }
ctrl+Z can output ^ Z,EOF file end flag
Buffer problem
int main() { char input[20] = { 0 }; printf("Please input a password:>"); scanf("%s", input);//abcdef //The array name itself is the address, which is not required& printf("Please confirm the password(Y/N):>"); int ch = getchar(); if (ch == 'Y') { printf("Confirmation successful\n"); } else { printf("Confirmation failed\n"); } return 0; }
Why is there a problem?
scanf actually looks at whether there is something in the input buffer
If not, wait
When the keyboard hits abcdef
The input buffer contains abcdef\n, and scanf takes abcdef directly
Remaining in input buffer \ n
Then getchar takes something from the input buffer and takes it directly \ n
ch = \n
The reason for the problem is that something in the input buffer interferes with getchar
Just clean up the input buffer with a getchar
int main() { char input[20] = { 0 }; printf("Please input a password:>"); scanf("%s", input);//abcdef getchar();//Take away \ n printf("Please confirm the password(Y/N):>"); int ch = getchar(); if (ch == 'Y') { printf("Confirmation successful\n"); } else { printf("Confirmation failed\n"); } return 0; }
Please enter the password: > ABCDEF hehe
Please confirm password (Y / N): > confirmation failed
If there are spaces in the input, an error occurs again
At this time, the input buffer has abcdef hehe\n
Scanf ('% s',...) ended when it encountered a space while reading a string
Hehe still in buffer \ n
A getchar can only take one h
Consider using cycles
Clean cache
int tmp = 0; while ((tmp = getchar()) != '\n') { ;//Empty statement }
int main() { char input[20] = { 0 }; printf("Please input a password:>"); scanf("%s", input);//abcdef //getchar();// Take away \ n //Clean cache int tmp = 0; while ((tmp = getchar()) != '\n') { ;//Empty statement } printf("Please confirm the password(Y/N):>"); int ch = getchar(); if (ch == 'Y') { printf("Confirmation successful\n"); } else { printf("Confirmation failed\n"); } return 0; }
#include <stdio.h> int main() { char ch = '\0'; while ((ch = getchar()) != EOF) { if (ch < '0' || ch > '9')//Non numeric character continue; putchar(ch); } return 0; } //The function of this code is to print only numeric characters and skip other characters
(ch = getchar()) pay attention to adding ()
Note priority comparison
ch = getchar() != EOF is wrong
If you enter a 4
getchar is understood as character 4, that is, '4'
for loop
int main() { int i = 1;//initialization while (i <= 10)//judge { printf("%d ", i); i++;//Adjustment part } return 0; } //The code is too long and the three parts are separated, which is easy to make mistakes
Export for loop
For (expression 1; expression 2; expression 3)
Loop statement;
Initialization, condition judgment, adjustment
#include <stdio.h> int main() { int i = 0; //for(i=1 / * initialization * /; i < = 10 / * judgment part * /; i + + / * adjustment part * /) for(i=1; i<=10; i++) { printf("%d ", i); } return 0; }
break/continue
#include <stdio.h> int main() { int i = 0; for(i=1; i<=10; i++) { if(i == 5) break; printf("%d ",i); } return 0; }
output
1 2 3 4
#include <stdio.h> int main() { int i = 0; for (i = 1; i <= 10; i++) { if (i == 5) continue; printf("%d ", i); } return 0; }
output
1 2 3 4 6 7 8 9 10
Continue skip the code after continue
for loop control variable
- Loop variables cannot be modified in the for loop body to prevent the for loop from losing control.
- It is suggested that the value of the loop control variable of the for statement should be written in "closed before open interval".
#include <stdio.h> int main() { int i = 0; for (i = 0; i < 10; i++) { i = 0;//Loop variable changed printf("hehe"); } return 0; }
Dead cycle, cycle control has changed
//Front closed and back open for(i=0; i<10; i++) {} //Both sides are closed intervals for(i=0; i<=9; i++) {}
< 10 has the same effect as < = 9
However, it is recommended to close the front and open the rear
10 means something
Cycle 10 times
for loop variant
int main() { for (;;) { printf("hehe\n"); } return 0; } //Dead cycle
The initialization part, judgment part and adjustment part of the for loop can be omitted
If the judgment part in the middle is omitted, it means that it is always true, which constitutes a dead cycle
If conditions permit, it is not recommended to omit the three expressions of the for loop,
Problems that may cause unpredictability are omitted
int main() { int i = 0; int j = 0; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { printf("hehe\n"); } } return 0; }
9 hehe
int main() { int i = 0; int j = 0; for (; i < 3; i++) { for (; j < 3; j++) { printf("hehe\n"); } } return 0; }
There are only three hehe
After the inner loop is executed 3 times, j is still 3
When exiting the inner loop, i++ i=2, and then entering the inner loop, but j is not initialized at this time,
j is still 3, which does not meet the cycle condition
End of loop
Cyclic variables can also be controlled with multiple variables
int main() { int x, y; for (x = 0, y = 0; x < 2 && y < 5; ++x, y++) { printf("hehe\n"); } return 0; }
A pen test question
//How many times does the cycle take? #include <stdio.h> int main() { int i = 0; int k = 0; for (i = 0, k = 0; k = 0; i++, k++)//k=0 is an assignment, not a judgment //==It's written as an assignment= k++; return 0; }
0 times
New languages such as go have only for loops
The go language is developed by Google
do while
int main() { int i = 1; do { printf("%d ", i); i++; } while (i <= 10); return 0; }
The do while statement executes the loop body at least once
break continue
#include <stdio.h> int main() { int i = 10; do { if (5 == i) break; printf("%d\n", i); } while (i < 10); return 0; }
output
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 and then the loop is dead
The screen is flashing all the time, indicating an endless cycle
practice
1. Calculate the factorial of n
Enter n
Number of 1-n
Print
int main() { int n = 0; scanf("%d", &n); int i = 0; int ret = 1; for (i = 1; i <= n; i++) { ret *= i; } printf("%d\n", ret); return 0; }
2. Calculate 1+ 2!+ 3!+……+ 10!
int main() { int n = 0; scanf("%d", &n); int i = 0; int j = 0; int ret = 1; int sum = 0; for (j = 1; j <= n; j++) { for (i = 1; i <= j; i++) { ret *= i; } printf("%d\n", ret); sum += ret; ret = 1;//ret to reset to 1 } //printf("%d\n", ret); printf("sum = %d\n", sum); return 0; }
result
10
1
2
6
24
120
720
5040
40320
362880
3628800
sum = 4037913
ret should start at 1 every time
for (i = 1,ret = 1; i <= j; i++)
ret=1 is easier to understand when it is initialized in for
2-layer for loop, time efficiency O(N^2)
ret* 1
ret* 1 * 2
ret* 1 * 2 * 3
...
Optimize it
Just a for loop
int main() { int n = 0; scanf("%d", &n); int j = 0; int ret = 1; int sum = 0; for (j = 1; j <= n; j++) { ret *= j; printf("%d\n", ret); sum += ret; } printf("sum = %d\n", sum); return 0; }
3. Find a specific number n in an ordered array.
Violence search
#include<stdio.h> int main() { int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; int k = 7; int i = 0; for (i = 0; i < 10; i++) { if (arr[i] == k) { printf("eureka,The subscript is%d\n", i); break; } } if (i == 10) { printf("can't find\n"); } return 0; }
Binary search / half search
#include<stdio.h> //Find a number in an ordered array int main() { int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; int k = 7; int sz = sizeof(arr) / sizeof(arr[0]); int left = 0; int right = sz - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] < k) { left = mid + 1; } else if (arr[mid] > k) { right = mid - 1; } else { printf("eureka,The subscript is%d\n", mid); break; } } if (left > right) { printf("can't find\n"); } return 0; }
4. Write code to demonstrate that multiple characters move from both ends and converge to the middle.
Demonstration effect:
hello bit!!!
################
h##############!
...
hello bit!!!
#include<stdio.h> #include<string.h> #include<windows.h> int main() { //char arr[] = "abc"; //[a b c \0] // 0 1 2 // 3 - 1 = 2 char arr1[] = "hello bit!!!!!!!"; char arr2[] = "################"; int left = 0; //int right = sizeof(arr1) - 2; //sizeof wants - 2 because it contains \ 0 int right = strlen(arr1) - 1; //strlen calculated without \ 0 while (left <= right) { arr2[left] = arr1[left]; arr2[right] = arr1[right]; printf("%s\n", arr2); Sleep(500);//Sleep function - in ms system("cls");//Execute system commands to clean the screen left++; right--; } printf("%s\n", arr2); return 0; }
5. Simulate user login scenario,
Simulate the user login scenario, and can only log in three times. (you are only allowed to enter the password three times. If the password is correct, you will be prompted that the login is successful. If you enter the wrong password three times, you will exit the program.)
#include<stdio.h> #include<string.h> int main() { int i = 0; char password[20] = ""; //Assume password "123456" for (i = 0; i < 3; i++) { printf("Please input a password:>"); scanf("%s", password); //password is the array name, which originally represents the address //if (password == "123456") //{ //Compare whether two strings are equal. Cannot be used== //Using strcmp string compare //} //Returns 0, indicating that the two strings are equal //Numbers less than 0 and greater than 0 may also be returned if (strcmp(password, "123456") == 0) //string compare { printf("Login successful\n"); break; } else { printf("Password error\n"); } } if (i == 3) { printf("3 All passwords are wrong,Exit program\n"); } return 0; }
Normally, the password is encrypted and put into the database
BC33. Calculate average score
float avg = 0.0f; Add f to indicate float. If not, the default is double
%. 1f means to keep one decimal place
Decimals are difficult to store accurately in memory, and generally have errors
BC19 direction outputs a four digit number
greatest common factor
Rolling phase division
Find the remainder of the decimal with a large number. If the remainder is 0, the divisor is the maximum common divisor. If the remainder is not 0, take the remainder as the divisor and the decimal as the dividend, and re calculate the remainder until the remainder is 0. At this time, the maximum common divisor is the remainder. For example: 27 and 6 27% 6 = 3 6%3=0. So the maximum common divisor is 3
Least common multiple = maximum common divisor of multiplication and division of two numbers
#include<stdio.h> int main() { int a = 0; int b = 0; int c = 0; scanf("%d %d", &a, &b); c = a % b;//No matter big or small, most of them are OK //If a > b is OK, even if a < B, it will enter the cycle. How to assign B to a int x = a; int y = b; while (c) { a = b; b = c; c = a % b; } printf("The maximum common divisor is:%d The least common multiple is:%d\n", b, x * y / b); return 0; }
//The most direct method: int main() { int m = 0; int n = 0; scanf("%d %d", &m, &n); //greatest common factor int ret = 0; //1. Find the smaller value of m and n, assuming that it is the greatest common divisor if (m > n) ret = n; else ret = m; //Just try one number at a time while (1) { if (m % ret == 0 && n % ret == 0) { break; } ret--; } //Print printf("%d\n", ret); return 0; }
Print leap year
Can be divided by 4 and cannot be divided by 100 or can be divided by 400
int main() { int year = 0; for (year = 1000; year <= 2000; year++) { if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { printf("%d ", year); } } return 0; }
Print prime
Prime numbers are also called prime numbers
Numbers that can only be divided by 1 and itself are prime numbers
Trial division:
To determine whether y is a prime,
Take the number 2 – > I-1 to try division
int main() { int y = 0; for (y = 100; y <= 200; y++) { //Judge whether y is a prime number //Take the number 2~y-1 and try to divide y int n = 0; int flag = 1;//Suppose y is prime for (n = 2; n < y; n++) { if (y % n == 0)//n can divide y { flag = 0;//If y is not a prime, jump out immediately break; } } if (flag == 1) printf("%d ", y); } return 0; }
//Optimization: //N < = sqrt (y) and even numbers cannot be prime numbers #include <math.h> #include<stdio.h> int main() { int y = 0; int count = 0; for (y = 101; y <= 200; y+=2)//+=2p { int n = 0; int flag = 1;//Suppose y is prime for (n = 2; n <= sqrt(y); n++) { if (y % n == 0) { flag = 0;//y is not prime break; } } if (flag == 1) { printf("%d ", y); count++; } } printf("\ncount = %d\n", count); return 0; }
The above methods are trial division
6. Number guessing game
//Figure guessing game //Randomly generate a 1-100 number //The computer will tell the player to guess big or small //You guessed right. Congratulations to the player and tell him the number of guesses #include<stdio.h> #include<stdlib.h> #include<time.h> void menu() { printf("*********************************\n"); printf("********* 1.play ***********\n"); printf("********* 0.exit ***********\n"); printf("*********************************\n"); } //The process of guessing numbers //The return value of time is time_t is actually a redefinition of int //The srand received value is unsigned int //In order to generate a random number, you need a random number??? //Just pass srand a value that changes frequently, and a number will be generated every second // The difference between the timestamp current time and the computer start time 19700101 //Generate random number rand function 0~RAND_MAX //#define RAND_MAX 0x7fff,32767 void game() { int guess = 0; int count = 0; int r = rand() % 100 +1;// 0 ~ 99+1 //Guess the number while (1) { printf("Guess the number\n"); scanf("%d", &guess); if (guess < r) { printf("Guess it's small\n"); count++; } else if (guess > r) { printf("Guess big"); count++; } else { count++; printf("Congratulations, you guessed right,Guess%d second\n", count); break; } } } int main() { int input = 0; srand((unsigned int)time(NULL));//Set up a random number generator. You don't need to use srand frequently. Just execute it once //The time function can obtain a timestamp do { //To print the menu, it is more appropriate to do while, regardless of whether the menu is printed first menu(); printf("Please select:>"); scanf("%d", &input); switch (input) { case 1: game(); break; case 0: printf("Exit the game\n"); break; default: printf("Selection error\n"); break; } } while (input); return 0; }
The random numbers written by the writing algorithm are pseudo-random numbers
The real random number is irregular, and the code written is regular
The time slave parameter is a pointer. If you don't want to pass the parameter, write NULL, while the srand parameter is unsigned int. you need to convert time to unsigned int
go to
#include<stdio.h> int main() { again: printf("hehe\n"); printf("haha\n"); goto again; //goto next; OK, but next needs to be in the same code block return 0; }
Dead cycle printing hehe haha
goto will jump randomly, disrupt the execution process of the program, reduce the controllability of the code and improve the risk
goto is not a good thing. It may bring unexpected mistakes. Use it with caution
Theoretically, goto statements can not exist
What's the use of goto statement?
The most common use is to terminate the processing of structures nested in some depth
Cheng.
for(...) for(...) { for(...) { if(disaster) goto error; } } ... error: if(disaster) // Handling error conditions
In the case of multi-layer loops, it is not possible to use break. It can only exit from the innermost loop to the upper loop.
How to replace goto?
Shutdown Sequence
//As long as the program starts, the countdown is 60s. If you enter: I'm a pig, the shutdown will be cancelled. If not, the countdown is shutdown //Shutdown shutdown command provided by windows //Shutdown - S - t shut down after 60 seconds //shutdown -a cancel shutdown //System is a library function designed to execute system commands #include<stdlib.h> #include<stdio.h> #include<string.h> int main() { char input[20] = { 0 }; system("shutdown -s -t 6000"); again: printf("Please note that,Your computer will shut down in 100 minutes,If input:I'm a pig,Just cancel the shutdown\n"); scanf("%s", input); //judge if (strcmp(input, "I'm a pig") == 0) { system("shutdown -a"); } else { goto again; } return 0; }
Replace with while
#include<stdlib.h> #include<string.h> #include<stdio.h> int main() { char input[20] = { 0 }; system("shutdown -s -t 6000"); while (1) { printf("Please note that,Your computer will shut down in 100 minutes,If input:I'm a pig,Just cancel the shutdown\n"); scanf("%s", input); //judge if (strcmp(input, "I'm a pig") == 0) { system("shutdown -a"); break; } } return 0; }
Dead cycle
go to
while
for