It's hard to hear C language? Why don't you come and see my article

1. Write in front

Today is the seventh day of the lunar new year. After a few days of new year's greetings, I have begun to update my C language series. The process of a Java programmer learning C language. As the saying goes, learning a new language and an introductory book are more important. Tan Haoqiang is the most important in China. Being reasonable is really rubbish, What I want to recommend today is "C programming language". This book is written by rich, the father of C language. There should be no better book for the introduction of C language than this one!

2. The first C language program

Xiaobai, who has learned other languages, or has not learned other languages, believes that the first program for everyone to learn any language is helloworld, so I will also take you to write a helloworld. Before writing this program, everyone's environment should be prepared. Of course, some people like to use vscode, which is OK. Turnips and vegetables have their own love! Let me be wordy here. Before learning C language, I hope you will finish the pre courses first CMake one is enough In this way, the basic pre environment is ready. Let's write the first program! The specific codes are as follows:

// Contains the contents of the standard library
#include <stdio.h>

main() // Define a function called main that does not accept parameter values
{ //The statements of the main function are enclosed in curly braces
    printf("hello world \n"); //The main function calls the library function printf to display the string sequence \ n for line breaks
}

The results of the operation are as follows:

We can see that our first program in C language is written. We need to understand the meaning of this large string of code. The first is the first sentence #include < stdio h> , from the perspective of java programmers, we can understand it as a guide package, okay! But some people said, I'm Xiaobai. I don't understand what to do. Looking down, we can see that we called a printf function, but we didn't write this function. Where did we come from? From stdio Introduced in H. One of the great functions of the program is to help us solve the problem of repetition. For example, we can't print statements here. I have to write this function every time I want to print something! Therefore, intelligent human beings can print this and then package it. Just write it once. We only need to import the header file when using it. We can open the header file to see what's in it. The details are as follows:

It can be seen that so many functions can be called, that is, the repeated functions are encapsulated into a function, which is the ability of abstraction and one of the abilities that we programmers need to exercise.

Let's continue to look at the whole of main() {}, which we call function, where main is the function name. Here we can understand the main function, which should be well understood by java programmers. I won't repeat it here, but it's not very easy to understand for Xiaobai. Then let me talk about it. Computers are machines, which are stupid, So you have to give it an entry, or it doesn't know where to start running your code. Here, main() {}, which we call the main function, is that the computer will start running this function.

Finally, let's take a look at the contents of our function body, printf("hello world \n"); It is a printed statement that calls the functions in the standard library. I won't repeat it here. When we talk about the standard library later, we will discuss it in detail.

Here's another thing we need to pay attention to, that is, what does the ending \ n mean? It means line feed. In each kind of special symbols, we need to escape, \ is the escape character. The common special ones are as follows:

Special symbolsmeaning
\nLine feed
\tTab
\bBS-Backspace
"Double quotation mark
\Backslash

3. Variables and arithmetic expressions

Let's look at a program that uses a formula
Photograph Surname degree = ( 5 / 9 ) ( Hua Surname degree − 32 ) Celsius = (5 / 9) (Fahrenheit - 32) Celsius = (5 / 9) (Fahrenheit − 32)
Print the comparison table corresponding to Fahrenheit and Celsius. The specific codes are as follows:

#include <stdio.h>

main() {
    int fahr, celsius;
    int lower, upper, step;

    lower = 0; // Lower limit of thermometer
    upper = 300; // Upper limit of thermometer
    step = 20; // step

    fahr = lower;
    while (fahr <= upper) {
        celsius = 5 * (fahr - 32) / 9;
        printf("%3d %6d\n", fahr, celsius);
        fahr = fahr + step;
    }
}

