The classic of the basic operation method of embedded C language

     Once the C language appeared, it was quickly popularized and promoted all over the world due to its rich functions, strong expressive ability, flexibility and convenience, and wide application range.

      C language not only has high execution efficiency but also has good portability, and can be used to develop application software, drivers, operating systems, etc.

      C language is also the originator language of many other high-level languages, so learning C language is a compulsory course for entering the programming world.

      hello,world

#include<stdio.h> 
int main()
{
    /*在双引号中间输入Hello World*/ 
    printf("Hello World");
    return 0; 
}

Note: In the latest C standard, the type before the main function intis notvoid

Concrete structure of C language

In simple terms, a C program is composed of several 头文件sums 函数.

picture

#include <stdio.h>It is a preprocessing command, its function is to inform the C language compilation system that some preprocessing work needs to be done before the C program is officially compiled.

  • 函数It is a small unit that implements code logic .

essential main function

A C program has one and only one main function, mainthe function.

picture

The C program is to execute the code in the main function. It can also be said that the main function is the only entry in the C language .

  • The int before main is the type of the main function.

  • printf()It is a format output function, remember its function here is to output the specified information on the screen

  • return is the return value of the function, depending on the type of the function, the returned value is also different.

  • \nis a newline within the escape character. (Note: The C program must be executed from the main function)

norms of good habits

  1. A description or a statement occupies one line , for example: include a header file, and an executable statement needs a line break at the end .

  2. The statements in the function body should be indented clearly , usually one indentation is made by pressing the Tab key once .

  3. Parentheses should be written in pairs , and if they need to be deleted, they should also be deleted in pairs .

  4. A semicolon is required at the end of an executable statement .

  5. All symbols in the code are English half-width symbols .

picture

Program Explanation - Notes

Comments are written for programmers, not for computers.

There are two ways to comment in C language:

Multi-line comments: /* 注释内容 */

Single line comment: //注释一行

Named C (identifier)

The C language stipulates that an identifier can be a string of letters (A~Z,a~z), numbers (0~9), and underscores _, and the first character must be a letter or an underscore . Note the following points when using identifiers:

The length of the identifier is best not to exceed 8 bits, because in some versions of C, the first 8 bits of the identifier are valid, and when the first 8 bits of two identifiers are the same, they are considered to be the same identifier.

  1. Identifiers are strictly case-sensitive. For example Imoocand imooc are two different identifiers.

  2. It is best to choose meaningful English words for the identifier to "see the name and know the meaning" instead of using Chinese.

  3. Identifiers cannot be keywords in the C language. Want to learn more about C language keywords.

Variables and assignments

A variable is a variable that can be changed, and each variable will have a name (identifier). A variable occupies a certain storage unit in memory. Variables must be defined before they are used , and variable names and variable values ​​are two different concepts.

picture

The general form of variable definition is: data type variable name;

Multiple variables of the same type: data type variable name, variable name, variable name...;

picture

Note: Continuous assignment is not allowed in the definition, int a=b=c=5;so it is illegal.

There are two ways to assign values ​​to variables:

  1. declare before assigning

  2. Simultaneous assignment of declaration

basic data type

In C language, data types can be divided into:

  1. basic data type

  2. construct data type

  3. pointer type

  4. Four categories of empty types

picture

The most commonly used integer, real and character types (char, int, float, double):

picture

Integer data refers to numbers without decimals (int, short int, long int, unsigned int, unsigned short int, unsigned long int):

picture

Note:

  • int short int long intDepending on the compilation environment, the ranges taken are different.

  • Wherein short intand long intis at least the range written in the table, but intin the table is the value range written in the 16-bit compilation environment.

  • In addition, the value range of the C language intdepends on the number of bytes it occupies. Different compilers have different regulations.

  • The ANSI standard definition intoccupies 2 bytes, and the TC is based on the ANSI standard, which intoccupies 2 bytes. But in VC, one intoccupies 4 bytes.

Floating-point data refers to numbers with decimals.

There are a lot of information in life that are suitable to be represented by floating-point data, such as: human weight (unit: kilogram), commodity prices, pi, and so on.

Because of the difference in precision, it is divided into three types (float, double, long double):

picture

Note: There is no string variable in C language, and the string can only exist in the character array, which will be discussed later.

formatted output statement

Formatted output statement, also can be called placeholder output , is to display various types of data from the computer according to the formatted type and specified position .

Its format is: printf("输出格式符",输出项);

picture

When the output statement contains ordinary characters, the following formats can be used:

printf("普通字符输出格式符", 输出项);

picture

Note: The number of format symbols should correspond to the number of variables, constants or expressions one-to-one

immutable constant

A quantity whose value does not change during program execution is called a constant .

