Basic knowledge of C language in C++

Table of contents

1 Introduction to C language

Two algorithms

Three data types

Operators and Expressions

Common data input/output functions

Select Structured Programming

conditional operator

Switch statement:

while statement:

Do..while statement

For loop statement

transfer statement


1 Introduction to C language

The development history of programming language: machine language, assembly language, high-level language

The characteristics of C language: high efficiency, flexibility, rich functions, strong expressive power, and good portability;

Sample program:


#include<stdio.h>  //包含头文件



int main()  //主函数入口

{

    printf("hello  C  \n");   //使用C函数

    printf("梦想还是要有的,万一实现了呢?");   //使用C函数



    return 0;  //程序返回0

}













完成的C程序:

#define _CRT_SECURE_NO_WARNINGS  //这一句是为了清除使用scanf函数的警告,否则无法使用scanf()函数

#include<stdio.h>  //包含头文件

#define Height 10 //定义常量

int calculate(int Long, int Width); //用户自定义函数calculate



int main()  //主函数入口

{



    int m_Long=0;//长度

    int m_Width=0;//宽度

    int result=0;//表示体积





    printf("长方形的高度为:%d\n",Height);   //使用C函数

    printf("请输入长度:\n");   //使用C函数

    int a=scanf("%d", &m_Long); //输入长方形的长度





    printf("请输入宽度:\n");   //使用C函数

    int b=scanf("%d", &m_Width); //输入长方形的长度





    result = calculate(m_Long, m_Width);

    printf("长方形的体积是 : %d ", result);



    return 0;  //程序返回0

}



//计算体积函数

int calculate(int Long, int Width) {

    int result = Long * Width * Height;

    return result;

}

Two algorithms

Developing a program usually needs to solve four problems: algorithm, data structure, programming method, language tool, and environment. The algorithm is the core and mainly solves the problems of "what to do" and "how to do it".

An algorithm is an implementation process formulated to solve a specific type of problem, and has the following characteristics:

Finiteness: the execution steps and time must be finite and cannot be executed indefinitely;

Determinism: each step is clearly defined and cannot be ambiguous;

Feasibility: the algorithm is executable and can get correct results;

inputs:  There should be zero or more inputs;

output: there should be one or more outputs;

Criteria for criticizing the pros and cons of algorithms:

Correctness: For any legal input, correct results will be obtained;

Readability: the algorithm is easy to understand, easy to expand and read;

Robustness: When the input is illegal, it can be intercepted to ensure that the program will not be paralyzed;

Time complexity and space complexity: the length of time the algorithm executes and the size of the memory space occupied;

Algorithm description method:

  1. Natural language: the natural language commonly used by people;
  2. Flowchart: It is mainly a form of drawing that uses flowchart symbols to express logic; there are three basic structures commonly used in programs: sequential structure, selection structure, and loop structure. Any complex algorithm can be drawn and expressed using these three structures;
  3. NS flow chart: write all algorithms in a rectangular box;

Three data types

Programming specification:

1. Code indentation: the code is indented with the tab key, which is easy to read and looks beautiful;

2. Naming conventions: constant names are all capitalized, member variables start with m_, ordinary variables start with the first letter of the type, pointer variables add p before the name and the first letter of the name is capitalized, and each word of the function name starts with Capitalize the letters.

3. Comments: Use line comments as much as possible

keywords:

Auto

Break

Case

Char

Const

Continue

Default

Do

Double

Else

Enum

Extern

Float

For

Goto

White

Int

Long

Register

Union

Short

Signed

Sizeof

Static

Struct

Switch

Typedef

Return

Unsigned

Void

Volatile

If

Identifier naming rules:

  1. Identifiers must start with a letter or underscore;
  2. Other characters except the beginning can be composed of letters, underscores, numbers;
  3. C language is case sensitive;
  4. Identifiers cannot be keywords;
  5. The identifier should reflect a certain functional meaning and be easy to understand;
  6. Identifiers can be of any length, but the external name must be uniquely distinguishable by only the first 6 characters.

type of data:

  1. Basic types: integer type (short, basic, long integer), character type, real type (single, double precision type), enumeration type;
  2. Structural types: form new data types by adding, designing, and combining;
  3. Pointer type: mainly used to represent memory addresses;
  4. Empty type: represented by void, used to limit the return value type of the function;

