"C language introduction guide" Collection Edition, is this enough for learning C language?

preface:

"C language introduction guide", the full text is divided into three parts, with a total of 34248 words. This is a collection version, which is suitable for beginners to get started with C language. Non beginners can also review the relevant knowledge points of C language through this article to strengthen their memory! Thirteen livers were finished in 7 days. The thief was tired. This note is also issued to review the C language!

  • References < C language course in Silicon Valley >
  • This article has been included in GitHub Open source warehouse[ Ye13 ], click to read the original text to jump to star!
  • GitHhub search: ye13

Development history

The birth of C language

1. Why C language was invented: the birth of C language is inseparable from the development of UNIX operating system. The original UNIX operating system used assembly

Written in, the core of UNIX operating system was rewritten in C language in 1973. Since then, C language has become the main language for writing operating system

  1. The influence of C language on other languages: many programming languages are deeply influenced by C language, such as C + + (originally an extension of C language), C #

Java, PHP, Javascript, Perl, LPC and C Shell of UNIX.

3. Those who master C language can learn other programming languages quickly. Many universities take C language as an introduction to computer teaching

language

4. Inventor

development history

Note: you need to know two important versions of C language 1 ANSI C (standard C), C89 2 C99

Characteristics of C language

1. Code level cross platform: due to the existence of standards, almost the same C code can be used for a variety of operating systems, such as Windows, DOS and UNIX

wait; It is also applicable to a variety of models.

2. Allow direct access to the physical address and operate the hardware: since C language allows direct access to the physical address, you can operate the hardware directly,

Therefore, it has the functions of both high-level language and low-level language. C language can be used to write system software (such as operating system, database,

Antivirus software, firewall, driver, server program)

3. C language is a procedural language with structured programming, variable scope and recursive function

4. C language transfer parameters can be pass by value or a pointer passed by value

5. In C language, there is no object, and different variable types can be combined with struct ures

6. The preprocessor generates high-quality object code and high program execution efficiency

Getting started HelloWorld

1. The VC + + start button is configured as follows

1. Click the button

2. Click Customize

3. Add command

4. Click Z below

5. Click the confirm button, and the effect is as follows:

Create a project and let it output hello world!

1. Create the project as shown in the figure

2. In test01 C write the following code

// This is a main function, which is the entry of program execution	

#include <stdio. h> / / import header file
void main(){
	// printf is a function that can only be used after importing header files
	// printf is in < stdio h> The next file needs to be imported
	printf("hello world!");

	getchar();// Let the window stay
}

3. Click Run, and the results are shown in the figure

Program operation mechanism

Document description

1. Editor: we wrote XX C file is the source code

2. Compile: put this XX C file to target file (xx.obj)

3. Link: generate the target file (. obj) + library file into an executable file (xx.exe)

4. Executable (xx.exe)

Compilation and linking are implemented at the bottom of the computer

C program operation mechanism - diagram

Compile cl.exe and connect link Exe is in the bin directory of vs2010 software file directory

The target file (xx.obj) and executable file (xx.exe) can be found in the computer

Basic knowledge

Escape character

6 most commonly used escape characters

\n Line feed (LF) moves the current position to the beginning of the next line 010
\r Press enter (CR) to move the current position to the beginning of the line 013
\t Horizontal tabulation (HT) (skip to next TAB position) 009
\ \ Represents a backslash character '\' 092
\' Represents a single quotation mark (apostrophe) character 039
\" Represents a double quote character 034

notes

1. Single line note

// Annotated content

2. Multiline comment

/*
Annotated content
*/

identifier

**C identifier: * * the name used to identify a variable, function, or any other user-defined item.

What is an identifier?

An identifier is underlined with the letters A-Z or A-Z_ Start with zero or more letters, underscores, and numbers (0-9).

Punctuation characters such as @, $and% are not allowed in the C identifier. C is a case sensitive programming language. Therefore, in C, manpower and manpower are two different identifiers. Several valid identifiers are listed below:

mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

Naming rules and specifications of identifiers

1. Similar case sensitive identifiers, int, x, x, shall not appear in the program; Variables X and X are easily confused

2. All macro definitions, enumeration constants and constants (read-only variables) are named in uppercase letters, and words are separated by underscores,

For example:

const double TAX_RATE = 0.08;//TAX_RATE read only variable #define FILE_PATH "/usr/tmp"

3. Don't forget to initialize variables. When defining variables, the compiler does not necessarily empty this memory. Its value may be invalid data. When running the program, it will exit abnormally

4. Variable name and function name: when composed of multiple words, the first word is lowercase, and the second word begins with the first capital of each word: xxxYyyZzz [hump method, small hump, such as short stuAge = 20;]

keyword

The following table lists the reserved words in C. These reserved words cannot be used as constant names, variable names, or other identifier names.

keyword explain
auto Declare automatic variables
break Jump out of current loop
case Switch statement branch
char Declare the return value type of a character variable or function
const Define constants. If a variable is modified by const, its value can no longer be changed
continue End the current cycle and start the next cycle
default "Other" branch in switch statement
do Loop body of a loop statement
double Declares the return value type of a double precision floating-point variable or function
else Conditional statement negative branch (used with if)
enum Declare enumeration type
extern Declared variables or functions are defined in other documents or elsewhere in this document
float Declares the return value type of a floating-point variable or function
for A circular statement
goto Unconditional jump statement
if Conditional statement
int Declare an integer variable or function
long Declare the return value type of a long integer variable or function
register Declare register variable
return Subroutine return statement (with or without parameters)
short Declare a short integer variable or function
signed Declare a variable or function of signed type
sizeof Calculate the data type or variable length (i.e. the number of bytes)
static Declare static variables
struct Declare structure type
switch For switch statements
typedef Used to alias data types
unsigned Declare an unsigned variable or function
union Declare common body type
void The declared function has no return value or parameter, and the declared function has no type pointer
volatile Description variables can be changed implicitly during program execution
while Loop condition of loop statement

variable

The variable is equivalent to the representation of a data storage space in memory. You can regard the variable as the house number of a room. Through the house number, we can find the room, and through the variable name, we can access the variable (value).

Three elements of variables: (variable name + value + data type)

Variable use cases

# include <stdio.h>
void main(){
	
	int num = 1 ; //integer 
	double score = 2.3; //decimal 
	char gender = 'A';//character 
	char name[] = "Shang Silicon Valley";//character string
	/**
	If the output is an integer -- >% d
	If the output is decimal -- >% F, if you want to keep it to 2 decimal places -- >%. 2F 
	If the output is a character char -- >% C
	If the output is a string -- >% s
	*/
	printf("num=%d score=%.2f gender=%c name=%s",num,score,gender,name);
	getchar();// Let the window stay
}

Precautions for variable use

  1. Variable represents a storage area in memory (different data types occupy different sizes of space)

  2. This area has its own name and type

  3. Variables must be declared before use

  4. The data in this area can change continuously within the same type range

  5. Variables cannot have the same name within the same scope

  6. Code demonstration

data type

In C language, data type refers to a wide range of systems used to declare different types of variables or functions. The type of variable determines the space occupied by variable storage and how to interpret the stored bit pattern.

The types in C can be divided into the following types:

be careful:

1. In c, there is no string type, but a string array is used to represent the string

2. On different systems, the byte length of some data types is different: for example, int, the number of bytes may be 2 or 4

Integer type

The following table lists details about the storage size and value range of standard integer types:

type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int / signed int 2 or 4 bytes -32768 to 32767 or - 2147483648 to 2147483647
unsigned int 2 or 4 bytes 0 to 65535 or 0 to 4294967295
short 2 bytes -32768 to 32767
unsigned short 2 bytes 0 to 65535
long 4 bytes -2147483648 to 2147483647
unsigned long 4 bytes 0 to 4294967295

Explanation: signed int is the type that does not distinguish between positive and negative. Precision > int precision

Use details of integer

The difference of integer bytes in different operating systems and different bit systems

1. The size of various types of storage is related to the operating system, system bits and compiler *. At present, the general 64 bit system is mainly used

In practice, c program usually runs under linux/unix operating system

2. The integer type of C language is divided into signed and unsigned. The default is signed

3. Integers in C programs are often declared as int types. long long is used unless it is not enough to represent large numbers

4. Bit: the smallest unit of storage in a computer. Byte: the basic storage unit in a computer.

1byte = 8bit [binary, to be more specific, a simple example is short 3 and int 3]

Sketch Map

short 3 occupies 2 bytes in memory

int 3 occupies 4 bytes in memory

float

The following table lists details about the storage size, value range, and precision of standard floating point types:

type Storage size Value range accuracy
float single precision 4 bytes 1.2E-38 to 3.4E+38 6 decimal places
Double double 8 bytes 2.3E-308 to 1.7E+308 15 decimal places

Floating point numbers are approximations

Detailed case:

# include <stdio.h>
void main(){
	float num1 = 1.1; //"Initialization": truncation from "double" to "float"
	//float num1 = 1.1f;// 1.1f is float
	//double num3 = 1.3; // ok
	//double d4 = 5.12
	double num5 = .512;// Equivalent to 0.512
	double num6 = 5.12e2;// Equivalent to the quadratic power of 5.12 * (10)
	double num6 = 5.12e-2;// Equivalent to 5.12 * (negative quadratic of 10)
	getchar();
}

Character type char

The character type can represent a single character. The character type is char. Char is a byte (which can store letters or numbers). Multiple characters are called strings

char array is used in C language. Array is not the basic data type, but the construction type [we will explain in detail about array later.]

Simple case:

# include <stdio.h>
void main(){
	char c1 = 'A'; 
	char c2 = '0';
	char c3 = '\t';
	printf("c1=%c c3=%c c2=%c", c1, c3, c2); //%c means output in the form of characters 
	getchar(); 
}

result:

