Introduction to C language

“This is the 26th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

About the author

  • The authors introduce

🍓 blog home page: author’s home page 🍓 Introduction: JAVA quality creator 🥇, a junior student 🎓, participated in various provincial and national competitions during school, and won a series of honors


Introduction to C language

As soon as C language appeared, it was rapidly popularized and promoted all over the world with its features of rich functions, strong expression ability, flexibility and convenience, and wide application. C language not only has high execution efficiency and good portability, can be used to develop application software, drivers, operating systems and so on. C is also the ancestor of many other high-level languages, so learning C is a required course to enter the programming world.

Create a function

C provides a number of library functions: stdio.h, for example, provides output functions

General form of a custom function:

Note:

  1. []Contains content that can be omitted, data type description omitted, default isintType function; Parameter omission indicates that the function isNo arguments functionThe parameter is not omitted to indicate that the function isHave reference function;
  2. Function names follow the naming conventions for identifiers;
  3. Custom functions should be placed as far as possiblemainBefore the function, if you want toAfter the main functionBefore mainFirst statementCustom function declaration format:
[Data Type Description]Function name ([parameter]);Copy the code

A function call

When we need a custom function, we call it, and when we call it, we call it a function call.

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

Function name ([parameter]); 
Copy the code

Note:

  1. Call to a function that has no arguments[]The omission of inclusion.
  1. []Can be ** constants, variables, or other constructively typed data and expressions. ** Multiple arguments are separated by commas.

Yes, no

Functions that require no function parameters are called parametric functions, and functions that require function parameters are called parametric functions.

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

The only difference between a function with and without parameters is that function () has an additional argument list.

  • Parameterized functions are more flexible, and the output can vary as n changes, simply by passing a single argument in the main function
  • In a nonparametric function, the output is relatively fixed, and you need to change the value of the loop variable in a custom method when needed.

The f takes part in the argument

The parameters of a function are divided into parameters and arguments.

  • A parameter is an argument used to define the name and body of a function to receive arguments passed in when the function is called.

Just like Xiao Ming, words are not deeds;

  • Arguments are arguments that are passed to the function when called.

Just like xiao Gang can actually take action.

Function parameters and arguments have the following characteristics:

  • The parameter allocates memory units only when it is called, and the allocated memory units are immediately freed when the call ends. Therefore, parameters are valid only inside functions.

This parameter cannot be used after the call returns the calling function.

  • Arguments can be constants, variables, expressions, functions, and so on.

No matter what type of quantity the arguments are, they must have certain values that can be passed to the parameters when a function call is made. Therefore, arguments should be given certain values in advance by methods such as assignment.

  • When passing parameters, arguments and parameters should be strictly the same in number, type, and order; otherwise, type mismatch errors will occur.

The return value of the function

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

The return value of the function should note the following:

  • The value of the function can only pass throughreturnStatement returns the calling function.

The usual form of a return statement is:

returnThe expression can also be:return(expression);Copy the code
  • The type of the function value should be the same as the type of the function in the function definition.

Notes: If they are inconsistent, the type is automatically converted based on the return type of the function.

  • No return valueThe function,The return typeforvoid.

Note:

void
Copy the code

Functions can have blocks of execution code, but no return values.

Void if there is a return statement, the ** statement can only end the function. ** The format is: return;

Recursive Function (I)

Recursion is when a function calls itself within its function.

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

Note that recursive functions must have termination conditions

Recursive function (2)

Take a look at how it works:

When the program computes the factorial of 5, it recurses, returns 1 when n=1 or n=0, and then computes and returns. It follows that a recursive function must have an end condition.

Recursive function features:

  1. Each level of function call has its own variable, but the function code is not copied. For example, when calculating the factorial of 5, the variable is different each time;
  2. Each call will return one time, such as when calculating the factorial of 5, each recursion will return the next time;
  3. In a recursive function, the statement before the recursive call has the same execution order as the function called at all levels.
  4. In a recursive function, the order of execution of the statements after a recursive call is reversed from the order of each function being called.
  5. Recursive functions must have termination statements.

To sum up recursion in one sentence: self – calling and complete state

The task monkey picked N peaches on the first day and ate half of them. Before he could eat enough, he ate another peach. The next day he ate half of the remaining peaches and one more. Eat half and a half of what’s left over from the day before every day. On the 10th day, when I wanted to eat, THERE was only one peach left. How many peaches did I pick on the first day? And reverse print the number of peaches left each day.

#include <stdio.h>
int getPeachNumber(int n)  
{
    int num;    
    if(n==10)
    {
       return 1;      
    } 
    else
    {
        num = (getPeachNumber(n+1) +1) *2;  
        printf("Peaches left on day %d \n", n, num); 
    }
    return num;
}
int main(a)
{
    int num = getPeachNumber(1);
    printf("The monkey picked %d peaches on the first day. \n", num);
    return 0;
}
Copy the code

Recursive demo.

