expression
Expressions are required: the expression part can be relational expressions, logical expressions, and numerical expressions. When entering an expression, you need to pay attention to whether the logic is clear and whether the content of the expression is consistent with your own judgment.
Branch (select)
if statement
Form 1: (no else part)
if (expression) { statement; }
Form 2: (with else clause)
if (expression) { statement; } else { statement; }
Form 3: (multiple if statements are nested in the else part)
if(expression) { statement; } else if(expression) { statement; } else if (expression) { statement; } else { statement; }
For example, the following code: (output = and = = error)
int main() { int a = 10; if (a = 5)//Writing 5 == a can avoid many error situations { printf("hehe\n"); }//hehe will still be printed because the equal symbol is marked as the assignment symbol. return 0; }
example
1. Judge whether a number is odd:
#include<stdio.h> int main() { int a = 0; scanf("%d",&a);// if(a % 2 != 0) printf("%d It's an odd number",a); else printf("%d It's an even number",a); return 0; }
2. Output odd numbers between 1-100
#include<stdio.h> int main() { int a = 1; for (a = 1;a<=100;a++) { if (a % 2 != 0) printf("%d",a); } return 0; }
switch statement:
Example 1
#include<stdio.h> int main() { int day = 0; scanf("%d",&day); switch (day)//Must be plastic { case 1://case must be followed by an integer constant expression case 2: case 3: case 4: case 5: printf("weekdays"); break; case 6: case 7: printf("weekend\n"); break; default: printf("Input error\n"); } return 0; }
Example 2: enter the month and year to get the number of days in the month
//#include<stdio.h> int main() { int month = 0; int year = 0; int day = 0; printf("Please enter year:"); scanf("%d", &year); printf("Please enter month:"); scanf("%d", &month); switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = 31; break; case 4: case 6: case 9: case 11: day = 30; break; case 2: if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) day = 29; else day = 28; break; default: // day = -1; break; } if (-1 == day) printf("Input error"); printf("Yes this month%d day",day); return 0; }
Examples
#include<stdio.h> int main() { int n = 1; int m = 2; switch(n) { case 1:m++; case 2:n++; case 3: switch(n) { case 1:n++; case 2: m++; n++; break; } case 4: m++; break: default: break; } printf("m = %d,n = %d ",m,n);//m = 5,n = 3 return 0; }
Cycle:
while loop:
First introduce the functions of two statements:
1.break: terminate all subsequent cycles
2.continue: end all subsequent cycles and jump directly to the judgment part
while(expression) { statement; }//If the expression is true, the loop is executed
Example: print 1-10:
#include<stdio.h> int main() { int a = 1; while (a <= 10) { if (5 ==a) { //continue;// Skip the following loop and start judging directly: 1234 dead loop //break;// End cycle: 1234 } printf("%d",a); a++; } return0; }
while, getchar and putchar
#include<stdio.h> int main() { int ch = getchar();//'a' - 97 no problem with shaping //printf("%c\n", ch); putchar(ch); //Output a character return 0; } /*getcahr -- Get a character -- only one character can be manipulated at a time getchar When reading fails, EOF -- (- 1) is returned putchar -- Output a character Standard input - keyboard; Standard output - screen;*/
#include<stdio.h> int main() { int ch = 0; while ((ch = getchar()) != EOF) {//If you get characters from the buffer, a loop is executed //If the result is not a character, it will return - 1 and the loop will terminate putchar(ch); } return 0; }
Example: enter password
#include<stdio.h> int main() { char input[20] = {0};//1 printf("Please input a password\n");// scanf("%c",input);//The array name is the address, so we don't need it here& //Problem 1 solution: /* getchar()//Used to read \ n */ //Problem 2 solution: /* int tmp = 0; while ((ch = getchar()) != '\n')//Can be used to clean up the buffer //Use a loop to read characters until it stops reading \ n { ;//Empty statement } */ printf("Please confirm the password\n");// int ch = getchar(); if (ch == ' Y') printf("success\n"); else printf("fail\n"); return 0; }
Case 1: enter abcdef and press enter
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-dujcicqj-1635573432073) (D: \ typera \ album \ password 001.png)]
Program explanation: Reason: enter abcde, and enter abcde on the keyboard. \ n
When scanf reads abcde, the buffer is left \ n, and then execute the following code. When it is the turn to execute getchar, getchar finds that the buffer has \ n, so getchar reads \ n, but \ n is not equal to 'Y', so it will report failure
Correction method; Add a getchar statement after the scanf function to read \ n
See the above for the solution - problem 1 solution
Case 2:
What if the password is abcde hehe\n (with a space in the middle)?
We already know that scanf ends when it encounters a space when reading a string
Followed by: hehe\n
getchar can only read one character at a time, so it is not suitable to use the above method, but you can add a loop to read a series of unnecessary characters
Solution - problem 2
for function
Advantages: it integrates initialization, cycle judgment and adjustment
//format for (ex1;ex2;ex3) { statement; }
The for loop execution process is important:
Step 1: ex1 -- it will be executed only once in the whole cycle
Step 2: ex2
Step 3: statement
Step 4: ex3 -- the third part starts after the execution of the loop
be careful
1. Try not to change the loop variable inside the for loop = ----- the loop may be changed - resulting in an endless loop
2. It is recommended to close left and open right: it can improve readability
for(a = 0; a < 10; a++)//Cycle ten times { } //The effect is the same up and down, but the above method is recommended //Higher readability for(a = 0; a<= 9; a++) { }
Other formats for the for loop
Omitting expressions is not recommended: errors may result
int main() { int a = 0; int b = 0; for (a = 0; a < 3; a++) { for (b= 0; b < 3; b++) printf("haha\n"); } }//Nine hehe
int main() { int a = 0; int b = 0; for (; a < 3; a++) { for (; b < 3; b++) printf("haha\n"); } }//Three heh
Add comma expression
for(a = 1,b = 1;a < 10; a++, b++)//Use commas to assign values to both a and b
However, when using comma expressions, you should also pay attention to the order at a specific time
for(a +=b ,b = 1;a < 10; a++, b++)//Here, a +=b is assigned first, and then b is assigned
for(a = 1;b = 0; b++)//This loop will not execute //Expression: b = 0; The expression result is 0; Then the judgment part is also 0 --- false
do while
Feature: at least once
expression:
do { ;Can be an empty statement } while;
//Print 1-10 #include<stdio.h> int main() { int a = 1; do { printf("%d ", a); a++; } while (a <= 10);//You can't leave out this semicolon here return 0; }
Here are some examples of loops
1. Find the factorial of n:
#include<stdio.h> int main() { int a = 1; int n = 0; int num = 1;//Cannot start at 0 scanf("%d", &n); for (a = 1; a <=n; a++)//Here<= { num = num * a; } printf("%d", num); return 0; }
2. Ask 1+ 2!= 3!…… n!;
Method 1:
#include<stdio.h> int main() { int a = 1; int b = 1; int n = 0; scanf("%d", &n); int sum = 0; int num = 1; for (a = 1;a<=n;a++) { num = 1;//When re cycling, you need to re assign num, otherwise the last calculation result will affect the next operation for (b = 1; b <= a; b++) { num = num * b; } sum +=num; } printf("%d", sum);use return 0; }
Method 2:
#include<stdio.h> int main() { int a = 1; int b = 1; int n = 0; scanf("%d",&n); int num = 1; int sum = 0; for (a = 1; a <= n; a++) { num *= a; sum += num; } printf("%d", sum); return 0; }
3. Find a number n in an ordered array
#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 (i == k) printf("eureka,Subscript time%d\n", i); } if (10 == i) printf("can't find\n"); return 0; }//Low efficiency
Method 2:
#include<stdio.h> int main() { int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; int k = 7; int sz = sizeof(arr) / sizeof(arr[1]); //40/4=10 int right = sz-1; int left = 0; while (left <= right) { int mid = (right + left) / 2; if (arr[mid] < k) left = mid + 1; else if (arr[mid > k]) right = mid - 1; else { printf("Yes, the subscript is:%d", mid); break; } } if(right<left) printf("can't find") return 0; }
4. Multiple characters move from both ends to gather in the middle
#include<stdio.h> #include<string.h> #include<windows.h> int main() { char arr1[] = {"hello world"};//2 char arr2[] = {"###########"}; int left = 0; int right = strlen(arr1) - 1;//sizeof minus 2 while (left <= right) { arr2[left] = arr1[left]; arr2[right] = arr1[right]; printf("%s\n", arr2); Sleep(1000);//The unit is milliseconds, and the header file of Windows.h is required system("cls");//Clear screen left++; right--; } return 0; }
In the above exercise, pay attention to the logic of the code and be careful not to be careless when inputting
Summarize the mistakes I make when I practice:
1. Adding a semicolon "naturally" after the for loop and if branch leads to an error in the result
2. No double quotation marks are added when initializing the array with string: wrong writing method: char arr [] = {hahaha}
3. When creating a character array, you need to use int to create it. It will react only when an error is reported
4. = and = = sometimes the input is wrong, and the error is found only when it falls into an endless loop
The end moves and gathers towards the middle
#include<stdio.h> #include<string.h> #include<windows.h> int main() { char arr1[] = {"hello world"};//2 char arr2[] = {"###########"}; int left = 0; int right = strlen(arr1) - 1;//sizeof minus 2 while (left <= right) { arr2[left] = arr1[left]; arr2[right] = arr1[right]; printf("%s\n", arr2); Sleep(1000);//The unit is milliseconds, and the header file of Windows.h is required system("cls");//Clear screen left++; right--; } return 0; }
In the above exercise, pay attention to the logic of the code and be careful not to be careless when inputting
Summarize the mistakes I make when I practice:
1. Adding a semicolon "naturally" after the for loop and if branch leads to an error in the result
2. No double quotation marks are added when initializing the array with string: wrong writing method: char arr [] = {hahaha}
3. When creating a character array, you need to use int to create it. It will react only when an error is reported
4. = and = = sometimes the input is wrong, and the error is found only when it falls into an endless loop