mtianyan: Constants in C language can be divided into direct constants and symbolic constants.

  • Direct constants are also called literal quantities , which can be used directly without explanation, such as:

    • Integer constants: 13, 0, -13;

    • Real constants: 13.33, -24.4;

    • Character constants: 'a', 'M'

    • String constant: "I love imooc!"

picture

In the C language, an identifier can be used to represent a constant, which is called a symbolic constant. Symbolic constants must be defined before they can be used , and their general form is:

 
 

#define 标识符 常量值

#include <stdio.h>
#define POCKETMONEY 10    //定义常量及常量值
int main()
{
    // POCKETMONEY = 12;  //小明私自增加零花钱对吗?
    printf("小明今天又得到%d元零花钱\n", POCKETMONEY);
    return 0;  
}

Symbolic constants cannot be changed.

automatic type conversion

There are cases of automatic conversion of data types.
Automatic conversion occurs when different data types are operated, and it is automatically completed at compile time .

picture

charConversion of typed data to inttyped data follows ASCIIthe corresponding value in the code.

Note:

Small bytes can be automatically converted to large bytes, but large bytes cannot be automatically converted to small bytes

char can be converted to int, int can be converted to double, char can be converted to double. But it cannot be reversed.

cast

Coercion is achieved by defining type conversion operations . Its general form is:

 
 

(datatype) (expression)

Its function is to cast the operation result of the expression into the type indicated by the type specifier

Pay attention to the following issues when using coercion:

  1. Both the data type and the expression must be enclosed in parentheses. If it is (int)(x/2+y)written (int)x/2+yas, it will be transformed into a shapex , then divided and then added.int2y

  2. After conversion, the type and variable value of the original data will not be changed, only temporary conversion in this operation .

  3. The operation result after forced conversion does not follow the rounding principle.

calculating signs

Operators in C language:

※ 算术运算符
※ 赋值运算符
※ 关系运算符
※ 逻辑运算符
※ 三目运算符

arithmetic operator

C language basic operators:

picture

Pay attention to the division operation :

If the two numbers to be divided are both integers, the result is also an integer, and the decimal part is omitted , such as 8/3 = 2;

If one of the two numbers is a decimal, the result is a decimal, such as: 9.0/2 = 4.500000.

mtianyan:  Pay attention to the remainder operation :

This operation is only suitable for the remainder operation with two integers10%3 = 1 , such as: ;

mtianyan: notes: And 10.0%3 is wrong; the sign after the operation depends on the sign of the modulus , such (-10)%3 = -1;as10%(-3) = 1;

mtianyan:  %%Indicates that this is a %symbol.

Note: There is no exponentiation operator in C language×, ÷ , and equal arithmetic symbols cannot be used .

Increment and Decrement Operators

  • The self-increment operator is ++, its function is to make the value of the variable self-increment by 1

  • The self-decrement operator is --, whose function is to decrement the value of a variable by 1.

They are often used in loops. The increment and decrement operators have the following forms:

picture

assignment operator

Assignment operators in C language are divided into simple assignment operators and compound assignment operators

Simple assignment operator =symbols , let's talk about compound assignment operators:

Compound assignment operators are =formed by adding other operators before a simple assignment operator.

For example+=、-=、*=、/=、%=

Analysis: Define an integer variable a and assign it a value of 3. a += 5;This formula is equivalent to a = a+5; adding the variable a and 5 and then assigning it to a

Note: There is no space between the operator and the equal sign in compound operators .

relational operator

Relational operators in C language :

picture

The value of the relational expression is the sum , which is represented by the sum of integers in the C program .10

Note: There cannot be spaces>=, <=, ==, != between such symbols .

Logical Operators

Logical operators in C language:

picture

There are also two types of logical operation values , and they are represented by integers 1 and 0 in C language. Its evaluation rules are as follows:

  • AND operation &&

The result is true when both variables involved in the operation are true, otherwise it is false. For example: 5>=5 && 7>5, the operation result is true;

  • OR operation ||

As long as one of the two variables involved in the operation is true, the result is true. When both quantities are false, the result is false. For example: 5>=5||5>8, the operation result is true;

  • not operation!

When the variable involved in the operation is true, the result is false; when the variable involved in the operation is false, the result is true. For example: !(5>8), the operation result is true.

Ternary operator

The ternary operator in C language: ?:, its format is:

表达式1 ? 表达式2 : 表达式3;

The execution process is:

First judge whether the value of expression 1 is true, if it is true, execute expression 2; if it is false, execute expression 3.

 
 
#include <stdio.h>
int main()
{
    //定义小编兜里的钱
    double money =12.0      ; 
    //定义打车回家的费用
    double cost =11.5       ;  
    printf("小编能不能打车回家呢:"); 
    //输出y小编就打车回家了,输出n小编就不能打车回家
    printf("%c\n",money>=cost?'y':'n'                        );
    return 0;
}

Priority comparison of operator competition

The order of various operation symbols:

picture

A priority of 1 has the highest priority , and a priority of 10 has the lowest priority.

