This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

First, C language programming

This chapter introduces the C language programming basic methods and basic program statements.

From the point of view of program flow, programs can be divided into three basic structures, namely sequence structure, branch structure and loop structure. These three basic structures make up all kinds of complex programs.

C provides a variety of statements to implement these program structures. This chapter introduces these basic statements and their applications, so that the reader has a preliminary understanding of THE C program, for the study of the following chapters to lay a foundation.

C program statements

The execution part of a C program consists of statements. The function of the program is also realized by the execution statement.

C statements can be divided into the following five categories:

1. Expression statement

2. Function call statements

3. Control statements

4. Compound statements

5. Empty statement

  1. Expression statement

An expression statement consists of an expression followed by a semicolon (;). Composition. Its general form is: expression; Executing an expression statement evaluates the value of an expression. For example, x = y + z; Assignment statement y+z; Add operation statement, but the result can not be retained, no practical significance i++; The increment statement increments the value of I by 1

  1. Function call statement

Function name, actual parameters plus semicolon “;” Composition. Its general form is: function name (actual parameter table); To execute a function statement is to call the body of the function, assign the actual parameters to the formal parameters in the function definition, and then execute the statement in the body of the called function to evaluate the value of the function. (More on this in Chapter 5 functions.) For example printf(“C Program”); Call the library function and print the string.

  1. Control statements

Control statements are used to control the flow of a program in order to implement the various structures of the program. They consist of specific statement definers.

C has nine control statements.

Can be divided into the following three categories:

(1) Conditional judgment statement if statement, switch statement

(2) Loop execution statement do while statement, while statement, for statement

(3) goto the break statement, goto statement, continue statement, return statement

  1. Compound statement

A compound statement consists of multiple statements enclosed in parentheses ({}). Compound statements should be treated as single statements rather than multiple statements in a program, for example

{
x=y+z;
a=b+c;
printf(" %d%d ", x, a); }Copy the code

Is a compound statement. Each statement in a compound statement must be preceded by a semicolon “;” At the end, you cannot add a semicolon outside the parentheses “} “.

  1. An empty statement

Only semicolon “;” The statements are called null statements. A null statement is a statement that executes nothing. Hollow statements can be used as the body of an empty loop in a program. For example, while (getchar ()! =’\n’); The function of this statement is to retype any character entered from the keyboard that is not a carriage return. The body of the loop here is an empty statement.

Assignment statements

An assignment statement is an expression statement consisting of an assignment expression plus a semicolon. Its general form is: variable = expression; Assignment statements have the same functions and features as assignment expressions. It is one of the most used statements in a program.

The following points need to be noted when using assignment statements:

  1. Since the expression to the right of the assignment “=” can also be an assignment expression, the following formal variable =(variable = expression); Is true, so it’s nested.

Its general form after expansion is: variable = variable =… = expression;

Such as:

a=b=c=d=e=5; According to the assignment operator's right conjugality, so in fact equivalent to: e=5;
d=e;
c=d;
b=c;
a=b;
Copy the code
  1. Note the difference between assigning an initial value to a variable in the variable specification and the assignment statement. Assigning an initial value to a variable is part of the variable description. The assigned variable must still be separated from other variables of the same class, and the assignment statement must end with a semicolon.

  2. In a variable specification, it is not allowed to assign initial values to multiple variables consecutively. Int a=5,b=5,c=5; Assignment statements, on the other hand, allow continuous assignments

  3. Note the difference between assignment expressions and assignment statements. An assignment expression is an expression that can appear anywhere an expression is allowed, whereas an assignment statement cannot.

If ((x=y+5)>0) z=x; Z =x if x=y+5 is greater than 0.

If ((x=y+5;)); >0) z=x; Because = y + 5; Is a statement and cannot appear in an expression.

4. Data output statement

This section describes statements that output data to the standard output device display. In C, all data input/output is done by library functions. So they’re all function statements. This section first introduces the printf and putchar functions. Printf function The printf function is called the format output function. The last letter f of the keyword in the printf function means “format”. Its function is to display the specified data on the display screen according to the format specified by the user. We have used this function several times in previous examples.

4.1 General form of printf function call

The printf function is a standard library function whose function prototype is in the header file “stdio.h”. But as a special case, you are not required to include the stdio.h file before using the printf function.

The general form of the printf function call is: printf(” format control string “, output table column) where the format control string is used to specify the output format. A format control string can be either a format string or a non-format string.

The format string is a string beginning with %, followed by various format characters to indicate the type, form, length, decimal place, and so on of the output data. For example, %d indicates a decimal integer, %ld indicates a long decimal integer, and %c indicates a character. This will be discussed exclusively later.

