computer literacy
-
What is a computer?
- As the name suggests, it is a machine that can perform data calculation (desktop computer, notebook computer, tablet computer, smart phone)
- Computer_ Baidu Encyclopedia
-
Who is the inventor of the computer?
- There are several answers to the question of who invented the electronic computer:
- In 1936, the British mathematician Turing first put forward the idea of a computer that generates output by the interaction between program and input data. Later generations named this machine general Turing computer
- In 1938, * * * Crand chuze * * * invented the first computer using * * * relay * * * to work. This computer is named * * * Z1 * * *, but the relay is mechanical and not complete electronic equipment
- In 1942 * * * atanasov and Bailey * * * invented the first computer using * * * vacuum tube * * *, which was named * * * ABC***
- ENIAC was born in 1946. It has the main structure and functions of today's computer. It is a general-purpose computer
- There are several answers to the question of who invented the electronic computer:
- The first modern electronic computer recognized by * * * in the world is ENIAC(Electronic Numerical Integrator And Calculator) born at the University of Pennsylvania in 1946
- What are the characteristics of computer?
-
Computer is an electrical appliance, so the computer can only recognize two states, one is power on and the other is power off
-
Because of this, the original ENIAC program was completed by many switches and connecting wires. However, it takes a long time for * * * to change the program once * * * (it needs to manually reset the status of many switches and connecting wires)
-
In order to improve efficiency, engineers want to put programs and data in memory. Mathematician von Neumann systematically expounds this idea in mathematical language and puts forward the computer model of storing programs (this is the so-called von Neumann machine)
-
How to use mathematical language to express the two states of power on and power off that can be recognized by the computer?
- It's very simple. Just use 0 and 1
- Therefore, all instructions recognized by the computer are composed of 0 and 1
- Therefore, the data stored and operated in the computer is also composed of 0 and 1
-
0 and 1 should be high level and low level more accurately, but there is no need to understand this. We only need to know that the computer can only recognize 0 and 1, and the stored data is composed of 0 and 1.
What is a computer program?
-
A computer program is a set of commands (statements) written in * * * computer language * * * to tell the computer to "do something or solve a problem"
-
As long as the computer executes this program, the computer will work automatically and orderly. All operations of the computer are controlled by the program. Without the program, the computer will accomplish nothing
-
In real life, how do you tell others how to do something or solve a problem?
- Through the language that people can understand: Zhang San, you go downstairs to buy me a pack of cigarettes, and then drop by the express box to bring my express
- In fact, we tell others that doing something through a language that people can understand is sending instructions one by one
- The same is true in computers. We can tell the computer what we want to do through computer language. Every thing we do is an instruction. The collection of one or more instructions is called a computer program
What is computer language?
- In daily life and work, language is a tool for people to communicate
- Chinese people communicate with Chinese people and use Chinese language
- Americans communicate with Americans in English
- People want to communicate with computers and use computer language
- It can be seen that in daily life and work, people use many kinds of languages
- If a great person may master both Chinese and English at the same time, you can use both Chinese and English if you want to communicate with this person
- In fact, the computer is a very good person. The computer has mastered dozens or even hundreds of languages at the same time, so we can communicate with the computer as long as we use any language that the computer has mastered
What are the common types of computer languages?
- machine language
- There are only 0 and 1 in all codes. 0 means no power on and 1 means power on (1 has holes and 0 has no holes when the paper tape is stored)
- Advantages: it directly affects the hardware, and the execution efficiency of the program is very, very high
- Disadvantages: too many instructions, hard to remember, poor readability and no portability
- assembly language
- Symbolic machine language, which uses a symbol (English word, number) to represent a machine instruction
- Advantages: it directly affects the hardware, the execution efficiency of the program is very high, and the readability is slightly good
- Disadvantages: too many symbols, hard to remember and no portability
- high-level language
- A high-level language very close to natural language, with grammar and structure similar to ordinary English
- Advantages: simple, easy to use, easy to understand, far from direct operation of hardware, portability
- Disadvantages: the execution efficiency of programs written in some high-level languages is not high
- Comparison (1 + 1 written in 3 types of languages)
- machine language
- 10111000 00000001 00000000 00000101 00000001 00000000
- assembly language
- MOV AX, 1 ADD AX, 1
- high-level language
- 1 + 1
- machine language
What is C language?
- C language is a high-level language used to communicate with computers. It has the characteristics of both high-level language and assembly language
- Very close to natural language
- The execution efficiency of the program is very high
- C language is a classic of all programming languages. Many high-level languages are derived from C language,
- For example: C + +, c#, Object-C, Java, Go, etc
- C language is a classic of all programming languages, and many famous system software is also written in C language
- Almost all operating systems are written in C language
- Almost all the underlying computer software is written in C language
- Almost all editors are written in C language
C language history
- The earliest high-level language: FORTRAN – > ALGOL – > CPL – > BCPL – > C – > C + +, etc
"At the beginning, there was no language in the world, only circuits and connections. When Daniel came out, heaven and earth opened, FORTRAN, LISP and ALGOL followed, and there were 10000 languages."
- In 1963, the University of Cambridge launched CPL (combined programming language). CPL language is close to hardware on the basis of ALGOL 60, but it is large and difficult to implement
- In 1967, Martin Richards of Cambridge University simplified the CPL language and introduced BCPL (base combined programming language)
- In 1970, Ken Thompson of Bell Laboratories in the United States made further simplification based on BCPL language, designed a very simple and very close to hardware B language (taking the first letter of BCPL), and wrote the first UNIX operating system in B language. But B language is too simple and has limited functions
- Between 1972 and 1973, Dennis of Bell Labs Ritchie designed C language (taking the second letter of BCPL) based on B language. C language not only maintains the advantages of BCPL language and B language (concise and close to hardware), but also overcomes their disadvantages (too simple, data typeless, etc.)
C language standard
- In 1983, the American National Standards Institute (ANSI) established a committee and began to formulate C language standards
- The C language standard was approved in 1989. This version of the C language standard is usually called ANSI C(C89)
- In 1999, the international organization for Standardization ISO revised the C language standard. On the basis of basically retaining the characteristics of the original C language, some functions were added according to the needs, named * * * C99***
- In December 2011, ANSI adopted the ISO/IEC 9899:2011 standard. This standard is usually * * * C11, which is the current standard of C programming language***
Current situation of C language
- Programming language of the year
- The award was given to the most popular programming language of the year
- The award was given to the most popular programming language of the year
- Programming language ranking view
Why learn C language?
- For more than 40 years
- The best language to understand the knowledge of operating system, compilation principle, data structure and algorithm
- Understand the underlying implementation principles of other languages and necessary languages
- Basic grammar is similar to other high-level languages. After learning C language, you can get twice the result with half the effort and know the root
When you want to understand the underlying principles, you will find that you regret not learning C language at the beginning
When you want to learn a new language, you will find that you regret not learning C
When you use some high-level frameworks or even system frameworks and find that the API s provided are written in C language, you find that you regret not learning C language at the beginning
Learn mathematics and chemistry well and don't take pictures all over the world
Learn C language well, no matter how many languages are not afraid
How to learn C language well
Before learning this set of courses | Learn from this set of courses | After studying this set of courses |
---|---|---|
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ghyaoc72-1623039894713)( https://upload-images.jianshu.io/upload_images/647982-c724f6cd01191121.png?imageMogr2/auto -orient/strip)] |
- How to achieve this effect
If a worker wants to do well, he must sharpen his tools first
What tools are used to write C language programs?
- Notepad (low development efficiency)
- VIM (high threshold for beginners)
- Vscode (dislike)
- Eclipse (not like)
- Clion (deep love, but charge)
- Xcode (high, but Apple Computer)
- QT creator (open source, free, cross platform installation and operation)
What is Qt Creator?
- Qt Creator is a new lightweight Integrated development environment (IDE). It can run across platforms and supports Windows, Linux (32-bit and 64 bit) and Mac OS X
- The design goal of Qt Creator is to enable developers to use Qt as an application framework to complete development tasks more quickly and easily
- Open source is free, easy to use, and can meet learning needs
Integrated Development Environment (IDE) is an application program used to provide program development environment, which generally includes code editor ,compiler,debugging Apparatus and graphical user interface And other tools. It integrates code writing function, analysis function compile Function, debugging function and other integrated development software service set.
Qt Creator installation
-
Remember to swallow it whole and don't worry about what it means. Successful installation for beginners is a success
-
Download Qt Creator offline installation package:
- http://download.qt.io/archive/qt/
- Speed download address:
- Link: https://pan.baidu.com/s/1gx0hNDBJkA2gx5wF1Jx34w
Extraction code: 0fg9
-
Run offline installation package as Administrator
-
Next, next, next, wait
+
+
-
Note that Chinese should not appear in the installation path
-
For beginners, selecting all is the easiest way (key!!!)
-
Configure Qt Creator development environment variables
Your installation path \ 5.11.0\mingw53_32\bin
Your installation path \ Tools\mingw530_32\bin
- Start the installed Qt Creator
- This is the end of non select all installation. Select all installation and continue to look down
- If this error occurs, just ignore it
- Wait until the installation is complete to resolve the error
- Find strawberry. In the installation directory MSI, double-click to run
- Find strawberry. In the installation directory MSI, double-click to run
What are environment variables?
- Open the two directories where we add environment variables. It's not difficult to find that most of them are exe executable
- If we do not configure environment variables, we must "find the folder corresponding to these applications" every time we want to use these "executable programs"
- In order to make it easier for us to use these "executable programs" anywhere on the computer, we must add environment variables, because when Windows executes a program, it will first look in the "Path specified by Path in environment variables"
Why configure system variables instead of user variables
- The user variable is only for the user specified using this computer
- A computer can set up multiple users. Different users use different user names and passwords
- When you set up multiple users for the computer, you will be asked to choose which user to log in when you start the computer
- The system variable is for all users who use this computer
- In other words, the system variable is set. No matter who logs in to this computer, you can use the configured tools
Qt Creator shortcut
How to create C language program
- In this world, the first code for almost all programmers to get started is Hello World
- The reason is that Dennis Ritchie, the author of C language, introduced it for the first time in his famous works and passed it on as a classic for later generations. Other languages also scrambled to follow suit to show their respect
How to create a C language file
C language program composition
-
Mobile phones have many functions, "power on", "power off", "call", "send text messages", "take photos" and so on
-
Each function in the mobile phone is equivalent to a program segment (function) in the C language program
-
One of the many functions will be executed first. It is impossible for multiple functions to be executed together
-
If you want to use the mobile phone, you must first perform the power on function of the mobile phone
-
Therefore, C language program is also composed of many functions and many program segments. One of the many C language program segments will be executed first. This first executed program segment is called "main function"
-
A C language program is composed of multiple "functions", and each function has its own function
-
A program * * * has and has only one main function***
-
If a program does not have a main function, the program does not have the ability to run
-
When the program is running, the system will * * * automatically call * * * main function, while other functions need to be called manually by the developer * * ****
-
The main function has a fixed writing format and template
Function definition format
- Format of main function definition:
- int means that the function will return a value of integer type after execution
- Main stands for the name of this function, which is called main
- () means this is a function
- {} represents the scope of this program segment
- return 0; Represents the integer 0 returned after the function is executed
int main() { // insert code here... return 0; }
- Format of other function definitions
- int means that the function will return a value of integer type after execution
- Call stands for the name of this function, which is called call
- () means this is a function
- {} represents the scope of this program segment
- return 0; Represents the integer 0 returned after the function is executed
int call() { return 0; }
How to execute a defined function
- The main function will be called automatically by the system, but other functions will not. Therefore, if you want to execute other functions, you must call them manually in the main function
- Call means finding something called call
- () represents that something called call to be found is a function
- ; The statement representing the calling function has been written
- So call(); Represents finding the call function and executing the call function
int main() { call(); return 0; }
- How to output content to the screen
- Output content is a complex operation, so the system has defined a function specially used for output content in advance, which is called printf function. We only need to execute the printf function defined by the system to output content to the screen
- Whenever a function needs to be executed, it is executed in the form of function name + parentheses
- The meaning of the following code is: when the program is running, the system will automatically execute the main function. When the system automatically executes the main function, we manually execute the call function and printf function
- After observing the code, we found two problems
- We didn't tell the printf function what we were going to output to the screen
- The implementation code of printf function cannot be found
int call(){ return 0; }
int main(){
call();
printf();
return 0;
}
- How to tell the printf function what to output
- Write the content to be output into the parentheses after the printf function
- Note: the content written in parentheses must be enclosed in double quotation marks
printf("hello world\n");
- How to find the implementation code of printf function
- Since the printf function is a function implemented by the system, if you want to use the printf function, you must tell the system where to find the implementation code of the printf function before using it
- #include <stdio. h> That is to tell the system to find the declaration and implementation of printf function in stdio file
#include <stdio.h>
int call(){
return 0;
}
int main(){
call();
printf("hello world\n");
return 0;
}
How to run a written program
- Mode 1:
- Click the small hammer to compile the "source code" into "executable file"
- Find the compiled source code and open the terminal (CMD) to run the executable file
- Mode 2
- Directly click Qt development tool run button
- Directly click Qt development tool run button
Notes on main function and other writing methods
- In C language, every complete statement must end with a semicolon
int main(){ printf("hello world\n") // If there is no semicolon, an error will be reported during compilation return 0; }
int main(){ // If there is no semicolon, when multiple statements are merged into one line, the system does not know from where to where is a complete statement printf("hello world\n") return 0; }
- Chinese cannot appear in C language except where notes and double quotation marks are enclosed
int main(){ printf("hello world\n"); // If the semicolon here is Chinese, it will report an error return 0; }
- A C language program can only have one main function
int main(){ return 0; } int main(){ // Errors will be reported during compilation and definitions will be repeated return 0; }
- A C language program cannot be without the main function
int call(){ // Error occurs when compiling, because there is only call function and no main function return 0; }
int mian(){ // When compiling, there is an error, because the name of the main function is written incorrectly, which is still equivalent to the absence of the main function return 0; }
- The int in front of the main function can be left blank or replaced with void
#include <stdio.h> main(){ // No error will be reported printf("hello world\n"); return 0; }
#include <stdio.h> void main(){ // No error will be reported printf("hello world\n"); return 0; }
- return 0 in the main function may not be written
int main(){ // No error will be reported printf("hello world\n"); }
- Reasons for not reporting errors in a variety of writing methods
- In the earliest days, C language was just a kind of specification and standard (such as C89, C11, etc.)
- The implementation of standards needs the support and implementation of major manufacturers
- During the implementation of support, due to the interests and understanding of major manufacturers, the implementation standards are different and changed
- Turbo C
- Visual C(VC)
- GNU C(GCC)
- That's why you can see that the formats written in different books are different. Some return int, some return void, and some even have no return value
- So you just need to remember the most standard way of writing
#include <stdio.h> int main(){ printf("hello world\n"); return 0; }
Tips:
Syntax error: the compiler will directly report an error
Logical error: there is no syntax error, but the running result is incorrect
C language program practice
- Write a C language program and output the following contents on the screen in at least two ways
*** *** ********* ******* **** **
- Ordinary youth realize
printf(" *** *** \n"); printf("*********\n"); printf(" *******\n"); printf(" ****\n"); printf(" **\n");
- 2B youth realization
printf(" *** *** \n*********\n *******\n ****\n **\n");
- The realization of literary and artistic youth (pretending to be forced, don't understand it first)
int i = 0; while (1) { if (i % 2 == 0) { printf(" *** *** \n"); printf("*********\n"); printf(" *******\n"); printf(" ****\n"); printf(" **\n"); }else { printf("\n"); printf(" ** ** \n"); printf(" *******\n"); printf(" *****\n"); printf(" **\n"); } sleep(1); i++; system("cls"); }
How to avoid bugs for beginners
_ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ . ' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---='............................................. Buddha bless Yes no BUG
━━━━━━Divine beasts haunt━━━━━━ ┏┓ ┏┓ ┏┛┻━━━━━━┛┻┓ ┃ ┃ ┃ ━ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┃ ┃ ┻ ┃ ┃ ┃ ┗━┓ ┏━┛Code is far away from bug with the animal protecting ┃ ┃ God beast bless,Code none bug ┃ ┃ ┃ ┗━━━┓ ┃ ┣┓ ┃ ┏━━┛┛ ┗┓┓┏━┳┓┏┛ ┃┫┫ ┃┫┫ ┗┻┛ ┗┻┛ ━━━━━━It feels cute━━━━━━
´´´´´´´´██´´´´´´´ ´´´´´´´████´´´´´´ ´´´´´████████´´´´ ´´`´███▒▒▒▒███´´´´´ ´´´███▒●▒▒●▒██´´´ ´´´███▒▒▒▒▒▒██´´´´´ ´´´███▒▒▒▒██´ Project: first C Language program ´´██████▒▒███´´´´´ Language: C language ´██████▒▒▒▒███´´ Editor: Qt Creator ██████▒▒▒▒▒▒███´´´´ Version control: git-github ´´▓▓▓▓▓▓▓▓▓▓▓▓▓▒´´ Code style: jiangge style ´´▒▒▒▒▓▓▓▓▓▓▓▓▓▒´´´´´ ´.▒▒▒´´▓▓▓▓▓▓▓▓▒´´´´´ ´.▒▒´´´´▓▓▓▓▓▓▓▒ ..▒▒.´´´´▓▓▓▓▓▓▓▒ ´▒▒▒▒▒▒▒▒▒▒▒▒ ´´´´´´´´´███████´´´´´ ´´´´´´´´████████´´´´´´´ ´´´´´´´█████████´´´´´´ ´´´´´´██████████´´´´ Most people are concerned about whether you fly high or not, but no one cares whether you are tired or not. This is the reality! ´´´´´´██████████´´´ I never believe in dreams, I, only, phase, faith, self, self! ´´´´´´´█████████´´ ´´´´´´´█████████´´´ ´´´´´´´´████████´´´´´ ________▒▒▒▒▒ _________▒▒▒▒ _________▒▒▒▒ ________▒▒_▒▒ _______▒▒__▒▒ _____ ▒▒___▒▒ _____▒▒___▒▒ ____▒▒____▒▒ ___▒▒_____▒▒ ███____ ▒▒ ████____███ █ _███_ _█_███ -------------Goddess bless, code none bug-----------
Multilingual comparison
- C language
#include<stdio.h> int main() { printf("Nange will show you B Fly with you"); return 0; }
- C + + language
#include<iostream> using namespace std; int main() { cout << "Nange will show you B Fly with you" << endl; return 0; }
- OC language
#import <Foundation/Foundation.h> int main() { NSLog(@"Nange will show you B Fly with you"); return 0; }
- Java language
class Test { public static viod main() { system.out.println("Nange will show you B Fly with you"); } }
- Go language
package main import "fmt" //Import fmt Library func main() { fmt.Println("Nange will show you B Fly with you") }
What is a comment?
- Annotation is a very important concept in all computer languages. Literally, it means annotation and interpretation
- Comments can be used to explain what a piece of program or a line of code means to facilitate communication between programmers
- Notes can be any text, that is, they can be written in Chinese
- The annotated content will have a special color in the development tool
Why use comments?
- A program that does not write any comments
void printMap(char map[6][7] , int row, int col); int main(int argc, const char * argv[]) { char map[6][7] = { {'#', '#', '#', '#', '#', '#', '#'}, {'#', ' ', ' ', ' ', '#' ,' ', ' '}, {'#', 'R', ' ', '#', '#', ' ', '#'}, {'#', ' ', ' ', ' ', '#', ' ', '#'}, {'#', '#', ' ', ' ', ' ', ' ', '#'}, {'#', '#', '#', '#', '#', '#', '#'} }; int row = sizeof(map)/sizeof(map[0]); int col = sizeof(map[0])/ sizeof(map[0][0]); printMap(map, row, col); int pRow = 2; int pCol = 1; int endRow = 1; int endCol = 6; while ('R' != map[endRow][endCol]) { printf("dear, Please enter the corresponding operation\n"); printf("w(Go up) s(Go down) a(turn left) d(turn right)\n"); char run; run = getchar(); switch (run) { case 's': if ('#' != map[pRow + 1][pCol]) { map[pRow][pCol] = ' '; pRow++;//3 map[pRow][pCol] = 'R'; } break; case 'w': if ('#' != map[pRow - 1][pCol]) { map[pRow][pCol] = ' '; pRow--; map[pRow][pCol] = 'R'; } break; case 'a': if ('#' != map[pRow][pCol - 1]) { map[pRow][pCol] = ' '; pCol--; map[pRow][pCol] = 'R'; } break; case 'd': if ('#' != map[pRow][pCol + 1]) { map[pRow][pCol] = ' '; pCol++; map[pRow][pCol] = 'R'; } break; } printMap(map, row, col); } printf("You are so awesome X Yes\n"); printf("Want to challenge yourself,Please purchase the full version\n"); return 0; } void printMap(char map[6][7] , int row, int col) { system("cls"); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { printf("%c", map[i][j]); } printf("\n"); } }
- Write annotated programs
/* R Represent a person #Represents a wall // 0123456 ####### // 0 # # // 1 #R ## # // 2 # # # // 3 ## # // 4 ####### // 5analysis: >1.Save map(Two dimensional array) >2.Output map >3.operation R forward(Control the little man to walk) 3.1.Receive user input(scanf/getchar) w(Go up) s(Go down) a(turn left) d(turn right) 3.2.Judge user input,Control the little man to walk 3.2.1.Replace data saved in 2D array ( 1.Judge whether it can be modified(If not#Can be modified) 2.Modify existing location to blank 3.Modify the next step to R ) 3.3.Output the modified two-dimensional array 4.Judge whether the user goes out of the exit
*/
//Declare how to print maps
void printMap(char map[6][7] , int row, int col);
int main(int argc, const char * argv[])
{
// 1. Define a two-dimensional array to save the maze map
char map[6][7] = {
{'#', '#', '#', '#', '#', '#', '#'},
{'#', ' ', ' ', ' ', '#' ,' ', ' '},
{'#', 'R', ' ', '#', '#', ' ', '#'},
{'#', ' ', ' ', ' ', '#', ' ', '#'},
{'#', '#', ' ', ' ', ' ', ' ', '#'},
{'#', '#', '#', '#', '#', '#', '#'}
};
// 2. Calculate the number of map rows and columns
int row = sizeof(map)/sizeof(map[0]);
int col = sizeof(map[0])/ sizeof(map[0][0]);
// 3. Output map
printMap(map, row, col);
// 4. Define variable record person location
int pRow = 2;
int pCol = 1;
// 5. Define the location of the variable record exit
int endRow = 1;
int endCol = 6;
// 6. Control character walking
while ('R' != map[endRow][endCol]) {
//6.1 prompt the user how to control the person walking
printf("pro, please enter the corresponding operation");
Printf ("W (up) s (down) a (left) d (right) \ n");
char run;
run = getchar();
//6.2 control people's walking according to user input
switch (run) {
case 's':
if ('#' != map[pRow + 1][pCol]) {
map[pRow][pCol] = ' ';
pRow++;//3
map[pRow][pCol] = 'R';
}
break;
case 'w':
if ('#' != map[pRow - 1][pCol]) {
map[pRow][pCol] = ' ';
pRow–;
map[pRow][pCol] = 'R';
}
break;
case 'a':
if ('#' != map[pRow][pCol - 1]) {
map[pRow][pCol] = ' ';
pCol–;
map[pRow][pCol] = 'R';
}
break;
case 'd':
if ('#' != map[pRow][pCol + 1]) {
map[pRow][pCol] = ' ';
pCol++;
map[pRow][pCol] = 'R';
}
break;
}
//6.3 re output the map after walking
printMap(map, row, col);
}
printf("you're so awesome \ n");
printf("if you want to challenge yourself, please buy the full version \ n");
return 0;
}
/**
- @brief printMap
- @param map is a two-dimensional array that needs to be printed
- @param row the number of rows of a two-dimensional array
- @param col number of columns of two-dimensional array
*/
void printMap(char map[6][7] , int row, int col)
{
//In order to ensure that the window is clean and tidy, clear the last print before each print
system("cls");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%c", map[i][j]);
}
printf("\n");
}
}
Classification of notes
-
Single-Line Comments
- //Annotated content
- Scope of use: comments can be written anywhere: outside and inside the function, after each statement
- Scope: from the second slash to the end of this line
- Shortcut keys: Ctrl+/
-
multiline comment
- /*Annotated content*/
- Scope of use: comments can be written anywhere: outside and inside the function, after each statement
- Scope of action: from the first / * to the nearest one*/
Notes on notes
- Single line notes can be nested with single line notes and multi line notes
// Nange / / it666 com // /*Brother Jiang*/ // handsome guy
- Multiline notes can nest single line notes
/* // Author: LNJ // Description: the first C language program function: This is a main function, the entry point of C program */
- Multiline comments * * * cannot * * * nest multiline comments
/* Ha ha ha /*Hee hee*/ Interesting */
Application scenario of annotation
- Train of thought analysis
/* R Represent a person #Represents a wall // 0123456 ####### // 0 # # // 1 #R ## # // 2 # # # // 3 ## # // 4 ####### // 5analysis: >1.Save map(Two dimensional array) >2.Output map >3.operation R forward(Control the little man to walk) 3.1.Receive user input(scanf/getchar) w(Go up) s(Go down) a(turn left) d(turn right) 3.2.Judge user input,Control the little man to walk 3.2.1.Replace data saved in 2D array ( 1.Judge whether it can be modified(If not#Can be modified) 2.Modify existing location to blank 3.Modify the next step to R ) 3.3.Output the modified two-dimensional array 4.Judge whether the user goes out of the exit
*/
- Describe the variables
// 2. Calculate the number of rows and columns of the map int row = sizeof(map)/sizeof(map[0]); int col = sizeof(map[0])/ sizeof(map[0][0]);
- Describe the function
/** * @brief printMap * @param map 2D array to print * @param row Number of rows of two-dimensional array * @param col Number of columns in a two-dimensional array */ void printMap(char map[6][7] , int row, int col) { system("cls"); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { printf("%c", map[i][j]); } printf("\n"); } }
- Multiple implementation logical sorting
// 1. Define a two-dimensional array to save the maze map char map[6][7] = { {'#', '#', '#', '#', '#', '#', '#'}, {'#', ' ', ' ', ' ', '#' ,' ', ' '}, {'#', 'R', ' ', '#', '#', ' ', '#'}, {'#', ' ', ' ', ' ', '#', ' ', '#'}, {'#', '#', ' ', ' ', ' ', ' ', '#'}, {'#', '#', '#', '#', '#', '#', '#'} }; // 2. Calculate the number of rows and columns of the map int row = sizeof(map)/sizeof(map[0]); int col = sizeof(map[0])/ sizeof(map[0][0]); // 3. Output map printMap(map, row, col); // 4. Define variables and record person positions int pRow = 2; int pCol = 1; // 5. Define the location of the variable record outlet int endRow = 1; int endCol = 6; // 6. Control people to walk while ('R' != map[endRow][endCol]) { ... ... }
Benefits of using annotations
- Annotation is a good habit that a programmer must have
- Help developers sort out implementation ideas
- Explain the program and improve the readability of the program
- Beginners can form the habit of writing programs: write comments before writing code
- Sort out your thoughts through comments and reflect them in code
- Because code is just a form of thought
What are keywords?
- Keywords, also known as reserved words. It refers to some words with special meaning given by C language
- Keyword characteristics:
- All lowercase
- Special colors are displayed in the development tool
- Keyword notes:
- Because keywords have special meanings in C language, they cannot be used as variable names, function names, etc
- There are 32 keywords in C language
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
---|---|---|---|---|---|---|---|
char | short | int | long | float | double | if | else |
return | do | while | for | switch | case | break | continue |
default | goto | sizeof | auto | register | static | extern | unsigned |
signed | typedef | struct | enum | union | void | const | volatile |
These do not need to be specially remembered, but will be used more. There are special colors in the compiler. We will explain how to use these keywords one by one when we use them. Now browse and have an impression
Keyword classification
What is an identifier?
- Literally, it is a symbol used to identify something. The purpose of identification is to distinguish these things
- In fact, the function of identifier is similar to that of human name. In order to distinguish everyone, a name is given when everyone is born
- C language is composed of functions. There may be multiple functions in a C program. In order to distinguish these functions, each function is given a name, which is an identifier
- To sum up: the programmer names functions and variables in the program is the identifier
Identifier naming rules
- It can only be composed of letters (a~z, A~Z), numbers and underscores
- Cannot contain special strings other than underscores
- Cannot start with a number
- Cannot be a keyword in C language
- Identifiers are strictly case sensitive. Test and test are two different identifiers
practice
- Which of the following are legal identifiers
fromNo22 | from#22 | my_Boolean | my-Boolean | 2ndObj | GUI | lnj |
Mike2jack | Brother Jiang | _test | test!32 | haha(da)tt | jack_rose | jack&rose |
Identifier naming convention
- See the name and know the meaning, which can improve the readability of the code
- Hump naming can improve the readability of the code
- Hump naming method is that when the variable name or function name is connected by multiple words to form an identifier, the first word starts with lowercase letters; The first letter of the second word is capitalized
- For example, variable names such as myFirstName and myLastName look like humps one after another
What is data?
-
Dealing with data all the time in life
- For example: People's weight, height, income, gender and other data
-
In the process of using computers, we will also be exposed to all kinds of data
- For example: document data, picture data, video data, etc
data classification
-
Static data
- Static data refers to some permanent data, which is generally stored in the hard disk. The storage space of hard disk is generally large. Now the hard disk of ordinary computer has about 500G, so some large files can be stored in the hard disk
- Storage time: when the computer is turned off and then turned on, the data is still there. As long as you don't actively delete it or the hard disk is not broken, the data will always be there
- What is static data: static data is generally stored on the hard disk in the form of files, such as documents, photos, videos, etc.
-
Dynamic data
- Dynamic data refers to the temporary data generated dynamically during program operation, which is generally stored in memory. The memory storage space is generally small. Now the memory of ordinary computers is only about 8G, so we should use memory carefully and don't occupy too much memory space
- Duration of storage: these temporary data will be cleared after the computer is shut down
- What are dynamic data: when running a program (software), the whole program will be loaded into memory. During the program running, a variety of temporary data will be generated, which are stored in memory. When the program stops running or the computer is forced to shut down, all temporary data generated by the program will be cleared.
-
Since the storage space of the hard disk is so large, why not load all applications into the hard disk for execution?
- The main reason is that the access speed of memory is N times faster than that of hard disk***
- Conversion between static data and dynamic data
- That is, load from disk to memory
- That is, load from disk to memory
- Conversion between dynamic data and static data
- That is, save from memory to disk
- That is, save from memory to disk
- UOM of data
- Both static and dynamic data are composed of 0 and 1
- The larger the data, the more zeros and 1s it contains
1 B(Byte byte) = 8 bit(position) // 00000000 is a byte // 111111111 is also a byte // 10101010 is also a byte // Any combination of 8 zeros and 1 is a byte 1 KB(KByte) = 1024 B 1 MB = 1024 KB 1 GB = 1024 MB 1 TB = 1024 GB
C language data type
- As programmers, we are most concerned about the dynamic data in memory, because the program we write runs in memory
- In the process of running the program, a variety of temporary data will be generated. In order to facilitate the operation and operation of data, C language classifies these data and provides rich data types
- There are four kinds of data types in C language: basic type, construction type, pointer type and null type
What is a constant?
- "Quantity" means data. Constant represents some fixed data, that is, data that cannot be changed
- Just like giving birth to boys and girls in real life, if you are born a boy, you will always be a boy, and if you are born a girl, you will always be a girl, so gender is a constant in real life
- Don't brag with brother Jiang that you are from Thailand. If you really come from Thailand, I can only say you won
Type of constant
-
integer constants
- Decimal integer. For example: 666, - 120, 0
- Octal integers and constants in octal form start with 0. For example: 0123, which is 83 in decimal system- 011, which is decimal - 9
- Hexadecimal integers and hexadecimal constants start with 0x. For example: 0x123, which is 291 in decimal system
- Binary integer, starting with two into one 0b. For example: 0b0010, which is 2 in decimal system
-
Real constant
- decimal form
- Single precision decimal: ends with the letter F or the letter F. For example: 0.0f, 1.01f
- Double precision decimal: decimal form. For example: 3.14, 6.66
- The default is double
- There can be no integer bits, only decimal places. For example:. 3,. 6f
- Exponential form
- Expressed as a power, an idempotent based on the letter E or the letter E followed by a 10
- Anyone who has been to junior high school should know the scientific counting method. The constant in exponential form is another expression of the scientific counting method. For example, 123000 is expressed as 1.23 by the scientific counting method × The 5th power of 10
- Expressed in C language, it is 1.23e5 or 1.23e5
- The letter E or the exponent after the letter e must be an integer
- There must be a number before or after the letter E
- There must be no spaces before or after the letter E
- Expressed as a power, an idempotent based on the letter E or the letter E followed by a 10
- decimal form
-
character constants
- Character constants are enclosed in '' (single quotation marks). For example: 'a', 'b', 'c'
- A character constant can have only one character in a single quotation mark
- Special case: if it is an escape character, there can be two characters in single quotation marks. For example: '\ n', '\ t'
-
string constant
- Character constants are enclosed by "" (double quotation marks). For example: "a", "abc", "lnj"
- The system will automatically add a character '\ 0' at the end of the string constant as the end of the string flag
-
Custom constant
- There is no need to understand the content of later explanation here
-
Constant type exercise
123 | 1.1F | 1.1 | .3 | 'a' | "a" | "Li Nanjiang" |
What are variables?
- "Quantity" means data. Variables represent some non fixed data, that is, data that can be changed
- Just like people's height and weight in real life, they will change with age, so height and weight are a manifestation of variables in real life
- Just like the storage grid in the supermarket in real life, the same grid can be used by different people in different periods, and the items stored in the grid can be changed. When Zhang San uses this lattice, it may contain diapers, but when Li Si uses this lattice, it may contain bread
How to define variables
- Format 1: variable type variable name;
- Why define variables?
- Any variable must be defined before use. Only when the variable is defined can the storage space be allocated and there is space to store data
- Why qualify types?
- Used to constrain the type of data stored in variables. Once the type is specified for a variable, the variable can only store this type of data
- Memory space is extremely limited, and different types of variables occupy different sizes of storage space
- Why specify a variable name?
- The space where data is stored doesn't mean anything to us. What we need is the value stored in the space
- Only with a name can we get the value in the space
- Why define variables?
int a; float b; char ch;
- Format 2: variable type, variable name, variable name;
- Continuous definition, multiple variables are separated by commas (,)
int a,b,c;
- Specification for naming variable names
- Variable names belong to identifiers, so the naming principle of identifiers must be strictly observed
How to use variables?
- You can use the = sign to store data in variables
- In C language, using the = sign to store data in variables is called assigning values to variables
int value; value = 998; // assignment
- be careful:
- The = sign here is not "equal" in mathematics, but the * * * assignment operator * * * in C language, which is used to assign the integer constant 998 on the right to the integer variable value on the left
- During assignment, the left side of the = sign must be a variable (10=b, error)
- In order to facilitate reading the code, it is customary to add a space on both sides of =
Initialization of variables
- In C language, the first assignment of variables is called "initialization"
- Two forms of initialization
- Define first and then initialize
- int value; value = 998; // initialization
- Initialize at the same time when defining
- int a = 10; int b = 4, c = 2;
- Other manifestations (not recommended)
int a, b = 10; //Partial initialization int c, d, e; c = d = e =0;
- Do not initialize what is stored inside?
- random number
- The storage space allocated by the program last time contains some contents, "garbage"
- Some data being used by the system
How to modify variable values?
- Multiple assignment is enough
- Each assignment overwrites the original value
int i = 10; i = 20; // Modify the value of the variable
Value transfer between variables
- The value stored in one variable can be assigned to another variable
int a = 10; int b = a; // Equivalent to a copy of 10 stored in a to b
How to view the value of a variable?
- Use printf to output the value of one or more variables
int a = 10, c = 11; printf("a=%d, c=%d", a, c);
- Output values of other types of variables
double height = 1.75; char blood = 'A'; printf("height=%.2f, Blood type is%c", height, blood);
Scope of variable
- All variables in C language have their own scope
- Variable definitions have different locations and different scopes
- According to the scope, it can be divided into two types: local variables and global variables
- local variable
- Local variables are also called internal variables
- Local variables are defined in * * * code block * * *, and their scope is limited to the code block. They cannot be used after leaving the code block
int main(){ int i = 998; // Scope start return 0;// End of scope }
int main(){ { int i = 998; // Scope start }// End of scope printf("i = %d\n", i); // out of commission return 0; }
int main(){ { { int i = 998;// Scope start }// End of scope printf("i = %d\n", i); // out of commission } return 0; }
- global variable
- Global variables, also known as external variables, are variables defined outside the code block
int i = 666; int main(){ printf("i = %d\n", i); // have access to return 0; }// End of scope int call(){ printf("i = %d\n", i); // have access to return 0; }
- Note:
- Variables with the same name cannot be in the same scope
int main(){ int i = 998; // Scope start int i = 666; // Error report, duplicate definition return 0; }// End of scope
int i = 666; int i = 998; // Error report, duplicate definition int main(){ return 0; }
- Variables with the same name can be in different scopes
int i = 666; int main(){ int i = 998; // No error will be reported return 0; }
int main(){ int i = 998; // No error will be reported return 0; } int call(){ int i = 666; // No error will be reported return 0; }
Variable memory analysis (simple version)
- Byte and address
- In order to better understand the storage details of variables in memory, let's first understand the "bytes" and "addresses" in memory
- Each small grid represents a byte
- Each byte has its own memory address
- Memory addresses are contiguous
- Space occupied by variable storage
- The storage space occupied by a variable is related to * * * the type declared when defining the variable * * * and * * * the current compilation environment * * *
type | 16 bit compiler | 32-bit compiler | 64 bit compiler |
---|---|---|---|
char | 1 | 1 | 1 |
int | 2 | 4 | 4 |
float | 4 | 4 | 4 |
double | 8 | 8 | 8 |
short | 2 | 2 | 2 |
long | 4 | 4 | 8 |
long long | 8 | 8 | 8 |
void* | 2 | 4 | 8 |
- Variable stored procedure
- Determine how much storage space needs to be opened up according to the type declared when defining variables and the current compilation environment
- Open up a piece of storage space in memory. When opening up, start from the one with large memory address (memory addressing from large to small)
- Save the data to the corresponding memory space that has been opened up
int main(){ int number; int value; number = 22; value = 666; }
#include <stdio.h> int main(){ int number; int value; number = 22; value = 666; printf("&number = %p\n", &number); // 0060FEAC printf("&value = %p\n", &value); // 0060FEA8 }
Don't worry. I've just begun to contact C language. I know so much first The details of storage will be explained in more depth later.
printf function
- The printf function is called the format output function, and the last letter f of the method name represents format. Its function is to output the specified data to the screen according to the format specified by the user
- The calling format of printf function is:
- printf("format control string", output item list);
- For example: printf ("a =% D, B =% d", a, b);
- If the non format string is output as is, the format control string will be replaced by the data in the output item list
- Note: format control string and output item must correspond to each other in quantity and type***
- Format control string
- Form:% [flag] [output width] [. Precision] [length] type
- type
- Format: printf("a =% type", a);
- The type string is used to represent the type of output data. Its format and meaning are as follows
type | meaning |
---|---|
d | Signed decimal integer |
i | Signed decimal integer |
u | Unsigned decimal integer |
o | Unsigned octal integer |
x | Unsigned hexadecimal integer |
X | Unsigned hexadecimal integer |
f | Single and double precision floating-point numbers (6 decimal places are reserved by default) |
e / E | Output single and double precision floating-point numbers in exponential form |
g / G | Output single and double precision floating-point numbers with the shortest output width |
c | character |
s | character string |
p | address |
#include <stdio.h> int main(){ int a = 10; int b = -10; float c = 6.6f; double d = 3.1415926; double e = 10.10; char f = 'a'; // Signed integer (negative number can be output) printf("a = %d\n", a); // 10 printf("a = %i\n", a); // 10// Unsigned integer (negative number cannot be output) printf("a = %u\n", a); // 10 printf("b = %u\n", b); // 429496786 // Unsigned octal integer (negative number cannot be output) printf("a = %o\n", a); // 12 printf("b = %o\n", b); // 37777777766 // Unsigned hexadecimal integer (negative number cannot be output) printf("a = %x\n", a); // a printf("b = %x\n", b); // fffffff6 // Unsigned hexadecimal integer (negative number cannot be output) printf("a = %X\n", a); // A printf("b = %X\n", b); // FFFFFFF6 // Single and double precision floating-point numbers (6 decimal places are reserved by default) printf("c = %f\n", c); // 6.600000 printf("d = %lf\n", d); // 3.141593 // Output single and double precision floating-point numbers in exponential form printf("e = %e\n", e); // 1.010000e+001 printf("e = %E\n", e); // 1.010000E+001 // Output single and double precision floating-point numbers with the shortest output width printf("e = %g\n", e); // 10.1 printf("e = %G\n", e); // 10.1 // Output character printf("f = %c\n", f); // a
}
- width
- Format: printf("a =% [width] type", a);
- Use decimal integer to specify the output width. If the actual number of digits is more than the specified width, it will be output according to the actual number of digits. If the actual number of digits is less than the specified width, it will be filled with spaces
#include <stdio.h> int main(){ // The actual number of digits is less than the specified width int a = 1; printf("a =|%d|\n", a); // |1| printf("a =|%5d|\n", a); // | 1| // The actual number of digits is greater than the specified width int b = 1234567; printf("b =|%d|\n", b); // |1234567| printf("b =|%5d|\n", b); // |1234567| }
- sign
- Format: printf("a =% [flag] [width] type", a);
sign | meaning |
---|---|
- | Left alignment, default right alignment |
+ | When the output value is positive, a + sign is added in front of the output value, which is not displayed by default |
0 | When aligning right, fill the width with 0 (filled with spaces by default) |
Space | When the output value is positive, a space is added before the output value, and when it is negative, a negative sign is added |
# | It has no effect on the types of c, s, d and u |
# | For type o, prefix the output with o |
# | For type X, prefix 0x when outputting |
#include <stdio.h> int main(){ int a = 1; int b = -1; // -No. sign printf("a =|%d|\n", a); // |1| printf("a =|%5d|\n", a); // | 1| printf("a =|%-5d|\n", a);// |1 | // +No. sign printf("a =|%d|\n", a); // |1| printf("a =|%+d|\n", a);// |+1| printf("b =|%d|\n", b); // |-1| printf("b =|%+d|\n", b);// |-1| // 0 flag printf("a =|%5d|\n", a); // | 1| printf("a =|%05d|\n", a); // |00001| // Space flag printf("a =|% d|\n", a); // | 1| printf("b =|% d|\n", b); // |-1| // #Number int c = 10; printf("c = %o\n", c); // 12 printf("c = %#o\n", c); // 012 printf("c = %x\n", c); // a printf("c = %#x\n", c); // 0xa }
- accuracy
- Format: printf("a =% [precision] type", a);
- Precision formatter with "." It starts with decimal integer followed by decimal integer, which is used to specify how many decimal places need to be output. If the output digit is greater than the specified precision, the excess part will be deleted
#include <stdio.h> int main(){ double a = 3.1415926; printf("a = %.2f\n", a); // 3.14 }
- Dynamically specify reserved decimal places
- Format: printf ("a =%. * f", a);
#include <stdio.h> int main(){ double a = 3.1415926; printf("a = %.*f", 2, a); // 3.14 }
- Real (floating point) significant digits
- For single precision numbers, only the first 6 ~ 7 digits are significant numbers when using% f format character for output
- For double precision numbers, the first 15 ~ 16 bits are significant numbers when using%lf format character for output
- The significant digits are different from the precision (how many digits are reserved). The significant digits refer to the accurate and credible digits with an error of no more than half a unit from the first non-zero digit
- Significant digits include non-zero digits before the decimal point
#include <stdio.h> int main(){ // 1234.567871093750000 float a = 1234.567890123456789; // 1234.567890123456900 double b = 1234.567890123456789; printf("a = %.15f\n", a); // The first eight digits are accurate, and the following ones are not accurate printf("b = %.15f\n", b); // The first 16 digits are accurate, and the following ones are not accurate }
- length
- Format: printf("a =% [length] type", a);
length | Modification type | meaning |
---|---|---|
hh | d,i,o,u,x | Output char |
h | d,i,o,u,x | Output short int |
l | d,i,o,u,x | Output long int |
ll | d,i,o,u,x | Output long int |
#include <stdio.h> int main(){ char a = 'a'; short int b = 123; int c = 123; long int d = 123; long long int e = 123; printf("a = %hhd\n", a); // 97 printf("b = %hd\n", b); // 123 printf("c = %d\n", c); // 123 printf("d = %ld\n", d); // 123 printf("e = %lld\n", e); // 123 }
- Escape character
- Format: printf ('% F%%', 3.1415);
- %No. has special meaning in the format control string, so if you want to output% you must add a transfer character
#include <stdio.h> int main(){ printf("%f%%", 3.1415); // Output 3.1415% }
Scanf function
- Scanf function is used to receive keyboard input. It is a blocking function. The program will stop where scanf function appears and will not execute the following code until data is received
- The calling format of printf function is:
- scanf("format control string", address list);
- For example: scanf ('% d', & Num);
- Basic Usage
- Only variable addresses can be passed in the address list item. Variable addresses can be obtained in the form of & symbol + variable name
#include <stdio.h> int main(){ int number; scanf("%d", &number); // Receive an integer printf("number = %d\n", number); }
- Spaces, tabs, and carriage returns are ignored when non character and string types are received
#include <stdio.h> int main(){ float num; // For example, enter Tab space, enter, enter Tab space 3.14, and the result is still 3.14 scanf("%f", &num); printf("num = %f\n", num); }
- If the non format string is input as is, the format control string will be assigned to the variable in the address item list item
- This is not recommended
#include <stdio.h> int main(){ int number; // The user must enter number = number, otherwise an unexpected value will be obtained scanf("number = %d", &number); printf("number = %d\n", number); }
- Receive multiple pieces of data
- Format control string and address list items must correspond to each other in quantity and type
- In the case of non character and string, if the separator of multiple pieces of data is not specified, you can use space or carriage return as the separator (this writing method is not recommended)
- In the case of non character and string, it is recommended to explicitly specify the separator between multiple pieces of data
#include <stdio.h> int main(){ int number; scanf("%d", &number); printf("number = %d\n", number); int value; scanf("%d", &value); printf("value = %d\n", value); }
#include <stdio.h> int main(){ int number; int value; // You can enter numbers, spaces, numbers, or enter numbers scanf("%d%d", &number, &value); printf("number = %d\n", number); printf("value = %d\n", value); }
#include <stdio.h> int main(){ int number; int value; // Enter a number and the number is OK scanf("%d,%d", &number, &value); printf("number = %d\n", number); printf("value = %d\n", value); }
- \N is the end symbol of the scanf function, so it cannot appear in the format string. \ n
#include <stdio.h> int main(){ int number; // After input, press enter to end the input scanf("%d\n", &number); printf("number = %d\n", number); }
scanf operation principle
- The system will put the user's input into the input buffer first
- The scanf method will take out the contents from the input buffer one by one and assign them to variables
- If the contents of the input buffer are not empty, scanf will always get from the buffer without requiring re-entry
#include <stdio.h> int main(){ int num1; int num2; char ch1; scanf("%d%c%d", &num1, &ch1, &num2); printf("num1 = %d, ch1 = %c, num2 = %d\n", num1, ch1, num2); char ch2; int num3; scanf("%c%d",&ch2, &num3); printf("ch2 = %c, num3 = %d\n", ch2, num3); }
- Use the fflush method to clear the buffer (not all platforms can use it)
- Format: fflush(stdin);
- fflush(stdin) has never been defined in the C and C + + standards
- The description "fflush on input stream is an extension to the C standard" is cleared in MSDN document
- Use the setbuf method to empty the buffer (valid for all platforms)
- Format: setbuf(stdin, NULL);
#include <stdio.h> int main(){ int num1; int num2; char ch1; scanf("%d%c%d", &num1, &ch1, &num2); printf("num1 = %d, ch1 = %c, num2 = %d\n", num1, ch1, num2); //fflush(stdin); // Empty input buffer setbuf(stdin, NULL); // Empty input buffer char ch2; int num3; scanf("%c%d",&ch2, &num3); printf("ch2 = %c, num3 = %d\n", ch2, num3); }
putchar and getchar
- putchar: output a character to the screen
#include <stdio.h> int main(){ char ch = 'a'; putchar(ch); // Output a }
- getchar: get a character from the keyboard
#include <stdio.h> int main(){ char ch; ch = getchar();// Get a character printf("ch = %c\n", ch); }
Basic concepts of operators
-
Like operators in mathematics, operators in C language are symbols that tell programs to perform specific arithmetic or logical operations
- For example, tell the program that two numbers are added, subtracted, multiplied, etc
- For example, tell the program that two numbers are added, subtracted, multiplied, etc
-
What is an expression
- An expression is a meaningful and result statement linked by operators;
- For example: a + b; Is an arithmetic expression. Its meaning is to add two numbers. The result of adding two numbers is the result of the expression
- Note: the expression must have a result
Operator classification
- By function:
- Arithmetic operator
- Assignment Operators
- Relational operator
- Logical operator
- Bitwise Operators
- Divided by the number of operands involved in the operation:
- Monocular operation
- There is only one operand, such as i + +;
- Binocular operation
- There are two operands, such as a + b;
- Binocular operation
- The only one in C language, also known as question mark expression, such as: a > b? 1 : 0;
- Monocular operation
Precedence and associativity of operators
- As early as in the mathematics textbook of primary school, we learned that "from left to right, multiply and divide first and then add and subtract, and those with brackets calculate those in brackets first". This sentence contains the problem of priority and combination
- In C language, the operation priority of operators is divided into 15 levels. Level 1 is the highest and level 15 is the lowest
- In C language expressions, operators with different priorities are executed from high to low
- In C language expression, operators with the same priority are executed in the direction specified by associativity
Arithmetic operator
priority | name | Symbol | explain |
---|---|---|---|
3 | Multiplication operator | * | Binocular operator, with left Associativity |
3 | division operator | / | Binocular operator, with left Associativity |
3 | Remainder operator (modulo operator) | % | Binocular operator, with left Associativity |
4 | Addition operator | + | Binocular operator, with left Associativity |
4 | Subtraction operator | - | Binocular operator, with left Associativity |
- matters needing attention
- If both operands involved in the operation are integers, the result is also an integer
- If one of the two operands involved in the operation is a floating point number, the result must be a floating point number
- Finding the remainder operator is essentially the remainder in the quotient and remainder of mathematics
- For the remainder operator, the two operands involved in the operation must be integers and cannot contain floating-point numbers
- Find the remainder operator. If the divisor is less than the divisor, the result is the divisor
- For the remainder operator, the positive and negative of the operation result depends on the divisor, which has nothing to do with the divisor. If the divisor is positive, the result is positive, and if the divisor is negative, the result is negative
- Find the remainder operator, the divisor is 0, and the result is 0
- Find the remainder operator. The divisor is 0. It's meaningless (don't write it like this)
#include <stdio.h> int main(){ int a = 10; int b = 5; // addition int result = a + b; printf("%i\n", result); // 15 // subtraction result = a - b; printf("%i\n", result); // 5 // multiplication result = a * b; printf("%i\n", result); // 50 // division result = a / b; printf("%i\n", result); // 2// Associativity and priority of arithmetic operators // Associativity: left associativity, from left to right int c = 50; result = a + b + c; // 15 + c; 65; printf("%i\n", result); // Priority: * /% is greater than +- result = a + b * c; // a + 250; 260; printf("%i\n", result);
}
#include <stdio.h> int main(){ // Integer divided by integer, the result is still integer printf("%i\n", 10 / 3); // 3 // Any number involved in the operation is a decimal, and the result is a decimal printf("%f\n", 10 / 3.0); // 3.333333 }
#include <stdio.h> int main(){ // 10 / 3 quotient equals 3 and the remainder is 1 int result = 10 % 3; printf("%i\n", result); // 1 // If the left is smaller than the right, the result is the left result = 2 % 10; printf("%i\n", result); // 2 // If the divisor is positive, the result is positive, and if the divisor is negative, the result is negative result = 10 % 3; printf("%i\n", result); // 1 result = -10 % 3; printf("%i\n", result); // -1 result = 10 % -3; printf("%i\n", result); // 1 }
Assignment Operators
priority | name | Symbol | explain |
---|---|---|---|
14 | Assignment Operators | = | Binocular operator, right associative |
14 | Assignment operator after division | /= | Binocular operator, right associative |
14 | Assignment operator after multiplication (modulus operator) | *= | Binocular operator, right associative |
14 | Assignment operator after modulo | %= | Binocular operator, right associative |
14 | Post addition assignment operator | += | Binocular operator, right associative |
14 | Assignment operator after subtraction | -= | Binocular operator, right associative |
- Simple assignment operator
#include <stdio.h> int main(){ // Simple assignment operator= // The value of = right will be assigned to the left int a = 10; printf("a = %i\n", a); // 10 }
- compound assignment operators
#include <stdio.h> int main(){ // Compound assignment operator + = - = * = / =%= // Take out the value in the variable and carry out the corresponding operation. After the operation, re assign the value to the variable int num1 = 10; // num1 = num1 + 1; num1 = 10 + 1; num1 = 11; num1 += 1; printf("num1 = %i\n", num1); // 11 int num2 = 10; // num2 = num2 - 1; num2 = 10 - 1; num2 = 9; num2 -= 1; printf("num2 = %i\n", num2); // 9 int num3 = 10; // num3 = num3 * 2; num3 = 10 * 2; num3 = 20; num3 *= 2; printf("num3 = %i\n", num3); // 20 int num4 = 10; // num4 = num4 / 2; num4 = 10 / 2; num4 = 5; num4 /= 2; printf("num4 = %i\n", num4); // 5 int num5 = 10; // num5 = num5 % 3; num5 = 10 % 3; num5 = 1; num5 %= 3; printf("num5 = %i\n", num5); // 1 }
- Combination and priority
#include <stdio.h> int main(){ int number = 10; // The priority of assignment operator is 14, and the priority of ordinary operator is 3 and 4, so calculate the ordinary operator first // In ordinary operators, multiplication priority is 3 and addition is 4, so multiplication is calculated first // number += 1 + 25; number += 26; number = number + 26; number = 36; number += 1 + 5 * 5; printf("number = %i\n", number); // 36 }
Self increasing and self decreasing operator
- In programming, we often encounter two very common operations, "i=i+1" and "i=i-1".
- C language provides two more concise operators for this operation, namely + + and –
priority | name | Symbol | explain |
---|---|---|---|
2 | Autoincrement operator (after) | i++ | Monocular operator with left Associativity |
2 | Autoincrement operator (before) | ++i | Monocular operator with right Associativity |
2 | Subtraction operator (after) | i– | Monocular operator with left Associativity |
2 | Subtraction operator (before) | –i | Monocular operator with right Associativity |
- Self increasing
- If there is only * * * single * * * variable, no matter + + is written before or after it, it will do + 1 operation on the variable
#include <stdio.h> int main(){ int number = 10; number++; printf("number = %i\n", number); // 11 ++number; printf("number = %i\n", number); // 12 }
- If it appears in an expression, there will be a difference between writing + + before and after it
- Prefix expression: + X, - x; Where X represents the name of the variable. First complete the self increasing and self decreasing 1 operation of the variable, and then use the value of X as the value of the expression; That is, "change before use", that is, the value of the variable changes first, and then the value of the variable participates in the operation
- Suffix expression: x++, x –; First use the current value of X as the value of the expression, and then perform the operation of self increasing and self decreasing 1. That is, "use first and then change", that is, first use the value of the variable to participate in the operation, and then increase and decrease the value of the variable
#include <stdio.h> int main(){ int number = 10; // ++After, first participate in the expression operation, and then increase by itself // Expression operation: 3 + 10; int result = 3 + number++; printf("result = %i\n", result); // 13 printf("number = %i\n", number); // 11 }
#include <stdio.h> int main(){ int number = 10; // ++Before, self increment first, and then participate in expression operation // Expression operation: 3 + 11; int result = 3 + ++number; printf("result = %i\n", result); // 14 printf("number = %i\n", number); // 11 }
- Self subtraction
#include <stdio.h> int main(){ int number = 10; // --After, first participate in the expression operation, and then self subtraction // Expression operation: 10 + 3; int result = number-- + 3; printf("result = %i\n", result); // 13 printf("number = %i\n", number); // 9 }
#include <stdio.h> int main(){ int number = 10; // --First, self subtraction, and then participate in expression operation // Expression operation: 9 + 3; int result = --number + 3; printf("result = %i\n", result); // 12 printf("number = %i\n", number); // 9 }
- Note:
- Self increment and self subtraction operations can only be used for a single variable, as long as it is a standard type variable, whether integer, real or character variables, but cannot be used for expressions or constants
- Incorrect usage: + + (a+b); 5++;
- In enterprise development, try to let + + - appear alone and try not to mix with other operators
- Self increment and self subtraction operations can only be used for a single variable, as long as it is a standard type variable, whether integer, real or character variables, but cannot be used for expressions or constants
int i = 10; int b = i++; // Not recommended perhaps int b = ++i; // Not recommended perhaps int a = 10; int b = ++a + a++; // Not recommended
- Please replace with the following code
int i = 10; int b = i; // recommend i++; perhaps; i++; int b = i; // recommend perhaps int a = 10; ++a; int b = a + a; // recommend a++;
- The C language standard does not specify how to calculate the same variable after self increment or self subtraction in the same expression. Different compilers get different results. Do not write this in enterprise development
int a = 1; // The following code runs 6 with Qt and 5 with Xcode // But in any case, the final value of a is 3 // In C language, this kind of code is meaningless. Don't study it deeply and don't write it like this // Features: the same variable is involved in the operation. When participating in the operation, the operation of self increase and self decrease is done, and it is in the same expression int b = ++a + ++a; printf("b = %i\n", b);
sizeof operator
-
sizeof can be used to calculate the memory bytes occupied by a variable or constant or data type
- Standard format: sizeof (constant or variable);
-
Several forms of sizeof
- Sizeof (variable \ constant);
- sizeof(10);
- char c = 'a'; sizeof(c);
- sizeof variables \ constants;
- sizeof 10;
- char c = 'a'; sizeof c;
- Sizeof (data type);
- sizeof(float);
- If it is a data type, parentheses cannot be omitted
- Sizeof (variable \ constant);
-
sizeof interview questions:
- sizeof() is a compound operator like + =, * = and consists of sizeof and (), but represents a whole
- So sizeof is not a function, but an operator whose priority is 2
#include <stdio.h> int main(){ int a = 10; double b = 3.14; // Since sizeof has higher priority than + sign, sizeof(a) will be calculated first; // a is of type int, so it takes 4 bytes to get the result 4 // Then add the calculation result and b, 4 + 3.14 = 7.14 double res = sizeof a+b; printf("res = %lf\n", res); // 7.14 }
Comma Operator
- In C language, comma "," is also an operator, which is called comma operator. Its function is to connect multiple expressions to form an expression, which is called comma expression
- The comma operator will take out the value of each expression from left to right, and the value of the last comma expression is equal to the value of the last expression
- Format: expression 1, expression 2,..., expression n;
- For example: int result = a+1,b=3*4;
#include <stdio.h> int main(){ int a = 10, b = 20, c; // () takes precedence over comma operator and assignment operator, so the content in () is calculated first // c = (11, 21); // () is a comma expression, and the result is the value of the last expression, so the calculation result is 21 // Assign the result of the comma expression to c, so the result of c is 21 c = (a + 1, b + 1); printf("c = %i\n", c); // 21 }
Relational operator
- Why learn relational operators
- By default, every correct code we write in the program will be executed. But many times, we want to execute a piece of code only when a certain condition is true
- In this case, you can use conditional statements, but before learning conditional statements, let's look at some more basic knowledge: how to judge whether a condition is true
- Authenticity in C language
- In C language, if the condition is true, it is called "true". If the condition is not true, it is called "false". Therefore, to judge whether the condition is true or not is to judge whether the condition is true or false
- How to judge true and false? C language stipulates that any value is true or false, any non-0 value is "true", and only 0 is "false". In other words, 108, - 18, 4.5, - 10.5, etc. are "true", and 0 is "false"
- There are only two kinds of operation results of relational operators: if the condition is true, the result is 1, that is, "true"; If the condition does not hold, the result is 0, which is "false"
priority | name | Symbol | explain |
---|---|---|---|
6 | Greater than operator | > | Binocular operator, with left Associativity |
6 | Less than operator | < | Binocular operator, with left Associativity |
6 | Greater than or equal to operator | >= | Binocular operator, with left Associativity |
6 | Less than or equal to operator | <= | Binocular operator, with left Associativity |
7 | equal operator | == | Binocular operator, with left Associativity |
7 | Not equal to operator | != | Binocular operator, with left Associativity |
#include <stdio.h> int main(){ int result = 10 > 5; printf("result = %i\n", result); // 1 result = 5 < 10; printf("result = %i\n", result); // 1 result = 5 > 10; printf("result = %i\n", result); // 0 result = 10 >= 10; printf("result = %i\n", result); // 1 result = 10 <= 10; printf("result = %i\n", result); // 1 result = 10 == 10; printf("result = %i\n", result); // 1 result = 10 != 9; printf("result = %i\n", result); // 1 }
- Priority and combination
#include <stdio.h> int main(){ // ==Priority is less than >, so calculate > // result = 10 == 1; result = 0; int result = 10 == 5 > 3; printf("result = %i\n", result); // 0 }
#include <stdio.h> int main(){ // ==And= The priority is the same, so according to the combination // Relational operators are left associative, so they are evaluated from left to right // result = 0 != 3; result = 1; int result = 10 == 5 != 3; printf("result = %i\n", result); // 1 }
- Exercise: calculate the result of result
int result1 = 3 > 4 + 7 int result2 = (3>4) + 7 int result3 = 5 != 4 + 2 * 7 > 3 == 10
- Note:
- Both float and double have accuracy problems, so we must avoid using = = to judge whether floating-point numbers are equal
#include <stdio.h> int main(){ float a = 0.1; float b = a * 10 + 0.00000000001; double c = 1.0 + + 0.00000000001; printf("b = %f\n", b); printf("c = %f\n", c); int result = b == c; printf("result = %i\n", result); // 0 }
Logical operator
priority | name | Symbol | explain |
---|---|---|---|
2 | Logical non operator | ! | Monocular operator with right Associativity |
11 | logical and operator | && | Binocular operator, with left Associativity |
12 | logical or operator | \|\| | Binocular operator, with left Associativity |
- Logical non
- Format:! Condition A;
- Operation result: true becomes false and false becomes true
- Operation process:
- First judge whether condition A is true. If adding A is true, the result will be 0, that is, "false";
- If condition A does not hold, the result is 1, that is "true"
- Usage Note:
- Logical non operators can be used consecutively multiple times
- !!! 0 Equivalent to (! (! (! 0)); The final result is 1
#include <stdio.h> int main(){ // () high priority, calculate the content in () first // 10 = = 10 is true, so result =! (1); // ! Represents true to false, false to true, so the result is false 0 int result = !(10 == 10); printf("result = %i\n", result); // 0 }
- Logic and
- Format: condition a & & condition B;
- Operation result: one false is false
- Operation process:
- Always judge whether "condition A" is true first
- If "condition A" is true, then judge whether "condition B" is true. If "condition B" is also true, the result is 1, that is, "true"
- If "condition A" is true and "condition B" is not true, the result is 0, i.e. "false"
- If "condition A" is not true, we will not judge whether "condition B" is true, because as long as one of logic and is not true, the result is not true
- Usage Note:
- "Condition A" is false and "condition B" will not be executed
#include <stdio.h> int main(){ // True & & true int result = (10 == 10) && (5 != 1); printf("result = %i\n", result); // 1 // False & & true result = (10 == 9) && (5 != 1); printf("result = %i\n", result); // 0 // True & & false result = (10 == 10) && (5 != 5); printf("result = %i\n", result); // 0 // False & & false result = (10 == 9) && (5 != 5); printf("result = %i\n", result); // 0 }
#include <stdio.h> int main(){ int a = 10; int b = 20; // Logical and, the front is false and will not continue to be executed later int result = (a == 9) && (++b); printf("result = %i\n", result); // 1 printf("b = %i\n", b); // 20 }
- Logical or
- Format: condition A | condition B;
- Operation result: one truth is true
- Operation process:
- Always judge whether "condition A" is true first
- If "condition A" is not true, then judge whether "condition B" is true. If "condition B" is true, the result is 1, that is, "true"
- If "condition A" is not true and "condition B" is not true, the result is 0, that is, "false"
- If "condition A" is true, we will not judge whether "condition B" is true, because logic or as long as one is true, the result is true
- Usage Note:
- "Condition A" is true and "condition B" will not be executed
#include <stdio.h> int main(){ // Really? Really int result = (10 == 10) || (5 != 1); printf("result = %i\n", result); // 1 // False and true result = (10 == 9) || (5 != 1); printf("result = %i\n", result); // 1 // True and false result = (10 == 10) || (5 != 5); printf("result = %i\n", result); // 1 // False | false result = (10 == 9) || (5 != 5); printf("result = %i\n", result); // 0 }
#include <stdio.h> int main(){ int a = 10; int b = 20; // Logical or, which is true in the front, will not continue to be executed later int result = (a == 10) || (++b); printf("result = %i\n", result); // 1 printf("b = %i\n", b); // 20 }
- Exercise: calculate the result of result
int result = 3>5 || 2<4 && 6<1;
ternary operator
-
Ternary operator, which requires three data or expressions to form a conditional expression
-
Format: expression 1? Expression 2 (result A): expression 3 (result B)
- Example: pass the exam? Pass: fail;
- Example: pass the exam? Pass: fail;
-
Evaluation rule:
- If "expression 1" is true, the operation result of the ternary operator is the value of "expression 2" (result A), otherwise it is the value of "expression 3" (result B)
Examples: int a = 10; int b = 20; int max = (a > b) ? a : b; printf("max = %d", max); Output results: 20 Equivalent to: int a = 10; int b = 20; int max = 0; if(a>b){ max=a; }else { max=b; } printf("max = %d", max);
- Attention
- The operation priority of conditional operators is lower than that of relational operators and arithmetic operators, but higher than that of assignment operators
- Conditional operator? And: it is a whole and cannot be used separately
#include <stdio.h> int main(){ int a = 10; int b = 5; // First calculate a > B // Then determine whether to return a or b according to the calculation result // Equivalent to int max = (a > b)? a : b; int max= a>b ? a : b; printf("max = %i\n", max); // 10 }
#include <stdio.h> int main(){ int a = 10; int b = 5; int c = 20; int d = 10; // Associativity is from right to left, so we will calculate the following contents first // int res = a>b?a:(c>d?c:d); // int res = a>b?a:(20>10?20:10); // int res = a>b?a:(20); // Then calculate the final result // int res = 10>5?10:(20); // int res = 10; int res = a>b?a:c>d?c:d; printf("res = %i\n", res); }
Type conversion
Cast type conversion (display conversion) | Automatic type conversion (implicit conversion) |
---|---|
(type to convert) (expression) | 1. Arithmetic conversion 2 Assignment conversion |
- Cast type conversion (display conversion)
// Convert double to int int a = (int)10.5;
- Arithmetic conversion
- The system will automatically perform an "automatic type promotion" operation on the type that occupies less memory. First convert it to the type that occupies more memory in the current arithmetic expression, and then participate in the operation
// The current expression uses 1.0 to occupy 8 bytes and 2 to occupy 4 bytes // Therefore, integer type 2 will be converted to double type before calculation double b = 1.0 / 2;
- Assignment conversion
// When assigning a value, the type on the left will be automatically converted to the type on the right and then saved int a = 10.6;
- Note:
- What type is involved in the calculation and what type is the result
// The result is 0 because all the integers involved in the operation are integers double a = (double)(1 / 2); // The result is 0.5 because 1 is cast to double and 2 is automatically promoted to double double b = (double)1 / 2;
- Type conversion does not affect the value of the original variable
#include <stdio.h> int main(){ double d = 3.14; int num = (int)d; printf("num = %i\n", num); // 3 printf("d = %lf\n", d); // 3.140000 }
Stage practice
- Enter an integer from the keyboard to judge whether the number is between 100 and 200
- What is the value of expression 6 = = 6 = = 6?
- The user enters three integers from the keyboard to find the maximum value, and then enters the maximum value
- Exchange the saved values of two variables in two ways
Before exchange int a = 10; int b = 20; After exchange int a = 20; int b = 10;
Basic concepts of process control
-
By default, after the program runs, the system will execute each line of code in the program from top to bottom in writing order. However, this can not meet all our development needs. In order to facilitate us to control the operation process of the program, C language provides three process control structures, and different process control structures can realize different operation processes.
-
The three process structures are sequence structure, selection structure and cycle structure
-
Sequential structure:
- Execute from top to bottom in writing order
- Execute from top to bottom in writing order
-
Select structure
- Judge the given conditions, and then determine the execution code according to the judgment results
- Judge the given conditions, and then determine the execution code according to the judgment results
-
Cyclic structure
- When the given conditions are true, execute a piece of code repeatedly
- When the given conditions are true, execute a piece of code repeatedly
Select structure
- C language provides two selection structures: if and switch
##Select structure if - if first form
- Indicates that if the expression is true, statement block 1 will be executed, otherwise it will not be executed
if(expression) { Statement block 1; } Subsequent statements;
if(age >= 18) { printf("Open network card\n"); } printf("Buy cigarettes\n");
- if the second form
- If the expression is true, execute statement block 1, otherwise execute statement block 2
- else cannot be used separately from if
if(expression){ Statement block 1; }else{ Statement block 2; } Subsequent statements;
if(age > 18){ printf("Open network card\n"); }else{ printf("Call parents to drive\n"); } printf("Buy cigarettes\n");
- if the third form
- If "expression 1" is true, execute "statement block 1", otherwise judge "expression 2". If it is true, execute "statement block 2", otherwise judge "expression 3". If "statement block 3" is true, when expressions 1, 2 and 3 are not satisfied, the last else statement will be executed
- Among the many braces, only the content in one brace will be executed
- The content in else braces will be executed only if all the previous additions are not satisfied
if(Expression 1) { Statement block 1; }else if(Expression 2){ Statement block 2; }else if(Expression 3){ Statement block 3; }else{ Statement block 4; } Subsequent statements;
if(age>40){ printf("Room card"); }else if(age>25){ printf("Give me your business card"); }else if(age>18){ printf("To network card"); }else{ printf("Give the good man a card"); } printf("Buy cigarettes\n");
- if nesting
- You can continue to nest if in if and if in else
if(Expression 1){ Statement block 1; if(Expression 2){ Statement block 2; } }else{ if(Expression 3){ Statement block 3; }else{ Statement block 4; } }
- if attention
- Any value is true or false
#include <stdio.h> int main(){ if(0){ printf("Yes if"); }else{ printf("Yes else"); // Be executed } }
- When there is only one statement after if else, the braces after if else can be omitted
// Extremely not recommended int age = 17; if (age >= 18) printf("Open network card\n"); else printf("Call parents to drive\n");
- When the braces after if else are omitted, else will automatically match the nearest if
#include <stdio.h> int main(){ if(0) if(1) printf("A\n"); else // Match with if(1) printf("B\n"); else // Matches if(0) because if(1) has already been matched if (1) printf("C\n"); // Output C else // Match with if(1) printf("D\n"); }
-
- If if else omits braces, variables cannot be defined later
#include <stdio.h> int main(){ if(1) int number = 10; // The system will report an error printf("number = %i\n", number); }
#include <stdio.h> int main(){ if(0){ int number = 10; }else int value = 20; // The system will report an error printf("value = %i\n", value); }
- Semicolon (;) in C language It is also a statement, which is called an empty statement
// Because if (10 > 2) is followed by a semicolon, the system will assume that if omits braces // if you omit braces, you can only control the following statement, so you can only control semicolons if(10 > 2); { printf("10 > 2"); } // Output result: 10 > 2
- Whenever a variable is equal to or not equal to a constant, write the constant in front of it
#include <stdio.h> int main(){ int a = 8; // if(a = 10) {/ / wrong writing, but no error will be reported if (10 == a){ printf("a The value of is 10\n"); }else{ printf("a The value of is not 10\n"); } }
-
if exercise
- Input an integer from the keyboard to judge whether it is an even number. If it is an even number, output YES, otherwise output NO;
- Receive the integer of 1 ~ 7 input by the user, and output the corresponding day of the week according to the integer input by the user
- Receive an integer entered by the user, month represents the month, and output the corresponding season according to the month
- Receive two integers input by the user, and output the larger number after judging the size
- Receive three integers input by the user, and output the larger number after judging the size
- Receive three integers input by the user and output them after sorting
-
Realize stone scissors and cloth
Scissors stone cloth game: 1)Define the rules of the game Scissors dry the cloth Stone kill scissors The cloth killed the stone 2)Show players start guessing 3)Receive player input 4)Let the computer randomly generate a fist 5)Judgment comparison (1)Player wins(Show player wins) (2)Computer wins(The computer won) (3)it ends in a draw(Show draw)
Select structure switch
- Because if else if is not concise enough, switch came into being. It is complementary to if else if. Switch provides multiple selection of points
- Format:
switch(expression){ case Constant expression 1: Statement 1; break; case Constant expression 2: Statement 2; break; case Constant expression n: sentence n; break; default: sentence n+1; break; }
- Semantics:
- Calculate the value of "expression" and compare it with the subsequent "constant expression" value one by one. When the value of "expression" is equal to the value of a "constant expression", execute the subsequent statement, and then jump out of the switch statement
- If the value of "expression" is different from the "constant expression" after all case s, the statement after default is executed
- Example:
#include <stdio.h>
int main() {
int num = 3; switch(num){ 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; default: printf("Go back to Mars\n"); break; }
}
- switch attention points
- The type of switch conditional expression must be integer or can be promoted to the value of integer (char, short)
#include <stdio.h>
int main() {
switch(1.1){ // report errors case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; default: printf("Go back to Mars\n"); break; }
}
- +The value of case can only be a constant and must also be an integer, or it can be promoted to an integer value (char, short)
#include <stdio.h>
int main() {
int num = 3; switch(1){ case 1: printf("Monday\n"); break; case 'a': printf("Tuesday\n"); break; case num: // report errors printf("Wednesday\n"); break; case 4.0: // report errors printf("Thursday\n"); break; default: printf("Go back to Mars\n"); break; }
}
- The value of constant expression after case cannot be the same
#include <stdio.h>
int main() {
switch(1){
case 1: / / an error is reported
printf("Monday \ n");
break;
case 1: / / an error is reported
printf("Monday \ n");
break;
default:
Pri n tf ("go back to Mars");
break;
}
}
- To define variables after case, you must add braces to the case
#include <stdio.h>
int main() {
switch(1){
case 1:{
int num = 10;
printf("num = %i\n", num);
printf("Monday \ n");
break;
}
case 2:
printf("Monday \ n");
break;
default:
Pri n tf ("go back to Mars");
break;
}
}
- As long as any case in the switch matches, all other cases and default will be invalid Therefore, if there is no break after case and default, the penetration problem will occur
#include <stdio.h>
int main() {
int num = 2; switch(num){ case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); // Be output case 3: printf("Wednesday\n"); // Be output default: printf("Go back to Mars\n"); // Be output break; }
}
- default in switch can be omitted
#include <stdio.h>
int main() {
switch(1){
case 1:
printf("Monday \ n");
break;
case 2:
printf("Monday \ n");
break;
}
}
- The position of default in the switch does not have to be written to the end. No matter where it is placed, it will not be executed until all case s do not match (except for penetration problems)
#include <stdio.h>
int main() {
switch(3){
case 1:
printf("Monday \ n");
break;
default:
printf("Other,\n");
break;
case 2:
printf("Monday \ n");
break;
}
}
- if and Switch conversion
- It seems that both if and switch can achieve the same function, so when do we use if and switch in enterprise development?
- If else multi-channel selection of if pin for range
- switch is a multi-channel selection for points
- Judge whether the data entered by the user is greater than 100
#include <stdio.h>
int main() {
int a = -1;
scanf("%d", &a);
if(a > 100){
printf("the data entered by the user is greater than 100");
}else{
printf("the data entered by the user shall not be greater than 100");
}
}
#include <stdio.h> int main() { int a = -1; scanf("%d", &a); // Pretty (T) cute (M) (D) I'm not sure switch (a) { case 101: case 102: case 103: case 104: case 105: printf("greater than\n"); break; default: printf("Not greater than\n"); break; } }
- practice
- Realize score grade judgment
The user is required to enter a score and output the corresponding grade according to the entered score A 90~100 B 80~89 C 70~79 D 60~69 E 0~59
- Implementation + - * / simple calculator
Cyclic structure
- C language provides three loop structures: while, dowhile and for
- Loop structure is a very important structure in program.
- Its characteristic is that when a given condition is true, a program segment is executed repeatedly until the condition is not true.
- The given condition is called "loop condition", and the repeatedly executed program segment is called "loop body"
Loop structure while
- Format:
while ( Cycle control condition ) { Statement in loop body; A statement that ends a loop; .... }
-
Several conditions of circular structure
- Cycle control condition
- The main basis of loop exit is to control when the loop exits
- Circulatory body
- Code snippets that are executed repeatedly during the loop
- Statements that can end the loop (increment, decrement, true, false, etc.)
- It can make the cycle condition false, otherwise exit the cycle
- Cycle control condition
-
Example:
int count = 0; while (count < 3) { // Cycle control condition printf("Fire bullets~Beep, beep, beep\n"); // Statements that need to be executed repeatedly count++; // A statement that ends a loop }
- while loop execution process
- First, it will determine whether the "loop control condition" is true. If it is false, it will directly jump to the back of the loop statement
- If the "loop control condition" is true, execute the loop body once, and then judge whether the "loop control condition" is true again. If it is true, continue to execute the loop body, and if it is false, jump out of the loop
- Repeat the above operation until the "cycle control condition" is false
#include <stdio.h> int main(){ int count = 4; // 1. Judge whether the loop control condition is true and false at this time, so skip the loop statement while (count < 3) { printf("Fire bullets~Beep, beep, beep\n"); count++; } // 2. Execute the code behind the loop statement and print "loop execution completed" printf("Cycle execution completed\n"); }
#include <stdio.h> int main(){ int count = 0; // 1. Judge whether the cycle control condition is true. At this time, 0 < 3 is true // 4. Judge whether the cycle control condition is true again. At this time, 1 < 3 is true // 7. Judge whether the cycle control condition is true again. At this time, 2 < 3 is true // 10. Judge whether the loop control condition is true again. At this time, 3 < 3 is false. Skip the loop statement while (count < 3) { // 2. Execute the code in the loop body and print "bullet" // 5. Execute the code in the loop body and print "bullet" // 8. Execute the code in the loop body and print "bullet" printf("Fire bullets~Beep, beep, beep\n"); // 3. Execute "statements that can end the loop" count = 1 // 6. Execute "statements that can end the loop" count = 2 // 9. Execute the "statement that can end the loop" count = 3 count++; } // 11. Execute the code after the loop statement and print "loop execution completed" printf("Cycle execution completed\n"); }
- while loop considerations
- Any value is true or false
#include <stdio.h> int main(){ while (1) { // Dead cycle printf("Fire bullets~Beep, beep, beep\n"); // There is no statement that can end the loop } }
- When there is only one statement after while, the braces after while can be omitted
#include <stdio.h> int main(){ while (1) // Dead cycle printf("Fire bullets~Beep, beep, beep\n"); // There is no statement that can end the loop }
- If braces are omitted from while, variables cannot be defined later
#include <stdio.h> int main(){ while (1) // Dead cycle int num = 10; // report errors // There is no statement that can end the loop }
- Semicolon (;) in C language It is also a statement, which is called an empty statement
#include <stdio.h> int main(){ int count = 0; while (count < 3);{ // Dead cycle printf("Fire bullets~Beep, beep, beep\n"); count++; } }
- The simplest dead cycle
// In general, there are many applications at the operating system level, and they are rarely used in daily development while (1);
- while exercise
- Calculate the sum of 1 + 2 + 3 +... n
- Obtain the number of multiples of 7 between 1 and 100
Loop structure do while
- Format:
do { Statement in loop body; A statement that ends a loop; .... } while (Cycle control condition );
- Examples
int count = 0; do { printf("Fire bullets~Beep, beep, beep\n"); count++; }while(count < 10);
-
Do while loop execution process
- First, the "loop body" is executed once regardless of whether the condition in while is true or not
- After executing the loop body once, judge whether the condition in while is true again. If it is true, continue to execute the loop body and if it is false, jump out of the loop
- Repeat the above operation until the "cycle control condition" is false
-
Application scenario
- Password verification
#include<stdio.h> int main() { int num = -1; do{ printf("Please input a password,Verify your identity\n"); scanf("%d", &num); }while(123456 != num); printf("master,You're back at last\n"); }
- while and dowile application scenarios
- In most cases, while and dowhile can be interchanged, so use while if you can use while
- In any case, you need to execute the loop body once before using dowile
- do while once proposed to abolish it, but it is still a little useful in input checking
Loop structure for
- Format:
for(Initialization expression; Cyclic condition expression; Operation expression after loop) { Statement in loop body; }
- Examples
for(int i = 0; i < 10; i++){ printf("Fire bullets~Beep, beep, beep\n"); }
-
for loop execution process
- The "initialization expression" is executed first, and * * * will execute * * * initialization expression only once in the whole cycle
- Then judge whether the "loop condition expression" is true, and execute the statement in the loop body if it is true
- After the execution of the loop body, the "operation expression after loop" will be executed, and then judge whether the condition is true again. If it is true, continue to execute the loop body, and if it is false, jump out of the loop
- Repeat the above process until the for loop ends when the condition is not true
-
for loop notes:
- As like as two peas while
- The simplest loop is for(;);
-
for and while application scenarios
- For can do whatever while can do, so for can be used in enterprise development, because for is more flexible
- And compared with while, for saves more memory space
int count = 0; // Initialization expression while (count < 10) { // Conditional expression printf("Fire bullets~Beep, beep, beep %i\n", count); count++; // Increment expression after loop } // If the value of the initialization expression needs to be used after the loop, use while printf("count = %i\n", count);
// Note: the variables defined in the initialization expression of the for loop can only be accessed in {} after the for loop // So: if the value of the initialization expression does not need to be used after the loop, use for // Because if the value of the initialization expression is not needed after the loop, using while will cause performance problems for (int count = 0; count < 10; count++) { printf("Fire bullets~Beep, beep, beep %i\n", count); } // printf("count = %i\n", count);
// If you need to use the value of the initialization expression, you can also write the initialization expression outside int count = 0; for (; count < 10; count++) { printf("Fire bullets~Beep, beep, beep\n", count); } printf("count = %i\n", count);
Four jumps
-
C language provides four jump statements, namely return, break, continue and goto
-
break:
- Immediately jump out of the switch statement or loop
-
Application scenario:
- switch
- Cyclic structure
-
break notes:
- break leaves the scope of application, and its existence is meaningless
if(1) { break; // Will report an error }
- In a multi-layer loop, a break statement jumps out only one layer
while(1) { while(2) { break;// It is only valid for while2 and will not affect while1 } printf("while1 Circulatory body\n"); }
- There can be no statement under break because it cannot be executed
while(2){ break; printf("Hit me!");// Cannot execute }
- continue
- End the * * * current * * * cycle and enter the * * * next * * * cycle
- Application scenario:
- Cyclic structure
- Cyclic structure
- continue notes:
- continue leaves the scope of application, and its existence is meaningless
if(1) { continue; // Will report an error }
- goto
- This is not a topic worth discussing. goto will destroy the structured programming process. It will make the program level unclear and difficult to read, so use it with caution
- goto statement can only realize jump in this function, and can not realize cross function jump (short jump). But he is very efficient when jumping out of multiple cycles
#include <stdio.h> int main(){ int num = 0; // loop: is a defined tag loop:if(num < 10){ printf("num = %d\n", num); num++; // goto loop means to jump to the marked position goto loop; } }
#include <stdio.h> int main(){ while (1) { while(2){ goto lnj; } } lnj:printf("All loops skipped"); }
- return
- Ends the current function and returns the result to the caller
- Don't worry, put it aside, learn the function, and we'll look back at it
Nested Loop
- There are other loop structures in the loop body of the loop structure, which we call loop nesting
- Note: generally, the nesting of loops should not exceed three layers
- The number of times the outer loop is executed * the number of times the inner loop is executed
- Format:
while(Conditional expression) { while Cyclic structure or dowhile Cyclic structure or for Cyclic structure }
for(Initialization expression; Cyclic condition expression; Operation expression after loop) { while Cyclic structure or dowhile Cyclic structure or for Cyclic structure }
do { while Cyclic structure or dowhile Cyclic structure or for Cyclic structure } while (Cycle control condition );
- Cycle optimization
- In multiple loops, if possible, the longest loop should be placed in the innermost layer and the shortest loop in the outermost layer, so as to reduce the number of CPU cross cutting the loop layer
for (row=0; row<100; row++) { // Low efficiency: long cycle in the outermost layer for ( col=0; col<5; col++ ) { sum = sum + a[row][col]; } }
for (col=0; col<5; col++ ) { // High efficiency: long cycle in the innermost layer for (row=0; row<100; row++) { sum = sum + a[row][col]; } }
- practice
- Print friends list
Friends list 1 Friend 1 Friend 2 Friends list 2 Friend 1 Friend 2 Friends list 3 Friend 1 Friend 2
for (int i = 0; i < 4; i++) { printf("Friends list%d\n", i+1); for (int j = 0; j < 4; j++) { printf(" role%d\n", j); } }
Graphic printing
- The first cycle solves the linear problem, while the second cycle and the third cycle can solve the plane and three-dimensional problems
- Print rectangle
**** **** ****
// 3 rows and 4 columns // Number of outer loop control lines for (int i = 0; i < 3; i++) { // Number of internal loop control columns for (int j = 0; j < 4; j++) { printf("*"); } printf("\n"); }
- Print triangles
- With the tip upward, change the conditional expression of the inner loop so that the conditional expression of the inner loop changes with the i value of the outer loop
- Tip down, change the initialization expression of the inner loop so that the initialization expression of the inner loop changes with the i value of the outer loop
* ** *** **** *****
/* Print up to 5 lines Print up to 5 columns What is the relationship between each row and each column? Number of columns < = number of rows */ for(int i = 0; i< 5; i++) { for(int j = 0; j <= i; j++) { printf("*"); } printf("\n"); }
***** **** *** ** *
for(int i = 0; i< 5; i++) { for(int j = i; j < 5; j++) { printf("*"); } printf("\n"); }
- practice
- Print special triangles
1 12 123
for (int i = 0; i < 3; i++) { for (int j = 0; j <= i; j++) { printf("%d", j+1); } printf("\n"); }
- Print special triangles
1 22 333
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= i; j++) { printf("%d", i); } printf("\n"); }
- Print special triangles
--* -*** *****
for (int i = 0; i <= 5; i++) { for (int j = 0; j < 5 - i; j++) { printf("-"); } for (int m = 0; m < 2*i+1; m++) { printf("*"); } printf("\n"); }
- Print 99 multiplication table
1 * 1 = 1 1 * 2 = 2 2 * 2 = 4 1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { printf("%d * %d = %d \t", j, i, (j * i)); } printf("\n"); }
Basic concepts of function
- C source program is composed of functions
- For example, in the course we learned earlier, a C language program can be formed through main function + scanf function + printf function + logic code
- C language not only provides a wealth of library functions, but also allows users to establish their own defined functions. Users can write their own algorithms into relatively independent functions, and then call it when necessary
- For example, if you write an MP3 player program in C language, its program structure is shown in the figure below
- It can be said that all the work of C program is completed by various functions, so c language is also called functional language
Classification of functions
- In C language, functions can be classified from different angles
- From the perspective of function definition, functions can be divided into library functions and user-defined functions
- Library function: provided by the C language system, the user does not need to define or make type description in the program. It can be called directly in the program only by including the header file of the function prototype in front of the program. printf, scanf, getchar, putchar and other functions are used repeatedly in the examples in the previous chapters
- ***User defined functions: * * * functions written by users on demand. For user-defined functions, not only the function itself should be defined in the program, but also the type description of the called function must be carried out in the main calling function module before it can be used
- From the perspective of function execution results, functions can be divided into functions with return value and functions without return value
- Function with return value: after this kind of function is called and executed, it will return an execution result to the caller, which is called function return value. (you must specify the return value type and use the return keyword to return the corresponding data)
- Function without return value: this kind of function is used to complete a specific processing task. After execution, it does not return the function value to the caller. (the return value type is void, so you don't need to use the return keyword to return the corresponding data)
- From the perspective of data transmission between the calling function and the called function, it can be divided into two types: nonparametric function and parametric function
- Parameterless function: there are no parameters in function definition, function description and function call. There is no parameter transfer between the calling function and the called function.
- Parametric function: there are parameters in function definition and function description, which are called formal parameters (formal parameters for short). Parameters must also be given during function call, which are called actual parameters (referred to as actual parameters for short)
Definition of function
-
Define the purpose of the function
- A commonly used function is encapsulated to facilitate subsequent calls.
-
Custom function writing format
Return value type function name(Parameter type formal parameter 1, parameter type formal parameter 2) { Function body; Return value; }
- Examples
int main(){ printf("hello world\n"); retrun 0; }
- To define a function
- Function name: what is the name of the function
- Function body: what does the function do and what code it contains
- Return value type: what and caller are returned after the function is executed
- Function definition without parameter and return value
- If there is no return value, return can be omitted
- Format:
void Function name() { Function body; }
- Example:
// 1. No return value / no formal parameter // If a function does not need to return any data to the caller, the return value type is void void printRose() { printf(" {@}\n"); printf(" |\n"); printf(" \\|/\n"); // Note: \ is a special symbol (conversion character). If you want to output \ you must write two slashes printf(" |\n"); // If the function does not need to return data to the caller, the return in the function may not be written }
- Function definition with return value without parameter
- Format:
Return value type function name() { Function body; return value; }
- Example:
int getMax() { printf("Please enter two integers, Separated by commas, End with enter\n"); int number1, number2; scanf("%i,%i", &number1, &number2); int max = number1 > number2 ? number1 : number2; return max; }
- Function definition with parameter and no return value
- Format of formal parameter list: type variable name, type variable 2
- Format:
void Function name(Parameter type formal parameter 1, parameter type formal parameter 2) { Function body; }
- Example:
void printMax(int value1, int value2) { int max = value1 > value2 ? value1 : value2; printf("max = %i\n", max); }
- Function definition with parameter and return value
- Format:
Return value type function name(Parameter type formal parameter 1, parameter type formal parameter 2) { Function body; return 0; }
- Example:
int printMax(int value1, int value2) { int max = value1 > value2 ? value1 : value2; return max; }
- Function definition note
-
- Function names cannot be the same
void test() { } void test() { // report errors }
Function parameters and return values
- Formal parameters
- When * * * defining function * * *, the variables defined in parentheses () after the function name are called formal parameters, or formal parameters for short
- The formal parameter variable allocates the memory unit only when it is called. At the end of the call, the allocated memory unit is released immediately.
- Therefore, the formal parameter is only valid inside the function. After the function call ends and returns to the calling function, the formal parameter variable can no longer be used
int max(int number1, int number2) // Formal parameters { return number1 > number2 ? number1 : number2; }
- Actual parameters
- When * * * calls function * * *, the value passed in is called the actual parameter, which is called the actual parameter for short
- Arguments can be constants, variables, expressions, functions, etc. no matter what type of quantities the arguments are, they must have definite values when calling the function, so as to pass these values to the formal parameters
- Therefore, we should use assignment, input and other methods in advance to obtain the determined value of the argument
int main() { int num = 99; // 88, num, 22+44 can get a certain value, so they can be used as arguments max(88, num, 22+44); // Actual parameters return 0; }
- Precautions for formal and actual parameters
- The number of arguments passed when calling the function must be consistent with the number of formal parameters of the function
int max(int number1, int number2) { // Formal parameters return number1 > number2 ? number1 : number2; } int main() { // The function needs two formal parameters, but we only passed one argument, so an error is reported max(88); // Actual parameters return 0; }
- If the parameter and argument types are inconsistent, they will be automatically converted to parameter types
void change(double number1, double number2) {// Formal parameters // Output result: 10.000000, 20.000000 // Automatically convert the argument to double type and save it printf("number1 = %f, number2 = %f", number1, number2); } int main() { change(10, 20); return 0; }
- When the basic data type (char, int, float, etc.) is used as the argument, only the value is passed between the argument and the formal parameter. Modifying the value of the formal parameter does not affect the argument function. There can be no formal parameter
void change(int number1, int number2) { // Formal parameters number1 = 250; // Does not affect arguments number2 = 222; } int main() { int a = 88; int b = 99; change(a, b); printf("a = %d, b = %d", a, b); // Output results: 88, 99 return 0; }
- Return value type precautions
- If the return value type is not written, the default value is int
max(int number1, int number2) {// Formal parameters return number1 > number2 ? number1 : number2; }
- The type of the return value of the function should be consistent with the type of the value actually returned by return. If the two are inconsistent, the return value type shall prevail and automatic type conversion shall be performed
int height() { return 3.14; } int main() { double temp = height(); printf("%lf", temp);// Output result: 3.000000 }
- A return statement can be used multiple times inside a function, but the code behind the return statement is no longer executed
int max(int number1, int number2) {// Formal parameters return number1 > number2 ? number1 : number2; printf("Cannot execute"); // Cannot execute return 250; // Cannot execute }
Declaration of function
- In C language, the definition order of functions is particular:
- By default, only the functions defined later can call the functions defined earlier
- If you want to write the definition of the function after the main function, and the main function can call these functions normally, you must declare the function in front of the main function, otherwise
- The system doesn't know if there is this function
- The system doesn't know how many parameters this function receives
- The system does not know what the return value type of this function is
- Therefore, the function declaration is to tell the system what the name of the function is, how many parameters the function receives, and what the return value type of the function is before the function call
- Declaration format of function:
- Copy the contents before {} when customizing the function to between calls
- For example: int max (int a, int b);
- Or: int max (int, int);
// Function declaration void getMax(int v1, int v2); int main(int argc, const char * argv[]) { getMax(10, 20); // Call function return 0; } // Function implementation void getMax(int v1, int v2) { int max = v1 > v2 ? v1 : v2; printf("max = %i\n", max); }
- Relationship between function declaration and Implementation
- Declaration only means to tell the system that there must be this function, and what the parameters and return values of this function are
- Implementation means telling the system how the specific business logic of this function works
- Precautions for function declaration:
- The implementation of a function cannot be repeated, while the declaration of a function can be repeated
// Function declaration void getMax(int v1, int v2); void getMax(int v1, int v2); void getMax(int v1, int v2); // No error will be reported int main(int argc, const char * argv[]) { getMax(10, 20); // Call function return 0; } // Function implementation void getMax(int v1, int v2) { int max = v1 > v2 ? v1 : v2; printf("max = %i\n", max); }
- The function declaration can be written outside the function or inside the function, as long as it is declared before the call
int main(int argc, const char * argv[]) { void getMax(int v1, int v2); // Function declaration, no error will be reported getMax(10, 20); // Call function return 0; } // Function implementation void getMax(int v1, int v2) { int max = v1 > v2 ? v1 : v2; printf("max = %i\n", max); }
- When the function definition of the called function appears before the calling function, the called function can also not be declared in the calling function
// Function implementation void getMax(int v1, int v2) { int max = v1 > v2 ? v1 : v2; printf("max = %i\n", max); } int main(int argc, const char * argv[]) { getMax(10, 20); // Call function return 0; }
- If the return value of the called function is an integer, you can call it directly without describing the called function
int main(int argc, const char * argv[]) { int res = getMin(5, 3); // No error will be reported printf("result = %d\n", res ); return 0; } int getMin(int num1, int num2) {// Return int without declaration return num1 < num2 ? num1 : num2; }
main function analysis
- main means:
- main is the name of the function. It is also an identifier like the function name we defined
- But the name main is special, and it will be called automatically when the program has started
- return 0; Meaning of:
- Tell the system whether the main function has been executed correctly
- If the main function performs normally, it returns 0
- If the main function does not execute normally, it returns a non-zero number
- Return value type:
- What type is written after a function return and what type the return value type of the function must be, so write int
- Meaning of formal parameter list
- int argc :
- The number of values passed to argv when the system calls the main function when starting the program
- const char * argv[] :
- The value passed in when the system starts the program. By default, the system will only pass in one value, which is the path of the main function execution file
- You can also pass in other parameters through the command line or project settings
- int argc :
- Function exercise
- Write a function to input three integer numbers from the keyboard to find out its maximum value
- Write a function to find the average of three numbers
Recursive function (understand)
- What is a recursive function?
- A function that is called in its function body is called a recursive call
void function(int x){ function(x); }
- Composition conditions of recursive function
- Do it yourself
- There is a condition that allows recursion to end
- The scale of the problem can be reduced
- Example:
- Gets the number entered by the user until the user enters a positive number
void getNumber(){ int number = -1; while (number < 0) { printf("Please enter a positive number\n"); scanf("%d", &number); }printf("number = %d\n", number);
}
void getNumber2(){ int number = -1; printf("Please enter a positive number abc\n"); scanf("%d", &number); if (number < 0) { // negative getNumber2(); }else{ // Positive number printf("number = %d\n", number); } }
-
Difference between recursion and loop
- The functions that can be realized by loop can be realized by recursion
- Recursion is often used in "backtracking", "tree traversal", "graph search" and other problems
- However, code understanding is difficult and memory consumption is high (easy to lead to stack overflow). Therefore, considering the difficulty of code understanding and memory consumption, loops are generally used in enterprise development without recursion
-
Recursive exercise
- Five people sat together and asked how old the fifth person was? He said he was two years older than the fourth man. Asked the age of the fourth person, he said that he was two years older than the third person. Ask the third person and say that he is two years older than the second person. Ask the second person that he is two years older than the first. Finally, the first person was asked. He said he was 10 years old. How old is the fifth person?
- Finding the factorial of N by recursive method
- Design a function to calculate the nth power of B
Basic concepts of binary system
-
What is hexadecimal?
- Hexadecimal is a way of counting, the representation of numerical value
-
Common binary
- Decimal, binary, octal, hexadecimal
-
Format and law of binary writing
- Decimal 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9 meet decimal one
- Binary 0 and 1 enter one every two
- Writing form: it needs to start with 0b or 0b, for example: 0b101
- Octal 0, 1, 2, 3, 4, 5, 6 and 7 enter one every eight
- Writing form: add a 0 before it, for example: 061
- Hexadecimal 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F enter one every hexadecimal
- Writing form: precede with 0X or 0X, for example: 0x45
-
practice
- 1. How many squares are there in different base numbers
- 2. Judge whether the following figures are reasonable
00011 0x001 0x7h4 10.98 0986 .089-109 +178 0b325 0b0010 0xffdc 96f 96.0f 96.oF -.003
Binary conversion
- Decimal to binary
- Divide by 2 and take the remainder, and the remainder is in reverse order; The resulting sequence is a binary representation
- For example: convert decimal (97) 10 to binary number
- Binary to decimal
- The value of each binary digit * the current index power of 2; Then add the values of all bits
- For example: convert binary 01100100 to decimal
01100100 Index right to left, Start from scratch Bit 0: 0 * 2^0 = 0; 1st place: 0 * 2^1 = 0; 2nd place: 1 * 2^2 = 4; 3rd place: 0 * 2^3 = 0; 4th place: 0 * 2^4 = 0; 5th place: 1 * 2^5 = 32; 6th place: 1 * 2^6 = 64; 7th place: 0 * 2^7 = 0; The final result is: 0 + 0 + 4 + 0 + 0 + 32 + 64 + 0 = 100
- Binary to octal
- The three binary bits represent an octal bit, because the maximum value of the three binary bits is 7, and octal is every 8 into 1
- For example: convert binary 01100100 to octal number
From right to left, every 3 bits are divided into 1 bit of octal, Not enough. Fill 0 in front 001 100 100 Bit 0: 100 Equal to decimal 4 1st place: 100 Equal to decimal 4 2nd place: 001 Equal to decimal 1 final result: 144 Is the value converted to octal
- Binary to hexadecimal
- Four binary bits represent a hexadecimal bit, because the maximum value of four binary bits is 15, and hexadecimal is 1 every 16
- For example: convert binary 01100100 to hexadecimal number
From right to left, every 4 bits are divided into 1 bit of hexadecimal, Not enough. Fill 0 in front 0110 0100 Bit 0: 0100 Equal to decimal 4 1st place: 0110 Equal to decimal 6 final result: 64 Is the value converted to hexadecimal
- Convert other base numbers to decimal
- Sum of coefficient * cardinality ^ index
decimal system --> decimal system 12345 = 10000 + 2000 + 300 + 40 + 5 = (1 * 10 ^ 4) + (2 * 10 ^ 3) + (3 * 10 ^ 2) + (4 * 10 ^ 1) + (5 * 10 ^ 0) = (1 * 10000) + (2 + 1000) + (3 * 100) + (4 * 10) + (5 * 1) = 10000 + 2000 + 300 + 40 + 5 = 12345
law:
The result of converting other base numbers to decimal = the sum of coefficient * base ^ index
Coefficient: the value of each bit is a coefficient
Cardinality: convert from base x to decimal, then x is the cardinality
Index: the number of increments starting from 0 in the lowest order
Binary --> decimal system
543210
101101 = (1 * 2 ^ 5) + (0 * 2 ^ 4) + (1 * 2 ^ 3) + (1 * 2 ^ 2) + (0 * 2 ^ 1) + (1 * 2 ^ 0)
= 32 + 0 + 8 + 4 + 0 + 1
= 45
Octal -- > decimal
016 = (0 * 8 ^ 2) + (1 * 8 ^ 1) + (6 * 8 ^ 0)
= 0 + 8 + 6
= 14
Hex -- > decimal
0x11f = (1 * 16 ^ 2) + (1 * 16 ^ 1) + (15 * 16 ^ 0)
= 256 + 16 + 15
= 287
- Fast conversion from decimal to other decimal
- Decimal divided by Radix, remainder, flashback reading
decimal system --> Binary 100 --> 1100100 100 / 2 = 50 0 50 / 2 = 25 0 25 / 2 = 12 1 12 / 2 = 6 0 6 / 2 = 3 0 3 / 2 = 1 1 1 / 2 = 0 1
Decimal -- > octal
100 --> 144
100 / 8 = 12 4
12 / 8 = 1 4
1 / 8 = 0 1
Decimal -- > hexadecimal
100 --> 64
100 / 16 = 6 4
6 / 16 = 0 6
Convert decimal to binary decimal
- The integer part can be directly converted to binary
- Decimal part, using "multiply by 2, round, order"
- Multiply the decimal fraction by 2 to get the product. Take out the integer part of the product, and then multiply the remaining decimal part by 2 until the decimal part in the product is zero or reaches the required accuracy
- Then the integer parts are arranged in order, that is, the decimal part is binary
- Finally, the binary of the integer part and the binary of the decimal part are combined to form a binary decimal
- For example: convert 12.125 to binary
// Integer part (divide by 2) 12 / 2 ------ 6 // Yu 0 / 2 ------ 3 // Yu 0 / 2 ------ 1 // Yu 1 / 2 ------ 0 // Yu 1 //12 --> 1100
//Fractional part (multiply by 2 to take the integral product)
0.125
-
0.25 //02
0.25 -
0.5 //02
0.5 -
1.0 //12
0.0
// 0.125 --> 0.001
// 12.8125 --> 1100.001
Convert binary decimals to decimal decimals
- The integer part can be converted from binary to decimal
- The decimal part is multiplied by the negative n power of 2 from the highest place, and N starts from 1
- For example: convert 1100.001 to decimal
// Integer part (multiplied by 2 to the nth power, n starts from 0) 0 * 2^0 = 0 0 * 2^1 = 0 1 * 2^2 = 4 1 * 2^3 = 8 // 1100 == 8 + 4 + 0 + 0 == 12
//Fractional part (multiplied by 2 to the negative nth power, n starts from 0)
0 * (1/2) = 0
0 * (1/4) = 0
1 * (1/8) = 0.125
// .100 == 0 + 0 + 0.125 == 0.125
// 1100.001 --> 12.125
- practice:
- Convert 0.8125 to binary
- Convert 0.1101 to decimal
0.8125 * 2 -------- 1.625 // 1 0.625 * 2 -------- 1.25 // 1 0.25 * 2 -------- 0.5 // 0 * 2 -------- 1.0 // 1 0.0
// 0. 8125 --> 0.1101
1*(1/2) = 0.5 1*(1/4)=0.25 0*(1/8)=0 1*(1/16)=0.0625 //0.1101 --> 0.5 + 0.25 + 0 + 0.0625 == 0.8125
Inverse complement of original code
- The computer can only recognize 0 and 1, so the data stored in the computer is stored in the form of 0 and 1
- Data is stored in the form of complement in the computer, and all data operations are carried out in the form of complement
- Source code, inverse code and complement of positive numbers
- The original code, inverse code and complement of a positive number are its binary
- For example, the original code, inverse code and complement code of 12 are
- 0000 0000 0000 0000 0000 0000 0000 1100
- 0000 0000 0000 0000 0000 0000 0000 1100
- 0000 0000 0000 0000 0000 0000 0000 1100
- Original code, inverse code and complement of negative numbers
- The highest bit of binary is called sign bit. The highest bit is 0, which means a positive number, and the highest bit is 1, which means a negative number
- The original code of a negative number is to change the binary highest bit of the negative number to 1
- The inverse code of a negative number reverses other bits of the original code of the number except the sign bit
- The complement of a negative number is its inverse code + 1
- For example, the original code, inverse code and complement code of: - 12 are respectively
0000 0000 0000 0000 0000 0000 0000 1100 // 12 binary 1000 0000 0000 0000 0000 0000 0000 1100 // -12 original code 1111 1111 1111 1111 1111 1111 1111 0011 // -12 inverse code 1111 1111 1111 1111 1111 1111 1111 0100 // -12 complement
- Inverse conversion of the original code, inverse code and complement of negative numbers
- Inverse = complement-1
- Original code = the highest bit of inverse code remains unchanged, and other bits are reversed
1111 1111 1111 1111 1111 1111 1111 0100 // -12 complement 1111 1111 1111 1111 1111 1111 1111 0011 // -12 inverse code 1000 0000 0000 0000 0000 0000 0000 1100 // -12 original code
- Why should we introduce inverse code and complement code
- Before learning this section, you must understand that computers can only do addition, not subtraction, multiplication and division. Therefore, subtraction, multiplication and division are realized by addition
- For example: 1 - 1, the internal is actually 1 + (- 1);
- For example: 3 * 3, the internal is actually 3 + 3 + 3;
- For example: 9 / 3, the internal is actually 9 + (- 3) + (- 3) + (- 3);
- First of all, let's take a look at what happens if only the original code is stored
- Obviously, through our observation, if there is only the original code, the result of 1-1 is wrong
// 1 + 1 0000 0000 0000 0000 0000 0000 0000 0001 // 1 original code +0000 0000 0000 0000 0000 0000 0000 0001 // 1 original code --------------------------------------- 0000 0000 0000 0000 0000 0000 0000 0010 == 2
- Before learning this section, you must understand that computers can only do addition, not subtraction, multiplication and division. Therefore, subtraction, multiplication and division are realized by addition
// 1 - 1; 1 + (-1);
0000 0000 0000 0001 / / 1 original code
+1000 0000 0001 / / - 1 original code
1000 0000 0000 0000 0000 0000 0000 0010 == -2
- It is precisely because for subtraction, if the original code is used, the result is incorrect, so the inverse code is introduced
-
- The result of subtraction through inverse code calculation is also an inverse code;
- The original code of the calculation result is obtained by keeping the sign bits of the calculation result unchanged and inverting the other bits
- Through the conversion of the original code, it is obvious that our calculation result is - 0, which is in line with our expectation
// 1 - 1; 1 + (-1);
0000 0000 0000 0000 0000 0000 0000 0001 // 1 inverse code
1111 1111 1111 1111 1111 1111 1111 1110 // -1 inverse code1111 1111 1111 1111 1111 1111 1111 1111 / / the calculation result is inversely coded
1000 million / / calculation result original code = = - 0
- Although the inverse code can meet our needs, the minus sign in front of 0 has no meaning, so the complement code is introduced
-
- Because int can only store 4 bytes, that is, 32-bit data, and the calculation result is 33 bits, the highest bit overflows and the symbol bit becomes 0, so the final result is 0
// 1 - 1; 1 + (-1);
0000 0000 0000 0000 0000 0000 0000 0001 // 1 Complement
1111 1111 1111 1111 1111 1111 1111 1111 // -1 Complement10000 million / / calculation result complement
0000 0000 0000 0000 0000 0000 0000 0000 // == 0
Bitwise Operators
- All data in the program is stored in binary form in the computer memory.
- Bit operation is to directly operate the binary bits of integers in memory
- C language provides six bit operators, which can only be used for integer operands
Symbol name Operation result & Bitwise AND The same as 1 is 1 | Bitwise OR 1 is 1 ^ Bitwise XOR The difference is 1 ~ Bitwise inversion 0 to 1, 1 to 0 << Shift left by bit Multiply by 2 to the power of n >> Shift right by bit Divide by 2 to the n th power - Bitwise AND:
- Only when the corresponding two binary bits are 1, the result bit is 1, otherwise it is 0
- Law: in binary, phase with 1 & remains in place, and phase with 0 & is 0
9&5 = 1
1001
&01010001
- Bitwise OR:
- As long as one of the corresponding two binary bits is 1, the result bit is 1, otherwise it is 0
9|5 = 13
1001
0101 1101
- Bitwise XOR
- When the corresponding binary is different (different), the result is 1, otherwise it is 0
- law:
- The result of the same integer phase is 0. For example, 55 = 0
- The results of multiple integers are independent of order. For example: 567 = 576
- If the same number is exclusive or another number is counted twice, the result is still that number. For example: 577 = 5
9^5 = 12
1001
^01011100
- Bitwise inversion
- Reverse each binary (0 to 1, 1 to 0)
~9 =-10 0000 0000 0000 0000 0000 1001 // Before inversion 1111 1111 1111 1111 1111 0110 // After inversion
//The result is obtained from the complement of negative numbers
1111 1111 1111 1111 1111 0110 / / complement
1111 1111 1111 1111 1111 0101 / / inverse code
1000 0000 1010 / / source code = = - 10
- Application scenario of bit operation:
- Judge parity (bitwise OR)
even numbers: Binary ends with 0 8 -> 1000 10 -> 1010
Odd: the binary of is ending with 1
9 -> 1001
11 -> 1011Any number and 1 are & manipulated to get the lowest order of the number
1000
&00010000 / / the result is 0, which means an even number
1011
&00010001 / / the result is 1, which means an odd number
- Permission system
enum Unix { S_IRUSR = 256,// 100000000 user readable S_IWUSR = 128,// 10000000 users can write S_IXUSR = 64,// 1000000 user executable S_IRGRP = 32,// 100000 groups readable S_IWGRP = 16,// 10000 groups writable S_IXGRP = 8,// 1000 groups executable S_IROTH = 4,// 100 other readable S_IWOTH = 2,// 10 other writable S_IXOTH = 1 // 1. Other executable }; // Suppose that the user permission is set to be readable and writable printf("%d\n", S_IRUSR | S_IWUSR); // 384 // 110000000
- Swap the values of two numbers (bitwise XOR)
a = a^b; b = b^a; a = a^b;
- Shift left by bit
- Move all binary bits of integer a to the left by n bits, discard the high bit and fill the low bit with 0
- Since shift left discards the highest bit and 0 complements the lowest bit, the symbol bit will also be discarded, and the result value moved left may change its positive and negative
- Law: shifting n bits to the left is actually multiplying by 2 to the nth power
- Move all binary bits of integer a to the left by n bits, discard the high bit and fill the low bit with 0
2<<1; //Equivalent to 2 * = 2 / / 4 0010 <<0100
2<<2; // Equivalent to 2 * = 2 ^ 2// eight
0010
<<1000
- Shift right by bit
- Shift all binary bits of integer a to the right by n bits and keep the sign bit unchanged
- When it is a positive number, the sign bit is 0, and the highest bit is supplemented by 0
- When it is negative, the sign bit is 1, and the highest bit is 0 or 1 (depending on the regulations of the compiling system)
- Rule: quickly calculate a number divided by 2 to the nth power
- Shift all binary bits of integer a to the right by n bits and keep the sign bit unchanged
2>>1; //Equivalent to 2 / = 2 / / 1 0010 >>0001 4>>2; //Equivalent to 4 / = 2 ^ 2 / / 1 0100 >>0001
- practice:
- Write a function to output a decimal number in binary format
#include <stdio.h> void printBinary(int num); int main(int argc, const char * argv[]) { printBinary(13); } void printBinary(int num){ int len = sizeof(int)*8; int temp; for (int i=0; i<len; i++) { temp = num; //Each time, the shift operation is performed on the basis of the original number temp = temp>>(31-i); //Number of bits per move int t = temp&1; //Take out the last bit if(i!=0&&i%4==0)printf(" "); printf("%d",t); } }
Variable memory analysis
- Memory model
- The memory model is linear (ordered)
- For 32 computers, the maximum memory address is 2 ^ 32 power bit(4294967296)(4GB)
- For 64 computers, the largest memory address is 2 ^ 64th power bit (18446744073709552000) (17.1 billion GB)
- CPU read / write memory
- There are three things to be clear about when the CPU is running
- Address of storage unit (address information)
- Device selection, read or write (control information)
- Read / write data (data information)
- There are three things to be clear about when the CPU is running
- How to clarify these three things
- Find the address of the storage unit through the address bus
- Send memory read and write instructions through the control bus
- The data to be read and written is transmitted through the data bus
- Address bus: the width of the address bus determines the physical address space (addressing capability) that the CPU can access
- For example, if the width of the address bus is 1 bit, it means that the memory of 0 and 1 can be accessed
- For example, if the number of bits of the address bus is 2, it means that the memory of 00, 01, 10 and 11 can be accessed
- Data bus: the number of bits of the data bus determines the amount of information that can be exchanged by the CPU in a single communication
- For example, if the width of data bus is 1 bit, 1 bit binary data can be transmitted at a time
- For example, if the number of bits of the address bus is 2 bits, 2-bit binary data can be transmitted at one time
- Control bus: used to transmit various control signals
-
Write process
- The CPU will find the memory with address fffffb through the address line
- The CPU sends a memory write command through the control line, selects the memory chip, and notifies it to write data.
- The CPU sends the data 8 into the memory fffb unit through the data line
-
Read process
- The CPU will find the memory with address fffffb through the address line
- The CPU sends out the memory reading command through the control line, selects the memory chip, and notifies it that the data will be read from it
- The memory sends the data 8 in unit fffb into the CPU register through the data line
-
Storage principle of variables
- Allocate memory with large byte address first, and then allocate memory with small byte address (memory addressing is from large to small)
- The first address of the variable is the byte address of the storage space occupied by the variable (the smallest address)
- The low bit is saved on the low address byte and the high bit is saved on the high address byte
10 Binary: 0b00000000 00000000 00000000 00001010 High byte← →Low byte
char type memory storage details
- Basic concepts of char type
- char is a flexible data type in C language, which is called "character type"
- char type variables occupy 1 byte of storage space, a total of 8 bits
- In addition to single characters, escape characters of C language can also be stored by char type
character significance \b Backspace (BS) backspace the current position by one character \r Press enter (CR) to move the current position to the beginning of the line \n Line feed (LF) moves the current position to the beginning of the next line \t Horizontal tabulation (HT), skip to the next TAB position \0 End tag used to represent a string \ Represents a backslash character\ \" Represents a double quote character“ \' Represents a single quote character ' - Principle of char data storage
- The computer can only recognize 0 and 1, so the data stored in char type is not to store a character, but to convert the character into 0 and 1 and then store it
- It is precisely because characters need to be converted into 0 and 1 when storing character types. Therefore, in order to unify, Lao Mei defined an object called ASCII table
- The ASCII table defines the integer corresponding to each character
char ch1 = 'a'; printf("%i\n", ch1); // 97
char ch2 = 97; printf("%c\n", ch2); // a
- Notes on char type
- char type takes up one byte and one Chinese character takes up three bytes (unicode table). All chars cannot store Chinese characters
char c = 'I'; // Wrong writing
- Multiple characters are not supported except escape characters
char ch = 'ab'; // Wrong writing
- When char type stores characters, it will first find the corresponding ASCII code value, which stores ASCII values, so the contents stored in character 6 and number 6 are different
char ch1 = '6'; // ASCII code 64 is stored char ch2 = 6; // The number 6 is stored
- practice
- Define a function to input a lowercase letter, which is required to be converted to uppercase output
type specifier
- Basic concepts of type specifier
- C language provides two types of specifiers for description length and description symbol bit. There are four types of specifiers in total:
- Short short (specify length)
- Long long integer (specify the length)
- Signed signed type (indicating sign bit)
- Unsigned unsigned (indicating sign bit)
- C language provides two types of specifiers for description length and description symbol bit. There are four types of specifiers in total:
- These specifiers are generally used to modify int type, so int can be omitted when using
- These specifiers belong to C language keywords
short and long
- short and long can provide integers of different lengths, that is, the value range of integers can be changed.
- In the 64bit compiler environment, int occupies 4 bytes (32bit), and the value range is - 2 ^ 31 ~ 2 ^ 31-1;
- short takes up 2 bytes (16bit), and the value range is - 2 ^ 15 ~ 2 ^ 15-1;
- long takes up 8 bytes (64bit), and the value range is - 2 ^ 63 ~ 2 ^ 63-1
- To summarize: in a 64 bit compiler environment:
- short takes up 2 bytes (16 bits)
- int takes up 4 bytes (32 bits)
- long takes up 8 bytes (64 bits).
- Therefore, if the integer used is not very large, you can use short instead of int. in this way, you can save memory overhead.
- There are many compilers in the world. Under different compiler environments, the value range and length of int, short and long are different. For example, in the 16bit compiler environment, long only takes up 4 bytes. Fortunately, however, ANSI \ ISO has the following rules:
- short and int must be at least 16 bits (2 bytes)
- long must be at least 32 bits (4 bytes)
- The length of short cannot be greater than int, and the length of int cannot be greater than long
- Char must be 8 bits (1 byte). After all, char is the smallest data type we can use in programming
- Two long can be used continuously, that is, long long. Generally speaking, the range of long long is no less than long. For example, in the 32bit compiler environment, long long occupies 8 bytes and long occupies 4 bytes. However, in the 64bit compiler environment, long and long are the same, both occupying 8 bytes.
#include <stdio.h>
int main()
{
//Char takes up one byte, and the value range of char is - 27 ~ 27
char num = 129;
printf("size = %i\n", sizeof(num)); // 1
printf("num = %i\n", num); // -127
//Short int takes up 2 bytes, and the value range of short int is - 215 ~ 215-1
short int num1 = 32769;// -32767
printf("size = %i\n", sizeof(num1)); // 2
printf("num1 = %hi\n", num1);// Int takes up 4 bytes, and the value range of int is - 2 ^ 31 ~ 2 ^ 31-1 int num2 = 12345678901; printf("size = %i\n", sizeof(num2)); // 4 printf("num2 = %i\n", num2); // long takes up 4 bytes in 32 bits and 8 bytes in 64 bits long int num3 = 12345678901; printf("size = %i\n", sizeof(num3)); // 4 or 8 printf("num3 = %ld\n", num3); // long takes up 8 bytes in 32 bits and 8 bytes in 64 bits - 2 ^ 63 ~ 2 ^ 63-1 long long int num4 = 12345678901; printf("size = %i\n", sizeof(num4)); // 8 printf("num4 = %lld\n", num4); // Because short / long / long is generally used to decorate int, int can be omitted short num5 = 123; printf("num5 = %lld\n", num5); long num6 = 123; printf("num6 = %lld\n", num6); long long num7 = 123; printf("num7 = %lld\n", num7); return 0;
}
signed and unsigned
- First of all, it should be clear that signed int is equivalent to signed and unsigned int is equivalent to unsigned
- The difference between signed and unsigned is whether their highest bit should be regarded as a sign bit. It does not change the length of data, that is, the number of bytes, like short and long.
- Signed: indicates that there is a sign, that is, the highest bit should be regarded as a sign bit. However, the highest bit of int is the sign bit, so signed is the same as int. signed is equivalent to signed int and int. The value range of signed is - 2 ^ 31 ~ 2 ^ 31 - 1
- Unsigned: indicates unsigned, that is, the highest bit is not a sign bit, so negative numbers are not included.
- Therefore, the value range of unsigned is: 0000, 0000, 0000, 0000 ~ 1111 1111 1111 1111 1111 1111 1111 1111 1111, that is, 0 ~ 2 ^ 32 - 1
#include <stdio.h>
int main()
{
// 1. By default, all types are represented by symbols
int num1 = 9;
int num2 = -9;
int num3 = 0;
printf("num1 = %i\n", num1);
printf("num2 = %i\n", num2);
printf("num3 = %i\n", num3);// 2.signed is used to specify that the currently saved data can be signed, which is rarely used in general signed int num4 = 9; signed int num5 = -9; signed int num6 = 0; printf("num4 = %i\n", num4); printf("num5 = %i\n", num5); printf("num6 = %i\n", num6); // signed can also omit data types, but this is not recommended signed num7 = 9; printf("num7 = %i\n", num7); // 3.unsigned is used to specify that signed values cannot be saved at present, only 0 and positive numbers can be saved // Application scenario: saving bank deposits and student scores cannot be negative unsigned int num8 = -9; unsigned int num9 = 0; unsigned int num10 = 9; // Note: it doesn't depend on how to deposit, but how to withdraw printf("num8 = %u\n", num8); printf("num9 = %u\n", num9); printf("num10 = %u\n", num10); return 0;
}
- Note:
- The specifier of modifier can be mixed with the specifier of modifier length
- Specifiers of the same type cannot be mixed
signed short int num1 = 666; signed unsigned int num2 = 666; // report errors
Basic concept of array
-
Array, literally, means a set of data. Yes, array is used to store a set of data
- In C language, array belongs to construction data type
-
Several nouns of array
- Array: an ordered collection of data of the same data type
- Array element: each data that constitutes an array.
- Subscript of array: index of the position of array element (starting from 0)
-
Application scenario of array
- An int type variable can save a person's age. What if you want to save the age of the whole class?
- The first method is to define many variables of type int to store
- The second method is to define only an array of int type to store
- An int type variable can save a person's age. What if you want to save the age of the whole class?
#include <stdio.h>
int main(int argc, const char * argv[]) {
/*
//Requirement: save the scores of 2 people
int score1 = 99;
int score2 = 60;// Requirement: save the scores of the whole class (130 people) int score3 = 78; int score4 = 68; ... int score130 = 88; */ // Array: if necessary, save ` One group `&# 96; Same type ` You can define an array to save the data // As long as an array is defined, each small storage space will be given a number inside the array. This number is called the index, and the index starts from 0 // 1. Define an array that can hold three int types int scores[3]; // 2. Store data into the array through the index of the array scores[0] = 998; scores[1] = 123; scores[2] = 567; // 3. Fetch the stored data from the array through the index of the array printf("%i\n", scores[0]); printf("%i\n", scores[1]); printf("%i\n", scores[2]); return 0;
}
Define array
- Element type array name [number of elements];
// int element type // ages array name // [10] Number of elements int ages[10];
Initialize array
- Initialize while defining
- Specify the number of elements and complete initialization
- The data values in {} are the initial values of each element, and the values are separated by commas
int ages[3] = {4, 6, 9};
- Do not specify the number of elements, full initialization
- Determine the number of elements of the array according to the number of elements in braces
int nums[] = {1,2,3,5,6};
- Specify the number of elements, partial initialization
- If there is no explicitly initialized element, the system will automatically initialize it to 0
int nums[10] = {1,2};
- Specify the number of elements, partial initialization
int nums[5] = {[4] = 3,[1] = 2};
- Partial initialization without specifying the number of elements
int nums[] = {[4] = 3};
- Define before initialize
int nums[3]; nums[0] = 1; nums[1] = 2; nums[2] = 3;
- What happens without initialization?
- If there is no initialization after defining the array, the array has values and is a random garbage number. Therefore, if you want to use the array correctly, you should initialize it.
int nums[5]; printf("%d\n", nums[0]); printf("%d\n", nums[1]); printf("%d\n", nums[2]); printf("%d\n", nums[3]); printf("%d\n", nums[4]); Output results: 0 0 1606416312 0 1606416414
- Note:
- When using an array, you cannot exceed the index range of the array. The index starts from 0 and ends with the number of elements - 1
- When using an array, do not use uninitialized elements arbitrarily. It may be a random value
- For an array, you can only initialize multiple values at the same time of definition. You cannot define multiple values first and then initialize them
int ages[3]; ages = {4, 6, 9}; // report errors
Use of arrays
- Accessed by subscript (index):
// Find the element with subscript 0 and assign a value of 10 ages[0]=10; // Take out the saved value of the element with subscript 2 int a = ages[2]; printf("a = %d", a);
Traversal of array
- Array traversal: traversal means to view each element of the array in order
int ages[4] = {19, 22, 33, 13}; for (int i = 0; i < 4; i++) { printf("ages[%d] = %d\n", i, ages[i]); }
Array length calculation method
- Because the number of bytes the array occupies in memory depends on the type of data it stores and the number of data
- Storage space occupied by array = storage space occupied by an element * number of elements (array length)
- Therefore, the following method can be used to calculate the length of the array
Length of array = total bytes occupied by array / bytes occupied by array elements
int ages[4] = {19, 22, 33, 13}; int length = sizeof(ages)/sizeof(int); printf("length = %d", length); Output results: 4
practice
- Positive order output (traversal) array
int ages[4] = {19, 22, 33, 13}; for (int i = 0; i < 4; i++) { printf("ages[%d] = %d\n", i, ages[i]); }
- Output (traverse) array in reverse order
int ages[4] = {19, 22, 33, 13}; for (int i = 3; i >=0; i--) { printf("ages[%d] = %d\n", i, ages[i]); }
- Enter the length of the array from the keyboard, build an array, and then receive numbers from the keyboard through the for loop to initialize the array. And use the for loop output to view
Array internal storage details
-
Storage method:
- 1) Memory addressing from large to small, from high address to open up a continuous unused memory to the array
- 2) Allocate space to each element from the position with small address in the allocated continuous storage space
- 3) The data is stored from the location with the largest address in the storage space allocated by each element
- 4) Use the array name to point to the address with the smallest storage space
-
Examples
#include <stdio.h> int main() { int num = 9; char cs[] = {'l','n','j'}; printf("cs = %p\n", &cs); // cs = 0060FEA9 printf("cs[0] = %p\n", &cs[0]); // cs[0] = 0060FEA9 printf("cs[1] = %p\n", &cs[1]); // cs[1] = 0060FEAA printf("cs[2] = %p\n", &cs[2]); // cs[2] = 0060FEAB
<span class="token keyword">int</span> nums<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{<!-- --></span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">}</span><span class="token punctuation">;</span> <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"nums = %p\n"</span><span class="token punctuation">,</span> <span class="token operator">&</span>nums<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// nums = 0060FEA0</span> <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"nums[0] = %p\n"</span><span class="token punctuation">,</span> <span class="token operator">&</span>nums<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">// nums[0] = 0060FEA0</span> <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"nums[1] = %p\n"</span><span class="token punctuation">,</span> <span class="token operator">&</span>nums<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">// nums[1] = 0060FEA4</span> <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
}
- Note: characters are stored in memory in binary form corresponding to ASCII code value instead of the above form.
Array out of bounds
- Problems caused by array out of bounds
- About the wrong object
- Program crash
char cs1[2] = {1, 2}; char cs2[3] = {3, 4, 5}; cs2[3] = 88; // Note: this sentence accesses memory that does not belong to cs1 printf("cs1[0] = %d\n", cs1[0] ); Output results: 88
Why does the above output 88 and draw brain compensation according to "details stored inside the array"
Array considerations
- When defining an array, [] can only write integer constants or expressions that return integer constants
int ages4['A'] = {19, 22, 33}; printf("ages4[0] = %d\n", ages4[0]);
int ages5[5 + 5] = { 19, 22, 33};
printf("ages5[0] = %d\n", ages5[0]);int ages5['A' + 5] = { 19, 22, 33};
printf("ages5[0] = %d\n", ages5[0]);
- Wrong writing
// No number of elements specified, error int a[];
//Variables cannot be placed in []
int number = 10;
int ages[number]; // The old version of C language specification does not support
printf("%d\n", ages[4]);int number = 10;
int ages2[number] = { 19, 22, 33} / / direct error//Only one-time (all assignment) initialization can be performed when defining the array
int ages3[5];
ages10 = { 19, 22, 33};//An array with a length of N, the maximum subscript is n-1, and the subscript range is 0~n-1
int ages4[4] = { 19, 22, 33}
ages4[8]; // Array subscript out of bounds
- practice
- Enter the price of BTC sold on the current day from the keyboard and calculate the total price and average price of BTC sold (for example, 10 bitcoins sold in a day)
Arrays and functions
- Arrays can be used as function parameters. Arrays can be used as function parameters in two forms:
- One is to use array elements as arguments
- One is to use the array name as the formal and actual parameters of the function
Array elements as function parameters
- The elements of the array are used as function arguments, just as simple variables of the same type are used as arguments. If it is a basic data type, the change of formal parameters will not affect the arguments
void change(int val)// int val = number { val = 55; } int main(int argc, const char * argv[]) { int ages[3] = {1, 5, 8}; printf("ages[0] = %d", ages[0]);// 1 change(ages[0]); printf("ages[0] = %d", ages[0]);// 1 }
- Using array elements as function parameters does not require formal parameters to be array elements
Array name as function parameter
- In C language, in addition to being the identifier of the variable, the array name also represents the starting address of the array in memory. Therefore, when the array name is used as a function parameter, the actual parameter and formal parameter are not "value transfer", but "address transfer"
- The parameter array name passes the starting address of the array to the formal parameter array. The two arrays share a memory unit, and the system will no longer allocate storage units for the shape parameter group
- Since the two arrays share a memory unit, when the formal parameter array is modified, the argument array is modified at the same time
void change2(int array[3])// int array = 0ffd1 { array[0] = 88; } int main(int argc, const char * argv[]) { int ages[3] = {1, 5, 8}; printf("ages[0] = %d", ages[0]);// 1 change(ages); printf("ages[0] = %d", ages[0]);// 88 }
Notes on using array names as function parameters
- In the function parameter table, it is allowed not to give the length of the shape parameter group
void change(int array[]) { array[0] = 88; }
- The types of formal parameter array and argument array must be consistent, otherwise an error will be caused.
void prtArray(double array[3]) // Wrong writing { for (int i = 0; i < 3; i++) { printf("array[%d], %f", i, array[i]); } } int main(int argc, const char * argv[]) { int ages[3] = {1, 5, 8}; prtArray(ages[0]); }
- When the array name is used as a function parameter, because it is automatically converted to a pointer type, the number of elements divided by the array cannot be dynamically calculated in the function
void printArray(int array[]) { printf("printArray size = %lu\n", sizeof(array)); // 8 int length = sizeof(array)/ sizeof(int); // 2 printf("length = %d", length); }
- practice:
- Design a function int arrayMax(int a[], int count) to find out the maximum value of array elements
- Input three numbers 0-9 from the keyboard, and then output which numbers in 0-9 have not appeared
- It is required to input 6 numbers from 0 to 9 from the keyboard and output them after sorting
Counting Sort
-
Counting sorting is a non comparison based sorting algorithm, which was proposed by Harold H. Seward in 1954. Its advantage is that it is faster than any comparative sorting algorithm when sorting integers in a certain range.
-
Sorting idea:
- 1. Find the maximum value of the array to be sorted
- 2. Define an array whose maximum index value is the maximum value of the array to be sorted
- 3. Traverse the array to be sorted, and make the value traversed by the array to be sorted as a new array index
- 4. Add + 1 to the stored value of the index corresponding to the new array
-
Simple code implementation:
int main() { // Array to be sorted int nums[5] = {3, 1, 2, 0, 3}; // Used to sort arrays int newNums[4] = {0}; // Calculate the length of the array to be sorted int len = sizeof(nums) / sizeof(nums[0]); // Traverse the array to be sorted for(int i = 0; i < len; i++){ // Get the current value of the array to be sorted int index = nums[i]; // Take the current value of the array to be sorted as the index of the sorted array // The original value of the corresponding index used to sort the array + 1 newNums[index] = newNums[index] +1; }
// Calculate the length of the array to be sorted int len2 = sizeof(newNums) / sizeof(newNums[0]); // The output sorted array index is the result after sorting for(int i = 0; i < len2; i++){ for(int j = 0; j < newNums[i]; j++){ printf("%i\n", i); } } /* // Calculate the length of the array to be sorted int len2 = sizeof(newNums) / sizeof(newNums[0]); // Restore the sorting result to the array to be sorted for(int i = 0; i < len2; i++){ int index = 0; for(int i = 0; i < len; i++){ for(int j = 0; j < newNums[i]; j++){ nums[index++] = i; } } } */ return 0;
}
Select sort
-
Selection sort is a simple and intuitive sorting algorithm. Its working principle is as follows. First, find the smallest element in the unordered sequence and store it at the beginning of the sorting sequence. Then, continue to find the smallest element from the remaining unordered elements, and then put it at the end of the sorting sequence. And so on until all elements are sorted.
-
Sorting idea:
- Assume sorting in ascending order
- 1. Compare the element 0 with all the following elements in turn
- 2. Judge whether the 0th element is larger than the current compared element, and exchange the position once it is smaller than
- 3. After the comparison between the 0th element and all subsequent elements is completed, the 0th element is the minimum value
- 4. Exclude the 0th element and repeat the operation 1 ~ 3 with the first element. After the comparison, the first element is the penultimate value
- And so on, until the current element has no comparable element, the sorting is completed
-
Code implementation:
// Select sort void selectSort(int numbers[], int length) {
// Why is the external circulation - 1? // The last one does not need to be compared, and there is no next one to compare with it, otherwise there will be wrong access for (int i = 0; i < length; i++) { for (int j = i; j < length - 1; j++) { // 1. Compare the current element with all subsequent elements if (numbers[i] < numbers[j + 1]) { // 2. Exchange positions once less than swapEle(numbers, i, j + 1); } } }
}
//Exchange the values of two elements, and i/j the index to be exchanged
void swapEle(int array[], int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Bubble sorting
- Bubble sort is a simple sorting algorithm. It repeatedly visits the sequence to be sorted, compares two elements at a time, and exchanges them if they are in the wrong order. The work of visiting the sequence is repeated until there is no need to exchange, that is, the sequence has been sorted. The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the sequence through exchange.
- Sorting idea:
- Assume sorting in ascending order
- 1. Start from the 0th element and compare with two adjacent elements each time
- 2. Once the latter element is found to be smaller than the previous element, the position will be exchanged
- 3. After a round of comparison, the last element is the maximum value
- 4. Exclude the last element, and so on. After each comparison, the maximum value will appear the last value of all elements to be compared
- Until the current element has no comparable elements, the sorting is completed
- Code implementation:
// Bubble sorting void bubbleSort(int numbers[], int length) { for (int i = 0; i < length; i++) { // -1. Prevent the corner marker from crossing the boundary: access to an index that does not belong to you for (int j = 0; j < length - i - 1; j++) { // 1. Compare the current element with adjacent elements if (numbers[j] < numbers[j + 1]) { // 2. Exchange positions once less than swapEle(numbers, j, j + 1); } } } } // Exchange the values of two elements, and i/j the index to be exchanged void swapEle(int array[], int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; }
Insert sort
- The algorithm description of insertion sort is a simple and intuitive sorting algorithm. Its working principle is to build an ordered sequence, scan the unordered data from back to front in the sorted sequence, find the corresponding position and insert it.
- Sorting idea:
- Assume sorting in ascending order
- 1. Start the forward comparison from the element with index 1. Once the previous element is greater than itself, let the previous elements move successively
- 2. Insert yourself into the current empty position until there are no comparable elements or the previous elements are smaller than yourself
- Code implementation:
int main() { // Array to be sorted int nums[5] = {3, 1, 2, 0, 3}; // 0. Calculate the length of the array to be sorted int len = sizeof(nums) / sizeof(nums[0]);
// 1. Start from the first element and take out all the elements used for comparison in turn for (int i = 1; i < len; i++) { // 2. Take out the elements for comparison int temp = nums[i]; int j = i; while(j > 0){ // 3. Judge whether the element is smaller than the previous element if(temp < nums[j - 1]){ // 4. Move the previous element backward one bit nums[j] = nums[j - 1]; }else{ break; } j--; } // 5. Insert the element into the empty position nums[j] = temp; }
}
int main() { // Array to be sorted int nums[5] = {3, 1, 2, 0, 3}; // 0. Calculate the length of the array to be sorted int len = sizeof(nums) / sizeof(nums[0]); // 1. Start from the first element and take out all the elements used for comparison in turn for (int i = 1; i < len; i++) { // 2. Traverse and take out the previous elements for comparison for(int j = i; j > 0; j--) { // 3. If the previous element is larger than the current element, the position will be exchanged if(nums[j-1] > nums[j]){ int temp = nums[j]; nums[j] = nums[j - 1]; nums[j - 1] = temp; }else{ break; } } } }
Shell Sort
- In 1959, Shell invented the first sorting algorithm to break through O(n2), which is an improved version of simple insertion sorting. It differs from insert sorting in that it preferentially compares elements that are far away. Hill sort is also called reduced incremental sort.
- Sorting idea:
- 1. Hill sorting can be understood as inserting an upgraded version of sorting. First divide the array to be sorted into several small arrays according to the specified step size
- 2. Use insert sort to sort small arrays, and then re merge several sorted small arrays into the original array
- 3. Repeat the above operations until the step size is 1, and then use the insertion sort to sort
- Code implementation:
int main() { // Array to be sorted int nums[5] = {3, 1, 2, 0, 3}; // 0. Calculate the length of the array to be sorted int len = sizeof(nums) / sizeof(nums[0]);
// 2. time step
int gap = len / 2;
do{
// 1. Take out all the elements used for comparison in turn from the first element
for (int i = gap; i < len; i++)
{
// 2. Traversal takes out the previous elements for comparison
int j = i;
while((j - gap) >= 0)
{
printf("%i > %i\n", nums[j - gap], nums[j]);
// 3. If the previous element is larger than the current element, the position is exchanged
if(nums[j - gap] > nums[j]){
int temp = nums[j];
nums[j] = nums[j - gap];
nums[j - gap] = temp;
}else{
break;
}
j–;
}
}
//After sorting each small array, recalculate the step size
gap = gap / 2;
}while(gap >= 1);
}
Brother Jiang tips:
For beginners, the sorting algorithm is not easy to learn too much at a time. Let's play with five first, and then continue to explain the other fiveHalf search
- Basic ideas
- In the ordered table, take the intermediate element as the comparison object. If the given value is equal to the number of intermediate elements to be searched, the search is successful; If the given value is less than the number of intermediate elements to be searched, continue to search in the left half of the intermediate element;
- If the given value is greater than the number of intermediate elements to be searched, the search continues in the right half of the intermediate element. Repeat the above search process until the search is successful or there are no data elements in the searched area, and the search fails
-
Implementation steps
-
In the ordered table, take the intermediate element as the comparison object. If the given value is equal to the number of intermediate elements to be searched, the search is successful;
-
If the given value is less than the number of intermediate elements to be searched, continue to search in the left half of the intermediate element;
-
If the given value is greater than the number of intermediate elements to be searched, the search continues in the right half of the intermediate element.
-
Continue to repeat the above search process until the search is successful, or there are no data elements in the searched area, and the search fails.
-
code implementation
int findKey(int values[], int length, int key) { // Defines the minimum index of a variable record int min = 0; // Define the maximum index of a variable record int max = length - 1; // Define a variable record intermediate index int mid = (min + max) * 0.5;
while (min <= max) { // If the value corresponding to mid is greater than key, max will become smaller if (values[mid] > key) { max = mid - 1; // If the value corresponding to mid is less than key, min will change }else if (values[mid] < key) { min = mid + 1; }else { return mid; } // After modifying min/max, recalculate the mid value mid = (min + max) * 0.5; } return -1;
}
Binary conversion (look-up table method)
- Realization idea:
- Store all possible characters in binary, octal, decimal and hexadecimal into the array
- Use the bitwise and operator and shift right to get the value of the corresponding position of the current base in turn
- Use the extracted value to query the output result of the current bit in the array
- Store the query result into a new array. When all bits are queried and stored, the value in the new array is the corresponding hexadecimal value
- code implementation
#include <stdio.h> void toBinary(int num) { total(num, 1, 1); } void toOct(int num) { total(num, 7, 3); } void toHex(int num) { total(num, 15, 4); }
void total(int num , int base, int offset)
{
// 1. Define tables for query results
char cs[] = {
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
// 2. Define an array to hold the results
char rs[32];
//Calculate the maximum angle mark position
int length = sizeof(rs)/sizeof(char);
int pos = length;//8while (num != 0) { int index = num & base; rs[--pos] = cs[index]; num = num >> offset; } for (int i = pos; i < length; i++) { printf("%c", rs[i]); } printf("\n");
}
int main()
{
toBinary(9);
return 0;
}
Two dimensional array
- The so-called two-dimensional array is a one-dimensional array, and each element is declared as a one-dimensional array to form a two-dimensional array It can be said that a two-dimensional array is a special one-dimensional array.
- Example:
- int a[2][3] = { {80,75,92}, {61,65,71}};
- It can be regarded as composed of one-dimensional array a[0] and one-dimensional array a[1], both of which contain three int type elements
Definition of two-dimensional array
- Format:
- Data type array name [number of one-dimensional arrays] [number of elements of one-dimensional arrays]
- "Number of one-dimensional arrays" indicates how many one-dimensional arrays are contained in the current two-dimensional array
- Where "number of elements of one-dimensional array" represents the number of elements of each one-dimensional array in the current previous two-dimensional array
Initialization of two-dimensional array
-
The initialization of two-dimensional numbers can be divided into two types:
- Initialize while defining
- Define before initialize
-
Initialize while defining
int a[2][3]={ {80,75,92}, {61,65,71}};
- Define before initialize
int a[2][3]; a[0][0] = 80; a[0][1] = 75; a[0][2] = 92; a[1][0] = 61; a[1][1] = 65; a[1][2] = 71;
- Assign values by line segments
int a[2][3]={ {80,75,92}, {61,65,71}};
- Continuous assignment by line
int a[2][3]={ 80,75,92,61,65,71};
- Other writing methods
- Fully initialized, the length of the first dimension can be omitted
int a[][3]={{1,2,3},{4,5,6}}; int a[][3]={1,2,3,4,5,6};
- Partial initialization, the length of the first dimension can be omitted
int a[][3]={{1},{4,5}}; int a[][3]={1,2,3,4};
- Note: some people may wonder why the number of rows can be omitted, but the number of columns cannot be omitted. Others may ask, can you specify only the number of rows, but omit the number of columns? In fact, this question is very simple. If we write this:
int a[2][] = {1, 2, 3, 4, 5, 6}; // Wrong writing
As we all know, the two-dimensional array will store the elements in the first row first. Because the number of columns is uncertain, that is, it is uncertain how many elements will be stored in the first row, there will be many situations here. 1 and 2 may belong to the first row, 1, 2, 3 and 4 may belong to the first row, or even 1, 2, 3, 4, 5 and 6 all belong to the first row
- Specifies the initialization of the element
int a[2][3]={[1][2]=10}; int a[2][3]={[1]={1,2,3}}
Application scenario of two-dimensional array
Traversal and storage of two-dimensional array
Traversal of two-dimensional array
- The two-dimensional array a[3][4] can be decomposed into three one-dimensional arrays, whose array names are:
- These three one-dimensional arrays have four elements. For example, the elements of one-dimensional array a[0] are a[0][0],a[0][1],a[0][2],a[0][3].
- Therefore, traversing a two-dimensional array is nothing more than taking out the one-dimensional array in the two-dimensional array, and then taking out the value of each element from the one-dimensional array
- Examples
char cs[2][3] = { {'a', 'b', 'c'}, {'d', 'e', 'f'} }; printf("%c", cs[0][0]);// The first [0] takes out the one-dimensional array, and the second [0] takes out the corresponding elements in the one-dimensional array
char cs[2][3] = { {'a', 'b', 'c'}, {'d', 'e', 'f'} }; for (int i = 0; i < 2; i++) { // Outer loop fetches one-dimensional array // i for (int j = 0; j < 3; j++) {// The inner loop takes out each element of a one-dimensional array printf("%c", cs[i][j]); } printf("\n"); }
Note: it must be emphasized that a [0], a [1] and a [2] cannot be used as subscript variables. They are array names, not simple subscript variables
Storage of two-dimensional array
- Like an array
- Allocate storage space to the array, starting with a large memory address
- Allocate space for array elements, starting from the one with a small memory address
- Store data in each element, starting with the high address
#include <stdio.h> int main() { char cs[2][3] = { {'a', 'b', 'c'}, {'d', 'e', 'f'} }; // cs == &cs == &cs[0] == &cs[0][0] printf("cs = %p\n", cs); // 0060FEAA printf("&cs = %p\n", &cs); // 0060FEAA printf("&cs[0] = %p\n", &cs[0]); // 0060FEAA printf("&cs[0][0] = %p\n", &cs[0][0]); // 0060FEAA return 0; }
Two dimensional arrays and functions
- pass by value
#include <stdio.h>
//Like a one bit array, it only depends on whether the formal parameter is a basic type or an array type
//If it is a basic type, modifying the formal parameter in the function will not affect the argument
void change(char ch){
ch = 'n';
}
int main()
{
char cs[2][3] = {
{'a', 'b', 'c'},
{'d', 'e', 'f'}
};
printf("cs[0][0] = %c\n", cs[0][0]); // a
change(cs[0][0]);
printf("cs[0][0] = %c\n", cs[0][0]); // a
return 0;
}
- Address delivery
#include <stdio.h>
//Like a one bit array, it only depends on whether the formal parameter is a basic type or an array type
//If it is an array type, modifying the formal parameter in the function will affect the argument
void change(char ch[]){
ch[0] = 'n';
}
int main()
{
char cs[2][3] = {
{'a', 'b', 'c'},
{'d', 'e', 'f'}
};
printf("cs[0][0] = %c\n", cs[0][0]); // a
change(cs[0]);
printf("cs[0][0] = %c\n", cs[0][0]); // n
return 0;
}
#include <stdio.h> // Like a one bit array, it only depends on whether the formal parameter is a basic type or an array type // If it is an array type, modifying the formal parameter in the function will affect the argument void change(char ch[][3]){ ch[0][0] = 'n'; } int main() { char cs[2][3] = { {'a', 'b', 'c'}, {'d', 'e', 'f'} }; printf("cs[0][0] = %c\n", cs[0][0]); // a change(cs); printf("cs[0][0] = %c\n", cs[0][0]); // n return 0; }
Notes on using two-dimensional array as function parameter
- Formal parameter error writing
void test(char cs[2][]) // Wrong writing { printf("I was executed\n"); }
void test(char cs[2][3]) / / correct writing
{
printf("I was executed \ n");
}void test(char cs[][3]) / / correct writing
{
printf("I was executed \ n");
}
- As a function parameter, a two-dimensional array cannot be obtained in the called function. It needs to be passed in through the parameter
void test(char cs[2][3]) { int row = sizeof(cs); // Output 4 or 8 printf("row = %zu\n", row); }
- The two-dimensional array is used as a function parameter, and the number of columns of the two-dimensional array can be calculated in the called function
void test(char cs[2][3]) { size_t col = sizeof(cs[0]); // Output 3 printf("col = %zd\n", col); }
task
-
The player controls the villain to move in different directions by entering W, s, a and d on the keyboard, where w represents moving upward, s represents moving downward, a represents moving left and d represents moving right. When the villain moves to the exit position, the player wins
-
Idea:
-
1. Define a two-dimensional array to store the map
###### #O # # ## # # # # ## # ######
- 2. Specify the direction of the map
- 3. Write program control direction
- When you enter w or W, the villain moves up x-1
- When entering S or S, the villain goes down x+1
- When you enter A or A, the villain turns left y-1
- When you enter D or D, the villain turns right y+1
- 4. Mobile villain
- Record the current position of the villain with variables
- 1) If the position where the villain will move is a wall, it cannot be moved
- 2) If the position where the villain will move is a road, it can move
- Record the current position of the villain with variables
- 5. Judge whether to walk out of the maze
Basic concepts of string
- A string is a sequence of characters enclosed in double quotes
- End with "\ 0" in memory, accounting for one more byte than the actual one
- End with "\ 0" in memory, accounting for one more byte than the actual one
Initialization of string
- There is no special string variable in C language. A character array is usually used to store a string.
- When a string is stored in an array, the terminator '\ 0' will be stored in the array as a sign of whether the string ends.
- With the '\ 0' flag, there is no need to judge the length of the string by the length of the character array
- initialization
char name[9] = "lnj"; //End with "\ 0" in memory, and the value of 0ASCII code is 0 char name1[9] = {'l','n','j','\0'}; char name2[9] = {'l','n','j',0}; // When the number of array elements is greater than the stored character content, the default value of the uninitialized part is 0, so the following can also be regarded as a string char name3[9] = {'l','n','j'};
- Wrong initialization method
//When omitting the number of elements, you cannot omit the end \ n // Incorrect writing, no \ 0 at the end, just an ordinary character array char name4[] = {'l','n','j'};
// " Cannot contain \ 0", Because \ 0 is the end flag of the string // \0 : End of string flag char name[] = "c\0ool"; printf("name = %s\n",name);
Output result: c
String output
- If a string is stored in the character array, the input and output of the character array will become simple and convenient.
- You don't have to use circular statements to input and output each character one by one
- You can use the printf function and the scanf function to output and input a string in a character array at one time
- The format string used is "% s", which means that the input and output are the output of a string
- output
- %The essence of s is to get the elements in the array one by one according to the address of the passed in name, and then output them until the \ 0 position is encountered
char chs[] = "lnj"; printf("%s\n", chs);
- Note:
- \Dirty reading caused by 0
char name[] = {'c', 'o', 'o', 'l' , '\0'}; char name2[] = {'l', 'n', 'j'}; printf("name2 = %s\n", name2); // Output result: lnjcool
- input
char ch[10]; scanf("%s",ch);
- Note:
- For a string array, if initialization assignment is not performed, the array length must be specified
- ch can store a string of 9 characters at most, and the position of the last character should be left for the end of the string to mark '\ 0'
- When using the scanf function to input a string, the string cannot contain spaces, otherwise spaces will be used as the end character of the string
Common methods of string
- C language provides a wealth of string processing functions, which can be roughly divided into string input, output, merge, modify, compare, convert, copy and search.
- Using these functions can greatly reduce the burden of programming.
- Use the string function of input and output, and include the header file "stdio.h" before use
- If other string functions are used, the header file "string.h" should be included
- String output function: puts
- Format: puts (character array name)
- Function: output the string in the character array to the display. The string is displayed on the screen.
- advantage:
- Auto wrap
- Can be any element address of the array
- shortcoming
- You cannot customize the output format, such as puts("Hello% I");
char ch[] = "lnj"; puts(ch); //Output result: lnj
- The put function can be completely replaced by the printf function. When you need to output in a certain format, you usually use the printf function
- String input function: gets
- Format: gets (character array name)
- Function: input a string from the keyboard of the standard input device.
char ch[30]; gets(ch); // Input: lnj puts(ch); // Output: lnj
- It can be seen that when the input string contains spaces, the output is still all strings. It indicates that the gets function does not end with a space as the sign of string input, but only with carriage return as the input. This is different from the scanf function.
- Note that gets can easily lead to array subscript out of bounds, which is an unsafe string operation function
- String length
- Using sizeof string length
- Because the string is stored character by character in memory, and one character occupies one byte, the length of the end character of the string is also the number of bytes of the memory unit occupied.
char name[] = "it666"; int size = sizeof(name);// Contains \ 0 printf("size = %d\n", size); //Output result: 6
- Using system function
- Format: strlen (character array name)
- Function: measure the actual length of the string (excluding the string end flag '\ 0') and return the value as a function.
char name[] = "it666"; size_t len = strlen(name2); printf("len = %lu\n", len); //Output result: 5
- Statistics with "\ 0" as string end condition
/** * Custom method to calculate the length of string * @param name String to calculate * @return Does not contain the length of \ 0 */ int myStrlen2(char str[]) { // 1. Define the length of the variable save string int length = 0; while (str[length] != '\0') { length++;//1 2 3 4 } return length; } /** * Custom method to calculate the length of string * @param name String to calculate * @param count Total length of string * @return Does not contain the length of \ 0 */ int myStrlen(char str[], int count) { // 1. Define the length of the variable save string int length = 0; // 2. Get all characters in the string through traversal and compare them one by one for (int i = 0; i < count; i++) { // 3. Judge whether it is the end of the string if (str[i] == '\0') { return length; } length++; } return length; }
- String concatenation function: strcat
- Format: strcat (character array name 1, character array name 2)
- Function: connect the string in character array 2 to the back of the string in character array 1, and delete the string flag "\ 0" after string 1. The return value of this function is the first address of character array 1.
char oldStr[100] = "welcome to"; char newStr[20] = " lnj"; strcat(oldStr, newStr); puts(oldStr); //Output: welcome to lnj“
- This program connects the character array of initialization assignment with the string of dynamic assignment. It should be noted that the character array 1 should be defined with sufficient length, otherwise it cannot load all the connected strings.
- String copy function: strcpy
-Format: strcpy (character array name 1, character array name 2) - function: copy the string in character array 2 to character array 1. The end of string flag "\ 0" is also copied. The character number name 2 can also be a string constant. This is equivalent to assigning a string to a character array.
char oldStr[100] = "welcome to"; char newStr[50] = " lnj"; strcpy(oldStr, newStr); puts(oldStr); // Output result: lnj / / the original data will be overwritten
- This function requires that the character array 1 should have sufficient length, otherwise it cannot load all the copied strings.
- String comparison function: strcmp
- Format: StrCmp (character array name 1, character array name 2)
- Function: compare the strings in two arrays in ASCII code order, and return the comparison result by the return value of the function.
- String 1 = string 2, return value = 0;
- String 1 > string 2, return value > 0;
- String 1 < string 2, return value < 0.
char oldStr[100] = "0"; char newStr[50] = "1"; printf("%d", strcmp(oldStr, newStr)); //Output result: - 1 char oldStr[100] = "1"; char newStr[50] = "1"; printf("%d", strcmp(oldStr, newStr)); //Output result: 0 char oldStr[100] = "1"; char newStr[50] = "0"; printf("%d", strcmp(oldStr, newStr)); //Output result: 1
practice
- Write a function char_contains(char str[],char key). If the string str contains the character key, the value 1 will be returned; otherwise, the value 0 will be returned
Basic concepts of string array
- String array actually defines an array to hold all strings
- 1. Store a string in one-dimensional character array, such as a name char name[20] = "nj"
- 2. If you want to store multiple strings, such as the names of all students in a class, you need a two-dimensional character array. char names[15][20] can store the names of 15 students (assuming that the names do not exceed 20 characters)
- If you want to store the names of students in two classes, you can use the three-dimensional character array char names[2][15][20]
##Initialization of string array
char names[2][10] = { {'l','n','j','\0'}, {'l','y','h','\0'} }; char names2[2][10] = { {"lnj"}, {"lyh"} }; char names3[2][10] = { "lnj", "lyh" };
Basic concepts of pointer
-
What is the address
- Address in life:
- Memory address:
- Address in life:
-
Address and data in memory unit are two completely different concepts
- The address is like the room number. According to this number, we can find the corresponding room
- Memory units are like rooms, which are dedicated to storing data
-
Variable address:
- The starting address of the memory unit allocated by the system to the variable
int num = 6; // Occupy 4 bytes //Then the address of the variable num is: 0ff06
char c = ‘a’; // Occupy 1 byte
//Then the address of variable c is 0ff05
What is a pointer
-
In the computer, all data are stored in memory cells, and each memory cell has a corresponding address. As long as this address is used, the data stored in the corresponding cell can be found
-
Since the required variable unit can be found through the address, we say that the address points to the variable unit. Visualized addresses are called "pointers"
-
The pointer (address) of the memory unit and the content of the memory unit are two different concepts.
What is a pointer variable
- In C language, it is allowed to use a variable to store the addresses of other variables. This kind of variable specially used to store the addresses of other variables is called pointer variable
- Example:
int age;// Define a common variable num = 10; int *pnAge; // Define a pointer variable pnAge = &age;
Defines the format of pointer variables
- The definition of pointer variable includes two contents:
- Pointer type description, that is to define the variable as a pointer variable;
- Pointer variable name;
- Example:
char ch = 'a'; char *p; // A pointer to a character variable p = &ch; int num = 666; int *q; // A pointer to an integer variable q = #
- Where, * indicates that this is a pointer variable
- The variable name is the defined pointer variable name
- The type specifier indicates the data type of the variable pointed to by this pointer variable
Initialization method of pointer variable
- There are two methods of initializing pointer variables: initializing while defining and initializing after defining
- Initialize while defining
int a = 5; int *p = &a;
- Define before initialize
int a = 5; int *p; p=&a;
- Initialize pointer to NULL
int *p=NULL; int *q=0;
- Illegal initialization:
- Pointer variables can only store addresses and cannot store other types
int *p; p = 250; // Wrong writing
- When assigning a value to a pointer variable, you cannot add "*" before the pointer variable
int *p; *p=&a; //Wrong writing
-
Note:
- Multiple pointer variables can point to the same address
- Multiple pointer variables can point to the same address
-
The direction of the pointer can be changed
int a = 5; int *p = &a; int b = 10; p = &b; // Modify pointer pointing
- The pointer is uninitialized. There is a garbage value in it. At this time, it is a wild pointer
- Wild pointers can cause the program to crash
- Wild pointer access you shouldn't access data
- Therefore, the pointer must be initialized to access the storage area it points to
Access the storage space pointed to by the pointer
- The address operator & is provided in C language to represent the address of variables. Its general form is:
- &Variable name;
- C language provides * to define pointer variables and access the memory storage space pointed to by pointer variables
- When defining a variable, * is a type specifier, indicating that the defined variable is a pointer variable
int *p=NULL; // Define pointer variables
- When a variable is not defined, * is an operator representing the storage space pointed to by the access pointer
int a = 5; int *p = &a; printf("a = %d", *p); // Access pointer variable
Pointer type
-
In the same compiler environment, the memory space occupied by a pointer variable is fixed.
-
Although all pointers occupy the same memory space in the same compiler, different types of variables occupy different bytes
- An int occupies 4 bytes, a char occupies 1 byte, and a double occupies 8 bytes;
- Now there is only one address. How can I know how many bytes of storage space to access backward from this address? Is it 4, 1 or 8.
- Therefore, the pointer variable needs the data type it points to to to tell it how many bytes of storage space to access
Secondary pointer
- If a pointer variable stores the address of another pointer variable, the pointer variable is called the pointer variable pointing to the pointer. Also known as "secondary pointer"
char c = 'a'; char *cp; cp = &c; char **cp2; cp2 = &cp; printf("c = %c", **cp2);
- Value rules of multi-level pointers
int ***m1; //Value * * * m1 int *****m2; //Value: **** m2
practice
- Define a function to exchange the values of two variables
- Write a function that returns the sum and difference of two numbers at the same time
##Concept and definition of array pointer
- Array element pointer
- A variable has an address. An array contains several elements. Each array element also has a corresponding address. Pointer variables can also save the address of array elements
- As long as a pointer variable holds the address of an array element, we call it an array element pointer
printf("%p %p", &(a[0]), a); //Output result: 0x1100, 0x1100
- Note: the array name a does not represent the entire array, but only the address of the first element of the array.
- “p=a;” The function of is to "assign the address of the first element of array a to the pointer variable p", rather than "assign the value of each element of array a to P"
Pointer to access array elements
int main (void) { int a[5] = {2, 4, 6, 8, 22}; int *p; // p = &(a[0]); p = a; printf("%d %d\n",a[0],*p); // Output result: 2, 2 }
- When the pointer points to an array element, the following operations are allowed:
- Add an integer (with + or + =), such as p+1
- Subtract an integer (with - or - =), such as p-1
- Self addition operation, such as P + +, + P
- Self subtraction operation, such as p –, -- p
- If the pointer variable p points to an element in the array, p+1 points to the next element in the same array and p-1 points to the previous element in the same array.
- Conclusion: there are two ways to access array elements:
- Subscript method, such as a[i] form
- Pointer method, * (p+i) form
- be careful:
- Although the array name is the first address of the array, the first address of the array saved by the array name cannot be changed
int x[10]; x++; //error int* p = x
Reproduced in: 130000 words C language from entry to proficiency nanny level tutorial 2021 Edition (recommended Collection)