Simple if statement of branch structure

A statement in a branch structure statement in C language if条件.

The basic structure of a simple if statement is as follows:

if(表达式)
{
  执行代码块;
}

Its semantics are: if the value of the expression is true, execute the following statement, otherwise, do not execute the statement.

Note: if()There is no semicolon behind, just write directly{}

Simple if-else statement of branch structure

The basic structure of a simple if-elsestatement:

picture

The semantics are: if the expression evaluates to true, code block 1 is executed, otherwise code block 2 is executed.

Notice:

if()There is no semicolon after it, just write {}, there is no semicolon after else, just write {}

Multiple if-else statements in branch structure

if-elseThe structure of multiple statements in C language is as follows:

picture

The semantics are: judge the value of the expression in turn, when a certain value is true, execute the corresponding code block, otherwise execute the code block n.

Note: When a certain condition is true, other statements of the branch structure will not be executed downward.

Nested if-else statement of branch structure

Nested statements in C language if-else. The meaning of nested if-elsestatement is if-elseto write the statement in the statement if-else. Its general form is:

picture

The while loop of the loop structure

Performing a certain action repeatedly is called a cycle by people in the quack  .

There are three loop structures in C language , first look at the structure of while loop in C language

picture

The expression represents the loop condition , and the execution code block is the loop body .

The semantics of the while statement are: calculate the value of the expression, and 真(非0)execute the code block of the loop body when the value is equal.

  1. The expression in the while statement is generally a relational expression or a logical expression. When the value of the expression is false, the loop body is not executed, otherwise, the loop body is always executed.

  2. Be sure to remember to change the value of the loop variable in the loop body, otherwise there will be an infinite loop (endless execution).

  3. If the loop body contains more than one statement, it must be enclosed in {}brackets to form a compound statement.

Do-while loop of loop structure

The general form of a loop in C language do-whileis as follows:

picture

The semantics of the do-while loop statement are:

It first executes the execution code block in the loop, and then judges whether the expression in while is true, if it is true, it continues the loop; if it is false, it terminates the loop. Therefore, the do-while loop must execute the loop statement at least once .

Note: mtianyan: do-whileWhen using a structural statement, there must be a semicolon after the while brackets.

For loop of loop structure (1)

The general form of for loop in C language :

picture

Its execution process is as follows:

  1. Execute expression 1 to initialize the loop variable;

  2. Judgment expression 2, if its value is true (not 0) , then execute the code block in the for loop body, and then execute downward; if its value is false (0) , then end the loop;

  3. Execute expressions 3, (i++) and other statements that operate on loop variables;

  4. Execute the second step after executing the code block in the for loop; the first step initialization will only be executed once.

  5. The loop ends, and the program continues to execute downwards.

Note: The two semicolons in the for loop must be written

For loop of loop structure (2)

In the for loop:

  • Expression 1 is one or more assignment statements , which are used to control the initial value of the variable ;

  • Expression 2 is a relational expression that determines when to exit the loop;

  • Expression 3 is the step value of the loop variable , which defines how the loop variable changes after each loop.

  • These three parts are separated by semicolons  ; .

When using the for statement, you should pay attention to :

  1. "Expression 1, 2, 3" in the for loop may not be empty, but the two semicolons (;;)cannot be defaulted.

  2. Omitting "expression 1 (assign initial value to loop variable)" means not to assign initial value to loop variable.

  3. Omit "expression 2 (loop condition)", do not do other processing, and the loop is always executed ( infinite loop ).

  4. Omit "expression 3 ( increase and decrease of loop variable )", do not do other processing, and the loop is always executed (infinite loop).

  5. Expression 1 may be an assignment expression for setting the initial value of the loop variable, or other expressions .

  6. Expression 1 and expression 3 can be a simple expression or multiple expressions separated by commas.

picture

  1. Expression 2 is generally a relational expression or a logical expression , but it can also be a numerical expression or a character expression. As long as its value is non-zero , the loop body is executed.

  2. The variables in each expression must be defined before the for loop .

How to get the hundreds, tens and ones of a number

  • Hundreds digit: num/100 can be obtained, because  int it is an integer type, the decimal part will be omitted. For example,  765/100 the result is7

  • Tens digit: num%100/10 . such as 765%100get first 65, 65/10get6

  • Single digit: num%10. 765%10get5

Comparison of Three Kinds of Loop Structures

The three loops of while, do-while and for are different in specific usage occasions, as follows:

It is more suitable to use a for loop when the number of loops is known ;

  1. A while or do-while loop is suitable when the number of loops is unknown:

    • If it is possible not to loop once, consider using a while loop

    • If you loop at least once you should consider using a do-while loop.

But in essence, while, do-while and for loops are interchangeable.

Multiple loops in loop structure

Multiple loops are loop structures appearing in the loop body of the loop structure.

