[learning notes] Introduction to the basics of C language - this one is enough!

This article is a summary of the author's notes in the process of learning C language. It will briefly describe the basic knowledge of C language. The content is clear and easy to understand. I believe you can easily learn the basic knowledge of C language. At the same time, I hope this article will help you. I believe you will succeed. Now let's have a look!

preface

As the most popular programming language at present, C language has the characteristics of good portability, functional diversity, execution efficiency and efficiency, and is deeply loved by developers.
Now, follow this article, let's learn C language together!

There are many contents. If you think this article can help you, don't forget to like Collection + attention.
Tip: the following is the main content of this article. The following cases can be used for reference.

1, The first C language program

As the saying goes: water developers, iron "Hello World." Many developers say hello to this beautiful world in the first sentence of code. When we start to get started with C language, let's also output "Hello World" in C language!

# include <stdio.h>
int main() {
	printf("Hello world\n");
	return 0;
}

A simple 5 lines of code can simply complete the operation of a developer saying hello to the world. So what does the code above mean? We are divided into two parts, including # include and int main() {}. Let's discuss and understand the following!

Part I:

# include <stdio.h> Yes indicates that the header file stdio. Is about to be imported H is usually written at the beginning of the file, indicating < preprocessing before compilation > which will be explained in detail later.

So why is it written include And?
include Including, can we understand that this document will be included soon?
Therefore, in the future, we will introduce a header file, which needs to be written at the beginning# Include means to include [this document]

that stdio.h What is your header file for?
If we put stdio.h If you split the file name, you may well understand its usefulness.
stdio.h >>> Standard +input +output =Standard output mode. [.h]Is the suffix of the header file
 This is a standard input / output header file. If we need to use it later, for example printf(),scanf()We need to introduce this header file. For example, we use it printf()Operation of.
meanwhile stdio.h The file function also includes file access and binary input/Output, formatted and unformatted input/Output, file location, error handling, file operation, etc.].
And, circle stdio.h Angle brackets for<>,Angle brackets indicate the content and are required!

To sum up, the first part # include <stdio.h> = = stdio will be introduced into the code to be executed H file

Part II

Part II int main(){  }Is to define a main function.
Its standard format should be:
int main() {
	return 0;
}
Among them, main Yes means that this is a main function, in C There is one and only one language program main Main function; because main The main function is C Language program entry.
C Language program by main Function, also by main The function ends when it runs. therefore main There is only one main function!
additional int main Medium int Is an integer function, which means that the return value of the function is an integer value.
Maybe you'll find that it always ends with a semicolon(;). stay C In languages, semicolons(;)Represents the end of the statement;

return It means to return, so here return 0;It corresponds to the previous sentence int main Returns an integer value.
return At the same time, it means that the function will stop when it runs here,And return the result content. return It supports not only the return of integer values, but also the return of expressions (not to be repeated here, please find the experience).

Braces{}Indicates the action area. The area enclosed by braces indicates the area of the function. If it exceeds the area, it will not be counted as the area of the function. The position of braces can be arbitrary without specific requirements.
In parentheses, we write printf(),printf yes C The standard output function in the language corresponds to outputting the content to the controller.\n Indicates line feed, which will also be explained in the following content.

To sum up, the representation in the second part defines a main function, and the contents in braces represent the contents to be executed by the function, return Indicates that the operation stops.

2, C language: explanation of compilation preprocessing

File contains: # include

C In language,# The number represents an instruction.# include It means that in the code to be executed, it will be introduced xxx Content. for example# include<stdio.h>
<stdio.h>  Is a file, which means  Standard +input +output =Standard output mode, angle brackets represent the content, which is required!
To sum up # include <stdio.h> = = stdio will be introduced into the code to be executed H file

Macro definition: # define

#define macro definitions are usually used in programs to replace the contents of specified constants

If defined in the program: #define N 100
When the compiling system preprocesses the C source program, replace N with 100, and replace with 100 as long as N is encountered.

Macro definition command∶ #define RES 30-5, then the value of expression RES*5+30 is 35
	RES*5+30=30-5*5+30=30-25+30=35

With macro definition∶#define TESTC) yy, then the value of the expression TEST (4-2) is 6
	TEST(4-2)Replaced with 4-2*4-2=4-8-2=-6