Unformatted strings are printed as they are when they are printed, and serve as hints in the display. Each output item is given in the output table column, and it is required that the format string and each output item correspond in number and type.

void main(a)
{
int a=88,b=89;
printf("%d %d\n",a,b);
printf("%d,%d\n",a,b);
printf("%c,%c\n",a,b);
printf("a=%d,b=%d",a,b);
}
a<-- 8 -,b<-- 89.

printf("%d %d\n",a,b);
printf("%d,%d\n",a,b);
printf("%c,%c\n",a,b);
printf("a=%d,b=%d",a,b);
Copy the code

In this example, the values of a and b are output four times, but the output is different because of the format control string. In the fourth line of the output statement format control string, there is a space (non-format character) between the two format strings %d, so there is a space between the output values a and b. The printf statement in line 5 adds a comma to the format control string, so there is a comma between the a and b values in the output. The format string in the sixth line requires the a,b values to be printed as characters. The seventh line adds an unformatted string to prompt the output.

4.2 Format String

In Turbo C, the general form of a format string is: [flag][output minimum width][.Precision][Length] Type The items in square brackets [] are optional.

The significance of each item is described as follows:

  1. Type Type characters are used to indicate the type of the output data. The format and meaning of the characters are shown in the following table:
Format Characters of the output type Format Character Meaning d Outputs signed integers in decimal (positive numbers do not output symbols) o Outputs unsigned integers in octal (no prefix O) x Output the unsigned integer in hexadecimal format (without the prefix OX). U Outputs the unsigned integer in decimal format. F Outputs the single or double precision real number e in decimal format Output single and double precision real numbers in exponential form g outputs single and double precision real numbers in the shorter output width of %f%e c outputs single character s output stringCopy the code
  1. mark

Flag characters include -, +, #, and space, whose meanings are shown in the following table:

Flag Format character Symbol Meaning - Results are left aligned, space is filled on the right + output symbol (plus or minus sign). The output value of space is preceded by a space when it is positive, and is preceded by a minus sign when it is negative. For the O class, prefix is added on the output. For the X class, prefix is added on the output0X; For classes E, G, and f, we only give the decimal point if the result has a decimalCopy the code
  1. Minimum output width

Represents the minimum number of bits in the output as a decimal integer. If the actual number of bits is more than the defined width, the output is the actual number of bits. If the actual number of bits is less than the defined width, the output is supplemented with Spaces or 0.

  1. precision

The precision format is “.” Begins with a decimal integer. The meaning of this item is: if a number is output, the number of decimal places; If the output is characters, it indicates the number of characters to be output. If the actual number of bits is greater than the defined precision, the excess is cut off.

  1. The length of the

The length format is h and L. H indicates the output by short integer, and L indicates the output by long integer.

void main(a){
int a=15;
float b=138.3576278;
double c=35648256.3645687;
char d='p';
printf("a=%d,%5d,%o,%x\n",a,a,a,a);
printf("Lf, b = % f, % % 5.4 lf, % e \ n",b,b,b,b);
printf("C = % lf, % f, % 8.4 lf \ n",c,c,c);
printf("d=%c,%8c\n",d,d);
} a<-- 15
b<-138.3576278
c<-35648256.3645687
d<--'p'

main()
{
int a=29;
float b=1243.2341;
double c=24212345.24232;
char d='h';
printf("a=%d,%5d,%o,%x\n",a,a,a,a);
printf("Lf, b = % f, % % 5.4 lf, % e \ n",b,b,b,b);
printf("C = % lf, % f, % 8.4 lf \ n",c,c,c);
printf("d=%c,%8c\n",d,d);
} 
Copy the code

In line 7 of this example, the value of the integer variable a is printed in four formats, where “%5d” requires a width of 5, and a value of 15 has only two digits, so three Spaces are added. Line 8 prints the value of the real quantity B in four formats. The output in %f and % LF formats is the same, indicating that l has no effect on f type. “% 5.4LF” specifies that the output width is 5, the accuracy is 4, because the actual length is more than 5, it should be the actual number of output, the decimal number more than 4 parts are truncated. The ninth line outputs a double precision real number. “% 8.4LF” truncates more than 4 bits because the accuracy is specified as 4 bits. “% BC” specifies that the output width is 8, so add 7 Spaces before the output character p.

Another concern when using the printf function is the order of evaluation in the output table columns. Different build systems are not necessarily the same, and can be left to right or right to left. Turbo C is pressed from right to left. Example 2.13 can be rewritten as follows:

void main(a){
int i=8;
printf("%d\n%d\n%d\n%d\n%d\n%d\n",++i,--i,i--,i++,-i--);
} i<-- 8 -
Copy the code