In actual development, up to three heavy cycles are generally used .

Because the more loop layers, the longer the running time and the more complicated the program, so generally 2-3 layers of multiple loops are enough. In addition, different loops can also be nested.

During the execution of multiple loops, the outer loop is loop and the inner loop is the child loop .

Once in the parent loop, the child loop needs to be executed completely until it breaks out of the loop. The parent loop enters the next time, and the child loop continues to execute...

picture

mtianyan: print triangular stack of stars

 
 
#include <stdio.h>
int main()
{
    int i, j, k;
    for(i=1; i<5; i++)
    {
        /* 观察每行的空格数量,补全循环条件 */
        for(j=i; j<5; j++)  
        {
            printf(" ");    //输出空格
        }
        /* 观察每行*号的数量,补全循环条件 */
        for( k=0;k<2*i-1;k++) 
        {
            printf("*");   //每行输出的*号
        }
        printf("\n");     //每次循环换行
    }
    return 0;
}

Print 9×9 multiplication table using for loop

#include <stdio.h>
int main() 
{ 
    // 定义相乘数字i,j以及结果result
    int i, j, result;
     for(i=9;i>=1;i--)
     {
        for(j=1;j<=i;j++)
        {
            printf("%d*%d=%d ",i,j,result=i*j);
        }
        printf("\n");
     }
    return 0;
}

The break statement of the end statement

Then when the cycle is 5 times, it is necessary to stop and not continue the training. In C language, you can use breakstatement to do this.

Note the following points when using breakstatements:

break cannot be used in a single if-else statement without a loop construct.

  1. In multi-level loops, a break statement only breaks out of the current loop.

The continue statement of the end statement

Then when the cycle is 5 times, it is necessary to continue training after interruption. In C, continuethis can be done using the statement

The function of the continue statement is to end this cycle and start the next cycle.

The difference between a break statement and a continue statement is:

break is to jump out of the current entire loop, and continue is to end this loop and start the next loop.

switch statement of branch structure

The switch statement structure is as follows:

picture

mtianyan:  You should also pay attention toswitch the following points when making statements :

  1. The values ​​of each constant expression after the case cannot be the same, otherwise an error will occur.

  2. If there is no break ; after the case clause, it will be executed until a break ; is encountered, and then the switch statement will jump out.

  3. The expression statement behind the switch can only be of integer or character type .

  4. After the case, multiple statements are allowed without {} brackets.

  5. The order of each case and default clause can be changed without affecting the program execution result.

  6. defaultClauses can be omitted.

mtianyan: Application of switch and if statement (calculation is the day of the year)

 
 
#include <stdio.h>

int main() 

{ 

    /* 定义需要计算的日期 */

    int date = 0;

    int year = 2008;

    int month = 8;

    int day = 8;

    switch(month)

    {

        case 12:date+=30;

        case 11:date+=31;

        case 10:date+=30;

        case 9:date+=31;

        case 8:date+=31;

        case 7:date+=30;

        case 6:date+=31;

        case 5:date+=30;

        case 4:date+=31;

        case 3:

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

        {

            date+=29;

        }

        else

        {

            date+=28;

        }
        case 2:

        date+=31;

        case 1:

        date+=day;

        printf("%d年%d月%d日是该年的第%d天",year,month,day,date);

        break;

        default:

        printf("error");

        break;

    }

    return 0;

}

Correct: continue can only be used inside a loop body

The notorious goto statement

There is also such a statement in C language, which is gotoa statement, and the goto statement is an unconditional branch statement.

The usage format of the goto statement is:

goto 语句标号;

picture

self-created function

C language provides a large number of library functions: such as stdio.hproviding output functions

The general form of a custom function:

picture

Notice:

  1. [] The included content can be omitted, the data type description is omitted, and the default is  int a type function; the parameter is omitted to indicate that the function is a function without parameters , and the parameter is not omitted to indicate that the function is a function with parameters ;

  2. The function name follows the identifier naming convention;

  3. mtianyan: Put the custom function  main before the function as much as possible. If you want to put it after the main function , you need to declare the custom function before the main function . The declaration format is:

[数据类型说明] 函数名称([参数]);

function call

When we need to use a custom function, we have to call it, so it is called a function call when we call it .

In the C language, the general form of a function call is:

函数名([参数]);

Notice:

  1. When calling a function without parameters, []the inclusion can be omitted.

  1. []can be constants, variables or other structured data and expressions, and multiple parameters are separated by commas.

With participation without participation

A function that does not require a function parameter is called a parameterless function , and a function that requires a function parameter in a function is called a parameterized function.

The general form of a function with and without parameters is as follows:

picture

The only difference between a parameterized function and a parameterless function is that () there is an additional parameter list in the function  .

  • Functions with parameters are more flexible, and the output content can be changed at will as n changes, as long as a parameter is passed in the main function.

  • However, the output in the no-argument function is relatively fixed, and when it needs to be changed, it is necessary to change the value of the loop variable in a custom method.