additional
 stay VSCode Required in scanf Errors may be reported directly. You can use the macro definition to put it in front of the program to avoid errors:
# define _CRT_SECURE_NO_WARNINGS 1

3, C language: identifier

The name of the identifier concept: (variable, function, array)

Naming rules:

  1. With letters or underscores () start;

  2. Only letters, numbers and underscores ();

  3. Different case from keyword

  4. Different keywords

C language identifier: Keyword

autointdoublelongcharfloatshortsigned
unsignedstructunionenumstaticswitchcasedefault
breakcontinueregisterconstvalatiletypedefexternreturn
voiddowhileifelseforgotosizeof

C language identifier: data type

There are three basic data types in C language: integer (integer), real (decimal / floating point number) and character.

Each data type has constants and variables

Data type: description of name and occupied bytes

data typeType nameCorresponding output modeOccupied bytes
characterchar%c1
integerint%d2/4
integershort%d2
integerlong%d4
integerlong int%d4
integerlong long%d8
Real typefloat%f (exact n decimal places:%. nf)4
Real typedouble%lf (exact n decimal places:%. nlf)8

Data type: bytes occupied by calculation content sizeof()

sizeof() function, used to find the number of bytes occupied by the contents in parentheses.
Small tips: if you need to use sizeof() function, you need to use the header file string h. At this time, we need to compile preprocessing and introduce string H documents.

For example:

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

sizeof(char) // output : 1

Data type: constant

Generally speaking, what we want to express is called a constant

Character constant: character constant

  • A character 'a', '2' and '!' enclosed in single quotation marks;
  • Control characters enclosed in single quotation marks;
  • The character constant takes 1 byte
Legal character constant:
'\n','1','a'
// Literal constant
int main(){
	'3'  // If there is no direct definition of content, it is called a literal constant
	'a'  // If there is no direct definition of content, it is called a literal constant
	return 0;
}

Character constant: string constant

  • Character combination enclosed in double quotation marks' 123 'and' abcd ';
  • '\ 0' indicates the end of the string, \ 0 takes 1 byte, and the program adds \ 0 at the end by default.
Legal string constant
"boy","i am a boy","when i was young"

Calculate the number of bytes occupied by the character constant:
For example: String"boy\0s"
The number of bytes occupied in memory is 4, where b+o+y+\0=1+1+1+1=4. because s stay\0 After that, it is not included in the string.

char s="\t\"Name\Address\"\n"
When sizeof(s)When, the output value is 17
 Of which:\t =1,\"=1,Name=4,\=1,Address=7,\"=1,\n=1
1+1+4+1+7+1+1+1=17

Data type: variable

Variable definition rules
  • All variables must be defined before use;
  • Definition method: variable data type and variable name;
  • Assignment: variable name = constant;
  • Definition initialization: type variable name = constant;
  • Continuous assignment must ensure that = the left is the variable.

For example:

// Define before assign
char a1;
a1 ='From here to University'

// Continuous definition
int x1,y1;

// Simultaneous definition + assignment
float y2=5.28;
int x2=5,y2=-9;

// Continuous definition assignment
double y3=x3=3;

// In addition, if there is a variable 
int a,b; b=a=3,5;

//After execution, the values of a and b are 3 and 3 respectively
//Because b = a = 3, 5 is defined; Yes means b equals a equals 3, where 5 does not work.

C language: extern calls variables of other project files

If a variable has been defined in other files in the project, we can use the extern keyword to call variables in other files.

Keyword extern, which can reference variables or functions defined in another file in one file.

For example:

# include<stdio.h>
// Suppose there is a file t.c
int num = 10;

// Suppose there is a file main c
int main(){
	extern int num;
	printf("%d",num);
	return 0;
}

C language: const constant variable that cannot be modified

Among the variables we usually define, we can modify the contents of their constants.

Now we will introduce a variable that cannot be modified: const constant variable

int main(){
	const int n = 10;  // A constant variable is defined, and const is used to represent a constant variable
	// The defined constant variable cannot be modified
	n = 20; //The program will report an error here because the value of n cannot be modified
	return 0;
}
  • If a variable whose constant cannot be changed, we call it a constant variable.
  • If a variable becomes a constant variable, the constant of the variable has a constant attribute.

C language: enumeration type (enumeration constant)