From this program, we are exposed to some new concepts: annotation, declaration, variable, arithmetic expression, loop, formatted output.

  1. notes

    In order to better explain the code written by yourself, the general program will have comments, but a good program can be understood by the first line. If you don't need too many comments, it may mislead others. The comments include single number comments, which are expressed by / / and multi line comments are expressed by / * * /. The lower limit of the above program / / thermometer is comments.

  2. Declare variable

    All variables must be declared before use. The declaration is usually placed at the beginning of the function. Before any executable statement, it is used to declare the attribute of the variable, which is composed of a type name and a variable table. Common data types are as follows:

    typemeaning
    charCharacter one byte
    shortShort
    longLong shaping
    doubleDouble precision floating point number
  3. loop

    Execution method of while loop statement: first test the condition in parentheses. If the condition is true, execute the loop body; Then retest the condition in parentheses. If it is true, execute the loop body again; When the conditional test result in parentheses is false, the loop ends and continues to execute the next statement after the while loop statement.

  4. Format output

    The% d in the printf function represents a placeholder, and the subsequent output variables will be output in this format. The common formatted output in C language is as follows:

    formatmeaning
    %dPrint as decimal integer
    %6dPrint as decimal integers, at least 6 characters wide
    %fPrint as floating point number
    %6fPrint as a floating point number, at least 6 characters wide
    %.2fPrint according to floating point number, with two decimal places after the decimal point
    %6.2fPrint according to floating point number, at least 6 characters wide, with two decimal places after the decimal point
    %OOctal number
    %xHexadecimal number
    %ccharacter
    %scharacter string
    %%Percent sign itself

After talking about some pre knowledge, let's take a look at the running results of this program. The details are as follows:

There is a serious problem with the above program. Because we use integer operation, the result is not very correct. For example, the degree Celsius corresponding to 0 degrees Fahrenheit should be - 17.8 instead of - 17. In order to get more accurate results, floating-point arithmetic should be used. We need to modify the procedure appropriately. The specific codes are as follows:

#include <stdio.h>

main() {
    float fahr, celsius;
    int lower, upper, step;

    lower = 0;
    upper = 300;
    step = 20;

    fahr = lower;
    while (fahr <= upper) {
        celsius = (5.0/ 9.0) * (fahr - 32) ;
        printf("%3.0f %6.1f\n", fahr, celsius);
        fahr = fahr + step;
    }
}

The results of the operation are as follows:

We can see that the result of our calculation is correct. The result of our calculation here is more accurate than before. But here I want to introduce a very important rule of calculation.

  • If all operands of an arithmetic operator are integers, the integer operation is performed.
  • If an integer is a floating-point type, the integer is automatically converted to a floating-point type and then calculated.

For the strongly typed language we learn, we should be very sensitive to types. A variable not only has a value, but also has a corresponding type. A variable is a whole only when it has a value and type.

4.for loop

Let's look at the above code. There are a lot of initialization and use of variables. What can we do to simplify the corresponding code? We can use our for loop to simplify the above code. The specific code is as follows:

#include <stdio.h>

main() {

    int fahr;

    for (fahr = 0; fahr <= 300; fahr = fahr + 20) {
        printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32));
    }
}


The results of the operation are as follows:

We can see that the loop mainly has three parts: for (fahr = 0; fahr < = 300; fahr = fahr + 20) {} where fahr = 0 is the initialization part of the for loop, which is executed only once before entering the loop, and the second part fahr < = 300 is the part that controls the test or condition of the loop. Loop control evaluates the condition, and if the result is true, the loop body is executed. After that, execute the third part fahr = fahr + 20, increase the cyclic variable fahr by one step, and evaluate the condition again. If the calculated condition is false, the loop will terminate.

At this time, someone may ask, when do we use while and when do we use for? My answer is that you are happy. Of course, there is also a standard: for is more suitable for initializing and increasing the step size of a single statement and is logically related, because it puts the loop control statements together.

5. Symbolic Constant

Let's take a look at the above program. We can see that there are 300, 20 and 0 in the program. These numbers are called magic numbers in our language. This is not a good thing. If one day we want to change the upper limit of temperature from 300 to 400, then I need to modify 300 in the whole program, so it is easy to forget and leak. So is there any good way to centrally manage these magic numbers? To tell you clearly, yes is a symbolic constant. We will change another version as follows:

