C language introductory knowledge finishing

C language introductory knowledge finishing

0 recommended books

If you want a more detailed C language knowledge system, please refer to the following books. This chapter will organize some important content. This part of knowledge is mainly suitable for getting started with programming and algorithms, and will ignore some details that are not necessary to delve into. 1. "C
Program Design"
2. "C Programming Learning Tutorial"
3. "Programming C Language Experiment Guide"
4. "C Prime Plus"
The first three books are relatively basic and suitable for beginners, and the translation of the last book is very exciting , it can be said to be a complete introduction to C language. It will introduce the breadth of knowledge in detail. It is recommended to read!

1 header file, main function, comments

1.1 Header file

The so-called header file refers to the part that is operated by the compiler during program preprocessing (this sentence can be skipped, no in-depth understanding is required for beginners), so why introduce the header file first? Because the header file contains many commonly used library functions, it is convenient for us to operate the program. Here are some examples: First, the
commonly used header files are given:

//常用
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
//不常用
#include<asset.h>
#include<errno.h>
#include<float.h>
#include<limits.h>
#include<locale.h>
#include<signal.h>
#include<time.h>
#include<stddef.h>
#include<stdarg.h>
#include<setjmp.h>

Next, we will give a brief introduction to commonly used header files and learn about some useful library functions to facilitate programming (you can skim this part first and go directly to the 1.2 main function part to read, and then check it after you have learned the following knowledge)
( 1) #include<stdio.h>
library variable -
size_t: This is an unsigned integer type, which is the result of the sizeof keyword.
This variable is very useful. For example, when you write an unsigned variable, its value is of size_t type. For example, When you need to dynamically allocate memory space, you need to write n*sizeof(int), which is a space

library macro

that allocates n int variables - EOF: This macro is a negative integer indicating that the end of the file has been reached. This macro will exist widely. In the input conditions of the question, EOF is actually -1, which marks the end of the file. For example, we can use it like this: while(scanf(“%d”,&n)!=EOF), when we enter n, By the way, check whether it has reached the end of the file. If it has, exit the reading
library function——

function effect For example
int scanf(const char *format, …) Read formatted input from stdin scanf(“%d”,&n)
int sscanf(const char *str, const char *format, …) Read formatted input from a string sscanf(str,“%d”,&n)
int printf(const char *format, …) Send formatted output to stdout printf(“%d”,n)
int sprintf(char *str, const char *format, …) send formatted output to string sprintf(str,“%d”,n)
int getchar(void) Get a character (an unsigned character) from the standard input stdin char ch = getchar()
char *gets(char *str) Reads a line from standard input stdin and stores it in the string pointed to by str. It stops when a newline character is read, or the end of the file is reached, as the case may be char s[50]; gets(s);
int putchar(int char) Write the character specified by parameter char (an unsigned character) to the standard output stdout putchar(ch)
int puts(const char *str) Writes a string to standard output stdout up to, but not including, the null character. Newlines will be appended to the output puts(s)

These library functions must be mastered, and their usage is very common
(2) #include<math.h>
This function library is a mathematical function, involving elementary operation

library functions of mathematics——

function effect For example
double fabs(double x) Returns the absolute value of x fabs(f)
double sqrt(double x) Returns the square root of x sqrt(f)
double pow(double x, double y) Returns x raised to the y power pow(2,10)=1024
double ceil(double x) Returns the smallest integer value greater than or equal to x ceil(4.9)=5
double floor(double x) Returns the largest integer value less than or equal to x floor(4.9)=4

(3) #include<string.h>
library macro - NULL: This macro is a value library function
of a null pointer constant - this function library mainly handles string operations, including splicing, copying, comparing size, length, etc.

function effect For example
void *memset(void *str, int c, size_t n) Copies character c (an unsigned character) to the first n characters of the string pointed to by parameter str memset(a,0,sizeof(a))
int strcmp(const char *str1, const char *str2) Compare the string pointed to by str1 with the string pointed by str2 strcmp(“hello”,“Hello”)>0
char *strcat(char *dest, const char *src) Append the string pointed to by src to the end of the string pointed by dest str = strcat(“Hello”,“World”)
char *strcpy(char *dest, const char *src) Copy the string pointed to by src to dest strcpy(str,str1)
size_t strlen(const char *str) Calculate the length of the string str up to, but not including, the null terminating character int len = strlen(str)

(4) #include<stdlib.h>
library function -
this function library mainly handles dynamic memory allocation processing and program running status operations