Enumeration type is a special type in C language;

Enumeration type allows our program to use some variable value ranges with fixed length and fixed value;

The enumeration type contains the constant contents that we need to enumerate one by one (it can be imagined that this is a container with constants);

Methods to define enumeration types:

enum enumeration type {enumeration value list};

For example:

enum month{
	// The variables put into the enumeration table will be assigned with constants of 0 1 2 3 by default
	// Corresponding to n enumeration constants, it is assigned to n-1.
	
	January, 
	February, 
	March, 
	// We can also assign new constant content to the content
	April = 4, 
	May = 5, 
	June = 7,
};
// How should we use it?
int main(){
	enum month Jan = January;
	enum month June = 6;
	printf("Jan = %d\n",Jan);
	printf("Feb = %d\n",February);
	printf("Mar = %d\n",March+1);  //Normal addition and subtraction can also be done
	printf("Jun = %d\n",June) // You can modify the content of the value
	return 0;
}

C language: scope {}

introduce

Variable classification
- Local variable: the scope is the local range of the variable;
- Global variable: the scope is within the whole project;

Try not to have the same name for local variables and global variables;
[When the local variable is the same as the global variable, the local variable takes precedence];

Declaration of local variables

# include<stdio.h>
int main() {
	int num = 10;  // A variable in a function is a local variable that can be used in a function.
	printf("%d",num);
	
	{
	int num2 = 20;  // The variable in a bracket is a local variable and can be used in brackets.  
	}
	return 0;
}

Declaration of global variables

# include<stdio.h>

int num = 10;  // The variables defined on the periphery of the function are called global variables, which can be used arbitrarily within the program.

int main(){
	printf("%d",num);
	return 0;
}

When is the execution life cycle of a variable? Next, we will introduce the concept of scope, which will make it easier for you to understand the life cycle of variable execution. Then let's have a look!

In code written in C language, the area circled by braces {} usually represents the scope

Through the above examples, we can observe that the main function will surround the content with curly braces {}, which is the execution area of the function. We can understand that the scope is the meaningful area of the content.

The same is true for variables

Variables within the scope can only be used in the scope. If variables are called outside the scope, they cannot be used.

For example:

# include<stdio.h>
int main(){
    {//Scope entry
        int num =5;  // Local variable num
    }//Scope exit
    printf("num = %d",num);
    return 0;
}

//The code here will report an error, because int num = 5 is in a scope in the main function and printf is around it, so the value of num cannot be called.

The output statement within the scope can output the previous content outside the scope

# include<stdio.h>
int main(){
    int num =5;  // Local variables in main function
    {//Scope entry
    	printf("num = %d",num);  
    }//Scope exit
    return 0;
}
// Output: num = 5

To sum up the four examples of local and global variables, let's make a summary of the life cycle of variables.

  • The scope of a local variable is the local scope of the variable; The life cycle starts when you enter the scope and ends when you leave the scope;
  • The scope of the global variable is the entire project file. The execution cycle is the cycle of the whole program.

C language: Escape Character

Escape characterinterpretationDecimal (ASCII)
?Use when writing consecutive question marks to prevent them from being parsed into three letter words;063
\'Used to represent character constant (');039
\''Double quotation marks used to represent the inside of a string;034
\\Used to represent a backslash to prevent it from being interpreted as an escape sequence character;092
\aWarning character, play system prompt tone; (Attention)007
\bBackspace; (Qiaoji: backspace)008
\fPaper feed symbol;012
\nLine feed; (Qiaoji: newline)010
\renter; (Qiaoji: return)013
\tHorizontal TAB, control 4 spaces, like a TAB key; (Note: tab)009
\vVertical tab;011
\dddddd represents 1 ~ 3 octal digits. For example: \ 130 X;Three digit octal
\xdddd represents 2 hexadecimal digits. For example: \ x30;hexadecimal

The escape character in C language occupies 1 byte of memory space

4, C language: operators

The symbols of calculation often used in our life. Computer language comes from our life and naturally serves our life. Here we will introduce the operators in C language. Let's have a look!

Bracket operator: ()

Shaped like parentheses in mathematical calculations

Arithmetic operators: +, -, *, /,%, + +, -=

+ - * /

Corresponding addition, subtraction, multiplication and division