mtianyan: Formal Participation Actual Parameters

Function parameters are divided into formal parameters and actual parameters .

  • Formal parameters are the parameters used when defining the function name and function body, and the purpose is to receive the parameters passed in when calling the function.

Just like Xiao Ming, who said what he said but didn't act;

  • Arguments are the parameters that are passed to the function when it is called.

Just like Xiaogang can actually act.

Function parameters and actual parameters have the following characteristics:

  • Formal parameters allocate memory units only when they are called, and release the allocated memory units immediately when the call ends. Therefore, formal parameters are only valid inside the function.

After the function call ends and returns to the calling function, the formal parameter variable can no longer be used.

  • Actual parameters can be constants, variables, expressions, functions, etc.

No matter what type of quantity the actual parameters are, they must have definite values ​​when the function is called , so that these values ​​can be transferred to the formal parameters. Therefore, methods such as assignment should be used in advance to obtain a definite value for the actual parameter.

  • When passing parameters, the actual parameters and formal parameters should be strictly consistent in quantity, type, and order, otherwise a type mismatch error will occur.

picture

function return value

The return value of a function refers to the value obtained by executing the program segment in the function body after the function is called and returned to the calling function.

The return value of the function should pay attention to the following points:

  • The value of the function can only returnbe returned to the calling function through the statement.

The general form of a return statement is:

return 表达式   或者为:return (表达式);
  • The type of the function value should be consistent with the type of the function in the function definition .

notes: If the two are inconsistent, the return type of the function shall prevail and the type conversion will be performed automatically.

  • A function that does not return a value , with  a return typevoid of .

Notice:

void Functions can have execution code blocks, but cannot return values.

mtianyan:  voidIf there is a statement in the function return, the statement can only end the function. Its format is: return;

Recursive function (1)

Recursion is when a function calls itself within its body.

Executing a recursive function will call itself repeatedly, entering a new level with each call.

Note that recursive functions must have an end condition

Recursive function (2)

Let’s analyze the factorial of 5 example and take a look at his calculation process:

picture

When the program calculates the factorial of 5, it performs recursion first, returns 1 when n=1 or n=0, and then pushes back to calculate and return. It can be seen that the recursive function must have an end condition.

Recursive function features:

  1. Each level of function has its own variable when calling, but the function code will not be copied, such as calculating the factorial of 5, the variable is different every time it is recursive;

  2. Each call will return once, for example, when calculating the factorial of 5, it will return for the next time every recursion;

  3. In a recursive function, the statement before the recursive call has the same execution order as the called function at all levels;

  4. In a recursive function, the execution order of the statements after the recursive call is opposite to that of each called function;

  5. There must be a terminating statement in a recursive function.

Summarize recursion in one sentence: self-invocation and completion status

Task
The monkey picked N peaches on the first day, and ate half of them at that time, but was not satisfied, so he ate another one. The next day, he ate half of the remaining peaches and ate one more. After that, eat half and one of the remaining one from the previous day every day. On the 10th day, when I wanted to eat, there was only one peach left. How many peaches were picked on the first day? And print the number of peaches left per day in reverse.

 
 
#include <stdio.h>
int getPeachNumber(int n)  
{
    int num;    
    if(n==10)
    {
       return 1;      
    } 
    else
    {
        num = (getPeachNumber(n+1)+1)*2;  
        printf("第%d天所剩桃子%d个\n", n, num); 
    }
    return num;
}
int main()
{
    int num = getPeachNumber(1);
    printf("猴子第一天摘了:%d个桃子。\n", num);
    return 0;
}

Recursive demo.

There are 5 people sitting together, how old is the fifth person? He said he was 2 years older than the 4th person. Ask the age of the fourth person, he said that he is 2 years older than the third person. Ask the third person, and say that he is two years older than the second person. Ask the second person and say that he is two years older than the first person. Finally, I asked the first person, and he said he was 10 years old. How old is the fifth person?

Program analysis:
Using the recursive method, the recursion is divided into two stages: backtracking and recursion. If you want to know the age of the fifth person, you need to know the age of the fourth person, and so on, until the first person (10 years old), and then push back.

 
 
#include <stdio.h> 
int dfs(int n) {
    return n == 1 ? 10 : dfs(n - 1) + 2;
}
int main() 
{

    printf("第5个人的年龄是%d岁", dfs(5)); 
    return 0;
} 

local and global

Variables in C language can be divided into two types according to the scope of scope, namely local variables and global variables.

  • Local variables are also known as internal variables. Local variables are defined within the function. Its scope is limited to the function, and it is illegal to use this variable after leaving the function. Variables can also be defined in a compound statement, and its scope is only within the scope of the compound statement.

  • Global variables are also known as external variables, which are variables defined outside a function. It does not belong to any function, it belongs to a source program file. Its scope is the entire source program.