(1) Character constants are single characters enclosed in single quotation marks ('). For example: char c1 = 'a';

char c3 = '9';

(2) The escape character '\' is also allowed in C to convert subsequent characters into special character constants. For example: char c3 = '\ n'; / / ' \N 'means change

Line character

(3) In C, the essence of char is an integer. When outputting, char is the character corresponding to ASCII code.

(4) . you can directly assign an integer to char, and then output it according to the corresponding ASCII characters [97]

(5) char type can be operated, which is equivalent to an integer, because it all corresponds to Unicode code

(6) . case demonstration

# include <stdio.h>
void main(){
	char c1 = 'a'; 
	char c2 = 'b';
	char c3 = 97;//At this time, when we output with% c, we will install the 97 corresponding character output corresponding to the ASCII coding table (understand the character < = = > number correspondence)
	int num = c1+10; // =97+10 = 107
	printf("c1=%c c2=%c c3=%c", c1, c2, c3); //%c means output in the form of characters 
	

	// be careful:
	// 1. The vs2010 editor is c89
	// 2. The definition of the variable is required before the statement
	printf("num=%d",num); //'num': undeclared identifier

	getchar(); 
}

Discussion on the essence of character types:

When the character type is stored in the computer, the code value (integer) corresponding to the character needs to be found

Storage: character 'a' -- > code value (97) - > binary (1100001) - > storage ()

Reading: binary (1100001) - > code value (97) - > character 'a' -- > reading (display)

Boolean type

1. C language standard (C89) does not define boolean type, so when C language judges true or false, 0 is false and non-0 is true [case]

2. But this approach is not intuitive, so we can use the macro definition of C language.

3. The C language standard (C99) provides_ Bool type_ Bool is still an integer type, but unlike general integers_ Bool variable can only be assigned 0 or 1,

Values other than 0 will be stored as 1. C99 also provides a header file < stdpool h> Bool representative is defined_ Bool, true for 1, false for

Table 0. Just import stdpool h. You can easily operate Boolean types, such as bool flag = false

  • Conditional control statement; if

  • Loop control statement; while …

# include <stdio.h>
void main(){
	int isPass = -1; 
	if(isPass) { // 0 means false, non-0 means true
		printf("Pass the exam");
	}
}

Macro definition case:

# include <stdio.h>

// Macro definition
#define BOOL int 
#define TURE 1
#define FALSE 0

void main(){
	BOOL isOK = TURE; // Equivalent to int isOK = 1
	if(isOK){
		printf("ok");
	}
	getchar();	
}

Basic data type conversion

Automatic type conversion

When C program is performing assignment or operation, the type with low precision is automatically converted to the data type with high precision

Data type automatic conversion table rules

Demo 1:

Char - > int - > double (conversion from low precision to high precision)

# include <stdio.h>
void main(){
	char c1 = 'a'; //ok
	int num1 = c1;  // ok
	double d1 = num1; //ok
	printf("d1= %.2f",d1);
	getchar();
}

Demo 2:

Different types of addition: the phase with low precision is converted to the phase with high precision and then added (short is converted to int and then added to int)

# include <stdio.h>
void main(){
	short s1 = 10;
	int num2 = 20; 
	int num3 = s1 + num2;	//ok
	printf("num3 = %d",num3);
	getchar();
}


Demo 3:

The type with high precision is converted to the type with low precision (double is assigned to float), resulting in precision loss

# include <stdio.h>
void main(){
	float f1 = 1.1f; //ok 
	double d2 = 4.58667435; 
	f1 = d2; // Loss of accuracy (double - > float) 
	printf("f1=%.8f", f1); // Expectation: 4.58667435 
	getchar(); 
}

Operation results:

Cast type

Convert high-precision data types to low-precision data types. The cast character () should be added when using, but it may cause precision reduction or overflow, so pay special attention.

# include <stdio.h>
void main(){
	double d1 = 1.934; 
	int num = (int)d1; //Note here that instead of rounding, the decimal part is truncated directly
	//printf("num = %d",num);
    
    
    //Cast is only valid for the most recent number. If you want to cast for more expressions, use () 
	int num2 = (int)3.5 * 10 + 6 * 1.5; // 	3 * 10 + 6 * 1.5 = 30 + 9.0 = 39.0 
	int num3 = (int)(3.5 * 10 + 6 * 1.5); // 35.0 + 9.0 = 44.0 -> int = 44
    
	getchar();
}	

Practice case:

# include <stdio.h>
void main(){
	char c = 'a'; 
	int i = 5; 
	float d = .314F; 
	double d2 = 1.0; 
	//double result = c+i+d; 
	// float -> double 
	char result = c+i+d+d2; // Hint// Warning double - > char 
	getchar();
}

Summary:

  • When the precision of data is high - > the precision is low, it is necessary to use forced conversion
  • The strong conversion symbol is only valid for the most recent operand, and parentheses are often used to raise the priority

Keyboard input statement

In programming, if you need to receive the data input by the user, you can use the keyboard to input statements to obtain.

demonstration:

# include <stdio.h>
void main() {
	char name[10] = "";
	int age = 0;
	double sal = 0.0;
	char gender = ' ';
	
	printf("Please enter user name:");
	scanf("%s",name);

	printf("Please enter age:");
	scanf("%d",&age); // Because we store the input to the address pointed to by the age variable, we need to add&
	
	printf("Please enter salary:");
	scanf("%lf",&sal); // lf%: accept double type

	printf("Please enter gender( m/f): ");
	scanf("%c",&gender); //Carriage return is accepted by gender, so it is empty
	scanf("%c",&gender);// This place is waiting for user input

	printf("\n name %s age %d sal %.2f  gender %c",name,age,sal,gender);
	getchar();//Received a carriage return
	getchar();//This getchar() will pause the console
}

Introduction to ASCII code (understand)

1. Inside the computer, all data is represented in binary. Each binary bit has two states of 0 and 1, so there are 8 binary bits

Bits can be combined into 256 States, which is called a byte. A byte can be used to represent = = 256 (the 8th power of 2) = = different states,

Each state corresponds to one symbol, that is, 256 symbols, from 0000000 to 11111111.

2. ASCII code: in the 1960s, the United States formulated a set of character codes, which made unified provisions on the relationship between English characters and binary bits.

This is called ASCII code. The ASCII code specifies a total of 127 characters. For example, the SPACE "SPACE" is 32 (binary 00100000),

The capital letter A is 65 (binary 01000001). These 128 symbols (including 32 control symbols that cannot be printed) only occupy one

The last 7 bits of a byte and the first 1 bit are uniformly specified as 0.

3. Look at a complete ASCII code table

ASCII code table reference address: https://tool.oschina.net/commons?type=4

C language standard library - Reference Manual

Introduction: C standard library is a set of C built-in functions, constants and header files, such as < stdio h>,<stdlib. h>,<math. h> , wait. This mark

The standard library can be used as a reference manual for C programmers.

Reference address of standard library: https://www.runoob.com/cprogramming/c-data-types.html

The above content exercises after class

Topic 1:

#include <stdio.h>
void main(){

	/*requirement: 

	a,Use variables to store name, age, grades, gender and hobbies 

	b,Add appropriate comments 

	c,Add escape character*/ 

	//Analysis: use different variables to save the corresponding data 

	char name[10] = "Zhang San"; //Character array, storing string 
	short age = 23; 
	float score = 78.5f; 
	char gender = 'M'; //C language course for college students in Silicon Valley 
	char hobby[20] = "Basketball, football"; 
	printf("full name\t Age\t achievement\t Gender \t hobby\n%s\t%d\t%.2f\t%c\t%s", name,age,score,gender,hobby); 
	getchar(); 
}

Topic 2:

#include <stdio.h>
void main(){

	int number1; 
	int number2; 
	int number3; 
	int number4 = 50; 
	int number5; 
	number1 = 10; 
	number2 = 20; 
	number3 = number1 + number2; //30 
	printf("\nNumber3 = %d" , number3);//30 
	number5 = number4 - number3;//20 
	printf("\nNumber5 = %d" , number5);//20 
	getchar(); 

}

4. Title:

#include <stdio.h> 

	void main() { 

		// ************************************* 
		// Little calculator 
		//************************************* 
		//10 + 5 =15 
		//10 - 5 = 5 
		//10 * 5 = 50 
		//10 / 5 = 2 
		//analysis 
		//1. Define two int s 
		//2. Calculate according to the requirements and get different results. You can redefine the variables 
		int n1 = 10; 
		int n2 = 5; 
		int sum = n1 + n2; 
		int sub = n1 - n2; 
		int mul = n1 * n2; 
		int div = n1 / n2; 
		int mod = n1 % n2;
		int num = 11; 
		//output 
		printf("\n*************************************"); 
		printf("\n 	Little calculator"); 
		printf("\n*************************************"); 
		printf("\n %d + %d = %d", n1, n2, sum); 
		printf("\n %d - %d = %d", n1, n2, sub); 
		printf("\n %d * %d = %d", n1, n2, mul); 
		printf("\n %d / %d = %d", n1, n2, div); 
		printf("\n %d model %d = %d", n1, n2, mod); 
		//Determine whether num is even or cardinal 
		//The branch structure to be learned later in if else will be explained in detail later 
		if(num % 2 == 0) { //even numbers 
			printf("\n%d It's an even number", num); 

		} else { 
			printf("\n%d It's an odd number", num); 
		}
		getchar(); 
}

constant

integer constant

Integer constants can be decimal, octal, or hexadecimal constants. Prefix specifies the base: 0X or 0X indicates hexadecimal, 0 indicates octal, and without prefix, it indicates decimal by default. Integer constants can also have a suffix. The suffix is a combination of U and L. U represents unsigned integer and l represents long integer. The suffix can be uppercase or lowercase, and the order of U and l is arbitrary

Examples of integer constants:

85 /* decimal system */

0213 /* octal number system */

0x4b /* hexadecimal */ Octal and hexadecimal are explained later

30 /* integer */

30u /* Unsigned integer */

30l /* long integer */

30ul /* Unsigned long integer */

Floating-Point Literals

Floating point constants are composed of integer part, decimal point, decimal part and exponential part. You can use decimal or exponential forms to represent floating-point constants

3.14159; //double constant
314159E-5; // Scientific counting method
3.1f; //float constant

character constants

Character constants are enclosed in single quotes. For example, 'x' can be stored in a variable of type char. A character constant can be an ordinary character (such as' x ') or an escape sequence (such as' \ t')

'X' 
'Y' 
'A'
'b'
'1' 
'\t

string constant

"hello, world" 
"Beijing"
"hello \
world"

Definition of constants

1. Use #define preprocessor
2. Use const keyword

#define preprocessor

#define constant name constant value
#include <stdio.h>
#define PI 3.14 / / define constant PI constant value 3.14 

int  main() { 
		//Is PI = 3.1415 OK It cannot be modified because PI is a constant 
		//Can I modify the PI value? 
		//PI = 3.1415; // Tip = lvalue must be modifiable 
		double area; 
		double r = 1.2;//radius 
		area = PI * r * r; 
		printf("area=%.2f",area);
		getchar();
		return 0;
}

const

You can use const to declare constants of the specified type

const Data type constant name = constant value; //That is, a statement
#include <stdio.h>
//1. const is a keyword. If it is well specified, it means that a constant is defined later 
//2. PI is a constant name, that is, it is a constant, and the constant value is 3.14 
//3. PI cannot be modified because it is a constant 
//4. const needs a semicolon when defining constants
const double PI = 3.14;  
int main() {
	//Is PI = 3.1415 OK?
	double area; 
	double r = 1.2;
	area = PI * r * r;
	printf("the measure of area : %.2f", area);
	getchar();
	return 0;
}

The difference between const and #define

1. const defines a constant with a type, and define without a type

2. const works when compiling and running, while define works in the preprocessing stage of compilation

3. define is a simple replacement without type checking. Simple string substitution can lead to boundary effects

4. const constant can be debugged, but define cannot be debugged. It is mainly because it has been replaced in the precompile stage and is not available during debugging

Yes

5. const cannot be redefined. You cannot define two symbols that are the same. Define cancels the definition of a symbol through undef and redefines it

6. Define can be used with #ifdef, #ifndef, #endif to make the code more flexible. For example, we can start it through #define

Or turn off debugging information.

Case of difference 6:

#include <stdio.h> 
#define DEBUG 
	void main() { 
	#ifdef DEBUG / / if debug is defined 
			printf("ok, debug information"); 
	#endif 
	#ifndef DEBUG / / if debug is not defined 
			printf("hello, Additional information"); 
	#endif 
			getchar(); 
}

operator

Operator is a special symbol used to represent the operation, assignment and comparison of data.

  1. Arithmetic operators (+,, *, /,%)
  2. Assignment operator (= + = - =...)
  3. Relational operators (comparison operators) (such as > > = < < = = = and so on)
  4. Logical operator (& & logical and | logical or! Logical not)
  5. Bitwise operators (& bitwise and | bitwise OR ^ bitwise XOR ~ bitwise inversion, etc.)
  6. Ternary operator (expression 1: expression 2)

Arithmetic operator

Arithmetic operators operate on numeric variables, which are used very much in C programs.

Case demonstration:

#include <stdio.h> 

void main() { 
	//Process 10 / 4 = 2.5 = = intercept integer = = > 2 = > 2.00000 
	double d1 = 10 / 4; // 
	double d2 = 10.0 / 4; //If you want to keep decimals, the number participating in the operation must have floating point numbers 
	//Let's give you a formula for taking the mold 
	// a % b = a - a / b * b 
	int res1 = 10 % 3; // Find the remainder of 10 / 3 1 
	int res2 = -10 % 3; // = -10 - (-10) / 3 * 3 = -10- (-3) * 3 = -10 + 9 = -1 
	int res3 = 10 % -3; // 10 - 10 / (-3) * (-3) = 10 - 9 = 1 
	int res4 = -10 % -3; // ? -1 
	//++Use of 
	int i = 10;
	int j = i++; // The operation rule equivalence is int j = I; i = i + 1; ==>  j = 10, i=11 
	int k = ++i; // Operation rule equivalence I = I + 1; int k = i; ===>  i=12, k =12 
	printf("\n i=%d j=%d", i, j); //i=12 
	j=10; 
	printf("\n i=%d k=%d", i ,k );// i = 12 k = 12 
	printf("\nd1=%f d2=%f res1=%d res2=%d res3=%d res4=%d", d1, d2, res1, res2, res3, res4); 
	//++Or -- it can also be used independently, which is equivalent to self increment 
	//K + + is equivalent to k = k +1 
	//++K is equivalent to k= k +1 
	//If you use + + k and k + + independently, they are completely equivalent 
	k++; // k = 13 
	++k;// k = 14 
	printf("\nk=%d", k); //k = 14 
	getchar(); 
}

Details

  1. For the division sign "/", there is a difference between integer division and decimal division: when dividing between integers, only the integer part is retained and the decimal part is discarded. For example: int x= 10/3, the result is
  2. When taking a module of a number, it can be equivalent to a%b=a-a/b*b, so we can see an essential operation of taking a module.
  3. When autoincrement is used as an independent language, whether it is + + i; Or i + +; All the same, equivalent
  4. When autoincrement is used as an expression, j = ++i is equivalent to i = i + 1; j = i;
  5. When autoincrement is used as an expression, j = i + + is equivalent to j = i; i = i + 1;

Relational operator

1. The result of a relational operator is either true (not 0) or false (0)
2. Relational expressions are often used in the conditions of if structures or loop structures

Demonstration case:

Details

1. The result of a relational operator is either true (non-0 means 1 by default) or false (0 means)

2. The expression composed of relational operators is called relational expression. a > b

3. The comparison operator "= =" (relational operator) cannot be mistakenly written as "=" (assignment)

Logical operator

It is used to connect multiple conditions (generally speaking, it is a relational expression), and the final result is either true (non-zero)
Indicates), or false (0 indicates).

List of logical operators

The following table shows all the logical operators supported by the C language. Suppose variable A has A value of 1 and variable B has A value of 0

Demonstration case:

1. & & use of

# include <stdio.h>
void main() {
	double score = 70;//achievement
	if(score>=60 && score<=80){
		printf("ok1");
	} else {
		printf("ok2");
	}
	getchar();
}
# include <stdio.h>
void main() {
	int a = 10, b = 99;
	if(a < 20 && b++>100) { 
		printf("ok100");
	}
	printf("b=%d\n", b); //b=100
	getchar();
}

3. Use of

# include <stdio.h>
void main() {
	int a = 10, b = 99;
	if(a < 5 || b++>100) {
		printf("ok100");
	}
	printf("b=%d\n", b);
	getchar();
}

Assignment Operators

The assignment operator is to assign the value =, after an operation, to the specified variable.

Characteristics of assignment operator

1. The operation order is from right to left

2. The left side of the assignment operator can only be variables, and the right side can be variables, expressions and constant values

3. The compound assignment operator is equivalent to the following effect

For example: a+=3; Equivalent to a=a+3;

Bitwise Operators

Bit operators act on bits and perform operations bit by bit.

ternary operator

Basic syntax:

Conditional expression? Expression 1: expression 2;

1) If the conditional expression is non-0 (true), the result of the operation is expression 1;

2) If the conditional expression is 0 (false), the result of the operation is expression 2;

3) . pithy formula: Master Yideng = Master Yizhen

Demonstration case:

# include <stdio.h>
void main() {
	int a = 10;
	int b = 99;
	int res = a > b ? a++ : b--;
	printf("res=%d",res); ///res =99
	getchar();
}

Demo 2: find the maximum value between three numbers

int a = 10;
int b = 100;
int c = 199;
int max = a > b ? a : b
int max2 = max>c ? max : c // max2 is the maximum of the three numbers

Operator priority

List of operator priority and Associativity

Table address: https://blog.csdn.net/u013630349/article/details/47444939

The following rules can be summarized in the above table:

  1. Only three directions of combination are from right to left, and the rest are from left to right.
  2. Among all binocular operators, only the combination direction of value operators is from right to left.
  3. The other two operators combined from right to left are also easy to remember because they are special: one is monocular operator and the other is ternary operator.
  4. There is only one ternary operator in C language.
  5. The comma operator has the lowest priority, remember.
  6. Also remember that for priority: arithmetic operators > relational operators > logical operators > assignment operators > comma operators. "Logical non!" in logical operator except.
  7. You don't need to memorize it deliberately, but to be proficient in it in use!

Some error prone priority issues

In the above table, if several operators with the same priority of 1 appear at the same time, how to determine the priority of the expression? This is where many beginners are confused. The following table summarizes these error prone situations:

Priority issues expression Often mistaken results Actual results
. takes precedence over * (- > operator is used to eliminate this problem) *p.f The field F of the object referred to by p is equivalent to: (* p) f Take the f offset of p as the pointer, and then dereference it, which is equivalent to: * (p.f)
[] higher than* int *ap[] ap is a pointer to an int array, equivalent to: int (*ap) [] ap is an array whose element is an int pointer, which is equivalent to: int *(ap [])
Function () is higher than* int *fp() fp is a function pointer. The indicated function returns int, which is equivalent to int (*fp)() FP is a function that returns int *, which is equivalent to int * (fp())
==And= Above bit operation (val & mask != 0) (val &mask) != 0 val & (mask != 0)
==And= Higher than assignor c = getchar() != EOF (c = getchar()) != EOF c = (getchar() != EOF)
Arithmetic operator is higher than displacement operator msb << 4 + lsb (msb << 4) + lsb msb << (4 + lsb)
The comma operator has the lowest priority among all operators i = 1, 2 i = (1,2) (i = 1), 2

For these error prone situations, I hope readers can make good debugging on the compiler, which will make a deeper impression. We must debug more. It's hard to improve the level just by looking at the code. Debugging code is the longest level.

Operator summary case:

# include <stdio.h>
void main() {
	//Define the number of seconds to save the variable, and print out xx hours, xx minutes and xx seconds 
	//thinking 
	//1. Define the number of second s to save the variable 
	//2. Define the saving hour s of variables 
	//3. Define the variable storage minutes min 
	//4. Define the variable and save the remaining description leftSecond 
	int second = 894567;
	int hour = second / 3600 ; // An hour has 3600 seconds 
	int min = second % 3600 / 60; // 
	int leftSecond = second % 60; 
	printf("%d Second combination%d hour%d minute%d second", second, hour, min, leftSecond); 
	getchar(); 

}

Binary sum bit operation

(1) Convert other hexadecimal to hexadecimal

Binary to decimal example

0123 = 3 * 8 ^ 0 + 2 * 8 ^ 1 + 1 * 8^2 = 3+16+64=83

Example of hexadecimal to decimal conversion

0x34A = 10 * 16 ^ 0 + 4 * 16 ^1 + 3 * 16^2 = 10+64+768=842

(2) , decimal to other decimal

Convert decimal to binary

==Rule: = = divide the number by 2 until the quotient is 0, and then reverse the remainder obtained in each step
Binary expected.
Case: Please convert 56 to binary

56 => 111000

As shown in the figure:

Convert decimal to octal

Rule: divide the number by 8 until the quotient is 0, and then reverse the remainder obtained in each step
Expected octal. Case: Please convert 156 to octal

156 =>234

The calculation process is shown in the figure:

Convert decimal to hexadecimal

Rule: divide the number by 16 until the quotient is 0, and then reverse the remainder obtained in each step
Corresponding hexadecimal.
Case: Please convert 356 to hexadecimal

356 => 164

The calculation process is shown in the figure:

(3) Convert binary to octal and hexadecimal

Binary to octal

Rule: starting from the low order, convert the binary number into the corresponding octal number every three bits.
Case: Please convert 11 010 101 to octal

11010101 => 0 3 2 5

Convert binary to hexadecimal

Rule: starting from the low order, convert the binary number into the corresponding hexadecimal number every four bits.
Case: Please convert 11010101 to hexadecimal

11010101 = 0xD5

(4) , octal, hexadecimal to binary

Octal to binary

Rule: convert every 1 bit of octal number into a corresponding 3-bit binary number.
Case: Please convert 0237 to binary

0237 = 10011111

Convert hex to binary

Rule: convert every 1 bit of hexadecimal number into a corresponding 4-bit binary number.
Case: Please convert 0x23B to binary

B=11=> 1011
0x23B = 1000111011

Thinking about bit operation

Look at the following code snippet. What is the result of answering a, B, C, D and E?

# include <stdio.h>
void main() {
	int a=1>>2; // 1 shifts 2 bits to the right, which also involves binary primary code, inverse code and complement code
	int b=-1>>2;
	int c=1<<2;//
	int d=-1<<2;//
	//a. What is the result of B, C, D, e
	printf("a=%d b=%d c=%d d=%d ",a,b,c,d);
	getchar();
}

Please answer that in C, the result of the following expression operation is: (bit operation)

~2=? // Bitwise inversion
2&3=?
2|3=?
~-5=?
13&7=?
5|4=?
-3^3=?

Description in binary reoperation

Binary is the carry system of every 2 carry, and 0 and 1 are the basic operators.
Modern electronic computer technology uses binary because it only uses two digital symbols: 0 and 1
, very simple and convenient, easy to implement electronically. The information processed inside the computer is binary
System number. Binary numbers represent any number with two numbers 0 and 1 and their combinations. enter
The bit rule is "every 2 into 1". The number 1 represents different values in different bits, in the order from right to left
The values are doubled

Original code, inverse code and complement code

  1. The highest bit of binary is the sign bit: 0 is a positive number and 1 is a negative number
  2. The original code, inverse code and complement of positive numbers are the same (three codes in one)
  3. Inverse code of negative number = the sign bit of its original code remains unchanged, and other bits are reversed (0 - > 1,1 - > 0)
  4. Complement of negative number = its inverse code + 1
  5. The inverse and complement of 0 are all 0
  6. In computer operation, it is calculated in the way of complement

Bitwise Operators

Introduction to median operators

Their operation rules are:

Bitwise AND &: both bits are 1, the result is 1, otherwise it is 0
Bitwise or |: one of the two bits is 1, and the result is 1, otherwise it is 0
Bitwise XOR ^: two bits, one is 0, the other is 1, the result is 1, otherwise it is 0
Reverse by bit: 0 - > 1, 1 - > 0
For example: ~ 2 =~- 5=? 2&-3=? 2|3=? 2^3=?

~2=?

Find the complement of - 3:

Control structure of program

In the program, the process control of program operation determines how the program is executed, which we must master. There are three main process control statements.

Sequential structure

The program is executed line by line from top to bottom without any judgment and jump

Select structure

Introduction to branch control if else: single branch, double branch and multi branch