You have five people sitting around and you say, how old is the fifth person? He said he was two years older than the fourth. Asked how old the fourth man was, he said he was two years older than the third. He asked the third man and said he was two years older than the second. Ask the second person and say he is two years older than the first person. Finally I asked the first guy, and he said he was 10. How old is the fifth person?

Program analysis: the use of recursion method, recursion is divided into back and recursion two stages. 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 you reach the first person (age 10), and then back again.

#include <stdio.h> 
int dfs(int n) {
    return n == 1 ? 10 : dfs(n - 1) + 2;
}
int main(a) 
{
    
    printf("The fifth person is %d years old.", dfs(5)); 
    return 0;
} 
Copy the code

Local and global

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

  • Local variables are also called internal variables. Local variables are defined within functions. Its scope is limited to the function, and it is illegal to use such a variable after leaving the function. Variables can also be defined in compound statements and are scoped only in compound statements.
  • A global variable, also known as an external variable, is a variable defined outside a function. It doesn’t belong to a function, it belongs to a source file. Its scope is the entire source program.

Variable storage category

C language divides variables into static storage mode and dynamic storage mode according to their life cycle.

  • Static storage: A method of allocating fixed storage space during the running of a program. Static storage stores variables, such as global variables, that exist throughout the execution of the program.
  • Dynamic storage: Dynamically allocates storage space during program running. The variables stored in the dynamic storage area are created and released according to the needs of the program operation, usually including: functional parameters; Automatic variable; Function call on the spot protection and return address, etc.

Storage in C language is divided into four categories:

  • Auto
  • Static
  • Register of registers
  • Extern (extern).

1. The variable defined by keyword auto is an automatic variable. Auto can be omitted. Such as:

Static variables defined inside a function are called static local variables. If defined outside of a function, it is called a static external variable. Static local variables are as follows:

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 run of the program. Static local variables are assigned initial values at compile time, that is, only once; For static local variables, an initial value of 0 (object value) or a null character (object character) is automatically assigned at compile time if no initial value is assigned when defining the local variable.

3. To improve efficiency, C allows the value of a local variable to be placed in a REGISTER in the CPU. This type of variable is called a register variable and is declared with the keyword register. Such as:

Note: Only local automatic variables and formal parameters can be used as register variables; The number of registers in a computer system is limited, so arbitrarily many register variables cannot be defined. Local static variables cannot be defined as register variables.

Extern = extern; extern = extern; extern = extern; extern = extern; extern = extern; extern = extern; extern = extern; Such as:

Internal and external functions

  • Static functions that cannot be called by other sources in C are called static functions defined by the static keyword.
  • Static is a limit on the scope of a function that can only be used in its source file, so it is ok to have internal functions with the same function name in different files.
  • Extern = extern; extern = extern; extern = extern; extern = extern;
  • C specifies that extern is considered external by default if the scope of a function is not specified, so extern can also be omitted when external functions need to be defined.

Static variables are assigned only once

External function exercises

hello.c

#include <stdio.h>
#include "test.c"   // reference the test.c file
extern void printLine(a)     // Is the method defined here correct?
{
   printf("**************\n");   
}
int main(a)
{
    say();
    return 0;
}
Copy the code

test.c

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

For hello.c, the test.c file is introduced directly. You can call the static method say() in testc, which is not introduced in test.c. You can declare another method exposed in the source file.

Comprehensive practice

Beijing taxi charging rules are as follows:

  1. The unit price per kilometer is 2.3 yuan
  2. Starting price: 13 yuan (including 3 km)
  3. Take a taxi from 23pm (inclusive) to 5am (exclusive), the unit price of each kilometer will be charged 20% more.
  4. A fuel surtax of 1 yuan is added for each ride.

Xiao Ming takes a taxi to and from work every day. The distance between the company and home is 12 kilometers. He goes to work at 9 a.m. and gets off work at 6 p.m. Please write a small program to calculate xiao Ming’s total taxi fare every day.

#include <stdio.h>

float taxifee(int clock,int miles)
{
    float money;
    if(miles<=3)
    {
        money=14;
        printf("The cost is 14\n");
    }
    else
    {
        if(clock>=23 || clock<5)
        {
            money=13+1+2.3*(miles- 3) *1.2;
            printf("Night fare: %f\n",money);
        }
        else
        {
            money=13+1+2.3*(miles- 3);
            printf("Day fare: %f\n",money); }}return money;    
}
int main(a)
{
    printf("Total cost of taxi: %.1f\n",taxifee(9.12)+taxifee(18.12));
    return 0;
}
Copy the code

After the language

The original intention of the director to write blog is very simple, I hope everyone in the process of learning less detours, learn more things, to their own help to leave your praise 👍 or pay attention to ➕ are the biggest support for me, your attention and praise to the director every day more power.

If you don’t understand one part of the article, you can reply to me in the comment section. Let’s discuss, learn and progress together!

Wechat (Z613500) or QQ (1016942589) for detailed communication.