This program is compared to example 2.13, which is just to change multiple printf statements into one printf statement output. But the results are different. Why would the results be different? That’s because the printf function evaluates the items in the output table from right to left. In this formula, the last term “-i–” is evaluated first, and the result is -8, and then I is reduced by 1 to 7. And then I ++ is worth -7, and then I is 8. The “I –” term is worth 8, and then I subtracts by 1 to 7. I ++ is 7, and then I is 8. Then find the “– I” item, I first decrement by 1 and output, the output value is 7. Finally, find the first item “++ I” in the output table column, and output 8 after I increases by 1. It is important to note, however, that the evaluation order is right-to-left, but the output order is left-to-right, so the output is the one described above.

4.3 Character output function

The putchar function is a character output function whose function is to output a single character on the display. The general form is putchar(character variable)

Such as:

putchar('A'); Output uppercaseA
putchar(x); Prints the value of the character variable xputchar('\n'); The newline performs the control function on the control character and is not displayed on the screen. To use this function, you must include the command in the file:#include<stdio.h>
void main(a){
char a='B',b='o',c='k';
putchar(a);putchar(b);putchar(b);putchar(c);putchar('\t');
putchar(a);putchar(b);
putchar('\n');
putchar(b);putchar(c);
}
Copy the code

Data entry statement

C data entry is also done by function statements. This section describes the functions scanf and getchar that enter data from the keyboard, the standard input device. Scanf function The scanf function is called the format input function, which inputs data from the keyboard into a specified variable in a format specified by the user.

5.1 General form of scanf function

The scanf function is a standard library function whose function prototype is in the header file “stdio.h”. Like the printf function, C also allows you not to include the stdio.h file before using scanf.

The general form of the scanf function is: scanf(” format control string “, address table column);

The function of the format control string is the same as that of the printf function, but the format control string cannot be displayed, that is, the prompt string cannot be displayed. The address table column gives the addresses of each variable. The address consists of the address operator “&” followed by the variable name. For example, &a and &b represent the addresses of variables A and B, respectively. This is the address in memory that the compilation system assigns to variables A and b. In C language, the concept of address is used, which is different from other languages. A distinction should be made between the values of variables and the addresses of variables. The address of the variable is assigned by the C compilation system, and the user does not have to care about the specific address. The relationship between the address of a variable and its value is as follows: &a– >a567 A is the name of the variable, 567 is the value of the variable, and &a is the address of a.

Assign a value to a variable in an assignment expression, such as a=567. The left side of the assignment number is the name of the variable, but the address of the variable cannot be written. The scanf function essentially assigns a value to a variable, but requires the address of the variable to be written, such as &a. The two are different in form. &is an address operator, and &a is an expression whose function is to find the address of a variable.

void main(a){
int a,b,c;
printf("input a,b,c\n");
scanf("%d%d%d",&a,&b,&c);
printf("a=%d,b=%d,c=%d",a,b,c);
} 
Copy the code

5.2 Pay attention to the usage of &!

In this case, the scanf function itself cannot display the prompt string, so the printf statement is used to output the prompt on the screen, asking the user to input the values of a, B, and C. After the scanf statement is executed, you exit the TC screen and enter the user screen for user input. The user enters 7, 8, and 9 and presses Enter. At this time, the system returns to the TC screen.

In the format string of scanf statement, there is no non-format character between “%d%d%d”, so more than one space or enter key should be used as the interval between each two input numbers.

Such as:7 8 97
8
9
Copy the code

5.3 Format String

The format string is in the following form: %[*][Input data width][Length] Type The items with square brackets [] are optional.

The significance of each item is as follows:

  1. type
Represents the type of input data, whose format and meaning are shown in the following table. Format Character Meaning d Enter a decimal integer O Enter an octal integer x Enter a hexadecimal integer U Enter an unsigned decimal integer F or e Enter a real number (in decimal or exponential form) c Enter a single character s Enter a stringCopy the code
  1. “*” character

Used to indicate that the input is read without assigning the corresponding variable, that is, the input value is skipped. Such as the scanf (” % d % d % d “, & a, & b); When the input is 1, 2, and 3, 1 is assigned to A, 2 is skipped, and 3 is assigned to B.

  1. The width of the

Specifies the width (that is, the number of characters) of the input as a decimal integer.

For example: the scanf (” % 5 d “, & a); Type: 12345678 and only assign 12345 to variable A, the rest is truncated.

Such as: the scanf (” % 4 d % 4 d “, & a, & b);

Typing: 12345678 will give 1234 to A and 5678 to B.

  1. The length of the