Single branch

Basic syntax:

if(Conditional expression){
	Execute code block;
}

Note: when the conditional expression is true (not 0), the code of {} will be executed. When it returns false (0), the code of {} will not be executed

Flowchart demonstration:

Double branch

Basic syntax:

if(Conditional expression){
	Execute code block 1; 
}
else{
	Execute code block 2; 
}

Note: when the conditional expression is true, execute code block 1, otherwise execute code block 2

Flow chart corresponding to two branches:

Multi branch

Basic syntax:

if(Conditional expression 1){
	Execute code block 1;
}
else if (Conditional expression 2){
	Execute code block 2;
}
......
else{
	Execute code block n;
}

Nested branch

Another complete branch structure is completely nested in one branch structure. The branch structure inside is called inner branch, and the branch structure outside is called outer branch.

Nested branches are not suitable for too many, no more than 3 layers at most

Basic syntax:

if(){
	if(){ 
        //Included can be single branch, double branch and multi branch
	}else{ 
    
    } 
}

Case:

If you take less than 8 seconds to enter the finals in the 100 meter games, otherwise you will be prompted to be eliminated. And enter the men's group or women's group according to the gender prompt. [let the students practice first], enter the score and gender and judge. 1 minute thinking
thinking

double second; char gender;

# include <stdio.h>
void main() {
	/*

	If you take less than 8 seconds to enter the finals in the 100 meter games, otherwise you will be prompted to be eliminated. And enter the men's group or women's group according to the gender prompt.
	[You can ask the students to practice and input the results and gender to judge. 1 minute thinking
	analysis:
	1,Use double second; Save time
	2,Save gender with char gender	
	double second; char gender;

	*/
	double second = 0.0; 
	char gender = '  ';
	printf("Please enter your sports score-time(s): ");
	scanf("%lf",&second);

	if(second <=8 ){
		printf("Please enter gender(m/f)"); // Received last carriage return scanf ('% C', & Gender); 
		scanf("%c", &gender); 	// Only this time did I receive gender information

		if(gender == 'm'){
			printf("Please enter the men's group");
		}else{
			printf("Please enter the women's group");
		}
	}else{
		printf("You're eliminated!");
	}
	getchar();
	getchar();
}

switch branch structure

Basic syntax:

switch(expression){
    case Constant 1: //When the expression value is equal to constant 1
    Statement block 1;
    break; //Exit switch
    
    case Constant 2; // Same meaning
    Statement block 2;
    break;
    ...
    case constant n;
    Statement block n;
    break;
    default:
    default Statement block;
	break; 
}

flow chart:

Demonstration case:

Please write a program that can receive a character, such as a,b,c,d,e,f,g

a means Monday, b means week

II. Display according to the user's input

Show dependent information Required use

switch statement complete

# include <stdio.h>
void main() {
	char c1 = ' '; 
	char c2 = 'a'; 
	printf("Please enter a character(a,b,c,d)"); 
	scanf("%c", &c1); 
	//switch 
	//Expression: any value can be regarded as an expression 
	switch(c1) { 
	case 'a' : //'a' => 97 
		printf("Today is Monday, Monkeys wear new clothes"); 
		break; //Exit switch 
	case 'b' : 
		printf("Today is Tuesday, Monkey as a waiter"); 
		break;
	case 'c' : 
		printf("Today is Tuesday, Monkey as a waiter"); 
		break;
	case	 'd':
		printf("Today is Thursday. The monkey is the fourth child");
		break;
	case 'e':
		printf("Today is Friday. The monkey is the fifth child");
		break;
	case 'f':
		printf("Today is Saturday. The monkey is a little Saturday");
		break;
	case 'g':
		printf("Today is Sunday. The monkey is a little day");
		break;
	default:
		printf("Input error!");
	}
	getchar(); 
	getchar();
}

switch details discussion

  1. The expression in the switch statement is a constant expression, which must be an integer (charshort, int, long, etc.) or an enumeration type
  2. The value in the case clause must be a constant, not a variable
  3. The default clause is optional. When there is no matching case, default is executed
  4. break statement is used to make the program jump out of the switch statement block after executing a case branch;
  5. If break is not written, the next case statement block will be executed until break is encountered or the end of switch is executed. This phenomenon is called penetration

Cyclic structure

Basic introduction: listen to its name and know its meaning, which is to make your code execute circularly

for loop

Cyclic variable definition:

for(①Loop variable initialization;②Cycle condition;④Cyclic variable iteration){ 

③Cyclic operation(Multiple statements); 

} 

Notes and details

1. A loop condition is an expression that returns true (not 0) or false (0)
2. or(; cycle judgment condition;) Initialization and variable iteration in can not be written (written elsewhere), but the semicolons on both sides cannot be omitted.
3. The initial value of the loop can have multiple initialization statements, but the types are required to be the same and separated by commas. The loop variable iteration can also have multiple variable iteration statements separated by commas.

for(i = 0, j = 0; j < count; i++, j += 2)

Example:

1. Print the number and sum of all integers between 1 and 100 that are multiples of 9 [complete with for]

# include <stdio.h>
void main() {
	int count = 0;
	int sum = 0;
	int i	;
	for(i = 1; i<=100; i++){
		if(i%9 == 0){
			sum+=i;
			count++;
		}
	}
	printf("number:%d,the sum:%d",count,sum);
	getchar();
}

2. Complete the following expression output

# include <stdio.h>
void main() {
	int i = 0;
	int j = 0;
	for(i=0; i<=6; i++){
		for(j=0; j<=6; j++){
			if(i+j == 6){
				printf("%d+%d\n",i,j);
			}
		}
	}
	getchar();
}

while Loop

①Loop variable initialization;
while(②Cycle condition){
    
	③Circulatory body(Multiple statements);
	④Cyclic variable iteration; 
}

Case: output 5 Hello! He Jingjing

# include <stdio.h>
void main() {
	int i = 1;
	while(i<=5){
		printf("Hello! He Jingjing \n");
		i++;
	}
	getchar();
}

Flow chart analysis:

Contact case:

# include <stdio.h>
# include <string.h>
void main() {
	char  name[10] = "";
	while(strcmp(name,"exit") != 0){
		printf("Please enter your first name:");
		scanf("%s",name);// There is no need to add &, because the name of the array is the address
		printf("The name you entered is=%s \n",name);
	}
	getchar();
	getchar();

}

do while loop

①Loop variable initialization;
do{
	②Circulatory body(Multiple statements);
	③Cyclic variable iteration; }
	while(④Cycle condition);
	
be careful: do – while There is a semicolon after it, which cannot be omitted

Case: output 5 Hello! He Zhuzhu

#include <stdio.h> 
void main() { 
	//output 
	int i = 1; //Loop variable initialization 
	while( i <= 5) { //Cycle condition 
		printf("Hello, pig he i=%d \n" , i); //Circular statement 
		i++; // Variable iteration 
	}
	getchar(); 

}

Case 2:

If the husband agrees to the wife's shopping, the wife will continue shopping until the husband says no [printf("wife asks: can I continue shopping? y/n")]

#include <stdio.h> 
void main() { 
	char answer = ' ';
	do{
		printf("The wife asked: can I continue shopping? y/n: ");
		scanf("%c",&answer);
		getchar(); //Its enter
	}while(answer == 'y' );

	printf("My God, my wife finally stopped shopping~~~~");
	getchar();
}

Test run results:

Multiple cycle control

1. A nested loop is formed when one loop is placed in another loop. Among them, for, while, do... While can be used as outer loop and inner loop. [it is recommended to generally use two layers, no more than three layers at most]. If there are too many nested loops, the readability will be reduced
2. In essence, nested loops treat the inner loop as the loop body of the outer loop. Only when the cycle condition of the inner cycle is false, will it completely jump out of the inner cycle, end the current cycle of the outer cycle and start the next cycle, for example.
3. If the number of outer layer cycles is m times and the number of inner layer cycles is n times, the inner layer cycle body actually needs to execute m*n times.

Case:

1. Count the results of three classes. There are five students in each class. Calculate the average score of each class and the average score of all classes = = [students' scores are input from the keyboard] = =.

2. Count the number of passing students in three classes. There are five students in each class.

#include <stdio.h> 
void main() { 
	int classNumber = 3; // Number of classes
	int stuNumber = 5; // Number of students
	double classTotalScore =0.0; // Individual class total score
	double allClassTotalScore =0.0; // Individual class total score
	double score = 0.0; // Receive students' grades
	int count = 0; // Number of qualified persons
	int i,j;

	for(i=1;i<=classNumber;i++){
		//Each time you output results to a class, you need to clear it
		classTotalScore=0.0;
		for(j=1; j<=stuNumber; j++){
			printf("\n Please enter page%d The second class%d A student's grade",i,j);
			scanf("%lf",&score);
			if(score>=60){
				count++;
			}
			classTotalScore +=score;
		}
		allClassTotalScore += classTotalScore;
		printf("The first%d What is the average score of the class%.2f",i,classTotalScore/stuNumber);

	}
	printf("Average score of all classes%.2f",allClassTotalScore/(stuNumber*classNumber));
	printf("Number of passes in all classes%d",count);
	getchar();// Go back
	getchar();
}

3. Print 99 multiplication table

#include <stdio.h>
void main(){
	int i,j;
	for(i=1;i<=9;i++){
		for(j=1;j<=i;j++){
			printf("%d * %d = %d ",j,i,i*j);
		}
		printf("\n");
	}
	getchar();
}

4. Print pyramid

#include <stdio.h>
void main(){
	int i,j,k;
	int totalLevel = 10;
	for(i=1;i<=totalLevel;i++){
		//Output space
		for(k=1;k<=totalLevel-i;k++){
			printf(" ");
		}
		// Output*
		for(j=1;j<=2*i-1;j++){
			printf("*");
		}
        //Line feed
		printf("\n");
	}
	getchar();
}

4. Print hollow pyramids

#include <stdio.h>
void main(){
	int i,j,k;
	int totalLevel = 10;
	for(i=1;i<=totalLevel;i++){
		//Output space
		for(k=1;k<=totalLevel-i;k++){
			printf(" ");
		}
		// Output*
		for(j=1;j<=2*i-1;j++){
			if(j==1 || j==2*i-1 || i ==totalLevel){
				printf("*");
			}else{
				printf(" ");
			}
		}
		//Line feed
		printf("\n");
	}
	getchar();
}

Job: print hollow diamond:

Realization idea:

Step 1: print solid rectangle first

Directly through the double for loop

*******
*******
*******
*******
*******
*******
*******

Step 2: print the solid pyramid

   *  // 3 spaces 
  *** // 2 spaces
 ***** //1 space
*******//0 spaces 
law totalLevel -i individual*

   *  // 1*
  *** // 2*
 ***** //5*
*******/ 7 individual*
Law: 2*i-1 individual*

Code implementation:

#include <stdio.h>
void main(){
	printArc(10);
}

void printArc(int num){
	int i,j,k;
	for(i=1;i<=num;i++){
		//Output space
		for(k=1;k<=num-i;k++){
			printf(" ");
		}
		// Output*
		for(j=1;j<=2*i-1;j++){
			printf("*");
		}
		//Line feed
		printf("\n");
	}
	getchar();
}

Step 3: print solid diamond

Idea: write another cycle to print symmetrical triangles

   *  
  *** 
 ***** 
*******
 *****
  ***
   *

break

break just jumps out of the current loop

Suppose: randomly generate a number until 97 is generated. How many times have you used it?

solve:

In the process of executing a loop, when a certain condition is met, you can exit the loop in advance. At this time, break may be used

Code implementation:

#include <stdio.h>
void main(){
	int i = 0;
	while(1) {
		printf("\n output%d",i++);
		if(i==97) {
			break;
		}
	}
	getchar();
}

continue

The continue statement is used to end this cycle and continue to execute the next cycle.

flow chart:

Demonstration case:

#include <stdio.h>
void main() {
	int i,j;
	for( j = 0; j < 4; j++){
		for( i = 0; i < 10; i++){
			if(i == 2){
				//See what the output values are and analyze them respectively
				continue ;
			}
			printf("i = %d\n" , i);
		}
		printf("================\n");
	}
	getchar();
}// Output 4 times I = 0, 1, 3, 4, 5, 6, 7, 8, 9

The results are shown in the figure below:

Notes and details:

The continue statement can only be used in conjunction with the loop language and cannot be used alone with switch/if

Exercise:

(1) Read in an uncertain number of integers from the keyboard and judge the number of positive and negative numbers read in. Enter 0 to end the program [complete with for loop, break, continue] [positive, negative]

#include <stdio.h>
void main() {
	int positive = 0;
	int negative = 0;
	int num = 0; //Number of input from the console
	for(; ;) {  //Dead cycle equivalent while(1) {}
		printf("Please enter an integer:");
		scanf("%d",&num);
		if(num==0){
			break; // Jump out of for loop
		}
		if(num>0){
			positive++;
			continue;
		}
		negative++;
	}
	printf("Number of positive numbers%d,Number of negative numbers%d",positive,negative);
	getchar();
	getchar();
}

Run test:

(2) A person has 100000 yuan and needs to pay a fee for each intersection. The rules are as follows:

5% for cash > 50000

When cash < = 50000, pay 1000 each time

Program to calculate how many intersections the person can pass, and use the while break method to complete

#include <stdio.h>
void main() {
	/*

	A person has 100000 yuan and needs to pay a fee for each intersection. The rules are as follows: 
	5% for cash > 50000 
	When cash < = 50000, 	 Pay 1000 each time
	Program to calculate how many intersections the person can pass,
	Use the while method to complete
	*/

	//Analysis: you can't pass when money < 1000
	double money = 100000;
	int count = 0;
	while(1){

		//Less than 1000 after judging money	
		if(money<1000){
			break;
		}
		if(money>50000){
			money=money*(1-0.05);
			count++;
		}else if(money<=50000){
			money-=1000;
			count++;
		}
	}
	printf("The number of crossings is:%d,surplus%.2f",count,money);
	getchar();

}

The operation results are shown in the figure below:

go to

1. The goto statement of C language can unconditionally transfer to the specified line in the program.

2. goto statements are usually used in conjunction with conditional statements. It can be used to realize conditional transfer, jump out of the loop body and other functions.

3. In C programming, goto statement is generally not advocated, so as not to cause confusion of program flow and make people understand

And debugging programs are difficult

Basic grammar

goto label 

.. . 

label: statement

demonstration:

#include <stdio.h>
void main() {
	printf("start\n");
	goto lable1; //lable1 is called a label
	printf("ok1\n");
	printf("ok2\n");
lable1: 
	printf("ok3\n");
	printf("ok4\n");
	getchar();
}

Operation results:

Comprehensive exercise:

(1) Judge whether a year is a leap year

analysis:

Judgment conditions of leap year: 1. It can be divided by 400; 2. It can be divided by 4 integers and cannot be divided by 100

Program statement implementation

if(year%400==0)

if(year%4==0 && year%100 != 0)

#include <stdio.h>
void main()
{
    int year;
    printf("Please enter the year:\n");
    scanf("%d",&year);
	if(year%400 == 0 || (year%4==0 && year%100 != 0)){
		 printf("%d This year is a leap year\n",year);
	} else{
		 printf("%d This year is not a leap year\n",year);
	}
	getchar();
	getchar();
}

(2) . number of daffodils within 1000: (for example: 153 = 13 + 53 + 3 ^ 3)

#include <stdio.h>
int main()
{
	int i;
	for(i = 0; i<1000; i++){
		int ge = i%10; // Bit
		int shi = i%100/10; //  Ten
		int bai= i/100; //Hundredth
		if(i = ge*ge*ge + shi*shi*shi + bai*bai*bai){
			printf("%d It's daffodils\n",i);
		}
	}
	getchar();
}

The operation results are shown in the figure below:

(3) Write a program to calculate the number of days of the month (1-12) according to the entered month and year. Note: leap year (February 29) and peaceful year (February 28) need to be considered

#include <stdio.h>
void main(){
	int year = 2019; 
	int month = 2;
	switch(month) { 
	case 1: 
	case 3: 
	case 5: 
	case 7: 
	case 8: 
	case 10: 
	case 12: 
		printf("%d Year %d Month is%d day", year, month, 31); 
		break; 
	case 2: 
		//Judge whether year is a leap year or a normal year 
		if( (year % 4 == 0 && year % 100 !=0) || year % 400 == 0) { 
			printf("%d Year %d Month is%d day", year, month, 29); 
		} else{
			printf("%d Year %d Month is%d day", year, month, 28); 
		}
		break; 
	default: 
		printf("%d Year %d Month is%d day", year, month, 30); 
		break;
	}
	getchar(); 
}

Operation results:

(4) What is the output of the following code? Focus: priority issues

#include <stdio.h>
void main(){
	int b1=0,b2=0; 
	// What will be output if B2 = = 5 > 0 is changed to B2 = 5 > 0 
	// Fully consider the priority of operators 
	if((b1==2>3) && (b2=5>0)){ 
		printf("\n(b1=2>3) && (b2=5>0)For true"); //output 
	}
	printf("\nb1= %d ;b2= %d", b1,b2);// b1=0 b2=1 
	getchar(); 
}

Output result:

(5) Output lowercase a-z and uppercase z-a

#include <stdio.h>
void main()
{
	char c1;
	for(c1 = 'a'; c1<'z';c1++){
		printf("%c ",c1);
	}
	for(c1 = 'A'; c1<'Z';c1++){
		printf("%c ",c1);
	}
	getchar();
}

(6) . find the sum of 1-1 / 2 + 1 / 3-1 / 4...... 1 / 100

Find rules to analyze and solve problems:

1-1/2+1/3-1/4......1/100 = (1/1)-(1/2)+(1/3)-(1/4)......(1/100)

Denominator is odd: sign is+

Denominator is even: sign is-

#include <stdio.h>
void main()
{
	//Define a variable sum to count and 
	double sum = 0.0; 
	int i ; 
	for(i = 1; i <= 100; i++) { 
		//If i is odd 
		if(i % 2 != 0) { 
			sum += 1.0/i; // Note that consider keeping the decimal 1.0 instead of 1 
		} else { 
			sum -= 1.0/i; 
		} 
	}
	printf("sum=%.2f", sum); 
	getchar();
}

Enum (enum)

1. Enumeration is a kind of constructed data type in C language. It can make the data more concise and easier to read. For only a few limited specific data, enumeration can be used
2. Enumeration corresponds to English (enumeration, abbreviated as enum)
3. An enumeration is a set of constants that contains a limited set of specific data
4. The enumeration syntax definition format is

Quick start cases:

#include <stdio.h>
int main() {
	enum DAY
	{
		MON=1, TUE=2, WED=3, THU=4, FRI=5, SAT=6, SUN=7	// Here, DAY is an enumeration type, which contains seven enumeration elements
	}; 
	enum DAY day;  // enum DAY is an enumeration type, and day is an enumeration variable
	day = WED; 		//	Assign a value to the enumeration variable day, and the value is an enumeration element
	printf("%d",day);	// 3. Each enumeration element corresponds to a value
	getchar();
	return 0;
}

Enumeration traversal

In C language, enumeration types are treated as int or unsigned int types. Enumeration types must be continuous and can realize conditional traversal. The following example uses for to traverse the elements of an enumeration

#include <stdio.h>
enum DAY {
	MON=1, TUE, WED, THU, FRI, SAT, SUN //If there is no assignment, the assignment will be in order
} day; // Indicates that an enumeration type enum Day is defined, and a variable day is defined at the same time (the type is enum DAY)
int main() {
	// Traverse enumeration elements
	//day + + will give a warning, but it can run
	for (day = MON; day <= SUN; day++) { // Enumeration elements are required to be continuously assigned values
		printf("Enumeration elements:%d \n", day);
	}
	getchar();
	return 0;
}

Application of enumeration in switch

#include <stdio.h>
int main() { 
	enum SEASONS {SPRING=1, SUMMER, AUTUMN, WINTER}; //Define enumeration type enum sessions 
	enum SEASONS season;//An enum type variable named season (enum SEASONS) is defined
	printf("Please enter your favorite season: (1. spring, 2. summer, 3. autumn 4 winter): ");
	scanf("%d", &season);
	switch (season) {
	case SPRING:
		printf("Your favorite season is spring");
		break;
	case SUMMER:
		printf("Your favorite season is summer");
		break;
	case AUTUMN:
		printf("Your favorite season is autumn");
		break;
	case WINTER:
		printf("Your favorite season is winter");
		break;
	}
	getchar();
	getchar();
}

Notes and details on the use of enumeration types

1. The default value of the first enumeration member is integer 0, and the value of subsequent enumeration members is added to the previous member by 1. In this example, we define the value of the first enumeration member as 1, the second as 2, and so on
2. Change the value of enumeration element when defining enumeration type [case]
3. Definition form of enumeration variable 1 - define enumeration type first, and then enumeration variable
4. Definition form of enumeration variables 2 - define enumeration variables while defining enumeration types
5. The definition form of enumeration variable 3- omit the enumeration name and directly define the enumeration variable

#include <stdio.h>
int main() { 
    //Definition method 1 - define enumeration variables while defining enumeration types
	enum DAY {
		MON=1, TUE, WED, THU, FRI, SAT, SUN
	} day;
    // Definition method 2 - omit the enumeration name and directly define the enumeration variable
	enum { 
		MON=1, TUE, WED, THU, FRI, SAT, SUN 
	} day; // When using enumeration in this way, the enumeration type can only be used once
    
    //Definition method 3: first define the enumeration type, and then define the enumeration variable
    enum DAY {
	MON=1, TUE, WED, THU, FRI, SAT, SUN 
};
    enum DAY day;
}

6. Integers can be converted to corresponding enumeration values

#include <stdio.h>
int main() {
	enum SEASONS {SPRING=1, SUMMER, AUTUMN, WINTER};
	enum SEASONS season;
	int n = 4;
	season = (enum SEASONS) n; // The integer int 4 is changed to the SEASONS type
	printf("season=:%d",season);
	getchar();
	return 0;
}

function

1. A collection of program instructions (statements) to complete a function is called a function.
2. In C language, functions are divided into user-defined functions and system functions (see the C language function manual)
3. There are other names for functions, such as methods. In this video course, we call them functions.

Definition of function

Form of function:

Return type function name (formal parameter list){
	Execute statement...; // Function body
	return Return value; // Optional
}

Header file

In actual development, we often need to call the defined functions of other files in different files, such as hello C, use myfuns How to implement the functions in C file? - > Use header file

Basic concepts of header file

1. The header file has an extension of h file, which contains C function declaration and macro definition, is referenced and shared by multiple source files. There are two types of header files: the header file written by the programmer and the header file of the C standard library
2. To use a header file in a program, you need to use the C preprocessing instruction #include to reference it. We've seen stdio before H header file, which is the header file of C standard library
3. #include is called the file include command, which is used to import the corresponding header file (. h file)# Include is also a preprocessing command of C language.

  1. #The process of include is very simple, that is, insert the contents of the header file into the location of the command, so as to connect the header file and the current source file into a source file, which is the same as the effect of copy and paste. However, we will not directly copy the contents of the header file in the source file, because it is easy to make mistakes, especially when the program is composed of multiple source files.
    5. It is recommended to write all constants, macros, system global variables and function prototypes in header files, and reference these header files at any time when necessary

Working principle diagram:

Header file quick start

Description: header file quick start - C programs call each other. We declare cal to the file myfun H, at myfun The cal function is defined in C. when other files need to use myfun H declared function, you can #include the header file and use it

1. Create myfun H and declare the int add(int a,int b) function

//Declare the function int add(int a,int b);
int add(int a ,int b);

2. Create myfun C and implement the int add(int a,int b) function

#include <stdio.h>
// Implement the function int add(int a,int b);

int add(int a,int b){
	return a+b;
}

3. Create test class test C to test int add(int a,int b) function

#include <stdio.h>
// Implement the function int add(int a,int b);

int add(int a,int b){
	return a+b;
}

The operation results are shown in the figure below:

Notes and details of header file

1. Referencing a header file is equivalent to copying the contents of the header file

2. The name of the source file may not be the same as the header file, but for good management, the header file name is generally the same as the source file name

3. The difference between include < > and include "" in C language

  • Include < >: refers to the header file in the compiler's class library path, which is used to refer to the system header file

  • include '': refers to the header file in the relative path of your program directory. If the referenced header file is not found in the program directory, find the header file in the directory of the compiler's class library path to refer to the user header file

  • explain:

    The system header file can be referenced in both forms, including < > high efficiency

    Reference user header file, only include '' can be used

4. One #include command can only contain one header file. Multiple header files require multiple #include commands

5. If the same header file is imported multiple times, the effect of multiple imports is the same as that of one import, because the header file has a mechanism to prevent repeated imports at the code level [example]

6. Another header file (. h) can be included in an included file (. c)

7. Both standard header files and user-defined header files can only contain declarations of variables and functions
Can contain definitions, otherwise repeated definition errors will be caused when importing multiple times (!!!)

Function call mechanism

How to understand the concept of method? Give us a popular example:

Example + illustration

No return value type:

Return value type:

4. If a function has a return value, the return value is assigned to the received variable

5. When a function returns, the stack space corresponding to the function will also be destroyed

For example:

Recursion of function

A function calls itself in the function body, which is called recursive call

Getting started with recursive calls

#include <stdio.h>
void test(int n) {
	if(n > 2) {
		test(n -1);
	}
	printf("\n n=%d", n);
}

void main() {
	test(4);  // Output what?
	getchar();
}

The results are shown in the figure below:

Graphic analysis:

Important principles for function recursion:

1. When a function is executed, a new protected independent space (new function stack) is created
2. The local variables of the function are independent and will not affect each other
3. Recursion must approach the condition of exiting recursion, otherwise it is infinite recursion, dead turtle:)
4. When a function finishes executing or encounters a return, it will be returned. The result will be returned to whoever calls it