#include <stdio.h>
#define LOWER 0
#define UPPER 300
#define STEP 20

main() {

    int fahr;

    for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) {
        printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32));
    }
}

The results of the operation are as follows:

#The define instruction can define a symbolic name (or symbolic constant) as a specific string: #define the text replaced by the name. The replaced text can be any character sequence, not limited to numbers.

6. Character input / output

6.1 document copying

We learned about output earlier. Today, let's learn about input. The old rule is to look at the code first. The specific code is as follows:

#include <stdio.h>

main() {
    int c;
    while ((c = getchar()) != EOF) {
        putchar(c);
    }
}

The getchar() function reads the next input character from the text stream entered by the keyboard and returns it as the result value.

putchar() reads the characters in the corresponding variables and prints them on the screen.

End of EOF file.

Therefore, the above program can be understood as: what we enter will be printed out. If we enter the terminator, the corresponding cycle will be ended, that is, ctrl+D.

6.2 character count

With the above basic knowledge, we can write a program to calculate the number of characters we input. The specific code is as follows:

#include <stdio.h>

main() {
    double nc;
    for (nc = 0; getchar() != EOF; ++nc);
    printf("%.0f\n", nc);
}

The results of the operation are as follows:

We entered ten characters, and one of them entered, so there are 11 printed here, no problem.

6.3 line count

With the above basic knowledge, we can write a program to calculate the number of lines of characters we input. The specific code is as follows:

#include <stdio.h>

main() {
    double c, n1;
    n1 = 0.0;
    while ((c = getchar()) != EOF) {
        if (c == '\n')
            ++n1;
    }
    printf("%0.f \n", n1);
}

Here we learned a new thing, that is, if judgment. The condition in the middle of the bracket is the condition. If the condition is met, the + + n1 operation will be executed. If the condition is not met, the + + n1 operation will not be executed. Where + + n1 = n1=n1 + 1, but this + + or - has pre operations and post operations. I'll make it clear to you when I write variables. The results of the operation are as follows:

We can see that the output of our program is correct.

6.4 word count

After the previous study, we write the following code:

#include <stdio.h>
#define IN 1
#define OUT 0

main(){
    int c, n1, nw, nc, state;
    
    state = OUT;
    n1 = nw = nc = 0;
    while ((c = getchar()) != EOF) {
        ++nc;
        if(c == '\n')
            n1 ++;
        if(c == ' ' || c == '\n' || c == '\t')
            state = OUT;
        else if(state == OUT){
            state = IN;
            ++nw;
        }
    }
    printf("%d %d %d \n", n1, nw, nc);
}

Looking at the above code, we have learned something new. One is the symbol "or", which means that if one of all the conditions is true, even if the whole expression is true, the other is & & which means that it will be true if all the conditions are met. In other cases, it will not be true. Then there is a new format:

if(expression)
Statement 1;
else
 Statement 2

When the above format expression is true, statement 1 will be executed. If the expression is not true, statement 2 will be executed.

There is another format, which is as follows:

if(Expression 1)
Statement 1
else if(Expression 2)
Statement 2
else
 Statement 3

If the above format expression 1 is true, statement 1 will be executed. If expression 2 is true, statement 2 will be executed. If none of them is true, statement 3 will be executed

7. Array

Let's look at a program first. The specific code is as follows:

#include <stdio.h>

main() {
    int c, i, nwhite, nother;
    int ndigit[10];

    nwhite = nother = 0;
    for (i = 0; i < 10; ++i) {
        ndigit[i] = 0;
    }

    while ((c = getchar()) != EOF){
        if(c >= '0' && c<='9')
            ++ndigit[c-'0'];
        else if (c==' ' || c=='\n' ||c=='\t')
            ++nwhite;
        else
            ++nother;
    }
    printf("digits=");
    for (i = 0; i < 10; ++i)
        printf(" %d", ndigit[i]);
    printf(", white space = %d, other = %d\n",nwhite, nother);
}