The length formatters are L and h, where L indicates input long integer data (such as %ld) and double precision floating point numbers (such as % LF). H indicates the input of short integer data.

There are some other things you must note when using the scanf function:

A. The scanf function has no precision control, for example: scanf(“%5.2f”,&a); It’s illegal. You cannot attempt to enter a real number with a 2-digit decimal with this statement.

B. Scanf requires the address of the variable. If the variable name is given, an error occurs. Such as the scanf (” % d “, a); Is illegal, should be changed to scnaf(“%d” &a); It’s legal.

C. If the format control string does not contain any non-format characters, space, TAB, or carriage return can be used as the interval between input data. C compilation ends when Spaces, tabs, carriage returns, or invalid data are encountered (for example, when “12A” is entered for “%d”, A is invalid data).

D. If the format control string contains no format characters, all characters are valid. For example: the scanf (” % % % c c c “, & a, & b, & c); Input: d e f assigns ‘d’ to a, ‘f’ to b, and ‘e’ to C. Only if the input is: def can ‘d’ be assigned to a,’e’ to b, and ‘f’ to C. If you add Spaces to the format control as spacing, such as scanf (“%c %c %c”,&a,&b,&c); Spaces can be added between data.

void main(a){
char a,b;
printf("input character a,b\n");
scanf("%c%c",&a,&b);
printf("%c%c\n",a,b);
} 
scanf("'C14F14%c%c",&a,&b);
printf("%c%c\n",a,b); 
Copy the code

Because there is no space in scanf function “%c%c”, enter M N, and the result output is only M. When the input is changed to MN, two characters of MN can be output, see the following input operation:

input character a,b
MN
MN
void main(a){
char a,b;
printf("input character a,b\n");
scanf("%c %c",&a,&b);
printf("\n%c%c\n",a,b);
}
Copy the code

scanf(“%c %c”,&a,&b); In this example, if Spaces exist between scanF format control string “%c %c”, the entered data can be separated by Spaces. E. If there are non-format characters in the format control string, enter the non-format characters.

Such as:

scanf("%d,%d,%d",&a,&b,&c); 
Copy the code

Among them with a format character “, “space mark, so the input should be: 5, 6, such as: the scanf (” a = % d, b = % d, c = % d”, & a, & b, & c); The input should be

a=5,b=6,c=7G. If the type of the input data is different from that of the output data, the compilation will be successful, but the result will be incorrect.void main() {int a;
printf("input a number\n");
scanf("%d",&a);
printf("%ld",a);
}
Copy the code

Because the input data type is an integer, and the format string of the output statement indicates a long integer, the output result is inconsistent with the input data.

If the changes are as follows:

void main(a){
long a;
printf("input a long integer\n");
scanf("%ld",&a);
printf("%ld",a); } The result is input along integer
1234567890
1234567890When the input data is changed to a long integer, the input and output data are equal.Copy the code

5.4 Keyboard input functions

The function of the getchar function is to enter a character from the keyboard.

The general form is: getchar();

An assignment statement is usually made by assigning the input character to a character variable, such as:

char c;
c=getchar(a);#include<stdio.h>
void main(a){
char c;
printf("input a character\n");
c=getchar(a);putchar(c);
}
Copy the code

There are a few other considerations when using the getchar function:

  1. The getchar function can only accept single characters, and input numbers are processed as characters as well. When more than one character is entered, only the first character is received.
  2. You must include the file “stdio.h” before using this function.
  3. When you run the program containing this function under the TC screen, you will exit the TC screen and enter the user screen for user input. Return to the TC screen.
void main(a){
char a,b,c;
printf("input character a,b,c\n");
scanf("%c %c %c",&a,&b,&c);
printf("%d,%d,%d\n%c,%c,%c\n",a,b,c,a- 32,b- 32,c- 32);
}
Copy the code

Input three lowercase letters and output their ASCII code and corresponding uppercase letters.

void main(a){
int a;
long b;
float f;
double d;
char c;
printf("%d,%d,%d,%d,%d".sizeof(a),sizeof(b),sizeof(f)
,sizeof(d),sizeof(c));
}
Copy the code

Outputs the length of each data type in bytes.

Six, branch structure program

6.1 Relational operators and expressions

In the program often need to compare the size of two quantities to determine the next step of the program work.

Operators that compare two quantities are called relational operators.

In C, there are the following relational operators:

< less than <= less than or equal to > Greater than >= Greater than or equal to == Equal to! = is not equal toCopy the code

All relational operators are binocular operators and their associativity is left associative.

Relational operators take precedence below arithmetic operators and above assignment operators.