Recursive function exercises

1. Fibonacci number

Please use recursion to find the Fibonacci number 1,1,2,3,5,8,13... Give you an integer n and find out its Fibonacci number?

#include <stdio.h>
/*
Title: find the Fibonacci number 1,1,2,3,5,8,13 Give you an integer n
 analysis:
	When n=1 and n=2, the return value is 1
	When n > 2, Fibonacci number = the sum of the first two numbers: fbn(n-1)+fbn(n-2)

*/
int fbn(int n){
	if(n ==1 || n ==2 ){
		return 1;
	}else{
		return fbn(n-1)+fbn(n-2);
	}
}

void main(){
	int result = fbn(4);
	printf("%d",result);
	getchar();
}

2. Find function value

Known f(1)=3; f(n) = 2*f(n-1)+1; Please use the idea of recursion to program and find the value of F (n)?

#include <stdio.h>
/*
Title: known f(1)=3; f(n) = 2*f(n-1)+1;  Please use the idea of recursion to program and find the value of F (n)?


*/

int f(int n){
	if(n ==1){
		 return 3;
	}else{
		return  2*f(n-1)+1;
	}
}
void main(){
	int result = f(10);
	printf("%d",result);
	getchar();
}

3. Monkey eating peach problem

There was a pile of peaches. The monkey ate half of them on the first day and ate another one! After that, monkeys eat half of them every day, and then eat one more. On the tenth day, when I wanted to eat again (I haven't eaten yet), I found that there was only one peach. Question: how many peaches were there in the beginning?

#include<stdio.h>
/*
There was a pile of peaches. The monkey ate half of them on the first day and ate another one!
After that, monkeys eat half of them every day, and then eat one more.
On the tenth day, when I wanted to eat again (I haven't eaten yet), I found that there was only one peach.
Question: how many peaches were there in the beginning?

Analysis: day10 has only one peach
		Launch day9 = (day10+1)*2 = 4
				day8 = (4+1)*2= 10;
				day7 = (10+1)*2= 22;

*/

int peach(int day){
	if(day == 10){
		return 1;
	}else {
		return (peach(day+1)+1)*2;
	}
}
void main(){
	int peachNum = peach(1);
	printf("On the first day%d A peach",peachNum);
	getchar();
}

Function considerations and detailed discussion

1. The formal parameter list of a function can be multiple.
2. C language transfer parameters can be pass by value or a pointer passed by value, which is also called reference transfer.
3. The naming of functions follows the identifier naming standard. The first letter cannot be a number. Hump method or underline method can be used, such as getMax() get_max().
4. Variables in the function are local and do not take effect outside the function [case description]

5. The basic data type is value transfer by default, that is, value copy. Modification in the function will not affect the original
Value of. [case demonstration]

#include<stdio.h>
void f2(int n) { 
	n++; 
	printf("\nf2 Medium n=%d", n); // n=10 
}

void main() { 
	//The variables in the function are local and do not take effect outside the function 
	//printf("num=%d", num); 
	int n = 9; 
	f2(n); 
	printf("\nmain In function n=%d", n); //9 
	getchar(); 
}

6. If you want the variables inside the function to modify the variables outside the function, you can pass in the address &, and operate the variables in the function in the form of pointers. In terms of effect, similar references (i.e. passing pointers) [case demonstration:]

Pointer passing

#include<stdio.h>
void f3(int *p) { 
	(*p)++;// Modification will affect variables outside the function 
}

void main() { 
	//The variables in the function are local and do not take effect outside the function 
	//printf("num=%d", num);
	int n = 9; 
	f3(&n); 
	printf("\nmain In function n=%d", n); //10 
	getchar(); 
}

Memory graph analysis:

7. C language does not support function overloading, and C language supports variable parameter functions

#include<stdio.h>
/*

	Please write a function swap(int \*n1, int \*n2) to exchange the values of n1 and n2


*/
void swap(int *n1, int *n2){
	int temp = *n1; // Indicates that the value of the variable pointed to by n1 pointer is assigned to temp 
	*n1 = *n2; // Assign the value pointed to by the n2 pointer to the value of the variable pointed to by the n1 pointer
	*n2 = temp; // Assign the value of temp to the value of the variable pointed to by the n2 pointer
}

void main(){
	int a = 3;
	int b = 4;
	swap(&a,&b);
	printf("a=%d,b=%d",a,b); // At this time, a = 4, B = 3
	getchar();
}

Exercise: please write a function swap(int *n1, int *n2) to exchange the values of n1 and n2

#include<stdio.h>
/*
	Please write a function swap(int \*n1, int \*n2) to exchange the values of n1 and n2

*/
void swap(int *n1, int *n2){
	int temp = *n1; // Indicates that the value of the variable pointed to by n1 pointer is assigned to temp 
	*n1 = *n2; // Assign the value pointed to by the n2 pointer to the value of the variable pointed to by the n1 pointer
	*n2 = temp; // Assign the value of temp to the value of the variable pointed to by the n2 pointer
}

void main(){
	int a = 3;
	int b = 4;
	swap(&a,&b);
	printf("a=%d,b=%d",a,b);
	getchar();
}

Transfer method of function parameters

When explaining the precautions and usage details of the function, we have already talked about the C language. The transfer parameters can be pass by value or a pointer passed by value, which is also called transfer address or reference transfer

Two delivery methods:

1. Value transfer

2. Reference passing (passing pointer, address)

In fact, whether it is value transfer or reference transfer, what is passed to the function is the copy of the variable. The difference is that the value transfer is the copy of the value, and the reference transfer is the copy of the address. Generally speaking, the address copy efficiency is high, because the amount of data is small, and the value copy determines the size of the copied data. The larger the data, the lower the efficiency.

Characteristics of value passing and reference passing

1. Value transfer: variables store values directly, and memory is usually allocated in the stack [case: schematic diagram]
2. By default, the data type of value transfer is 1 Basic data type 2 Structure 3 Common body 4 Enumeration type
3. Reference passing: the variable stores an address, and the space corresponding to this address really stores data (value).
4. The default data types passed by reference are pointer and array

5. If you want the variable inside the function to modify the variable outside the function, you can pass in the address &, and operate the variable (* pointer) in the function as a pointer. In terms of effect, it is similar to quoting [case demonstration: draw a schematic diagram], such as modifying the properties of the structure

Variable scope

The so-called variable Scope refers to the effective range of variables

1. The scope of the local variable defined by the declaration inside the function is limited to the inside of the function.

2. The parameters and formal parameters of a function are regarded as local variables in the function. If they have the same name as the global variable, they will give priority to the local variable

3. In a code block, such as a local variable in for / if, the scope of this variable is in the code block

4. Variables defined outside all functions are called global variables, and the scope is valid in the whole program.

Initializing local and global variables

1. For local variables, the system will not initialize them by default. They must be initialized before they can be used. Otherwise, the program may exit abnormally after running

2. Global variable, which will be initialized automatically, as shown below

Scope considerations and details

1. Global variables are stored in the global storage area of memory and occupy static storage units. Its scope is the whole program by default, that is, all code files, including source files (. c files) and header files (. h files). [c program memory layout!!!]
2. Local variables are stored in the stack. When a function is called, it dynamically allocates storage units for variables, and its scope is limited to the interior of the function.

Reference: ↓↓↓↓↓

c program memory layout

3. C language stipulates that you can only look for variables from a small scope to a large scope, but not vice versa
4. In the same scope, variable names cannot be repeated. In different scopes, variable names can be repeated. When using, the compiler adopts the principle of proximity
5. Code blocks surrounded by {} also have separate scopes

c program memory layout

static keyword

static keyword is commonly used in c language. Proper use can greatly improve the modularity of the program and is conducive to expansion and maintenance.

Local variables are decorated with static

1. After the local variable is modified by static, we call it static local variable

2. If the corresponding static local variable is declared without an initial value, the compiler will initialize it to 0.

3. Static local variables are stored in the process's static storage area * * (global nature), * * will only be initialized once, and its value will remain unchanged even if the function returns [Case + illustration]

#include<stdio.h>
void fn(void){
	int n = 10; //Common variable
	printf("n=%d\n", n);
	n++;
	printf("n++=%d\n", n);
}
void fn_static(void) {
	static int n = 10; //Static local variables - initialize only once
	printf("static n=%d\n", n);
	n++;
	printf("n++=%d\n", n);
}
int main(void) {
	//fn();
	printf("--------------------\n");
	fn_static();
	printf("--------------------\n");
	//fn();
	printf("--------------------\n");
	fn_static();
	getchar();
	return 0; 
}

Global variables are decorated with static

1. Ordinary global variables are visible to the whole project, and other files can be directly used after extern al declaration. In other words, other files cannot define a variable with the same name (otherwise the compiler will think they are the same variable). Static global variables are only visible to the current file, and other files cannot be accessed. Other files can define variables with the same name, which do not affect each other

(1) Create a class file01 with global variables c. The code is as follows:

int n = 10; //General global variable
//static int n = 20;  // Static global variables can only be used in this file, not in other files!

(2) Create test class file02 c. The code is as follows:

#include <stdio.h>
//#include "file01.c"; // Method 1: import through header file

// In one file, you can use the global variables of another file and use extern to import them
extern int n;
extern int m;

void main(){
	printf("%d",n);
	getchar();
}

2. When defining global variables that do not need to be shared with other files, adding the static keyword can effectively reduce the coupling between program modules, avoid the conflict of variables with the same name in different files, and will not be misused

The function is decorated with static

(1) Create file03 with ordinary function class c. The code is as follows:

#include <stdio.h>
void fun1(void) {//Ordinary function (non static function)
printf("hello from fun1.\n");
}
static void fun2(void) {//Static functions - can only be used in this file
printf("hello from fun2.\n");
}

(2) Create test class file04 c. The code is as follows:

#include <stdio.h>
extern void fun1(void)
//extern void fun2(void); // There must be an error
void main(){
	fun1();
	//fun2();  // There must be an error
	getchar();
}

It is found that the static function can only be used in this class and cannot be called by external classes

System function

Reference address of standard library: https://www.runoob.com/cprogramming/c-data-types.html

String system function

1. Get the length of the string

size_t strlen(const char *str)
Calculates the length of the string str until the null terminated character, but excluding the null terminated character.

2. Copy string
char *strcpy(char *dest, const char *src)

Copy the string pointed to by src to dest.
3. Connection string
char *strcat(char *dest, const char *src)

Append the string pointed to by src to the end of the string pointed to by dest.

Test case:

#include<stdio.h>
#include<string.h>

void main(){
	char src[50], dest[50];
	char * str = "abcdff";
	printf("str.len=%d", strlen(str));  //Return 6

	strcpy(src, "hello ");  //  Output [src = hello] and overwrite the original abcdff
	strcpy(dest, "Ren Ping Ye"); 
	strcat(dest, src); // Append the contents of src to desc without overwriting the original contents [the result is: ye Renping, hello]
	printf("Final target string: |%s|", dest);//[result: ye Renping, hello]
	getchar();
}

Function of time and date

(1) . get the current time

char *ctime(const time_t *timer)

Returns a string representing the local time, which is based on the parameter timer.

Case demonstration 1:

#include <stdio.h>
#include <time.h>
int main () {
	time_t curtime; // time_t is a structure type
	time(&curtime); // time() can complete the initialization task
	printf("current time  = %s", ctime(&curtime)); //  Returns a string representing the local time, which is based on the parameter timer.
	getchar();
	return(0);
}

Result: displays the current local time

Demo case 2:

Time spent executing two for loops

#include <stdio.h>
#include <time.h>
void test() {
	int i = 0;
	int sum = 0;
	int j = 0;
	for(i = 0; i < 77777777;i++) {
		sum = 0;
		for (j = 0; j< 10;j++) {
			sum += j;
		}
	} 
}
void main () {
	// Define two variables star_t is the start time, end_t indicates the end time
	time_t start_t,end_t; 
	double diff_t;	// Time difference between the two
	printf("*********Program start************\n");
	time(&start_t);		//Get current time	
	test(); // Test
	time(&end_t);		//Gets the time at the end
	diff_t = diff_t = difftime(end_t,start_t);  // The time difference between the two is the current time
	printf("implement test Function time consuming%.2fs",diff_t);
	getchar();
}

result:

Mathematical function math h

1,double exp(double x)
Returns the value of e to the power of x.
1,double log(double x)
Returns the natural logarithm of x (logarithm of base e)
3,double pow(double x, double y)
Returns the y-power of x.
4,double sqrt(double x)
Returns the square root of x.
5,double fabs(double x)

Returns the absolute value of x.

Case:

#include <stdio.h>
#include <math.h>
void main (){
	double d1 = pow(2.0,3.0); // the cube of 2
	double d2 = sqrt(5.0); // Returns the square root of 5.0
	printf("d1=%.2f", d1);
	printf("d2=%.2f", d2); 
	getchar();
}

Conversion of basic data type and string type

In program development, we often need to convert the basic data type into string type (i.e. char array). Or convert the string type to the basic data type.

Usage of sprintf function:

1. The function of sprintf is very similar to the printf function we usually use. The sprintf function prints to a string, while the printf function prints to the screen. Sprintf function is widely used in our operation of converting other data types into string types
2. This function is included in stdio In the header file of H

Demonstration case:

#include<stdio.h>
void main() {
	char str1[20]; //Character array, i.e. string
	char str2[20];
	char str3[20];
	int a=20984,b=48090;
	double d=14.309948;
	sprintf(str1,"%d %d",a,b);
	sprintf(str2, "%.2f", d); 
	sprintf(str3, "%8.2f", d); 
	printf("str1=%s str2=%s str3=%s", str1, str2, str3);
	getchar();
}

String type to basic data type

atoi (string)

Convert string array to integer

atof (string)

Convert string array to decimal

Case:

#include<stdio.h>
#include<stdlib.h>
void main() {
	char str[10] = "123456";
	char str2[10] = "12.67423";
	char str3[3] = "ab";
	char str4[4] = "111";
	int num1 = atoi(str); // Convert str to an int integer
	short s1 = atoi(str4); 
	double d = atof(str2);// Convert str2 to double type
	char c = str3[0]; //  Gets the first element a of the string
	printf("num1=%d d=%f c=%c s1=%d", num1, d, c, s1);
	getchar();
}

be careful:

When converting char array type to basic data type, ensure that it can be converted to valid data. For example, we can convert "123" to an integer, but we can't convert "hello" to an integer; If the format is incorrect, it will be converted to 0 or 0.0 by default [case demonstration]

Function exercises

(1) Functions can have no return value cases. Write a function, input an integer from the terminal, and print out the corresponding gold pagoda. [after class exercise] - > encapsulate the original code into the function!

#include <stdio.h>
void printfA(int totalLevel){
	int i,j,k;
	for(i=1;i<=totalLevel;i++){
		//Output space
		for(k=1;k<=totalLevel-i;k++){
			printf(" ");
		}
		// Output*
		for(j=1;j<=2*i-1;j++){
			if(j==1 || j==2*i-1 || i ==totalLevel){
				printf("*");
			}else{
				printf(" ");
			}
		}
		//Line feed
		printf("\n");
	}
}

void main(){
	int totalLevel = 0;
	printf("Please enter the number of pyramid layers:");
	scanf("%d",&totalLevel);
	printfA(totalLevel);
	getchar();
	getchar();
}


(2) Write a function, input an integer (1-9) from the terminal, and print out the corresponding multiplication table

#include <stdio.h>
void print99(int num){
	int i,j;
	for(i = 1;i <= num; i++){
		for(j = 1; j<=i; j++){
			printf("%d * %d = %d",j,i,i*j);
		}
		printf("\n");
	}
	getchar();
}

void main(){
    int num = 0;
	printf("Please enter:");
	scanf("%d",&num);
	print99(num);
}

(3) Define a function to find the maximum value of two double numbers and return

double getMax(double a,double b){
	return a>=b?a:b;
}

void main(){

	printf("Maximum:%.2f",getMax(3.2,2.1));
	getchar();
}

Preprocessing command

1. Before using library functions, you should use #include to import the corresponding header file. This kind of command starting with = = is called preprocessing command = =.

2. These processes of simple processing of source files before compilation are called preprocessing (i.e. preprocessing, pre-processing)

3. Preprocessing is mainly used to process commands starting with # such as #include < stdio h> Wait. Preprocessing commands should be placed outside all functions and generally in front of the source file

4. Preprocessing is an important function of C language, which is completed by preprocessing program. When compiling a source file, the system will automatically call the preprocessing program to process the preprocessing part of the source program. After processing, it will automatically enter the compilation of the source program

5. C language provides a variety of preprocessing functions, such as macro definition, file inclusion, conditional compilation, etc. rational use of them will make the written program easy to read, modify, transplant and debug, and is also conducive to modular program design

Getting started with preprocessing commands

Question:

Develop a C language program, let it pause for 5 seconds and then output the content "Hello, ye Renping! ~", and it is required to be cross platform and run under Windows and Linux. How to deal with it

Tips

1. The prototype of the pause function under Windows platform is void Sleep(DWORD dwMilliseconds), and the unit of the parameter is "millisecond"

Seconds "in < windows h> Header file.

  1. The prototype of the pause function on Linux platform is unsigned int sleep (unsigned int seconds), and the unit of the parameter is

"Seconds" at < unistd h> Header file

  1. #if, #elif, #endif are preprocessing commands, which are executed by the preprocessor before compilation.

solve the problem:

#include<stdio.h>
#if _WIN32  // If it is a win32 platform, execute #include < windows h> , import: windows h
#include <windows.h>
#elif __linux__ // Otherwise, if it is a linux platform, execute #include < unistd h> , import: unistd h
#include <unistd.h>
#endif / / end 
int main() {
	//Different platforms call different functions
#if _WIN32 / / recognize windows platform
	Sleep(5000);
#elif __linux__ // Identify Linux platform
	sleep(5);
#endif / / end
	// text
	puts("hello, Ren Ping Ye~"); // 5 seconds later - output hello, ye Renping~
	getchar();
	return 0; 
}

explain:

Under Windows operating system and Linux operating system, the generated source code is different!

  • The source code generated under Windows is:
#include<stdio.h>
include <windows.h>
int main() {
	puts("hello, Ren Ping Ye~"); // 5 seconds later - output hello, ye Renping~
	getchar();
	return 0; 
}
  • The source code generated under Linux is
#include<stdio.h>
#include <unistd.h>
int main() {
	puts("hello, Ren Ping Ye~"); // 5 seconds later - output hello, ye Renping~
	getchar();
	return 0; 
}

Macro definition

#define is called macro definition command. It is also a kind of C language preprocessing command.

The so-called macro definition is to use an identifier to represent a string. If the identifier appears in the following code, it will be all
Replace the part with the specified string

Quick review

Macro definition considerations and details

1. Macro definition is to use the macro name to represent a string, and replace the macro name with the string when the macro is expanded. This is just a simple replacement. The string can contain any character. It can be constant, expression, if statement, function, etc. the preprocessor does not check it. If there is an error, it can only be found when compiling the source program that has been expanded.
2. A macro definition is not a description or statement. You do not need to add a semicolon at the end of the line. If you add a semicolon, it will be replaced with a semicolon
3. The macro definition must be written outside the function, and its scope is from the macro definition command to the end of the source program. To terminate its scope, use the #undef command case

↓ examples are as follows

#include<stdio.h>
#define PI 3.14159
int main(){
	printf("PI=%f", PI);
	return 0;
}
#undef PI / / cancel macro definition
void func(){
	// Code
	printf("PI=%f", PI);//Error, PI cannot be used here
}

4. If the macro name in the code is surrounded by quotation marks, the preprocessor will not macro it instead of case 4

5. The macro definition allows nesting. The defined macro name can be used in the string of the macro definition. When the macro is expanded, the preprocessor replaces it layer by layer. Case 5

6. Traditionally, macro names are expressed in uppercase letters to distinguish them from variables. But lowercase letters are also allowed

7. Macro definitions can be used to represent data types, making writing convenient [case]

#define UINT unsigned int
	void main() {
	UINT a, b; // Macro replace unsigned int a, b;
}

8. The macro definition represents the difference between the data type and the data specifier defined with typedef: the macro definition is just a simple string replacement * *, which is processed by the preprocessor; Typedef is processed by the compiler in the compilation stage * *. It is not a simple string replacement, but gives a new name to the original data type and takes it as a new data type.

Macro definition with parameters

1. C language allows macros with parameters. The parameters in the macro definition are called "formal parameters", and the parameters in the macro call are called "actual parameters", which is somewhat similar to the function
2. For macros with parameters, not only string replacement, but also formal parameters should be replaced with arguments
3. The general form of macro definition with parameters is #define macro name (formal parameter list) string, which can contain various formal parameters
4. The general form of macro call with parameters is: macro name (argument list); [Case + description]

For example:

Create a macro definition with parameters. The code is as follows:

#define MAX(a,b) (a>b) ? a : b
int main(){
	int x , y, max;
	printf("input two numbers: ");
	scanf("%d %d", &x, &y);
	// 1,MAX(x,y); Call macro definition with parameters
	// 2. During macro replacement (preprocessing, which is completed by preprocessing), the string will be replaced, and the formal parameters will be replaced with arguments
	// MAX(x, y) / / after macro replacement (x > y)? x : y	
	max = MAX(x, y);
	printf("max=%d\n", max);
	getchar();
	getchar();
	return 0;
}

Precautions and details of macro definition with parameters

1. In a macro definition with parameters, spaces can appear between formal parameters, but there can be no spaces between the macro name and the formal parameter list

#define MAX(a,b) (a>b)?a:b If it's written #define MAX (a, b) (a>b)?a:b
 Will be considered a parameterless macro definition, macro name MAX Representative string(a,b) (a>b)?a:b
 instead of : MAX(a,b) representative (a>b) ? a: b Yes

2. In a macro definition with parameters, memory is not allocated for formal parameters, so there is no need to specify the data type. In the macro call, the arguments contain specific data, which should be used to replace the formal parameters, so the arguments must indicate the data type

3. In macro definitions, formal parameters in strings are usually enclosed in parentheses to avoid errors. [Case + description]

#include <stdio.h>
#include <stdlib.h>
#define SQ(y) (y)*(y) / / macro definition with parameters. The formal parameters in the string are usually enclosed in parentheses to avoid errors
int main(){
	int a, sq;
	printf("input a number: ");
	scanf("%d", &a);
	sq = SQ(a+1); // Macro replacement (a+1) * (a+1)
	printf("sq=%d\n", sq);
	system("pause");
	return 0;
}

Differences between macro definitions and functions with parameters

1. Macro expansion is only the replacement of string and does not evaluate the expression; Macros are disposed of before compilation. They have no chance to participate in compilation and will not occupy memory.

2. A function is a piece of code that can be reused. It will be compiled and memory will be allocated to it. Every time a function is called, the code in this memory will be executed

3. Case description: it is required to use functions to calculate the square value and macros to calculate the square value, and summarize the differences between the two

Case analysis difference: fusion vs define

Functions: function

#include <stdio.h>
#include <stdlib.h>
int SQ(int y){
	return ((y)*(y));
}
int main(){
	int i=1;
	while(i<=5){ // 1, 4, 9, 16, 25
		printf("%d^2 = %d\n", (i-1), SQ(i++)); //Why write i-1 because you want to execute it 	 SQ(i++)
	}
	system("pause");
	return 0;
}

Macro definition -- > is actually replacement

#include <stdio.h>
#include <stdlib.h>
#define SQ(y) ((y)*(y))
int main(){
	int i=1;
	while(i<=5){ // This is equivalent to calculating the square of 1,3,5 					 i =  	 1  3  5
		printf("%d^2 = %d\n", (i-2), SQ(i++)); //SQ(i++) = ((i++)*(i++)) 1 9 25  
	}
	system("pause");
	return 0; 
}

Summary of C language preprocessing commands

A preprocessing instruction is a line of code that begins with a # sign, which must be the first character of the line except for any white space characters# Followed by the instruction keyword. Any number of white space characters are allowed between the keyword and # number. The whole line of statements constitutes a preprocessing instruction, which will do some conversion to the source code before the compiler compiles

instructions explain
# Empty command, no effect
#include Contains a source code file
#define Ding Yihong
#undef Cancel defined macros
#if If the given condition is true, compile the following code
#ifdef If the macro is already defined, compile the following code
#ifndef If the macro is not defined, compile the following code
#elif If the #if given condition is not true and the current condition is true, compile the following code
#endif End a #if... #else conditional compilation block

Precautions for using preprocessing instructions

1. Preprocessing function is a special function of C language. It is completed by preprocessing program before formal compilation of source program. Programmers call these functions with preprocessing commands in the program.
2. A macro definition can have parameters. When a macro is called, it replaces formal parameters with arguments instead of "value transfer".
3. In order to avoid errors in macro substitution, the string in the macro definition should be bracketed, and the formal parameters in the string should also be bracketed.

4. File inclusion is an important function of preprocessing. It can be used to connect multiple source files into one source file for compilation, and the result will generate a target file.

5. Conditional compilation allows only the program segments that meet the conditions in the source program to be compiled, so that the generated target program is shorter, which reduces the memory overhead and improves the efficiency of the program.
6. The use of preprocessing function is convenient for program modification, reading, transplantation and debugging, as well as modular program design

array

Array can store multiple data of the same type. Array is also a data type and a construction type. Delivery is delivered by reference (that is, the address is delivered)

quick get start

There are six chickens in a chicken farm. Their weights are 3kg, 5kg, 1kg, 3.4kg, 2kg and 50kg respectively. What is the total weight of these six chickens? What is the average weight? Please make a program

Code implementation:

#include <stdio.h>
#include <stdlib.h>
#define SQ(y) ((y)*(y))
int main(){
	// Define an array of 6 chickens
	double hens[6];
	double totalWeight = 0.0;
	double avrageWeight = 0.0;
	int i;
	// Initial weight of each chicken
	hens[0] = 3;
	hens[1] = 3.3;
	hens[2] = 2.3;
	hens[3] = 2;
	hens[4] = 1;
	hens[5] = 4.5;

	for(i=0; i<6; i++){
		totalWeight+=hens[i];
	}
	printf("What is the total weight of the six chickens%.2f kg,Average body weight is%.2f kg",totalWeight,totalWeight/6);
	getchar();
}

Array definition and memory distribution

Definition of array

Data type array name [Array size];

int a [5]; // A array name, type int, [5] size, that is, array a can store up to 5 int data

Assign initial value a[0] = 1; a[1] = 30; ....

explain
  1. The array name represents the first address of the array, that is, the address of a[0]
  2. Each element of the array is continuously distributed. If a[0] address 0x1122, a [1] address = address of a[0] + number of int bytes (4) = 0x1122 + 4 = 0x1126
    , the following a[2] address = a[1] address + number of int bytes (4) = 0x1126 + 4 = 0x112A, and so on

Three ways to initialize arrays

int arr[3]; //Define first, then copy, given length
arr[0] = 1;
arr[1] = 1;
arr[2] = 1;

int arr2[3] = {4,5,6};// Edge definition, edge assignment, given length

int arr3[] = {7,8,9,10};// Edge definition, edge assignment, unlimited length
 

Use of arrays

Problem: input 5 scores circularly from the terminal, save them to the double array and output them

code implementation

#include <stdio.h>
/*
Input 5 scores circularly from the terminal, save them to the double array and output them
*/

int main(){
	double arr[5];
	// Total bytes / bytes occupied by a single double = array length
	int arrLen = sizeof(arr)/sizeof(double);
	int i;
	for(i=0; i<5; i++){
		printf("\n Please enter a decimal:");
		scanf("%lf",&arr[i]);
	}
	for(i=0; i<5; i++){
		printf("arr[%d] =%.2f",i,arr[i]);
	}
	getchar();//Filter enter
	getchar();
}

The effect is shown in the figure:

Array usage considerations and details

1. Array is a combination of multiple data of the same type. Once an array is declared / defined, its length is fixed and cannot change dynamically.

2. After the array is created, if there is no assignment, the following rules shall be followed

  • Global array default 0
  • The initial value of non global array is the machine garbage value = = (that is, the value allocated to this space by the original system)==

3. Step 1 of using arrays Define array 2, assign values to each element of the array, and use array, which can also be achieved in one step

4. The subscript of the array starts from 0, not 1

5. The array subscript must be used within the specified range. If it is compiled, it will be abnormally interrupted when the array is out of bounds: for example, the valid subscripts of int arr [5] are 0-4

6. The array of C belongs to the construction type and is passed by reference (the address is passed). Therefore, when an array is passed to a function / or variable, function / variable

The array operation will affect the original array

Application case of array:

1. Create an array of 26 elements of char type and place 'A' - 'Z' respectively. Use the for loop to access all elements and print them out== Prompt: = = character data operation 'A' + 1 - > 'B

#include <stdio.h>

int main(){
	char arr[26];
	int i;
	//Deposit
	for(i = 0; i <26; i++){
		arr[i] = 'A'+i;
	}
	// Print
	for(i = 0; i <26; i++){
		printf("\n %c",arr[i]);
	}
	getchar();
}

2. Request the maximum value of an array and get the corresponding subscript

#include <stdio.h>

int main(){
	int a[] = {1,2,3,7,4};
	int max =  a[0];
	int index = 0;
	int i;
	// Array length = Total Bytes / bytes occupied by a single double
	int len = sizeof(a)/sizeof(int);
	for(i=0; i<len; i ++){
		if(a[i]>max){
			max = a[i];
			index = i;
		}
	}
	printf("The maximum number in the array is%d,The subscript is%d",max,index);
	getchar();
}

Character arrays and strings

The array used to store characters is called character array,

A character array is actually a collection of a series of characters, that is, a string. In C language, there is no special string variable and no string type. Usually, a character array is used to store a string

Case:

1) char a[10]; //One dimensional character array with length of 10 