In the above program, we have come into contact with a new knowledge, that is, array. We need to know that the index of array is the length of array. The index of array cannot exceed the length of array. If it is exceeded, the subscript will cross the boundary. Array can be understood as a series of memory spaces, then store values of the same type, and finally access the value of the corresponding position through subscript.

The above program is to count. We enter the value and count the corresponding number. The position of 0-9 of the array represents the number of corresponding numbers 0-9 respectively. The running results are as follows:

8. Function

First look at the following procedure:

#include <stdio.h>
// Function definition
int power(int m, int n);

main() {
    int i;
    for (i = 0; i < 10; ++i)
        printf("%d %d %d\n", i, power(2, i), power(-3, i));
    return 0;
}

// Function implementation
int power(int base, int n) {
    int i, p;
    p = 1;
    for (i = 0; i <= n; ++i)
        p = p * base;
    return p;
}

From the above program, we can get the general types of functions, which are as follows:

Return value type function name(0 One or more parameter declarations)
{
Declaration part
 Statement sequence
}

be careful:

  • The function does not necessarily need to return value, and the parameters do not necessarily need to have (the variables appearing in the list in parentheses in the function definition are called formal parameters, while the values corresponding to formal parameters in the function call are called actual parameters, and the parameter names in the function prototype and function declaration are not required to be the same)
  • There can be at most one return value
  • The return value is returned to the caller through return

The running results of the above program are as follows:

9. Parameter - value transfer call

All parameters in C language are passed by value, that is, the passed parameter is a value, that is, modifying the value of the parameter will not affect the value of the original parameter, but many people need to modify the value of the parameter and also affect the value of the original parameter. At this time, the pointer needs to be passed in.

All values in the computer are stored in binary to an address, and the pointer is used to store the address. Since the address is given to you, you can find this variable, and your modification will affect the value of this variable.

10. Character array

Let's take a look at the following procedure first. The details are as follows:

#include <stdio.h>

#define MAXLINE 1000

int getLine(char line[], int maxline);

void copy(char to[], char from[]);

main() {
    int len;
    int max;
    char line[MAXLINE];
    char longest[MAXLINE];

    max = 0;
    while ((len = getLine(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0)
        printf("%s", longest);
    return 0;

}

int getLine(char s[], int lim) {
    int c, i;
    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

void copy(char to[], char from[]) {
    int i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}

The above program is to copy the string you entered and print it. Here we only need to focus on one point, that is, in C language, the string must end with \ 0, otherwise there will be problems with the printed content.

11. External variables and scope

Let's take another look at the procedure, which is as follows:

#include <stdio.h>

#define MAXLINE 1000

int max;
char line[MAXLINE];
char longest[MAXLINE];

int getLine(void);
void copy(void);

main() {
    int len;

    max = 0;
    while ((len = getLine()) > 0)
        if (len > max) {
            max = len;
            copy();
        }
    if (max > 0)
        printf("%s", longest);
    return 0;

}

int getLine(void) {
    int c, i;
    for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        line[i] = c;
    if (c == '\n') {
        line[i] = c;
        ++i;
    }
    line[i] = '\0';
    return i;
}

void copy(void ){
    int i = 0;
    while ((longest[i] = line[i]) != '\0')
        ++i;
}

The above program is an adaptation of the original program, mainly to introduce local variables and external variables. The life cycle of local variables dies with the death of the function, while external variables die with the death of the program. Therefore, local variables are an individual, and their modification will not affect others, but external variables, as long as the external variable modified by the function, Other functions are also visible.

12. Write at the end

This blog mainly introduces a brief overview of the C language. Later, I intend to introduce the corresponding contents bit by bit according to the contents of the book. Finally, I wish you a good start.

Keywords: C

Added by vijdev on Mon, 07 Feb 2022 06:13:41 +0200