constant:

  1. Integer constants: There are three representation modes: decimal, octal, and hexadecimal;
  2. Real constants: also known as floating-point constants, there are two ways to represent real types: decimals and exponents;

    double sum = 12.22222;  //小数表示法

     double sum2 = 1.23e5;   //指数表示法
  1. Character constants: mainly refer to character constants and string constants, characters are surrounded by symbols ' ', and strings are surrounded by "";
  2. escape character:

 \n --- carriage return line feed

 \t ---- horizontally jump to the next tab position

\v----vertical tabbing

\b---backspace

\r --- carriage return

\f---- paper feed

\\ --- backslash "\"

\' ----apostrophe

\a--- ring the bell

\ddd---1~3 characters represented by octal numbers

\xhh---The character represented by 1~2 hexadecimal numbers

  1. Symbolic constant: mainly refers to the symbolic constant defined by #define, such as #define PI 3.14

variable:

A variable is a quantity that can change while the program is running. The variable definition format is: variable type variable name = initial value;

  1. Classification of variable type modifiers:

type

keywords

type

keywords

signed primitive integer

int

unsigned short integer

Unsigned short

unsigned primitive integer

Unsigned

signed long integer

Long

signed short integer

short

unsigned long

Unsigned long

single precision type

Float

double type

Double

long double type

Long double

character type

Char

Variable storage type:

  1. Automatic variable auto: The variable is stored in the dynamic storage area of ​​the memory, and the variable generally uses auto by default, such as auto int a=20;

Every time the variable definition statement is executed, a new variable will be generated and re-initialized;

  1. Static variable static: Stored in the static storage area of ​​the memory, after the initial execution of the static modified variable, it will always be the value used for the first time in subsequent executions;

  1. Register variable register: apply to put the variable in the register, but it may not be effective in practice.

  1. External variable extern: external storage variable, that is to say, the variable currently to be used is stored externally.

File A code:

#include<stdio.h>

int iExtern = 12;



文件B代码并访问外部变量:

#include<stdio.h>  

int main()

{

    extern int iExtern;

    printf("%d", iExtern);

    return 0;

}

Mixed operations:

Different types of data need to be converted to the same type before operations are performed. The conversion rules are as follows:

Char、short---》int--->unsigned---》long、float---》double

For example:

  

  char c = 'a';

    float f = 2.3f;

    long s = 123222;

    double sum = c + f + s;

    printf("%d\n", sum);

Operators and Expressions

Operator classification:

  1. Assignment operator: =
  2. Arithmetic operators: + , -, * , / , % , +, - (the last two represent positive and negative, and the first two represent addition and subtraction), ++, --
  3. Relational operators: >, >=, <, <=, ==, !=
  4. Logical operators: && (logical and), || (logical or), ! (logical not)
  5. Bitwise logical operators: << ,>>,&, ^, |
  6. Comma operator: , (commas are used to separate multiple expressions)
  7. Compound assignment operators: += , -=, *= , /= , % =,

Expression: Composed of operators and operands, the expression can appear on the right side of an assignment statement or in the parameters of a function.

#include<stdio.h>  

#define PI 3.1415



int main()

{

    extern int iExtern;

    int b = 20;

    int c = 0;



    printf("%d\n", iExtern + b);



    c = b + 22;

    printf("%d\n", c);





    printf("%d\n", iExtern);

    printf("%d\n", b);

    printf("%d\n", c);



    



    

    getchar();



    return 0;

}





自动类型转换:低字节类型向高字节类型转换系统会自动完成,但是会损失精度,如小数点截断等。

    float f = 12.4f;

    int a = f; //会截断小数部分,只取整数部分



强制类型转换:不同变量类型之间的强制转换,由开发人员自行决定。

    float d = 12.45;

    int c = (int)d; //强制转换为int型





自增与自减运算在变量前后位置的区别:

    int c = 123;

    c++; //先使用变量c的值,然后在自增1

    ++c; //先自增变量c的值,然后载使用变量

Common data input/output functions

The input functions are:

  1. Character data input getchar();
  2. String data input gets
  3. formatted data input scanf