2) char b[5][10]; //Two dimensional character array. We will introduce two-dimensional array in detail later 

3) char c[20]={'c', ' ', 'p', 'r', 'o', 'g', 'r', 'a','m'}; // Assign values to some array elements

String considerations:

1. In C, strings are actually one-dimensional character arrays terminated with null characters ('\ 0'). Therefore, a null terminated string contains the characters that make up the string.

2. '\ 0' is the 0th character in the ASCII code table, expressed in NUL and called null character. This character can neither be displayed nor controlled. Outputting this character will not have any effect. It is only used as the end mark of the string in C language.

3. Layout analysis of character array (string) in memory

4. Think about what char str[3] = {'a','b','c'} outputs? Why?

Output abc# % #$%;

Reason: the end character \ 0 has no place to put

Solution: expand the array to str[4]

Conclusion:

When assigning a value to a character array, (1) if the number of assigned elements is less than the length of the array, it will be automatically followed by '\ 0', indicating the end of the string, (2) if the number of assigned elements is equal to the length of the array, it will not be automatically added '\ 0' char str2 [] = {t ','m', 'o'} what is the output? The output is tmo garbled code

Discussion on using character pointer variable and character array to represent string

1. The character array is composed of several elements, and each element puts a character; The character pointer variable stores the address (the first address of the string / character array). It is never to put the string into the character pointer variable (the first address of the string) [figure]

2. You can only assign values to each element of a character array. You cannot assign values to a character array in the following ways

char str[14];
str=" hello tom"; //error
str[0] = 'i'; //ok

3. It is possible to assign values to character pointer variables by the following methods

char* a="yes";
a=" hello tom";

4. If a character array is defined, it has a definite memory address (that is, the name of the character array is a constant); When defining a character pointer variable, it does not point to a certain character data, and can be assigned multiple times [code + diagram]

String correlation function

List of common string functions

Notes and details on the use of string (character array)

1. Programs often rely on detecting the position of '\ 0' to determine whether the string ends, rather than determining the length of the string according to the length of the array. Therefore, the string length will not count '\ 0', and the character array length will count [case]

2. When defining the character array, the actual string length should be estimated to ensure that the array length is always greater than the actual string length. Otherwise, unknown characters may appear when outputting the character array

3. The system also automatically adds a '\ 0' as the terminator to the string constant. For example, "C Program" has 9 characters in total, but takes up 10 bytes in memory. The last byte '\ 0' is added automatically by the system. (verified by sizeof() function)

4 when defining a character array, if the number of characters given is smaller than the length of the array, the system will set the remaining element space to '\ 0' by default. For example, char str[6] = "ab", and the str memory layout is [a][b][[a] [b] [\ 0] [\ 0] [\ 0] [\ 0]][[a] [b] [\ 0] [\ 0] [\ 0] [\ 0]][[a] [b] [\ 0] [\ 0] [\ 0] [\ 0]][[a] [b] [\ 0] [\ 0] [\ 0] [\ 0]]

5. There are many ways to define and initialize character arrays, such as

#include <stdio.h>

int main(){
	char str1[ ]={"I am happy"}; // Default followed by '\ 0'
	char str2[ ]="I am happy"; // Omit the {} sign and add '\ 0' after it by default
	char str3[ ]={'I',' ','a','m',' ','h','a','p','p','y'}; // The character array will not be followed by '\ 0', which may be garbled
	char str4[5]={'C','h','i','n','a'}; //The character array will not be followed by '\ 0', which may be garbled
	char * pStr = "hello"; //Yes, right!
	printf("str=%s",pStr);
	getchar();
}

Sort and find

Sorting is also called sort algorithm. Sorting is the process of arranging a group of data in a specified order.

Sort by:

1. Internal sorting:

It refers to loading all data to be processed into internal memory (memory) for sorting.

2. External sorting method:

The amount of data is too large to be loaded into memory, so it needs to be sorted with the help of external storage

Bubble sorting

The basic idea of Bubble Sorting is to compare the values of adjacent elements from front to back (starting from the elements with smaller subscripts) through the sequence to be sorted, and exchange if the reverse order is found, so that the elements with larger values gradually move from front to back, just like bubbles under the water

Because in the sorting process, each element is constantly close to its own position. If there is no exchange after a comparison, it indicates that the sequence is orderly. Therefore, it should be set in the sorting process
A flag flag determines whether elements have been exchanged. This reduces unnecessary comparisons

Law exploration:

Code implementation, first attempt

#include<stdio.h>
void main(){

	int arr[] = {3,9,-1,10,-2};

	// Round 1 sorting
	int j;
	int t; //Temporary variable
	for(j=0;j<4;j++){
		if(arr[j]>arr[j+1]){ //If the number in front is greater than that in the back, swap
			t = arr[j];
			arr[j] = arr[j+1];
			arr[j+1] = t;
		}
	}
	// After the first round of sorting, the results
	for(j=0;j<5;j++){
		printf("%d ",arr[j]);
	}

	printf("\n------------------------\n");

	// Round 2 sorting
	for(j=0;j<3;j++){
		if(arr[j]>arr[j+1]){ //If the number in front is greater than that in the back, swap
			t = arr[j];
			arr[j] = arr[j+1];
			arr[j+1] = t;
		}
	}
	// After the second round of sorting, the results
	for(j=0;j<5;j++){
		printf("%d ",arr[j]);
	}


	printf("\n------------------------\n");
	// Round 3 sorting
	for(j=0;j<2;j++){
		if(arr[j]>arr[j+1]){ //If the number in front is greater than that in the back, swap
			t = arr[j];
			arr[j] = arr[j+1];
			arr[j+1] = t;
		}
	}
	// After the third round of sorting, the results
	for(j=0;j<5;j++){
		printf("%d ",arr[j]);
	}

		printf("\n------------------------\n");
	// Round 4 sorting
	for(j=0;j<1;j++){
		if(arr[j]>arr[j+1]){ //If the number in front is greater than that in the back, swap
			t = arr[j];
			arr[j] = arr[j+1];
			arr[j+1] = t;
		}
	}
	// After the fourth round of sorting, the results
	for(j=0;j<5;j++){
		printf("%d ",arr[j]);
	}
	getchar();
}

Code implementation, further optimization and final results:

#include<stdio.h>
void main(){

	int arr[] = {3,9,-1,10,-2};

	int j;
	int i;
	int t; //Temporary variable
	int arrLen = sizeof(arr)/sizeof(int); //Length of array
	for(i=0;i<arrLen-1;i++){
		for(j=0;j<arrLen-1-i;j++){ //4 is decreasing
			if(arr[j]>arr[j+1]){ //If the number in front is greater than that in the back, swap
				t = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = t;
			}
		}
	}

	//result
	for(j=0;j<5;j++){
		printf("%d ",arr[j]);
	}
	getchar();
}  

Sequential search

#include<stdio.h>

int queryNum (int arr[], int len, int val){
	int i;
	for(i=0; i<len; i++){
		if(arr[i]==val){
			return i;
		}
	}
	return 1;
}
void main(){
	int arr[] = {1,2,3,4};
	int len =  sizeof(arr)/sizeof(int);
	int index = queryNum(arr,len,3);
	if(index == -1){
		printf("i 'm sorry! I can't find it");
	}else{
		printf("Found, subscript%d",arr[index]);
	}
	getchar();
}

Binary search

Prerequisite: must be an ordered array

#include<stdio.h>
// Binary search
int queryNum (int arr[], int leftIndex, int rightIndex	,int findVal){

	// First find the middle number midVal;
	int midIndex = (leftIndex + rightIndex)/2;
	int midVal = arr[midIndex];

	// If leftindex > rightindex, the array has been compared and not found
	if(leftIndex>rightIndex){
		return -1; 
	}
	// If midval > findval, it indicates that it should be found on the left
	if(midVal > findVal){
		queryNum(arr,leftIndex,midIndex-1,findVal);
	// If midval > findval, it indicates that it should be found on the left
	}else if(midVal > findVal){
		queryNum(arr,midIndex + 1,rightIndex,findVal);
	}else{
		return midIndex; // Once found, it is the middle number. Return the subscript of the middle number
	}

}
void main(){
	int arr[] = {1,2,3,4,6,10,11};
	int len = sizeof(arr)/sizeof(int);
	int index = queryNum(arr,0,len-1,51111);
	if(index != -1){
		printf("Found, array subscript is%d",index);
	}else{
		printf("Can't find!");
	}
	getchar();
}

Multidimensional array - 2D array

Quick start cases:

Please output the following graphics with a two-dimensional array

0 0 0 0 0 0 

0 0 1 0 0 0 

0 2 0 3 0 0 

0 0 0 0 0 0 
#include <stdio.h> 
void main() {
	//a[4][6]: represents a two-dimensional array with 4 rows and 6 columns 
	int a[4][6]; // If not initialized, it is the garbage value of allocated memory 
	int i, j; 
	//Initialize all 0 
	for(i = 0; i < 4; i++) { //Traverse rows first 
		for(j = 0; j < 6; j++) {//Traversal column 
			a[i][j] = 0; 
		} 
	}
	a[1][2] = 1; 
	a[2][1] = 2; 
	a[2][3] = 3; 
	//Output 2D array 
	for(i = 0; i < 4; i++) { 
		for(j = 0; j < 6; j++) { 
			printf("%d ", a[i][j]); 
		}
		printf("\n"); 
	}

	Look at the memory layout of a two-dimensional array 
	printf("\n Two dimensional array a First address of=%p", a); 
	printf("\n Two dimensional array a[0]Address of=%p", a[0]);
	printf("\n Two dimensional array a[0][0]Address of=%p", &a[0][0]); 
	printf("\n Two dimensional array a[0][1]Address of=%p", &a[0][1]); 
	printf("\n"); 
	for(i = 0; i < 4; i++) { 
		printf("a[%d]Address of=%p ", i, a[i]); 
		for(j=0; j < 6; j++) { 
			printf("a[%d][%d]Address of=%p ", i, j , &a[i][j]); 
		}
		printf("\n"); 
	}
	getchar(); 
}

Usage 2

 Type array name[size][size] = {{Value 1,Value 2..},{Value 1,Value 2..},{Value 1,Value 2..}}; 2) perhaps 
 Type array name[size][size] = { Value 1,Value 2,Value 3,Value 4,Value 5,Value 6 ..};