function effect For example
int abs(int x) Returns the absolute value of x abs(n)
void exit(int status) Cause the program to terminate normally exit(0)
void *malloc(size_t size) Allocates the required memory space and returns a pointer to it malloc(sizeof(int))
void *calloc(size_t nitems, size_t size) Allocates the required memory space and returns a pointer to it calloc(n,sizeof(int))
void *realloc(void *ptr, size_t size) Try to resize the memory block pointed to by ptr allocated by a previous call to malloc or calloc. realloc(ptr,sizeof(int))
void free(void *ptr) Release the memory space allocated by calling calloc, malloc or realloc before free(ptr)

(5) #include<ctype.h>
library function -
this function library mainly processes single characters and involves ASCII code conversion

function effect For example
int tolower(int c) This function converts uppercase letters to lowercase letters tolower(‘A’)
int toupper(int c) This function converts lowercase letters to uppercase letters toupper(‘a’)
int isalnum(int c) This function checks whether the characters passed are letters and numbers isalnum('7')
int isalpha(int c) This function checks whether the passed character is a letter isalpha(‘a’)
int isdigit(int c) This function checks whether the passed character is a decimal number isdigit('9')
int islower(int c) This function checks whether the passed characters are lowercase letters islower(‘a’)
int isupper(int c) This function checks whether the passed character is an uppercase letter isupper(‘A’)
int isspace(int c) This function checks whether the passed character is a whitespace character isspace(’ ')

1.2 Main function

The so-called main function refers to the main function. Just remember the writing method here:

int main(){
    
    

	return 0;
}

Don’t forget to add return 0; this is a sign that the program ends normally (because internal errors in the program will return other values, there is no need to go into details here)

1.3 Notes

Here are two commonly used comments: // and /* */

//1.此注释为行注释,只能注释一行
/*

2.此注释为段落注释,可注释一个段落

*/

2 Variable definition and type

Type name + variable name = assign initial value;
very simple, here is an example:

int a = 10;			//定义整数a=10
double f = 0.22;	//定义浮点数f=0.22
char s = 'A';		//定义字符s = 'A'
int b[10] = {
    
    1,2};	//定义整数数组b[0]=1,b[1]=2

These are the definitions of variables. To define a variable, you must specify the type, so these two concepts should be understood together.

3 Simple program structures (branch, loop, selection)

After having variables, the next step is to define some simple program structures. Here we mainly introduce three types: branch, loop, and selection.

3.1 Branch

To put it simply, it is what the program needs to judge, for example:

if(a >= 10){
    
    
	b = 1;
}else{
    
    
	b = 2;
}

a > = 10 a>=10 a>=10,我们就将 b = 1 b=1 b=1,否则 b = 2 b=2 b=2,这里很好理解,稍微复杂一些的判断结构有:

if(条件1){
    
    

}else if(条件2){
    
    
	if(条件4){
    
    
		
	}else if(条件5){
    
    
	
	}
}else if(条件3){
    
    

}else{
    
    

}

也就是说,判断可以嵌套,判断之中含有判断,一层一层的叠加

3.2 循环

简单来说,你需要重复做一件事情,那么需要不断循环!举例:

int sum = 0;
for(int i=1;i<=10;i++){
    
    
	sum += i;
}

显而易见,这里 s u m sum sum可以从1累加到10,输出即为55,就是高斯求和的展开式,复杂一些,可以有如下结构:

for(int i=1;i<=10;i++){
    
    
	for(int j=1;j<=10;j++){
    
    
		for(int k=1;k<=10;k++){
    
    

		}
	}
}

比如多层循环等等

3.3 选择

选择是一种特殊的结构,这里单指switch:

switch(a){
    
    
	case 1:b = 10;break;
	case 2:b = 100;break;
	case 3:b = 1000;break;
	default:b = 1;break;
}

我们考察a的值,a若为1,则b的值为10,a若为2,则b的值为100,a若为3,则b的值为1000,a若为其他,则b的值为1000,这里要注意的是,break的作用是跳出switch,而不是顺序执行(初学者记住每句话后加break即可)

4 简单程序

有了前3个概念之后,我们就可以写出简单的程序了,主体框架如下:

//1.头文件部分

//2.主函数

//输入输出 + 简单结构

再加上输入/输出,这样一个简单的程序就完成了(输入/输出请参考1.1(1)#include<stdio.h>库,要求掌握所有的输入输出基本函数),比如举个例:

#include<stdio.h>
int main(){
    
    
	//输入
	//程序处理
	//输出
	return 0;
}

这一块书写应熟练,是整个程序基本的框架
学完这些之后,可练习:
团体程序设计天梯赛-L1组
所有5分和10分的题目

5 子程序

有了主程序之后,接下来就引入了子程序的概念,所谓子程序,是指相对于主程序的一个子函数,这个子函数可以完成一项或多个重复的功能,为了避免程序调用的时候,频繁书写重复的语句,因此定义一个子程序并反复调用是最佳的选择,例如,我们有一个阶乘函数:

int fac(int n);

接下来在主程序中,我们需要反复调用它:

int fac(int n){
    
    
	int res = 1;
	for(int i=1;i<=n;i++){
    
    
		res *= i;
	}
	return res;
}
int main(){
    
    
	int a = fac(5);
	int b = fac(11);
	return 0;
}

至此,子程序就介绍结束了

6 递归

所谓递归,就是一系列重复的操作,那么这和之前的子程序有什么区别呢?子程序是一次操作完成一个或多个既定的功能,调用一次,返回结果;而递归是调用自己N次,逐层返回后才能得结果,例如,还是刚刚的阶乘函数,递归写法:

int fac(int n){
    
    
	if(n == 1){
    
    
		return 1;
	}
	return fac(n-1)*n;
}

fac函数中调用fac函数自身,这叫递归,递归有结束的时候,这就是边界条件,当n=1时,n!=1

7 数组

7.1 一维数组

顾名思义——数组,就是将一串数字按照成组的方式排列起来,一维就是线性的,例如:
1 2 3 4 5 6这就是6个线性排列的数字,放置在一个容器中,这个容器就是数组:

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

我们可以通过下标对数组进行访问,下标从0-(n-1),如a[3]=4

7.2 二维数组及多维数组

二维,在一维基础上增加了一个维度,也就是拥有行、列两个维度:

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

数字1-6分成两行表示了,这也就是矩阵的表示法
同样地,也可以通过下标进行访问,如a[1][2]=6

8 结构体与枚举

8.1 结构体

结构体,通俗理解就是一个打包的数据类型集合,比方说我们要记录一本图书,就需要书名、ISBN号、价格、字数等多种信息,把这些信息打包,就是一个结构体,可表述为{书名、ISBN号、价格、字数}
这里要掌握结构体的两种定义方法:
(1)普通定义

struct book{
    
    
	char book_name[20];
	char ISBN[20];
	double price;
	int words;
}

这样我们就定义了一个结构体,包含了以上4个信息
(2)复杂定义

typedef struct{
    
    
	char book_name[20];
	char ISBN[20];
	double price;
	int words;
}book;

重命名意义下更常用一些(程序设计)

8.2 枚举

枚举,同一块存储空间可共用不同的类型定义,只能选择其中之一的类型
这一块可暂时略过,因为算法实践中基本不使用这种技术

9 指针

这一块是C语言最为核心和精彩的一部分,但对于初学者而言,无需深入了解,指针在系统设计、文件访问有着相当深入的应用
我们主要介绍指针访问数组的情形,例如这样:
一维数组,依旧保存了6个数字,我们已经可以用下标的方式对其访问了,那么,如何用指针访问呢?
我们可以把指针看作一个箭头,开始指向数组头,即第一个格子,然后每加1,指向的格子就向后移动一格,这样,输出数组元素的值,等价于输出指针箭头指向的格子内元素的值,例如,要输出a[3]:

int a[6] = {
    
    1,2,3,4,5,6};
int *ptr = a; 				//创建指针
printf("%d",*(ptr+3));

这样,就完成了 7.1部分 同样的功能,二维指针原理同上

10 排序

这里介绍C语言库中自带的一个函数qsort(此处可参考1.1部分 阅读库),

void qsort(void* base,size_t num,size_t width,int(__cdecl*compare)(const void*,const void*));

参数:
1 void* base,待排序数组,排序之后的结果仍放在这个数组中
2 size_t num,数组中待排序元素数量
3 size_t width。各元素的占用空间大小(单位为字节)
4 int(__cdecl*compare),指向函数的指针,用于确定排序的顺序(需要用户自定义一个比较函数)
例如,我们对一个无序的数组进行排序:

int cmp_int(const void* _a , const void* _b){
    
    
    int* a = (int*)_a;   
    int* b = (int*)_b;
	return *a - *b;
}
int main(){
    
    
	int a[6] = {
    
    5,1,6,3,4,2};
	qsort(a,6,sizeof(int),cmp_int); 
	
	return 0;
} 

这样就完成了排序,方便快捷(C++有更好的方法,sort函数)

结束语

希望大家在掌握了C语言基本知识的基础上,再回看1.1库函数这一节,深入理解并记忆这些基本的库函数,相信对后面的程序与算法设计大有帮助!

Guess you like

Origin blog.csdn.net/weixin_41801682/article/details/124561951