variable storage class

mtianyan: C language is divided according to the life cycle of variables, which can be divided into static storage mode and dynamic storage mode.

  • Static storage method: refers to the method of allocating fixed storage space during the running of the program. Variables that exist throughout the program execution, such as global variables, are stored in the static storage area.

  • Dynamic storage method: refers to the method of dynamically allocating storage space according to the needs during the running of the program. The variables stored in the dynamic storage area are established and released according to the needs of program operation, usually including: function formal parameters; automatic variables; field protection and return address when the function is called, etc.

The storage category in C language is divided into four categories:

  • automatic (auto),

  • static,

  • register

  • external (extern).

1. The variable defined with the keyword auto is an automatic variable, and auto can be omitted. If auto is not written, it is implicitly designated as "automatic storage category", which belongs to the dynamic storage method. like:

picture

2. Modified with static is a static variable. If it is defined inside a function, it is called a static local variable; if it is defined outside a function, it is called a static external variable. The following are static local variables:

picture

Note: Static local variables belong to the static storage category. Storage units are allocated in the static storage area and are not released during the entire running of the program; static local variables are assigned initial values ​​at compile time, that is, they are only assigned initial values ​​once; if local variables are defined If the initial value is not assigned at the time, then for static local variables, the initial value 0 (for numeric variables) or a null character (for character variables) is automatically assigned at compile time.

3. In order to improve efficiency, the C language allows the value of a local variable to be placed in a register in the CPU. This variable is called a "register variable" and is declared with the keyword register. For example:

picture

mtianyan: Note: Only local automatic variables and formal parameters can be used as register variables; the number of registers in a computer system is limited, and any number of register variables cannot be defined; local static variables cannot be defined as register variables.

4. The variable declared with extern is an external variable. The meaning of an external variable is that a function can call a variable defined after the function. like:

picture

Intrinsic and extrinsic functions

  • In C language, functions that cannot be called by other source files are called internal functions. Internal functions are defined by the static keyword, so they are also called static functions. The form is: static [data type] function name
    ([parameter])

  • The static here is a limitation on the scope of the function, and the function can only be used in the source file where it is located, so there is no problem with internal functions with the same function name appearing in different files.

  • In C language, a function that can be called by other source files is called an external function. The external function is defined by the extern keyword, and the form is:
    extern [data type] function name ([parameter])

  • The C language stipulates that when the scope of the function is not specified, the system will consider it as an external function by default, so extern can also be omitted when an external function needs to be defined.

Static variables are only assigned once

External function exercise

hello.c

#include <stdio.h>
#include "test.c"   //引用test.c文件
extern void printLine()     //这里定义的方法对吗?
{
   printf("**************\n");   
}
int main()
{
    say();
    return 0;
}

test.c

 
 
#include <stdio.h>
void printLine();
static void say(){
printLine();
printf("I love imooc\n");
printf("good good study!\n");
printf("day day up!\n");
printLine();
}

For hello.c, the test.c file is directly introduced. Then you can call the static method say() in testc,
which is not introduced in test.c, and you can call the method exposed in another source file through declaration.

Combined training

The taxi fare rules in Beijing are as follows:

  1. The unit price per kilometer is 2.3 yuan

  2. The starting price is 13 yuan (including 3 kilometers)

  3. Take a taxi from 23:00 in the evening (inclusive) to 5:00 in the morning of the next day (exclusive), and the unit price per kilometer will be charged by 20%.

  4. A fuel surcharge of 1 yuan is charged for each ride.
    Xiao Ming has to take a taxi to and from get off work every day. The distance between the company and his home is 12 kilometers.
    Please write a small program to calculate the total cost of Xiao Ming's daily taxi rides.

#include <stdio.h>

float taxifee(int clock,int miles)
{
    float money;
    if(miles<=3)
    {
        money=14;
        printf("费用为14\n");
    }
    else
    {
        if(clock>=23 || clock<5)
        {
            money=13+1+2.3*(miles-3)*1.2;
            printf("夜间车费为:%f\n",money);
        }
        else
        {
            money=13+1+2.3*(miles-3);
            printf("日间车费为:%f\n",money);
        }
    }

    return money;    
}
int main()
{
    printf("打的总费用:%.1f\n",taxifee(9,12)+taxifee(18,12));
    return 0;
}

Array first experience

The program also needs a container, but the container is a bit special. It is a continuous memory space with a fixed size and the same data type in the program . It also has a nice name called an array. An array can be understood as a fixed size, and the items placed are a shopping bag of the same type, and
the items in the shopping bag are placed in a certain order.

Let's see how to declare an array:

数据类型 数组名称[长度];