%Sign operator

A remainder operator that takes the remainder of an operation, such as 7%3  ===>  Corresponding to 7÷3 : 2x3 = 6,Remainder 1, then 7%3 The result is 1.
It is often used to judge odd and even numbers

++Sign operator

Each operation+1,Commonly used in for,while In the statement

– sign operator

Each operation-1,Commonly used in for,while In the statement

=Sign operator

Assign constant to variable

Logical operator: & & (and) | (or)! (non)

&&And juxtaposition

Juxtaposition relationship, two exist at the same time, which is often expressed in an interval, such as 1<=x<=5  : x>=1&&x<=5.

||Or any relationship

A||B,A,B All results can be established

! Illogical relation

If the content is not determined, the operation is established

Relational operators: <, >, < =, > =, = ==

<, >, < =, > = operators

Corresponding size comparison

==Operator

Equality judgment a and b Whether equal, use a==b

Small tips: An equal sign = Is assignment, two equal signs == Is equal

!= operator

Non equal judgment: if a is not (not) equal to (! =) b

Among them,
If the judgment is true, the result is 1
The judgment is not tenable, and the result is 0

if a=10,b=20,Then expression !(a<b)The value of is 0
a<b → 1
!(ab)→ 0

set up a=1,b=2,c=3,be a<b<c The value of is 1
a<b  >>1
1<c  >>1

Compound operators: + =, - =, * =, / =,%=

+=Operator

a+=b ==> a=a+b

-=Operator

a-=b ==> a=a-b

*=Operator

a*=b ==> a=a x b

/=Operator

a/=b ==>a=a/b

%=Operator

a %= b ==> a=a%b

Comma operator:,

Calculate from left to right and take the rightmost value.

For example:

When the defined variable is known int a=1, b=2,(a + 3,b=a+ b,b+5,a+ b)The value of is 4
a+3 >>>1+3
b=a+b >>b=1+2=3
b+5 >>>2+5
a+b >>>1+3=4

expression x=(a=3,6*a)After execution, a The value of is 3, x The value of is 18

?: operator

Operation rule: execute A first. If A is true, execute B; If A is false, execute C.

usage method:

A?B:C;   //Semicolons cannot be lost

give an example:

int main(){
	int a=1,b=3,c;
	c =a>b?a:b;  //First judge whether a > b is true. If a < B is not true, then c=b
	printf("%d",c);  // outpu: c=3
	return 0;
}

5, C language: select structure

In daily life, we will inevitably make choices. Different choices will lead to different results. Programming language comes from our life, so what is the choice structure in C language? Let's have a look!

If else statement

if (condition 1 is true) > > > execute statement 1. if it is false, execute the next statement or else() statement

Simple if else statement

# include<stdio.h>
int main() {
	int a, b, c;
	a = 3;
	b = 2;
	c = 6;
	if (c == a + b) {
		printf("yes\n");
	}
	else {
		printf("no\n");
	}
	return 0;
}

If else statement nesting

When there are multiple statements after if or else, enclose them with {};

C language stipulates that nested if statements are always paired with the nearest if without else

int main() {
	int a, b, c;
	a = 3;
	b = 2;
	c = 6;
	if (c == a + b) {
		printf("yes\n");
	}
	else {
		if (c >= a + b) {
			c = c - (a + b);
			printf("C greater than ab=%d\n", c);
			printf("Done!\n");
		}
		else {
			printf("no");
		}
	}
	return 0;
}

Nested if else else statements

Multiple nesting

int main() {
	float a, b, c, delta;
	scanf_s("%f %f %f", &a, &b, &c);
	delta = b * b - 4 * a * c;
	if (delta > 0) {
		printf("delta=%f,The equation has two real roots\n", delta);
	}
	else if (delta ==0) {
		printf("delta =0,The equation has a real root\n");
	}
	else {
		printf("deleta =%f,The equation has no real root\n", delta);
	}

	return 0;
}

6, C language: circular structure

Loop structure is a common structure in our programming. It can complete a command and execute it repeatedly for many times until we get the result we want. Here we will briefly introduce the loop structure in C language.

while statement:

Rules for using while statements:

while(Condition is true){
	Circulatory body;
}