Among the six relational operators,<,<=,>,>= has the same precedence over == and! =, == and! = has the same priority.

6.2 Relational Expressions

The general form of a relational expression is: Expression relational operator expression

For example: a + b > c, d, x > 3/2, ‘a’ + 1 < c, – I – 5 * j = = k + 1; These are all legal relational expressions.

Since an expression can also be a relational expression. Therefore, nesting is also allowed, for example: a>(b>c),a! C = = = (d), etc. The values of relational expressions are “true” and “false”, denoted by “1” and “0”.

For example, if 5>0, the value is true, that is, 1. (a=3)>(b=5) because 3>5 is not true, so its value is false, that is, 0.

void main(a){
char c='k';
int i=1,j=2,k=3;
float x=3e+5,y=0.85;
printf("%d,%d\n".'a'+5<c,-i2 -*j>=k+1);
printf("%d,%d\n".1<j<5,x5.25<=x+y);
printf("%d,%d\n",i+j+k==2 -*j,k==j==i+5);
}
char c='k';
int i=1,j=2,k=3;
float x=3e+5,y=0.85;
printf("%d,%d\n".'a'+5<c,-i2 -*j>=k+1);
printf("%d,%d\n".1<j<5,x5.25<=x+y);
printf("%d,%d\n",i+j+k==2 -*j,k==j==i+5); 
Copy the code

In this example, various relational operators are evaluated. A character variable is calculated by its corresponding ASCII code. For the expression containing multiple relational operators, such as k==j== I +5, according to the left associativity of the operator, k==j is calculated first, and the expression is not true, and its value is 0. Then, 0== I +5 is also not true, so the expression value is 0.

6.3 Logical operators and Expressions

Logical operators in the C language provides three logical operators && and operation | | or operation! The operation

&& and | or operator and operator | are binary operator. It’s left associative.

Non operator! Is a monocular operator with right associative property.

The relationship between the precedence of logical operators and other operators can be expressed as follows:

In order of precedence of the operators, we can derive:

A >b && c>d is equivalent to (a>b) && (c>d)! B = = c | | d < a equivalent to ((! B) = = c) | | (d (a) a + b > c && x + y < b equivalent to the ((a + b) > c) && ((x + y) < b)Copy the code

6.4 Value of the logical operation

The value of a logical operation can also be “true” or “false”, denoted by “1” and “0”.

The evaluation rules are as follows:

  1. And operation && The result is true only if both of the quantities involved in the operation are true, otherwise it is false. For example, 5>0 && 4>2, since 5>0 is true, 4>2 is also true, and so is the result of phase and phase.
  2. Or operation | | to participate in the operation of two quantities as long as there is a true, the result is true. When both quantities are false, the result is false. For example: 5 > 0 | | 5 > 8, because the 5 > 0 is true, as a result of their phase or will be true
  3. The operation! The result is false when the amount of computation involved is true; The result is true when the amount of computation involved is false.

For example:! (5>0) is false. Although C compilation gives the value of the logical operation as “1” for “true” and “0” for “false”. But conversely, when judging whether a quantity is “true” or “false”, “0” represents “false”, and non-” 0 “values are” true “.

For example, since 5 and 3 are not “0”, the value 5&&3 is “true”, i.e., 1.

Such as: 5 | | 0 value is “true”, namely to 1.

Logical expression The general form of a logical expression is: expression Logical operator expression

The expressions can also be logical expressions, forming nested cases.

For example: (a&&b)&&c According to the left associative nature of the logical operators, the above expression can also be written as: the value of the logical expression a&&b&&c is the final value of the various logical operations in the expression, with “1” and “0” representing “true” and “false” respectively.

void main(a){
char c='k';
int i=1,j=2,k=3;
float x=3e+5,y=0.85;
printf("%d,%d\n",! x*! y,!!! x);printf("%d,%d\n",x||i&&j- 3,i<j&&x<y);
printf("%d,%d\n",i==5&&c&&(j=8),x+y||i+j+k);
}
Copy the code

In this case! X and y! Y is 0, factorial. x*! Y is also 0, so its output is 0. Because x is not 0, so!! The logical value of x is 0. For x | | I & j – 3 type, calculating the value of j – 3 for the first 0, again ask I & j – 3 logic value is 1, so the x | | I & j value of 1-3 of logic. For I <j&&x<y, the value of I <j is 1, and x<y is 0, so the value of the expression is 1, 0 phase and, and the final value is 0. For I ==5&&c&&(j=8), since I ==5 is false, that is, the value is 0. This expression consists of two and operations, so the value of the whole expression is 0. For type x + y | | I + j + k due to x + y has a value of 0, so the whole or the value of the expression of 1.