Just declaring the array doesn't work, let's see how the array is initialized. Speaking of initialization, there are three forms of array initialization in C language, namely:

  1. datatype array name[length n] = {element1, element2...elementn};

  2. datatype array name[] = {element1, element2...elementn};

  3. Data Type ArrayName[length n]; ArrayName[0] = Element 1; ArrayName[1] = Element 2; ArrayName[n-1] = Element n;

How do we get the elements in the array after we put the data in the array?

When getting an array element: array name [subscript corresponding to the element];

For example: to initialize an array  int arr[3] = {1,2,3}; , then arr[0] is element 1.

Notice:

  1. The subscripts of the array all start with 0 ;

  2. When the array is initialized, the number of elements in the array cannot be greater than the declared array length;

  3. mtianyan: If the first initialization method is used, when the number of elements is less than the length of the array, the redundant array elements are initialized to 0;

  4. When the array is not initialized after declaring, the initial value of the array elements of the static (static) and external (extern) types is 0 , and the initial value of the elements of the array of the automatic (auto) type is uncertain.

array traversal

The array can traverse each element in a circular manner, instead of manually obtaining the element at a specified position each time. For example, we use a for loop to traverse an array:

picture

Note the following points:

  1. It is best to avoid array out-of-bounds access , and the loop variable should not exceed the length of the array.

  2. Once the array length of C language is declared, the length is fixed and cannot be changed , and C language does not provide a method to calculate the array length .

Since the C language does not have a mechanism to check the length of the array or the array is out of bounds, it may be compiled and passed in the editor, but the result is not certain, so it is better not to cross the bounds or change the length of the array.

c language to get the length of the array

 
 
int length = sizeof(arr)/sizeof(arr[0]);

array as function parameter

Arrays can use the entire array as a function parameter, or an element in the array as a function parameter:

  1. The entire array is used as a function parameter, that is, the array name is passed into the function , for example:

picture

The elements in the array are used as function parameters, that is, the parameters in the array are passed into the function, for example:

picture

Note the following when using arrays as function parameters:

  1. When the array name is passed as a function argument, the array type parameter at the function definition as the receiving parameter can either specify the length or not specify the length.

  2. When an array element is passed as a function argument, the type of the array element must be consistent with the data type of the formal parameter.

mtianyan: Application of arrays (1) [bubble sort]

Taking ascending sort as an example, the idea of ​​bubble sorting: compare adjacent elements pairwise, and put the larger number behind until all the numbers are sorted. Just like when queuing up in elementary school, we line up according to size. Pull out a classmate to compare with the ones behind.

#include <stdio.h>
int main()
{
    double arr[]={1.78, 1.77, 1.82, 1.79, 1.85, 1.75, 1.86, 1.77, 1.81, 1.80};
    int i,j;
    printf("\n************排队前*************\n");
    for(i=0;i<10;i++)
    {
        if(i != 9)   
            printf("%1.2f, ", arr[i]);  //%1.2f表示小数点前一位,小数点后精确到两位
        else
            printf("%1.2f", arr[i]);    //%1.2f表示小数点前一位,小数点后精确到两位
    }
    for(i=8; i>=0; i--)
    {
        for(j=0;j<=i;j++)
        {
            if( arr[j]>arr[j+1])      //当前面的数比后面的数大时
            {
                double temp;    //定义临时变量temp
                temp=arr[j];//将前面的数赋值给temp
                arr[j]=arr[j+1];             //前后之数颠倒位置
                arr[j+1]=temp;//将较大的数放在后面    
            }                 
        }                
    }
    printf("\n************排队后*************\n");
    for(i=0;i<10;i++)
    {
        if(i != 9)   
            printf("%1.2f, ", arr[i]);  //%1.2f表示小数点前一位,小数点后精确到两位     
        else
            printf("%1.2f", arr[i]);    //%1.2f表示小数点前一位,小数点后精确到两位
    }
    return 0;    
}

Application of array (2) [Array search function]

When we go shopping and return home with a shopping bag, we will check the items in the shopping bag one by one to see if they are missing or are all things we want to buy.

Then when applied to the program, you can use the array search function to see if the data exists, and if so, return the subscript of the element.

#include <stdio.h>
int getIndex(int arr[5],int value)
{
    int i;
    int index;
    for(i=0;i<5;i++)
    {
       /* 请完善数组查询功能 */
       if(arr[i]==value)
        {
            index=i;
            break;
        }  
       index=-1;
    }
    return index;
}

int main()
{
    int arr[5]={3,12,9,8,6};
    int value = 8;
    int index = getIndex(arr,value);      //这里应该传什么参数呢?
    if(index!=-1)
    {
        printf("%d在数组中存在,下标为:%d\n",value,index);             
    }
    else
    {
        printf("%d在数组中不存在。\n",value);    
    }
    return 0;    
}

Strings and Arrays

In the C language, there is no way to directly define the string data type, but we can use an array to define the string we want. Generally, there are two formats:

  1. char string name[length] = "string value";

  2. char string name[length] = {'Character 1','Character 2',...,'Character n','\0'};