The usage of while statement is summarized as follows:

  • Define and assign the cyclic variable (i);
  • Write while {}
  • The steps of executing the operation of the write cycle and the exit mode;
  • Infinite loop: while(1)

Simple example:

int main(){
	int i;
	i = 1;
	while(i<=10){
		printf("%5d",i);
		i++;
	}
	return 0;
}

// output 1     2     3     4     5......     10

for statement

Usage rule: for (initial value; condition is true; variable update) {loop body}

Tips for using the for statement:

  • Define loop variable i
  • Write for (initial value; condition is true; variable update method) {loop body}
  • Assign values to variables in turn and write cycle conditions;
  • Update variable i
  • Infinite loop for(;);

give an example:

int main(){
	int i;
	for(i=1,i<=10,i++){  // When the initial i is 1 and i < = 10, for is established, i+1 each time
		printf("%3d",i);
	}
	return 0;
}

7, C language: array

One dimensional array

Define array and data:

Define array: data type array name [number of elements]; a[3],a[].

You can input the elements of the array from the keyboard and assign values one by one with the for loop;

Or direct assignment, in which the data value is input with braces {};

Extract array data

The method of using an element in the array alone: array name [label];

The subscript range of elements in the array with length n is 0 ~ n-1 
;

Let's do a few one-dimensional array exercises to practice our hands:

// Calculate and output the average value of all elements in one-dimensional integer array[5];
// First, we define an array, named array, with five contents

int main() {
	float array[5];
	float num;
	float sum = 0;
	float avg;
	
	for (int i = 0; i < 5; i++) {
		scanf("%f", &array[i]);
	}
	
	for (int i = 0; i < 5; i++) {
		num = array[i];
		sum += num;
	}
	avg = sum / 5.0;
	printf("%.2f", avg);
	return 0;
}

// input 1 2 3 4 5
// output 3.00

//Find the maximum value of the array and output its position subscript;
int main(){
	int a[6]={10,7,15,20,3,1};
	int i,max,num;
	max =a[0];
	num =0;
	for(i=1;i<6;i++){
		if(a[i]>max){
			max=a[i];
			num=i;
		}
	}
	printf("Maximum:%d\n",max);
	printf("subscript %d\n",num);
	return 0;
}

// Maximum output 20, subscript 3

Two dimensional array

Define array and data:

Data type array name [array row] [array column];

Elements that are not assigned will be automatically set to 0;

If the two-dimensional array a has m columns, the number of elements before a[i][j] is m*i+j

For example:

a[][3]={1,2,3,4,5,6,7};
The array should be:
1  2  3
4  5  6
7  0  0
// There is no limit on the number of rows. When the number of columns is full, it will enter the next row
// The number of rows can not be expressed, but the number of columns must be expressed! Otherwise, it will be one-dimensional.

// Array definition: two dimensional array name [number of array rows] [number of array columns]
//It can be understood as: generate a two-dimensional array of n rows and n columns called xx.
a[2][3] ={{1,2,3},{4,5,6}} // The number of parentheses in the outermost curly braces represents the number of rows, and the data in parentheses represents the column data


//The corresponding matrix arrangement can be as follows
a[3][4] ={{1,2,3,4},{4,5,6},{7,8}};    
// Note that what is declared here is 4 data in the first row and 3 data in the second row. The missing column number data will be automatically supplemented with 0
1  2  3  4  //{1,2,3,4}
4  5  6  0  //{4,5,6}   
7  8  0  0  //{7,8}

Extract two-dimensional array data

Extract the data in the array, corresponding to: array name [array n-1 row] [array n-1 column]

Starting from 0

For example:

a[3][3]={1,2,3,4,5,6,7,8,9}; //Three rows and three columns
1 2 3
4 5 6
7 8 9
//Propose 5
a[1][1];

Character array:

Define array and data

Definition method: data type array name [number of elements];

for example char s[20]={"a","b","c","1","2","3","\0"};  // \0 means the end, and the system will add it automatically

it's fine too char s[20]="abc123"  //Automatic generation method. Here s[20], if there are less than 20 contents, 0 will be automatically added at the end.

char s[3] ='abc\0' At the end of the array, you need to add\0

8, C language: function

Declaration and use of functions

Declaration of function:

Declaration format:

Return value type arbitrary function name(Data type formal parameters,......){
	return Return value;
}