The output functions are:

  1. Character data output putchar()
  2. String data output puts()
  3. Formatted data output printf()


   

 //字符输出函数

    putchar('q'); //输出一个字符,也可以填入转义码

    char c = getchar();//输入一个字符,并用变量获取

    putchar(c);//输出一个字符,这里直接使用字符变量c作为参数输入

puts("打印一段字符串"); //在屏幕上面打印一段字符串





    //字符串输入函数

    char ch[20];//用于保存输入的字符串

    gets(ch); //原来的gets函数已弃用,这个函数在vs中使用不了

puts(ch);//输出数据





    char c = 'a';

    int a = 0;

    //格式输出函数

    printf("%c",c); // %c 代表需要转换为char型输出, c为需要转义的char变量,若有多个变量转义则需要转义的字符的位置和变量的位置一一对应。



//格式输入函数

scanf("%d",&a); //两个参数含义为: 转义类型 和 参数地址,当有多个转义及地址时也需要一一对应;

    printf("%d", a);//把输入的额变量值输出



Select Structured Programming

if statement:

The format is if (expression) { execution logic when the condition is true }

if (5>4)

{

printf("大于....");

}

If else statement:

The format is if (expression) {execute code when condition is true} else{execute code when condition is false}

if (5>4)

{

printf("大于....");

}

else

{

printf("小于.....");

}

Else if statement:

The syntax is if (expression) { } else if (expression) { } ..... else{ }

if (5>4)

{

printf("大于....");

}

else if (4>3)

{

printf("大于.....");

}

else

{

printf("小于.....");

}

conditional operator

The syntax is: expression1 ? expression2 : expression3

int a = 2000332;

int b = 7833 * 12;



int c = a > b ? 1 : 0;

if (c==1)

{

printf("a大于b");

}

else

{

printf("a小于b");

}

Switch statement:

grammar:

switch(expression) {

Case Scenario 1:

statement block

Break;

......

}

int a = 2000332;

int b = 7833 * 12;

switch (a>b)

{

case true:

printf("大于");

break;



case false:

printf("小于");

break;



}

while statement:

Syntax: while (expression) { statement block (loop body) }

int i = 0;

while (i<10)

{

printf("%d \n", i);

i++;

}



死循环:while表达式的值永远为true的时候,那么while将无限循环下去。

Do..while statement

The syntax is do{execution statement}while(conditional expression);

int i = 0;

do

{

printf("%d \n", i);

i++;

} while (i < 10);

For loop statement

The syntax is for (initial value of loop variable; loop condition; loop variable change) { loop body }

for (int i = 0; i < 10; i++)

{

printf("%d \n",i);

}



For循环的其他几种写法:

int i = 0

for (; i < 10; i++) //预先定义初始变量,直接省略不写

{

printf("%d \n",i);

}





for (int i = 0; ; i++) //省略第二个判断表达示不写,程序陷入死循环

{

printf("%d \n",i);

}



for (int i = 0;i < 10 ; ) //省略第三个判断表达示不写,把自增表达式写在循环体里面

{

printf("%d \n",i);

         i++;

}



Int i,j;

for ( i = 0,j=0; i < 10; i++,j++) //在表达式1和3处可以用逗号分割写多个表达式

{

printf("%d \n",i);

}

Loops can be nested, and the above three types of loops can be nested arbitrarily.

transfer statement

Transfer statements include goto statement, break statement, continue statement;

The Goto statement is an unconditional statement, which can make the program jump to any executable statement inside the function. It can also be used to break out of a loop or jump into a loop.

int main()

{

int a = 14;

//跳转到标签的代码处

goto print;

printf("a的值为:%d", a);

//定义要跳转的标签名称

print:

printf("hello");



    return 0;

}

Break statement:  used to terminate the current loop, and then continue to execute the following code.

int main()

{

int a = 0;

for (a = 0; a < 10; a++)

{

if (a==5)

{

break; //如果条件满足,便结束当前循环

}

}

printf("hello");

    return 0;

}

Continue statement: end the remaining unexecuted codes of this loop, and continue to the next loop,

Guess you like

Origin blog.csdn.net/XiaoWang_csdn/article/details/131019196