matters needing attention:

1. You can only assign values to some elements, and the unassigned elements will automatically take the "zero" value

2. If all elements are assigned values, the length of the first dimension may not be given

int a[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 

int a[][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

3. Two dimensional arrays can be regarded as nested by one-dimensional arrays; If each element of an array is another array, it is a two-dimensional array.

Two dimensional array a[3][4]It can be regarded as three one-dimensional arrays. Their array names are a[0],a[1],a[2]. 

These three one-dimensional arrays have four elements, such as one-dimensional array a[0] The element of is a[0][0],a[0][1],a[0][2],a[0][3]

breakpoint debugging

One practical requirement:

In the development, the programmer finds a very strange error, which cannot be found by looking at the source code. At this time, the old programmer will give a warm prompt that you can use breakpoint debugging to see the process of source code execution step by step, so as to find the error.

What is breakpoint debugging

Baidu Encyclopedia: breakpoint debugging refers to setting a breakpoint in a certain line of the program. When debugging, the program will stop running to this line, and then you can debug step by step. During the debugging process, you can see the current value of each variable. If there is an error, the error will be displayed when debugging to the wrong code line. Stop. The program can then analyze to find this.

Shortcut key

f5:  Start debugging and execute to the next breakpoint
f11: Execute code sentence by sentence, Will enter the function body
f10: Process by process execution(If a function is encountered, it will not enter the function body)
shift+f11: Jump out(Jump out of a function, Before jumping out, the function will be executed)
shift+f5: Terminate debugging

Pointer

The pointer represents an address (the address is stored), as shown in the following figure

//Introduction to pointer
# include <stdio.h>
void main(){
	int num = 1;
	int *ptr = &num;
	// Address of num
	// If you want to output the address of a variable, the format used is% p
	printf("num Your address is:%p",&num);
	printf("\n ptr Your address is:%p ,  ptr An address for storing values is:%p , ptr What is the value of the address pointed to%d: ",&ptr,ptr,*ptr);
	getchar();
}

Operation results:

Practice case:

//Introduction to pointer
# include <stdio.h>
void main(){
	//Write a program to obtain the address of an int variable num and display it to the terminal for the C language course of college students in Silicon Valley 
	//Assign the address of num to the pointer ptr, and modify the value of num through ptr 
	//Analyze that the type of ptr is int *. Note that the type of pointer corresponds to the type of variable pointed to by the pointer 
	//And draw the memory layout of the case 
	//int num = 88; 
	//int * ptr = # 
	First output num No modification 
	//printf("\nnum value =% D, Num address =% P", num, & Num)// num= 88 
	//*ptr = 99; //  Modify the value of num through PTR, and the value of num variable will be modified accordingly 
	//printf("\n num value =% D, Num address =% P", num, & Num)// num = 99 
	int a = 300; // a = 300 
	int b = 400; // b = 400 
	int * ptr = &a; //ok ptr points to a 
	*ptr = 100; // a = 100 
	ptr = &b; // ok ptr points to b 
	*ptr = 200; // b = 200 
	printf("\n a=%d,b=%d,*ptr=%d", a, b, *ptr); //a = 100, b = 200, *ptr = 200 
	getchar(); 
}

Pointer details

1. Basic types have corresponding pointer types in the form of data type *. For example, the pointer corresponding to int is int *, the pointer corresponding to float is float *, and so on.

2. In addition, there are pointers to arrays, structures, and common objects (secondary pointers, multi-level pointers). We'll talk about numbers later

Group, structure and common body will be explained in detail.

Value passing and address passing

1. Type of default transfer value: basic data type (integer type, decimal type, character type), structure and common body.

2. The default address passing (pointer passing) is similar to: pointer and array

Pointer operator

A pointer is an address represented by a numeric value. You can perform arithmetic operations on pointers. Four arithmetic operations can be performed on the pointer: + +, –, +, -.

Pointer increment operation (+ +)

#include<stdio.h>
const int MAX = 3;
int main () {
	int var[] = {10, 100, 200}; // 
	int i, *ptr; // 
	ptr = var;
	for ( i = 0; i < MAX; i++) {
		printf("var[%d] address= %p \n", i, ptr );
		printf("Stored value: var[%d] = %d\n", i, *ptr );
		ptr++;
	}
	getchar();
	return 0; 
}

Operation results:

Pointer increment operation (–)

#include<stdio.h>
const int MAX = 3;
int main () {
	int var[] = {10, 100, 200};
	int i, *ptr;
	/* The address of the last element in the pointer */
	ptr = &var[MAX-1];
	for ( i = MAX; i > 0; i--) {
		printf("ptr Address of storage=%p, var[%d] Address of= %p\n", ptr, i
			&var[i-1] );
		printf("Stored value: var[%d] = %d\n", i-1, *ptr );
		ptr--; }
	getchar();
	return 0;
}

Operation results:

Pointer+

#include<stdio.h>
int main () {
	int var[] = {10, 100, 200};
	int i, *ptr;
	ptr = var;
	ptr += 2; //
	printf("var[2]=%d var[2]Address of=%p ptr=%p ptr Content of the address pointed to=%d" ,var[2], &var[2], ptr, *ptr);
		getchar();
	return 0; 

}

Operation results:

Pointer array

Pointer to the address of the array element or other type of data to point to (int). You can use pointer arrays

Pointer array definition

data type *Pointer array name[size];
For example: int *ptr[3];

1. ptr is declared as an array of pointers
2. It consists of three integer pointers. Therefore, every element in ptr is a pointer to the int value.

quick get start

#include<stdio.h>
void main (){
	int var[] = {10, 100, 200};
	int i, *ptr[3];
	int MAX = 3;
	for ( i = 0; i < MAX; i++)
	{
		ptr[i] = &var[i]; /* Address assigned as an integer */ }
	for ( i = 0; i < MAX; i++)
	{
		printf("Value of var[%d] = %d\n", i, *ptr[i] );
	}
	getchar();
}

String pointer array

Please write a program to define a pointer array pointing to characters to store the string list (four famous book titles), and display the string information by traversing the pointer array (that is, define a pointer array, and each element of the array points to a string)

Code implementation:

#include<stdio.h>
void main(){
	char *books[] = {
	"Water Margin",
	"Romance of the Three Kingdoms",
	"Journey to the West",
	"The Dream of Red Mansion",
	"Water Margin"
	};
	int i ,len = 4;
	for(i=0; i<len; i++){
		printf("\nboos[%d]The string pointed to is<%s>",i,books[i] ); // No need to add*
	}
	getchar();

}

Multiple pointer

A pointer to a pointer is a form of multi-level indirect addressing, or a pointer chain. Usually, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, and the second pointer points to the position containing the actual value (as shown in the figure below)

#include<stdio.h>
int main () {
	int var;
	int *ptr;
	int **pptr;
	var = 3000;
	ptr = &var;
	pptr = &ptr;
	printf("var Address of=%p var = %d \n", &var, var );
	printf("ptr Your own address=%p ptr Address of storage=%p *ptr = %d \n", &ptr, ptr, *ptr );
		printf("pptr Self address = %p pptr Address of storage=%p **pptr = %d\n", &pptr, pptr, **pptr);
		getchar();
	return 0;
}

Function that returns a pointer

Please write a function strlong() to return the longer one of the two strings.

#include<stdio.h>
#include <string.h>
char *strlong(char *str1, char *str2){ //char * (pointer) returned by function
	printf("\nstr1 Length of%d str2 Length of%d", strlen(str1), strlen(str2));
		if(strlen(str1) >= strlen(str2)){
			return str1;
		}else{
			return str2;
		}
}
int main(){
	char str1[30], str2[30], *str;
	printf("\n Please enter the first string");
	gets(str1);
	printf("\n Please enter the second string");
	gets(str2);
	str = strlong(str1, str2);
	printf("\nLonger string: %s \n", str);
	getchar();
	return 0;
}

The results are shown in the figure below:

1. When using the pointer as the return value of the function, it should be noted that all local data defined inside the function will be destroyed after the operation of the function, including local variables, local arrays and formal parameters. The pointer returned by the function cannot point to these data [case demonstration]

2. After the function runs, all local data of the function will be destroyed. The so-called destruction here does not clear all the internal * * * * memory occupied by the local data, but the program gives up its permission, and the following code can use this memory

3. C language does not support returning the address of local variables when calling functions. If there is such a requirement, you need to define local variables as static variables

Function pointer

1. A function always occupies a continuous memory area, and the function name is sometimes converted into the first address of the memory area where the function is located in the expression, which is very similar to the array name.

2. Give the first address (or entry address) of the function to a pointer variable, so that the pointer variable points to the memory area where the function is located, and then the function can be found and called through the pointer variable. This pointer is a function pointer

returnType (*pointerName)(param list);

1, `returnType `Return value type for function

2,`pointerName `Is the name of the pointer

3,`param list` List of function parameters

4,The type and name of the parameter can be given in the parameter list at the same time, or only the type of the parameter can be given, and the name of the parameter can be omitted

5,be careful( )Priority over*,The first bracket cannot be omitted if writing r`eturnType *pointerName(param list);`It becomes the function prototype, which indicates that the return value type of the function is`returnType `

Demonstration case:

    #include<stdio.h>
    int max(int a, int b);
    int main(){
        int x, y, maxVal;
        // Description: function pointer	
        // Name of function pointer: pmax
        // Int means that the return value of the function pointer is of type int
        // (int, int) indicates that the function parameter pointed to by the function pointer accepts two ints
        // When defining a pointer function, you can also write the formal parameter name: for example - int (*pmax)(int x, int y) =max
        int (*pmax)(int, int) = max; 
        printf("Pleace input two numbers:");
        scanf("%d %d", &x, &y);
        maxVal = (*pmax)(x, y);
        printf("Max value: %d\n", maxVal);
        getchar();
        getchar();
        return 0;
    }
    int max(int a, int b){
        return a>b ? a : b;
    }

Callback function

1. A function pointer variable can be used as a parameter of a function. A callback function is a function called through a function pointer.

2. Simply put: a callback function is a function that you pass in when it is executed by someone else's function (through the function pointer)

Case demonstration:

#include<stdio.h>
#include <stdlib.h> 


	/*
		Callback function)
		f Is a function pointer, which can receive the function expression (return int, function without formal parameters)
	*/
void initArray(int *array, int arraySize, int (*f)(void)) {
	int i ;
	for ( i=0; i<arraySize; i++)
		array[i] = f(); // Loop 10 times and call back our getNextRandomValue(void) function
}
// Get random value
int getNextRandomValue(void) {
	return rand();  //System function, you can return a random integer!
}
int main(void) {
	int myarray[10],i;
	/*
		explain:
		1,Call initArray function
		2,Pass in a function name getnextrandomvalue (address), which needs to be introduced with function pointer
		initArray(myarray, 10, getNextRandomValue);

	*/
	initArray(myarray, 10, getNextRandomValue);
	for(i = 0; i < 10; i++) {
		printf("%d ", myarray[i]);
	}
	printf("\n");
	getchar();
	return 0;
}

1 pointer variables store addresses. From this point of view, the essence of pointers is addresses.

2 when declaring variables, if there is no exact address assignment, it is a good programming habit to assign a NULL value to the pointer variable.

3 a pointer assigned a NULL value is called a NULL pointer. A NULL pointer is a pointer defined in the standard library < stdio h> Constant with zero value in #define NULL 0

#include<stdio.h>
void main(){

	int *p = NULL; // Empty finger needle p
	int num =33;
	p = &num;
	printf("p= %d",*p);
	getchar();
}

4. Pointer usage list (see below)

Null pointer

A pointer assigned a NULL value is called a NULL pointer. A NULL pointer is a pointer defined in the standard library < stdio h> Constant with zero value in #define NULL 0

#include<stdio.h>
void main(){

	int *p = NULL; // Empty finger needle p
	int num =33;
	p = &num;
	printf("p= %d",*p);
	getchar();
}

Dynamic memory allocation

1. Global variable - static storage area in memory

2. Non static local variables -- dynamic storage area in memory -- stack stack

3. Temporarily used data - establish a dynamic memory allocation area, open it up at any time when needed, and release it in time when not needed - heap heap

4. Apply to the system for the space of the required size as required. Since it is not defined as a variable or array in the declaration part, these data cannot be referenced through the variable name or array name, but only through the pointer

Correlation function of dynamic memory allocation

1. Header file #include < stdlib h> Four functions about dynamic memory allocation are declared

2. Function prototype

 void * malloc(usigned int size) //malloc = memory allocation 
  • Function - allocate a continuous space of size in the dynamic storage area (heap area) of memory.
  • The type of formal parameter size is unsigned integer. The return value of the function is the address of the first byte of the allocated area, that is, the function is a pointer function, and the returned pointer points to the beginning of the allocated area.
  • malloc(100); Open up a temporary space of 100 bytes, and the return value is the address of the first byte

3. Function prototype

void *calloc(unsigned n,unsigned size)
  • Function - allocate n continuous spaces of size in the dynamic storage area of memory. This space is generally large enough to hold an array
  • calloc function can be used to open up dynamic storage space for one-dimensional array. n is the number of array elements, and the length of each element is size
  • The function returns a pointer to the starting position of the assigned field; Allocation failed, NULL returned.
  • p = calloc(50, 4); // Open up a temporary space of 50 * 4 bytes and allocate the starting address to the pointer variable P

4. Function prototype: void free (void *p)

  • Action - release the dynamic space pointed to by variable p so that this part of the space can be reused by other variables.
  • p is the return value of the function when the calloc or malloc function was last called
  • The free function has no return value
  • free§; // Free the allocated dynamic space pointed to by p

5. Function prototype void *realloc (void *p, unsigned int size)

  • Function - reallocate the dynamic space size obtained by malloc or calloc function, change the dynamic space size pointed to by p to size, keep the value of p unchanged, and return NULL if allocation fails
  • realloc(p, 50); // Change the allocated dynamic space pointed to by P to 50 bytes

6. Return type description

C99 standard locates the basic types of malloc, calloc and relloc functions as void type. This kind of pointer is called typeless pointer, which means that it does not point to a specific type of data, only provides a storage address, and does not point to any specific object.

Application examples

Dynamically create an array, input the scores of 5 students, and another function will output unqualified scores if the score is less than 60

Code implementation:

structural morphology

Mrs. Zhang has two cats: one is Xiaobai, 3 years old, white. There is also a flower named Xiaohua, 100 years old this year. Please write a program to display the name, age and color of the kitten when the user enters the name of the kitten. If the kitten name entered by the user is wrong, it will show that Mrs. Zhang doesn't have the kitten

Current knowledge - traditional program:

void main() {
char cat1Name[10] = "Xiaobai";
int cat1Age = 3;
char cat1Color[10] = "white";


char *catsName[2] = {
	"Xiaobai",
	"floret"
} ;
int catsAge[] = {3,100}

Disadvantages:

It is not conducive to data management and maintenance, because the three attributes of the cat (name, age and color) are a whole. It will be disassembled in the traditional way, which requires the use of structure!

Structure quick start

Schematic diagram of the relationship between structure and structure variables

==Note: = = in addition to Cat structure, there can also be Person structure, Fish structure, etc

Schematic diagram of the relationship between structure and structure variables

Quick start - object oriented approach (struct) to solve the problem of raising cats

Code implementation:

#include<stdio.h>
void main(){

	struct Cat{ //The structure is called cat. Cat is a data type formed by ourselves!
		char *name; // Name, using a pointer to point to a string
		int age; // Age
		char *color; // colour
	};

	// Using the structure, create the corresponding variable
	struct Cat cat1; 
	
	cat1.name ="Xiaobai";
	cat1.age = 3;
	cat1.color = "white";


	// Using the structure, create the corresponding variable
	struct Cat cat2; 
	cat2.name ="floret";
	cat2.age = 100;
	cat2.color = "Decor";

	// Output information of two cats
	printf("\n First cat name = %s age= %d color = %s",cat1.name,cat1.age,cat1.color);
	printf("\n The second cat name = %s age= %d color = %s",cat2.name,cat2.age,cat2.color);
	getchar();
}

Differences and relations between structure and structure variables

A struct is a custom data type that represents a data type

Structural variables represent a specific variable, such as

nt num1 ; // Int is a data type, and num1 is a concrete int variable
struct Cat cat1; // Cat is a structure data type, while cat1 is a cat variable

Cat is like a "template". The defined structure variables contain the same members. You can also compare the structure to "drawing" and the structure variable to "part". The characteristics of parts produced according to the same drawing are the same

Structure memory analysis:

Declaration structure

struct Structure name { // Structure names are capitalized, such as cat and person
	Member list; 
}

give an example:

#include<stdio.h>
void main(){
	struct Student{
		char *name; //full name
		int num; //Student number
		int age; //Age
		char group; //Study Group
		float score; //achievement
		//Members can also be structures

	};
}

Notes and details

1. The syntax of member declaration is the same as that of variable. Example: data type member name;
2. The types of fields can be: basic type, array or pointer, structure, etc
3. After creating a structure variable, you need to assign a value to the member. If you use it without assignment, it may lead to abnormal termination of the program. [case demonstration]:

#include<stdio.h>
void main(){
	struct Cat{ // It is recommended to capitalize the structure name
		char *name; //Name. Pointer type is required here
		int age; //Age
		char *color; // colour
	}; 
	struct Cat cat1;
	printf("\n name=%s Age=%d colour=%s ", cat1.name, cat1.age, cat);
	getchar();
}

4. The members of different structural variables are independent and do not affect each other. The change of the members of one structural variable does not affect the other. [case demonstration + Monster]

Create structure and structure variables

Method 1 - first define the structure, and then create the structure variable

#include<stdio.h>
void main(){
	struct Stu{
		char *name; //full name
		int num; //Student number
		int age; //Age
		char group; //Study Group
		float score; //achievement
	};
	struct Stu stu1, stu2;
	//Two variables stu1 and stu2 are defined, both of which are Stu types and are composed of five members
	//Note that the keyword struct cannot be less
}

Method 2 - define structure variables while defining structure

#include<stdio.h>
void main(){
		struct Stu{
		char *name; //full name
		int num; //Student number
		int age; //Age
		char group; //Study Group
		float score; //achievement
	} stu1, stu2;
	//While defining the structure Stu, two structure variables stu1 and stu2 are created
}

Method 3 - if only stu1 and stu2 variables are required, the structure data type is no longer required. Other variables can be defined without giving the structure name

struct { //Did not write Stu
char *name; //full name
int num; //Student number
int age; //Age
char group; //Study Group
float score; //achievement
} stu1, stu2;
stu1.name = "tom"; stu1.num = 100;....
//1. The data type of this structure has no name and is anonymous
//2. stu1 and stu2 are the two variables of the structure

Case 2:

#include<stdio.h>
void main(){
	struct{
		char *name; //full name
		int num; //Student number
		int age; //Age
		char group; //Group
		float score; //achievement
	} stu1 = {"Jia Baoyu", 11, 18, 'B', 90.50}, stu2 = { "Lin Daiyu", 12, 16, 'A', 100 };
}

Application case

1. Write a Dog structure, including name(char[10]), age(int) and weight(double) attributes

#include<stdio.h>

struct Dog{
	char *name;
	int age;
	double weight;
};

// say function
char *say(struct Dog dog){
	// Put this information into a string
	static char info[100]; // local variable
	sprintf(info, "name=%s age = %d weight = %.2f",dog.name,dog.age,dog.weight);
	return info;
}

void main(){
	//Define structure variables
	struct Dog dog = {"He Jingjing",18,99.9};
	char* info = NULL;
	info = say(dog);
	printf("The dog information is:%s",info);
	getchar();
}

Scenic spot ticket cases:

2. Please compile the visitor structure, determine the ticket price that can be purchased according to the age and output it

3. Rules: if the age is > 18, the ticket is 20 yuan, and other circumstances are free.

4. You can cycle to input the name and age from the console and print the ticket charge. If you enter n for the name, you will exit the program.

#include<stdio.h>
#include<string.h>
//Define structure 
struct Visitor { 
	char name[10]; 
	int age; 
	double pay; //Fare payable 
}; 
void ticket(struct Visitor * visitor) { 
	//judge 
	if( (*visitor).age > 18) { 
		(*visitor).pay = 20; 
	} else { 
		(*visitor).pay = 0; 
	} 
}

void main() { 
	//test 
	//Create structure variable (create a visitor) 
	struct Visitor visitor; 
	//Enter the name and age of the loop 
	while(1) { 
		printf("\n Please enter the tourist name"); 
		scanf("%s", visitor.name); 
		//Judge if the name is n, exit the program 
		if(!strcmp("n", visitor.name) ) { 
			break; 
		}
		printf("\n Please enter the age of the tourist"); 
		scanf("%d", &visitor.age);
		//Call the function ticket to obtain the payable ticket price 
		ticket(&visitor); 
		printf("\n The tourist should pay the fare=%.2f", visitor.pay); 
	}
	printf("Exit program"); 
	getchar(); 
	getchar(); 
}

Box case:

Program to create a Box structure, in which three members are defined to represent the length, width and height of a cube. The length, width and height can be input through the console. Define a function to get the volume of the cube. Create a structure and print the volume of a cube of a given size.

Common body

There is a form about student information and teacher information. Student information includes name, number, gender, occupation and score, while teacher information includes name, number, gender, occupation and teaching subject. Please see the table below:

Traditional way to solve:

struct Person{
char name[20];
int num;
char sex;
char profession;
float score; // Students use score
char course[20]; // The teacher uses course 
};

It will cause a waste of space. For example, students only use score, but it also takes up 20 bytes of course members

Solution

(1) , do struct Stu and struct Teacher [but if there are many occupations, it will correspond to multiple structure types, which is not conducive to management

(2) . use common body

What is a community

1. A Union is a construction type that can contain multiple members of different types. It is very similar to the structure, but there are also differences
A consortium is sometimes called a consortium or a consortium, and the definition format is as follows:

union Common body name{
	Member list
};

The difference between a structure and a common body is that each member of the structure will occupy different memory and have no influence on each other; All members of the community occupy the same memory. Modifying one member will affect all other members

quick get start

There are three ways to define common body types and common body variables (the same as structure)

1: Define the community first, and then create the community variable

union data{
int n;
char ch;
double f;
};
union data a, b, c;

2: Common body variables are created while defining common bodies

union data{
int n;
char ch;
double f;
} a, b, c;

3: Anonymous community

union{
int n;
char ch;
double f;
} a, b, c;

Case demonstration:

#include<stdio.h>

union data{  // Data is a common body data type. Three members share a data space. The size of the space is subject to the largest member
	int n; // 4 bytes
	char ch; // 1 byte
	short m; // 2 bytes
};
void main(){
	union data a; // Define a common variable a
	printf("%d  --  %d\n",sizeof(a),sizeof(union data)); // 4 bytes
	a.n = 0x40; // Hexadecimal
	printf("%d, %c, %d\n", a.n, a.ch, a.m);
	a.ch = '9';
	printf("%d, %c, %d\n", a.n, a.ch, a.m);
	a.m = 0x2059;
	printf("%d, %c, %d\n", a.n, a.ch, a.m);
	a.n = 0x3E25AD54;
	printf("%d, %c, %d\n", a.n, a.ch, a.m);
	getchar();

}

Analysis of common memory layout

To deeply understand why the results of the previous case output, we need to analyze how the common body is arranged in memory

Case practice

There is a form about student information and teacher information. Student information includes name, number, gender, occupation and score, while teacher information includes name, number, gender, occupation and teaching subject. Please look at the table below - please use common programming to complete

#include<stdio.h>
#define TOTAL 2 / / total number of personnel

// Defines a structure Persion, which contains an anonymous common body sc
struct Person{
	char name[20]; // name
	int num;// number
	char sex; // Gender f = female m = male
	char profession; // Occupation s = > Student t = > teacher
	union{ //sc is a common variable
		float score;
		char course[20];
	} sc;
};
void main(){
	int i;
	struct Person persons[TOTAL]; // Defines an array of structs
	//Enter personnel information
	for(i=0; i<TOTAL; i++){
		printf("Please input infomation: ");
		scanf("%s %d %c %c", persons[i].name, &(persons[i].num), &(persons[i].sex), &(persons[i].profession)); // For int and char characters, you need to prefix & to get the address
		if(persons[i].profession == 's'){ //If it's a student
			printf("Please input the student's score:");
			scanf("%f", &persons[i].sc.score);
		}else{ //If it's a teacher
			printf("Please input the teacher's course");
			scanf("%s", persons[i].sc.course);
		}
		fflush(stdin); // Refresh input
	}

	// Output member information
	printf("\nName\t\tNum\tSex\tProfession\tScore / Course\n");
	for(i=0; i<TOTAL; i++){
		if(persons[i].profession=='s'){
			printf("\n%s\t\t%d\t%c\t%c\t%f\n",persons[i].name,persons[i].num,persons[i].sex,persons[i].profession,persons[i].sc.score);
		}else{
			printf("\n%s\t\t%d\t%c\t%c\t%s\n",persons[i].name,persons[i].num,persons[i].sex,persons[i].profession,persons[i].sc.course);
		}
	}
	getchar(); // Go back 
	getchar();
}

CRM system (project)

#include <stdio.h>
#include <string.h>

struct Customer {
	int id;
	int age;
	char name[10];
	char gender;
	char  phone[10];
	char  email[10];
};
char key ;
char loop=1;
int customerNum=1;


//Customer structure array
struct Customer customers[20];

//Get a customer's information
void getInfo(struct Customer *customer) {
	
	/*sprintf(info, "\n%d\t%s\t%c\t%d\t%s\t%s", (*customer).id, (*customer).name, 
		(*customer).gender, (*customer).age, (*customer).phone,(*customer).email);*/
	printf("\n%d\t%s\t%c\t%d\t%s\t%s", (*customer).id, (*customer).name, 
		(*customer).gender, (*customer).age, (*customer).phone,(*customer).email);
}

//Provide various operations


//1. Add
void add(){
	//Automatic number growth
	customers[customerNum].id = customerNum + 1;
	printf("\n---------------------Add customer---------------------");
	printf("\n full name:");
	scanf("%s", customers[customerNum].name);
	getchar();
	printf("\n Gender:");
	scanf("%c", &(customers[customerNum].gender));
	getchar();
	printf("\n Age:");
	scanf("%d", &(customers[customerNum].age));
	getchar();
	printf("\n Telephone:");
	scanf("%s", customers[customerNum].phone);
	getchar();
	printf("\n Email:");
	scanf("%s",customers[customerNum].email);
	getchar();
	printf("\n---------------------Add complete---------------------");
	customerNum++;
	
}

//Find the corresponding subscript according to the entered id. if not, return - 1
int findIndex(int id){
	int index = -1;
	int i;
	for (i = 0; i < customerNum ; i++) {
		if (customers[i].id == id) {
			index = i;
			break;
		}
	}
	return index;
}

//2. Delete customer
int del(int id){
	//Find the element subscript corresponding to id
	int index = findIndex(id);
	int i;
	if (index == -1) {
		return 0;//Indicates that this customer does not exist
	}else {
		//Once found, move forward as a whole from index+1
		for (i = index + 1; i < customerNum; i++) {
			customers[i - 1] = customers[i];
		}
		--customerNum;
		return 1;
	}
}

//Display part

//1. Show all
void showList(){
	int i = 0;
	printf("\n---------------------------Customer list---------------------------");
	printf("\n number\t full name\t Gender\t Age\t Telephone\t mailbox");
	for (i = 0; i < customerNum; i++) {
		getInfo(&customers[i]);
	}
}

//2. Complete the delete interface
//---------------------Delete customer---------------------
//Please select the customer number to be deleted (- 1 exit): 1
//Confirm to delete (Y/N): y
//---------------------Delete complete---------------------

void delView(){
	int id;
	char choice = ' ';
	printf("\n---------------------Delete customer---------------------");
	printf("\n Please select the customer number to be deleted(-1 sign out): ");
	scanf("%d", &id);
	getchar();
	if (id == -1) {
		printf("\n---------------------Deletion not completed---------------------");
		return;
	}

	printf("Confirm whether to delete(Y/N): ");
	scanf("%c", &choice);
	getchar();
	if (choice == 'Y') {
		if(del(id)){
			printf("\n---------------------Delete complete---------------------");
		}else{
			printf("\n---------------------Deletion is not complete, no such id---------------------");
		}
	} 
}


//3. Main menu
void mainMenu() {
	do {
		printf("\n-----------------Customer information management software-----------------");
		printf("\n                 1 Add customer");
		printf("\n                 2 Modify customer");
		printf("\n                 3 Delete customer");
		printf("\n                 4 Customer list");
		printf("\n                 5 retreat          Out");
		printf("\n Please select(1-5):");
		scanf("%c", &key);
		getchar();

		switch (key) {
		case '1':
			add();
			break;
		case '2':
			break;
		case '3':
			delView();
			break;
		case '4':
			showList();
			break;
		case '5':
			loop = 0;
			break;
		default:
			printf("\n Input error, please re-enter");
			break;
		}

	} while (loop);

	printf("\n You have successfully exited the system....");
	getchar();
}


void main() {
	For testing convenience
	customers[0].id = 1;
	customers[0].age = 18;
	strcpy(customers[0].email , "shiye13@foxmail.com");
	customers[0].gender = 'f';
	strcpy(customers[0].name , "Ye shisan");
	strcpy(customers[0].phone , "110");

	mainMenu();

	return ;
}

File operation

Files are not unfamiliar to us. Files are a kind of data source (where data is stored), such as word documents, txt files, excel files... Which are often used by everyone. File most

The main function is to save data. It can save not only a picture, but also video and sound

Files are operated in the form of streams in programs

Stream: the path of data between the data source (file) and the program (memory)

Input stream: the path of data from data source (file) to program (memory)

Output stream: the path of data from program (memory) to data source (file)

C standard library - stdio H the header file defines three variable types, some macros and various functions to execute input and output, which can be queried during the development process

C Input & output

1. When we talk about input, this means writing some data to the program. The input can be in the form of a file or from the command line. C language provides a series of built-in functions

Number to read the given input and write it into the program as needed.

2. When we talk about output, this means displaying some data on the screen, on the printer, or in any file. C language provides a series of built-in functions to output data to the meter

On the computer screen and save data to a text file or binary file

Standard documents

==C language treats all devices as files. Therefore, devices (such as displays) are processed in the same way as files== The following three files are automatically opened during program execution to access the keyboard and screen

2. The file pointer is the way to access the file. We will explain how to read the value from the screen and how to output the result to the screen.

3. I/O (input / output) in C language usually uses printf() and scanf () functions. The scanf() function reads and formats from standard input (keyboard)

The printf() function sends formatted output to standard output (screen)

Case demonstration, output the content to the screen

#include <stdio. h> / / this library is required to execute printf() function
int main()
{
	printf("hello"); //Show contents in quotation marks
	return 0;
}

getchar()&putchar()

getchar()

The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only one single word at a time

Symbol. You can use this method within a loop to read multiple characters from the screen.

putchar()

The int putchar(int c) function outputs characters to the screen and returns the same characters. This function will only output a single character at a time.

You can use this method within a loop to output multiple characters on the screen

Test case

#include <stdio.h> 
int main()
{	
	int c;
	printf("Please enter a value:"); 
	c = getchar(); // Read a char and return an int
	printf("\nYou entered: ");
	putchar( c );// Can be displayed on the screen
	printf("\n");

	getchar(); // Filter enter
	getchar(); // Stop interface
	return 0;
}

gets() & puts()

gets()

1. The char *gets(char *s) function reads a line from stdin to the buffer pointed to by s until a terminator or EOF.

puts()

2. The int puts(const char *s) function writes the string s and a trailing newline character to stdout.

Application case:

#include <stdio.h>
int main( )
{
	char str[100];
	printf( "Please enter a character :");
	gets( str );
	printf( "\nYou entered: ");
	puts( str );
	getchar();

	return 0;
}

scanf() and printf()

1,int scanf(const char *format, ...) The function reads the input from the standard input stream stdin and browses the input according to the provided format.

2, int printf(const char *format, ...) The function writes the output to the standard output stream stdout and generates the output according to the provided format.

3. format can be a simple constant string, but you can specify% s,% d,% c,% f, and so on to output or read strings, integers, characters, or floating-point numbers. There are many other formatting options available that you can use as needed. For complete details, check the reference manuals for these functions. Now let's deepen our understanding through the following simple example

Application example:

When you enter a text and press enter, the program reads the input, but the format is required to match

#include <stdio.h>
int main( ) {
	char str[100];
	int i;
	printf( "please input  a value :");
	scanf("%s %d", str, &i);
	getchar(); // Filter enter
	printf( "\nYou entered: %s %d ", str, i);
	printf("\n");
	getchar(); // Interface stop
	return 0;
}

C file reading and writing

1. Explain the standard input and output equipment of C language processing. We will show you how to create, open, and close text files or binaries.

2. A file, whether it is a text file or a binary file, represents a series of bytes. C language not only provides access to top-level functions, but also provides bottom-level (OS) calls to process files on storage devices. (important)

Open file

Use fopen() function to create a new FILE or open an existing FILE. This call will initialize an object of type FILE, which contains the

There is the necessary information to control the flow. The following is the prototype of this function call:

FILE *fopen( const char * filename, const char * mode );

explain:

1. ilename is a string used to name the file

2. The value of access mode can be one of the following values:

If you are dealing with binary files (pictures, videos...), you need to use the following access modes: "rb", "wb", "ab", "rb +", "r+b", "wb +", "w+b", "ab +", "a+b" / / B: binary binary

Close file

int fclose( FILE *fp );

1. The fclose() function returns zero if the file is successfully closed, and EOF if an error occurs when the file is closed. This function actually empties the buffer

According to, close the file and free all memory for the file. EOF is defined in the header file stdio Constant in H.

2. C standard library provides various functions to read and write files by characters or in the form of fixed length strings.

3. After using the file (read, write), be sure to close the file

write file

The following is a function that writes characters to the stream

int fputc( int c, FILE *fp );

explain:

The function fputc() writes the character value of parameter c to the output stream pointed to by fp. If the writing is successful, it will return the written character, and if an error occurs, it will return EOF.

You can use the following function to write a null terminated string to the stream:

int fputs( const char *s, FILE *fp );

explain:

The function fputs() writes the string s to the output stream pointed to by fp. It returns a non negative value if the write is successful and EOF if an error occurs. You can also

Use the int fprintf(FILE *fp,const char *format,...) function to write a string into a file

Application case:

#include <stdio.h>
int main( ) {
	FILE *fp = NULL;
	fp = fopen("d:/a.txt","w+");  //w + overwrites the original content without adding
	// Write content to file
	fprintf(fp,"Hello, it's ye shisan\n");
	fputs("Hello, Hu Jiani\n",fp);

	//close file ,if we not close the file,our content is not saved to the file
	fclose(fp);
	printf("Create and write information");
	getchar();
}

read file

The following is a function to read a single character from a file

int fgetc( FILE * fp );

explain:

The fgetc() function reads a character from the input file pointed to by fp. The return value is the read character. If an error occurs, EOF is returned.

The following function reads a string from the stream:

char *fgets( char *buf, int n, FILE *fp );

1. Description: the function fgets() reads n - 1 characters from the input stream pointed to by fp. It copies the read string to the buffer buf and appends a null character at the end to terminate the string. If this function encounters a newline '\ n' or EOF at the end of the file before reading the last character, it will only return the read characters, including the newline character.

2. You can also use int fscanf(FILE *fp, const char *format,...) Function to read a string from a file, but it stops reading when the first space character is encountered

Application case:

#include <stdio.h>
int main( ) {
	// Create a file pointer
	FILE *fp = NULL;
	// Define a buffer
	char buff[1024];
	// Open file
	fp = fopen("d:/a.txt","r");
	// Method 1: read a line from the file pointed to by fp to buff
	//fscanf(fp,"%s",buff);
	//printf("%s\n",buff);
	//getchar();
	// Method 2: read the whole file from the file pointed to by fp to buff
	/*
			Note: the loop reads the contents of the file pointed to by fp. If it reads NULL, it ends
	*/
	while(fgets(buff,1024,fp)!=NULL){
		printf("%s",buff);
	}
	// closed file
	fclose(fp);
	getchar();
}

author

The same name of the whole network: ye shisan

This article has been included in GitHub Open source warehouse[ Ye13]: Click jump

To get more information about programming, you can collect the open source project of star 13, or you can follow the official account of star 13!

Tags: C C++ C# Programming

Posted by kuma on Mon, 09 May 2022 01:56:03 +0300