// The return value of return is used to return to the caller. The data type of the return value must be consistent with the return value type declared by the function.

Function Tips:

  • The function can be defined before or after the main function. For example, after the main function, you need to declare the existence of the function in the main function, such as the following;

    //After the main function, you need to declare the existence of the function in the main function
    int f(int a);
    int main(){
    	int a,b
    	b =f(a);  // The parameters returned after the call are called arguments
    	return 0;
    }
    
    int f(int a){   // int a and a are formal parameters. The parameters passed in during the call are called formal parameters
    	return a*a;
    }
    
  • The return value type of a function is the function type defined by the function.

  • The return type is void (null), and the return statement is not written, but it is not recommended to write this method as the main function

  • Formal parameters and actual parameters are one-way value transfer, which can be changed into two-way transfer by using function pointer;

  • The variables defined in the function are only valid in this function. The variables in the function are called local variables, and the global variables need to be defined around the main function

  • The implicit storage type of any local variable whose storage category is not specified in the function is (auto).

  • For global variables that do not specify a storage category in the function, the implied storage type is (extern).

  • In C language, if the function type is not declared, the implicit type of the function is int type.

  • Function definitions cannot be nested, but function calls can be nested;

  • The main function cannot be called by other functions

Function call:

Function call, because the program is browsed from top to bottom, and the first entry of the function is the main function. If you want to write a function after the main function, you need to declare the existence of the function

// You need to make a declaration after the main function
int f(int a);  //There is a function named f that passes in the integer a
int main(){
	int a,b
	b =f(a);  // Call function
	return 0;
}

int f(int a){   // 
	return a*a;
}

//No declaration is required before the main function
int f(int a){   // 
	return a*a;
}

int main(){
	int a,b
	b =f(a);  // Call function
	return 0;
}

9, Summary of C language knowledge:

This article is coming to an end, so we might as well make a small summary and a small knowledge reminder~

C language: main function programming concept

main function basis

  • Main function = program main function;

  • C language program is composed of functions;

  • C language program has and only has one main function;

  • The C language program will be executed from the main function;

  • The main function of C language will end at return 0;

  • The main function of C language should be surrounded by braces {}, and the position of braces will not affect the operation of the program.

C language miscible concept

  • The main function is the main function in programming, and other functions cannot be declared as main functions;

  • The main function cannot be used as a user identifier;

  • The main function can appear anywhere in the program, but to call other functions at the beginning, you need to declare the function name in the main function.

  • C language is a high-level language, and C language programming is to convert the high-level language into machine language (0101);

  • C language has three circulation modes, which cannot be nested with each other!

C language: programming knowledge

  • 8 bits (bit) is 1 byte (B);

  • C language input under English input method;

  • Semicolon (;) in C language Represents the end of the statement;

  • When the program requires case conversion, according to ASCII code: lower case to upper case: - 32; Capital to lowercase: + 32;

  • C language has three structures: sequential structure (from top to bottom), selective structure (branch structure) and circular structure.

  • C language condition holds: non-zero integer (1)

  • C language condition does not hold: 0

  • A number of arbitrary length. Extract the number of single digits n / / 1% 10;

  • A number of arbitrary length. Extract the ten digit number n / / 10% 10;

  • A number of arbitrary length. Extract the number of hundred digits n / / 100% 10;

  • A number of arbitrary length, extract the number of thousands n / / 1000% 10, and so on;

C language: program running process

  1. Edit the source program;

  2. Compile the source program;

  3. Connection target program;

  4. Run executable program

C language: dropout after running

  • Source program: the dropout is c

  • Target file: dropout is obj

  • Executable: dropout is exe

10, Conclusion

This article is coming to an end. I'm glad we meet again here!

This article is the basic introduction notes of C language. But the learning of C language does not stop like this. It's a long way to learn. I hope you can make new progress every day after reading this article. I wish you and me ha ha ha~

This article is the author's study notes. If there are mistakes or mistakes, I hope to point them out in the comment area. Let's make progress together~

Creation is not easy. If you think this article can help you, don't forget to like Collection + attention. Your encouragement is my motivation to continue to create. In the future, I will continue to share my learning experience and many interesting programming projects in Python or C language.

Keywords: C Programming

Added by alevsky on Tue, 01 Feb 2022 09:59:36 +0200