Notice:

  1. The length in [] can be omitted;

  2. When using the second method, the last element must be '\0', '\0' means the end of the string;

  3. When using the second method, Chinese cannot be written in the array. Use : or ;
    when outputting strings .printf(“%s”,字符数组名字);puts(字符数组名字)

mtianyan: string function

Commonly used string functions are as follows (strlen, strcmp, strcpy, strcat, atoi):

picture

Note the following when using string functions:

strlen() gets the length of the string, '\0' is not included in the length of the string, and the length of Chinese characters and letters is different. for example:

picture

When strcmp() compares, it converts the strings into ASCII codes and then compares them. The returned result is 0, which means the ASCII codes of s1 and s2 are equal. The returned result is 1, which means that the ASCII codes of s1 are larger than s2. The returned result is -1 indicates that the ASCII code of s1 is smaller than that of s2, for example:

picture

After copying by strcpy(), the original string will be overwritten and the string constant cannot be copied, for example:

picture

When strcat is used, the memory spaces pointed to by s1 and s2 cannot overlap, and s1 must have enough space to accommodate the string to be copied, such as:

picture

Multidimensional Arrays

The definition format of a multidimensional array is:
data type array name [constant expression 1] [constant expression 2]...[constant expression n];

picture

A two-dimensional array named num and data type int is defined. Among them, the first [3] indicates the length of the subscript in the first dimension, just like the shopping that is stored in categories when shopping; the second [3] indicates the length of the subscript in the second dimension, just like the elements in each shopping bag.

picture

The initialization of multidimensional arrays is similar to the initialization of one-dimensional arrays, and there are two types:

  1. Data type array name [constant expression 1] [constant expression 2]...[constant expression n] = {{ value1,..,valuen},{value1,..,valuen},. ..,{value1,..,valuen}};

  2. DATA TYPE ARRAYNAME[CONSTEXPR1][CONSTEXPR2]...[CONSTEXPRn]; ARRAYNAME[SUBSCRIPT1][SUBSCRIPT2]...[SUBSCRIPTn] = value;

When initializing multidimensional arrays, pay attention to the following:

  1. When using the first type of initialization, the array declaration must specify the dimension of the column. mtianyan: Because the system will allocate space according to the total number of elements in the array, when the total number of elements and the dimension of the column are known, the dimension of the row will be directly calculated;

  2. When using the second type of initialization, the array declaration must specify both the row and column dimensions.

When defining a two-dimensional array, the number of rows may not be specified, but the number of columns must be specified

When defining a two-dimensional array, the number of rows may not be specified, but the number of columns must be specified.

Traversal of multidimensional arrays

Multidimensional arrays also exist for traversal, and like one-dimensional array traversal, loops are also required. The difference is that multidimensional arrays need to use nested loops.

Note: The subscript of each dimension of the multidimensional array cannot exceed the bounds.

Combined training:

#include <stdio.h>
#define N 10
//打印分数 
void printScore(int score[])
{
    int i;
    printf("\n");
    for(i=0;i<N;i++)
    {
        printf("%d ",score[i]);               
    }
    printf("\n");     
}
//计算考试总分 
int getTotalScore(int score[])
{
    int sum = 0;
    int i;
    for(i=0;i<N;i++)
    {
        sum+=score[i];                
    } 
    return sum;
}
//计算平均分 
int getAvgScore(int score[])
{
    return getTotalScore(score)/N;   
}
//计算最高分 
int getMax(int score[])
{
    int max = -1;
    int i;
    for(i=0;i<N;i++)
    {
        if(score[i]>max)
        {
            max = score[i];              
        }                
    } 
    return max;
}
//计算最低分 
int getMin(int score[])
{
    int min =100;
    int i;
    for(i=0;i<N;i++)
    {
        if(score[i]< min)
        {
            min = score[i];              
        }                
    } 
    return min;
}
//分数降序排序 
void sort(int score[])
{
    int i,j;
    for(i=N-2;i>=0;i--)
    {
        for(j=0;j<=i;j++)
        {
            if(score[j]<score[j+1])
            {
                int temp;
                temp = score[j];
                score[j] = score[j+1]; 
                score[j+1]=temp;                  
            }                 
        }                   
    }
    printScore(score);     
}

int main()
{
    int score[N]={67,98,75,63,82,79,81,91,66,84};
    int sum,avg,max,min;
    sum = getTotalScore(score);
    avg = getAvgScore(score);
    max = getMax(score);
    min = getMin(score);
    printf("总分是:%d\n",sum);
    printf("平均分是:%d\n",avg);
    printf("最高分是:%d\n",max);
    printf("最低分是:%d\n",min);
    printf("----------成绩排名---------\n");
    sort(score);
    return 0;    
}

Guess you like

Origin blog.csdn.net/weixin_41114301/article/details/132415970