Chapter III: C language program design preliminary

xiaoxiao2021-03-06  19

Chapter III: C language program design preliminary

C language program design This lesson introduces the basic method of C language program design and basic program statement. From the perspective of the program process, the program can be divided into three basic structures, namely the sequential structure, branch structure, and loop structure. These three basic structures can form all of all complex programs. The C language provides a variety of statements to implement these program structures. This chapter introduces these basic statements and its applications, making readers a preliminary understanding of the C procedure, and lay the foundation for the latter chapters. The execution portion of the c program is composed of statements. The functionality of the program is also implemented by executing statements. The C statement can be divided into the following five categories: Function call statement 3. Control statement 4. Composite statement 5. Empty statement 1. Expression statement expression statement is incorporated by a semicolon ";" . Its general form is: expression; execution expression statement is the value calculating expression. For example: x = y z; assignment statement y z; addition operation statement, but calculation results cannot be retained, no practical meaning i ; self-increasing 1 statement, I value increase 1

2. Function call statement consists of function name, actual parameters, and a semicolon ";" Its general form is: function name (actual parameter table); execution function statement is to call the function body and assign the actual parameter to the formal parameters in the definition of the function, and then perform the statement in the invigible representation to obtain a function value. (In the fifth chapter function, more details), such as Printf ("C Program"); ​​call the library function, output strings.

3. Control the statement control statement to control the process of the program to implement the various structural methods of the program. They consist of a particular statement definition. The C language has nine control statements. It 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) steering statement BREAK statement, goto statement, continue statement, return statement 4. The composite statement puts a plurality of statements that consist of multiple statements in parentheses {}. In the program, the composite statement should be regarded as a single statement, not a plurality of statements, such as {x = y z; a = B C; Printf ("% D% D", X, a);} is a Composite statement. Each statement in the complex statement must be terminated in a semicolon ";", it cannot be added to the bracket "}". 5. The empty statement is only a semicolon ";", the statement is called empty statement. The null statement is the statement that does not execute. The empty statement in the program can be used as a empty cycle. For example, while (GetChar ()! = '/ N'); the function of this statement is to re-enter as long as the characters entered from the keyboard are not cargo. The cyclic body here is an empty statement. The assignment statement assignment statement is an expression statement configured by the assignment expression. Its general form is: variable = expression; the function and characteristics of assignment statements are the same as assignment expressions. It is one of the most useful statements in the program. I need to pay attention to the following points in the use of assignment statements: 1. Since the expression on the right side of the assignment, it is also an assignment expression, therefore, the following form variable = (variable = expression); is established To form a nesting situation. The general form after the development is: variable = variable = ... = expression; for example: a = b = c = D = E = 5; according to the right bondability of the assignment operator, therefore actually equivalent to: E = 5 ; D = E; c = D; b = C; a = b; 2. Note the difference between the variable assignment and assignment statements in the variable description. The initial value to the variable is part of the variable description, and the number of variables after the initial value must still be comma intervals between the other similar variables, and the assignment statement must end with the semicolon. 3. In the variable description, it is not allowed to be assigned to multiple variables to the first value. The following description is wrong: int a = b = c = 5 must be written as int a = 5, b = 5, c = 5; and assignment statements allow continuous assignments 4. Note the difference between assignment expressions and assignment statements. Assignment expressions are an expression that can appear in any place where the expression appears, and the assignment statement cannot be. The following statement is legal: if ((x = y 5)> 0) z = x; the function of the statement is that if the expression x = y 5 is greater than 0 z = x. The following statement is illegal: IF ((x = y 5;)> 0) z = x; because = y 5; is a statement, it cannot appear in the expression. Data Output State This section describes the statement that outputs data to the standard output device display. In the C language, all data input / output is done by the library function. It is therefore all function statements. This section describes the Printf function and the PUTCHAR function. The Printf function printf function is called the format output function, and the last letter f is the meaning of "format". Its function is to display the specified data on the display screen by the format specified by the user. In the first example we have used this function multiple times. First, the general form of the Printf function call is a standard library function, its function prototype in the header file "stdio.h".

However, as a special case, the stdio.h file must be included before using the Printf function. The general form of the Printf function call is: Printf ("Format Control String", Output List) where the format control string is used to specify the output format. Format control strings can be composed of two format strings and non-format strings. The format string is a string that starts with%, with a variety of format characters in%, to illustrate the type, form, length, and lower number of output data. Such as "% D" means that the "% LD" is output according to the decimal output, "% C" indicates that according to the character output, etc. The discussion will be given later. Non-format strings are illuminated when the output is displayed, and prompts in the display. Each output item is given in the output list, requiring the format string and each output item to correspond to the number and type. Void main () {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); the value of A and B is output four times in this example, but due to the different format control strings, the results of the output are different. In the output statement format control string of the fourth line, a space (non-format character) is added between the two formatter% D, so there is a space between the outputs A and B values. The PRINTF statement format of the fifth line is added to the non-format character comma, so there is a comma between the output A and B values. The format string of the sixth line requires the A and B values ​​in accordance with the character type. In the seventh line, in order to prompt the output, the non-format string is added. Second, the format string is in general forms of format strings in Turbo C to: [Mark] [Output Minimum Width] [. Precision] [Length] Type 1 of which is optional. The meaning of each item is as follows: 1. Type type character is used to indicate the type of output data, its formatting character and meaning the following table shows: Indicated format character format character in the output type, output with symbol integers in ten-way form (positive Do not output symbols) o Output unsigned integer (no output prefix O) x in an octazone form (no output prefix OX) U output unsigned integer f in decimal form, output order, Double precision real est 8 output single, double precision real g is shorter output width output single, double precision real number C output a single character S Output string 2. Sign flag characters -, , # Four kinds of spaces, the meaning shown below: Sign Format Character Sign Significance - Results The left alignment, the right edge fill the space output symbol (positive or negative) space output value is timing crown, the crown Negative number # 无 类 类 类 类;; 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 类 0 类 类 类 类 类 类 类 0 类 类 类 类 类 类 0 类 类 类 类 类 类 0 类 类 类Different points 3. Output minimum width with decimal integers to represent the minimum number of outputs. If the actual number of digits is more than the defined width, then the actual number of digits is output. If the actual number of bits is less than the defined width, it is safer or 0.4. The precision accuracy format is "." Begins, and then following the decimal integer. The meaning of this is: If the number is output, the number of digits is indicated; if the output is the character, the number of output characters is indicated; if the actual number of digits is greater than the defined accuracy, the exceeding portion is cut. 5. The length of the length format is H, L, h indicates that the shorter amount is output, and L is indicated by the long output.

Void main () {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 ("B =% F,% LF,% 5.4LF,% E / N", B, B, B, B); Printf ("C =% LF,% F,% 8.4LF / N ", C, C, C); Printf (" D =% C,% 8C / N ", D, D);} a <- 15b <- 138.3576278c <- 35648256.3645687d <- ' P 'main () {Int a = 29; float b = 1243.2341; Double C = 24212345.24232; char c =' H'Printf ("A =% D,% 5D,% O,% x / N", A, A , a, a); Printf ("B =% F,% LF,% 5.4LF,% E / N", B, B, B, B); Printf ("C =% LF,% F,% 8.4LF / N ", C, C, C); Printf (" D =% C,% 8C / N ", D, D);} In this case, the value of the integer variable A is output in four formats, of which "% 5D" requires the output width of 5, and a A value is 15 seconds of two, and three spaces. The value of the real amount B is output in four formats in four formats. Wherein "% f" and "% LF" format are the same, indicating that the "L" symbol has no effect on the "F" type. "% 5.4LF" specifies that the output width is 5, the accuracy is 4, and the actual length is output, and the number of decimal bits exceeds the 4 digits to be cut. The ninth line output double precision implement, "% 8.4LF" cuts more than 4 digits due to the designated accuracy of 4. The tenth line outputs the character quantity D, where "% BC" specifies that the output width is 8 so that 7 spaces are added before the output character P. Pay attention to a problem when using the Printf function, which is the order in the output table column. Different compilation systems are not necessarily the same, can be left to right, or from right to left. Turbo C is made from right to left. If an example 2.13 rewritten as follows: void main () {INT i = 8; Printf ("% D / N% D / N% D / N% D / N% D / N% D / N", i, - i, i -, i , - i - I -);} i <- 8 This program is compared with Example 2.13 to change multiple printf statements to the outputf statement output. However, it can be seen from the results. Why is the result that the result will be different? Just because the PrintF function is performed from the order in which each quantity in the output table is performed. In the formula, the last "-i-" value is first, the result is -8, and then i is 7 after 1. Then the "-i " item is worth -7, and then I is 8 afterwards. Then, the "I-" item is worth 8, then I will then reduce 1 after 7. Request "i " item 7, then I will increase by 8 after another. Request "--i" item, i first below 1, output, the output value is 7. Finally, the first " i" in the output table column will be obtained. At this time I outputs 8 afterwards. However, it must be noted that although the order sequence is from right to left, but the output order is or from left to right, the resulting result is the output result. The character output function PUTCHAR function PUTCHAR function is a character output function that is functional to output a single character on the display.

Its general form is: PUTCHAR (character variable), for example: PUTCHAR ('a'); output uppercase letters aputchar (x); output character variable x value PUTCHAR ('/ n'); Retracence pair control characters perform control functions, Not displayed on the screen. You must use the file with the file to contain the file: #include #include void main () {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);} Data input statement C language data input is also done by the function statement. This section describes the function scanf and getchar input data from the standard input device-keyboard. The scanf function scanf function is called a format input function, which is in the format specified by the user from the keyboard to the specified variable. First, the general form of the scanf function is a standard library function. Its function prototype in the header file "stdio.h", the same is the same as the Printf function, and the C language also allows you to include the stdio.h file before using the Scanf function. The general form of the ScanF function is: Scanf ("Format Control String", address list column); where the format control string is the same as the Printf function, but the non-format string cannot be displayed, that is, the prompt string cannot be displayed. The address of each variable is given in the address table column. The address is composed of the address operator "&" followed by the variable name. For example, & A, & B represents the address of the variables A and the variable B, respectively. This address is the address that the compilation system is assigned to the A and B variables in memory. In the C language, the concept of address is used, which is different from other languages. The value of the value of the variable and the address of the variable should be distinguished from different concepts. The address of the variable is the Association system allocation, and the user does not have to care about the specific address. The relationship between the address and variable values ​​of the variable is as follows: & a ---> A567 A is the variable name, 567 is the value of the variable, & a is the address of the variable A. Assign the variable to the variable in the assignment expression, such as: a = 567 is the variable name on the left side of the assignment number, cannot write the address, and the scanf function is in nature to assign a value to the variable, but requires the address of the write variable, such as & a. Both are different in form. & Is an address operator, & A is an expression, its function is the address of the variable. Void main () {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);} Note & Usage! In this example, since the SCANF function itself cannot display a prompt string, first use the printf statement on the screen on the screen. Please enter the value of A, B, and C. Exit the Scanf statement, exit the TC screen to enter the user screen waiting for the user to enter. When the user enters 7, 8, 9, press the Enter key, at which time, the system will return to the TC screen. In the format string of the scanf statement, since there is no non-format character, the interval is input between "% D% D" D% D, so it is necessary to use more than one space or the Enter key when entering. Between the two inputs. Interval.

Such as: 7 8 9 or 789 Format string format string general form is:% [*] [Enter Data Width] [Length] Type With square bracket [] items for options. The significance is as follows: 1. Type indicates the type of input data, its formatting and meaning shown below. Format Character Sign D Enter Ten Import Integer O Input Octa Integer X Enter Hexadecimal Entario 10 No Symbol Decimal Integer F or E Enter Truth (Forms) C Enter a single character S Enter string 2. " * "The value is used to indicate that the input item does not give the corresponding variable after reading, that is, skip the input value. Such as Scanf ("% D% * D% D", & A, & B); when the input is: 1 2 3, 1 gives 1 to a, 2 is skipped, 3 give B. 3. The width uses the decimal integer specifies the width of the input (ie, the number of characters). For example: SCANF ("% 5D", & A); input: 12345678 Give only 12345 to the variable A, the remainder is cut off. Another example: scanf ("% 4D% 4D", & A, & B); input: 12345678 will give 1234 to A, and give 5 b. 4. The length of the length format is L and H, and L represents the input length integer data (such as the% LD) and the double precision floating point number (as% LF). h represents the short integer data. You must also pay attention to the following: a. There is no precision control in the scanf function, such as Scanf ("% 5.2f", & a); is illegal. You cannot try to use this statement to enter a decimal number of 2 digits. b. SCANF is required to give a variable address, if the variable name will be wrong. Such as scanf ("% d", a); is illegal, it should be changed to SCNAF ("% D", & a); it is legal. c. When entering multiple numerical data, if there is no non-format character in the format control string, there is a space, TAB, or a carriage return. C compiles the space, Tab, carriage return, or illegal data (if "12A" input "12A" is input to "% D", that is, it is considered to end. d. When entering the character data, if there is no non-format character in the format control string, all the characters that all entered are valid characters. For example: SCANF ("% C% C% C", & A, & B, & C); input to: D e f, gives 'D' to A, 'F' Give B, 'E' Give C. On only when the input is: DEF, the 'D' is assigned to a, 'E' gives C. If you add spaces in the format control as spacing, such as Scanf ("% C% C% C", & A, & B, & C); then add space between each data when input. Void main () {Char A, B; Printf ("Input Character A, B / N"); Scanf ("% C% C", & A, & B); Printf ("% C / N", A, b);} scanf ("'C14F14% C% C", & A, & B); Printf ("% C / N", A, B); due to the SCANF function "% C% C" no space, input Mn, the result is only M.

When the input is changed to Mn, the MN can be output, see the following input operation: Input Character A, BMnmnvoid main () {Char A, B; Printf ("Input Character A, B / N"); scanf (" % C% C ", & A, & B); Printf (" / n% C / N ", A, B);} Scanf ("% C% C ", & A, & B); this example represents SCANF format control When there is a space between the string "% C% C", the input data can be spaced apart. e. If there is a non-format character in the format control string, you should also enter the non-format character. For example: SCANF ("% D,% D,% D", & A, & B, & C); in which the non-format "," is separated, the input should be: 5, 6, 7, such as: scanf ( "A =% D, B =% D, C =% D", & A, & B, & C); then the input should be A = 5, b = 6, c = 7g. If the input data is inconsistent with the output type Although the compilation can pass, the result will be incorrect. Void main () {int A; Printf ("Input A Number / N"); Scanf ("% D", & A); Printf ("% ld", a);} Due to the input data type is integer, output The format string of the statement is explained as a long integer, so the output result and the input data do not match. If the change program is as follows: void main () {long a; printf ("Input A long integer / n"); scanf ("% ld", & a); printf ("% ld", a);} Run results: Input a long integer12345678901234567890 When the input data is changed to a long integer, the input and output data is equal. The keyboard input function getChar function getchar function is entered from the keyboard. Its general form is: getChar (); usually gives an input character to a character variable, constitutes an assignment statement, such as: CHAR C; c = getchar (); # include void main () {char C; printf ("Input a character / N"); c = getchar (); putchar (c);} You should also pay attention to several issues using the getchar function: 1.GetChar function can only accept a single character, and enter the number and press the character. When you enter more than one character, only the first character is received. 2. You must include file "stdio.h" before using this function. 3. When running under the TC screen, you will exit the TC screen into the user screen waiting for the user to enter. The input is completed and then returned to the TC screen. Void main () {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);} Enter three lowercase letters output their ASCII code and Corresponding uppercase letters. Void main () {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));} Outputs the byte length of various data types.

Branch structure program relationship operators and expressions often need to compare two amounts of size relationships in programs to determine the procedure's next step. Compare two amount operators called relational operators. There is a relationship operator in the C language: greater than> = greater than or equal to == equal to! = Not equal to the relational operator is a binocular operator, its bonding is left binding. The priority of the relationship operator is lower than the arithmetic operator, which is higher than the assignment operator. In the six relationship operators, <, <=,>,> = is the same, higher than == and! =, == and! = Priority the same. The general form of relational expression relationship expression is: expression relational operator expression, for example: A B> CD, X> 3/2, 'a' 1 (b> c), A! = (C == d), etc. The value of the relationship expression is "true" and "false", expressed with "1" and "0". Such as: 5> 0 is "true", that is, 1. (A = 3)> (b = 5) Since 3> 5 is not established, its value is false, that is, 0. Void main () {char c = 'k'; int i = 1, j = 2, k = 3; float x = 3e 5, y = 0.85; Printf ("% D,% d / n", 'a ' 5 = k 1); Printf ("% D,% D / N", 1 = k 1); Printf (" % D,% D / N ", 1

The relationship between the logical operator and other operator priority can be represented as follows: According to the priority order of the operator: A> B && C> D is equivalent to (a> b) && (c> d)! B == C || D C && x y c) && (X Y) 0 && 4> 2, due to 5> 0 true, 4> 2 is true, the results are true. 2. Or Operations || Two quantities participating in the calculation As long as one is true, the result is true. The two quantities are false, the result is false. For example: 5> 0 || 5> 8, due to 5> 0 is true, the phase or the result is true 3. Non-operation! When the carrier is true, the result is a fake; the participation of the operation is fake, the result It is true. For example:! (5> 0) results are fake. Although C is compiled when a logical operation is given, "1" represents "true", "0" represents "false". However, when it is determined that one amount is "true" or "false", "0" represents "false", the value "true" is "true". For example, since 5 and 3 are not "0" therefore the value of 5 && 3 is "true", that is, 1. Another example: 5 || 0 value is "true", that is, 1. A general form of logical expression logical expressions: The expression logical operator expression is a logical expression, thereby constituting a nested situation. For example: (A && B) && C, according to the left binding of the logical operator, the above equation can be written as: A && B && C logical expression value is the final value of various logical operations in the style, representing "1" and "0" respectively " True "and" false ". Void main () {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

For X || I && J-3, the value of J-3 is calculated is not 0, and then the logical value of I && J-3 is 1, so the logical value of X || I && J-3 is 1. For I

1. The first form is a basic form IF (expression) statement; its semantics is that if the value of the expression is true, then the following statement is executed, otherwise the statement is not executed. The process can be represented as the following picture void main () {Int A, b, max; printf ("/ n INPUT TWO NUMBERS:"); Scanf ("% D% D", & A, & B); max = a; if (Max

In this example, two numbers A, B are entered. Turn A to the variable max, then discriminate the size of Max and B with the IF statement, such as MAX is less than B, then give B. Therefore, MAX is always large, and finally outputs the value of the max. 2. The second form is an IF-ELSE form IF (expression) statement 1; ELSE statement 2; its semantics is that if the value of the expression is true, the statement 1 is executed, otherwise the statement 2 is executed. Void main () {Int A, B; Printf ("Input Two number," "% D% D", & A, & B); if (A> b) Printf ("max =% d / n" , a); ElsePrintf ("max =% d / n", b);} Enter two integers to output large numbers. Change the size of the IF-ELSE statement to determine A, B, if A is large, then output A, otherwise output B. 3. The third form of the IF statement in the first two forms of IF-ELSE-IF is generally used for two branches. When there are multiple branch selection, IF-ELSE-IF statement can be used, and its general form is: IF (Expression 1) statement 1; ELSE IF (Expression 2) statement 2; ELSE IF (Expression 3) Statement 3 ... ELSE IF (Expression M) Statement M; ELSE Statement N; It is semantically to determine the value of the expression, and the corresponding statement is executed when a certain value is true. Then run the executor outside the entire IF statement. If all expressions are fake, the statement n is executed. Then continue the follow-up program. The execution process of the IF-ELSE-IF statement is shown in Figure 3-3.

#include "stdio.h" void main () {char C; Printf ("INPUT a character:"); c = getchar (); if (c <32) Printf ("this is a control character / n"); Else IF (C> = '0' && c <= '9') Printf ("this is a digit / n"); Else IF (c> = 'a' && c <= 'z') Printf ("this is a Capital Letter / N "); Else IF (C> = 'a' && c <= 'z') Printf (" this is a sales sall letter / n "); ElsePrintf (" this is an an other character / n ");} IF (C <32) Printf ("this is a control character / n"); ELSE IF (c> = '0' && c <= '9') Printf ("this is a digit / n"); ELSE IF C> = 'a' && c <= 'z') Printf ("this is a capital letter / n"); Else IF (c> = 'a' && c <= 'z') Printf ("this is a sales / N "); ElsePrintf (" this is an an other character / n "); this example requires the category of the keyboard input character. The type can be discriminated based on the ASCII code of the input character. The ASCII code is known to be less than 32 of the control character. The number between "0" and "9", between "A" and "Z" is uppercase letters, between "A" and "Z" lowercase letters, and the rest is other characters. This is a multi-branch choice problem, with the IF-ELSE-IF statement programming, determine the range of the input character ASCII code, gives different outputs. For example, it is input to "G", and the output is displayed to lowercase characters. 4. You should also pay attention to the following issues (1) in the IF statement in the IF statement, both in the IF key. This expression is typically a logical expression or a relationship expression, but it can also be other expressions, such as assignment expressions, etc., or even a variable. For example: if (a = 5) statement; if (b) statement; it is allowed. As long as the value of the expression is not 0, it is "true". Such as IF (a = 5) ...; the value of the expression is always non-0, so the subsequent statement is always executed, of course, this situation does not necessarily appear in the program, but in the grammar is legal . Another example, there is a block: if (a = b) Printf ("% d", a); ElsePrintf ("a = 0"); this statement is semantically assigned to A, such as non-0 output This value, otherwise output "A = 0" string. This usage often occurs in the program. (2) In the IF statement, the condition judges that the expression must be enclosed in parentheses, and you must add a bit number after the statement.

(3) In three forms of the IF statement, all statements should be a single statement. If you want to execute a set of (multiple) statements when you meet the conditions, you must enclose this group of statements to make a set of {}. Composite statement. However, it should be noted that it cannot be added again after}. For example: if (a> b) {A ; B ;} else {a = 0; b = 10; Situation. Its general form can be represented by the following: if (expression) IF statement; or if (expression) IF statement; ELSE IF statement; if the IF statement in nested may be IF-ELSE type, this will appear The case of an IF and multiple ELSE overlap, then pay special attention to the matching problem of IF and ELSE. For example: IF (Expression 2) IF (Expression 2) statement 1; ELSE statement 2; where is the ELSE is paired? It should be understood as: or it should be understood as: IF (Expression 1) IF Expression 1) IF (Expression 2) IF (Expression 2) statement 1; statement 1; ELSE ELSE Statement 2; Statement 2; In order to avoid this erriness, C language regulations, Else always nearestly The IF pair, so the above example should be understood in the previous case. Void main () {Int A, B; Printf ("Please Input A, B:"); Scanf ("% D% D", & A, & B); if (a! = b) IF (A> b) Printf ("A> b / n"); Else Printf ("a b) Printf ("a> b / n"); Else Printf ("a B, A B) Printf (" a> B / N "); Else Printf (" a

The general form of the conditional operator constitutes a conditional expression: Expression 1? Expression 2: Expression 3 The value rule is: if the value of the expression 1 is true, the value of expression 2 is used as a conditional expression. The value, otherwise be used as the value of the entire conditional expression with the value of the expression 2. Conditional expressions are commonly used in assigning statements. For example, conditions statement: if (a> b) max = a; else max = b; available conditional expression is MAX = (a> b)? A: B; Semantics to execute this statement are:, such as A> B is true Then give a to Max, otherwise the b is given to Max. When using conditional expressions, you should also pay attention to the following: 1. The operational priority of the conditional operator is lower than the relational operator and the arithmetic operator, but is higher than the assignment. Therefore, MAX = (a> b)? A: B can be written to max = a> B? A: B2. Conditional operator? And: Is a pair of operators, cannot be used separately. 3. The combination of conditional operators is right to left. For example: A> B? A: C> D? C: D should be understood as a> b? A: (c> d? C: d) This is the case of conditional expression nested, ie in the expression 3 It is also a conditional expression. Void main () {Int A, B, Max; Printf ("/ N INPUT TWO NUMBERS:"); Scanf ("% D% D", & A, & B); Printf ("max =% d", A> B ? a: b);} Use the conditional expression to reprogram the previous example, output large numbers in two numbers. The Switch Statement C language also provides another Switch statement for multi-branch selection, its general form: Switch {CASE constant expression 1: statement 1; case constant expression 2: statement 2; ... case Constant expression N: statement n; default: statement n 1;} It is semantically: calculating the value of the expression. Compared to its constant expression value, when the value of the expression is equal to the value of a constant expression, the following statement is not performed, and then the statement after all CASE is continued. If the value of the expression is different from the constant expression after all CASE, the statement after DEFAULT is executed. Void main () {Int A; Printf ("Input Integer Number:"); Scanf ("% D", & A); Switch (a) {Case 1: Printf ("Monday / N"); Case 2: Printf "Tuesday / N"); Case 3: Printf ("Wednesday / N"); Case 4: Printf ("Thursday / N"); Case 5: Printf ("Friday / N"); Case 6: Printf ("Saturs / N "); Case 7: Printf (" sunday / n "); default: printf (" error / n ");}}

This program is required to enter a number and output an English word. However, when input 3, Case3 and all the following statements are executed, and all words and future words are output. This is of course undesirable. Why do this happen? This just reflects a feature of the Switch statement. In the Switch statement, "Case constant expression" is only equal to one statement label, the expression of the expression and a certain number of times are turned to the label execution, but cannot automatically jump out of the entire Switch statement after executing the statement of the label, so appears Continue to perform all back CASE statements. This is completely different from the IF statements described earlier, pay special attention. In order to avoid the above, the C language also provides a BREAK statement, dedicated to jump out of the switch statement, and the Break statement has only a keyword BREAK, no parameters. Also described later. The program of modifying the scrip, adds the BREAK statement after each CASE statement so that each execution can be jumped out of the Switch statement, thereby avoiding the result that should not be output. Void main () {Int A; Printf ("INPUT INTEGER NUMBER:"); Scanf ("% D", & A); Switch (a) {Case 1: Printf ("Monday / N"); Break; Case 2: Printf ("Tuesday / N"); Break; Case 3: Printf ("Wednesday / N"); Break; Case 4: Printf ("Thursday / N"); Break; Case 5: Printf ("Friday / N") Break; Case 6: Printf ("Saturday / N"); Break; Case 7: Printf ("sunday / n"); Break; default: printf ("error / n");}} When using the Switch statement Note the following points: 1. The value of each constant expression after CASE cannot be the same, otherwise an error will occur. 2. After CASE, multiple statements are allowed, can be enclosed without {}. 3. The order of each case and default clause can change without affecting the program execution. 4. DEFAULT clause can be omitted. Program example input three integers, output maximum and minimum. Void main () {Int A, B, C, Max, Min; Printf ("INPUT Three Numbers:"); Scanf ("% D% D% D", & A, & B, & C); if (A> B) {MAX = a; min = B;} else {max = B; min = a;} if (max c) min = C; printf ("max =% d / nmin =% D ", MAX, min);

In this program, first compare the size of the inputs A, B, load large numbers into the MAX, load the size into the min, then compare with C, if the max is smaller than c, then the c is given to Max; if C is less than min, Then give C to MIN. Therefore, MAX is always the maximum number, while MIN is always the minimum. The last output of MAX and MIN can be output. Calculator program. The user inputs the calculation and the four operators, and the output calculation results are output. Void main () {Float A, B, S; Char C; Printf ("INPUT Expression: A (-, *, /) b / n"); scanf ("% f% c% f", & a, & c, & b); Switch (C) {CASE ' ': Printf ("% f / n", A b); Break; Case '-': Printf ("% f / n", ab); Break; casser * ': Printf ("% f / n", a * b); Break; Case' / ': Printf ("% f / n", A / b); Break; Default: Printf ("Input Error / N" }}

Float A, B, S; CHAR C; Printf ("INPUT Expression: A (-, *, /) b / n"); scanf ("% f% c% f", & a, & c, & b); switch ( c) {CASE ' ': Printf ("% f / n", A b); Break; Case '-': Printf ("% f / n", ab); break; cas '*': Printf "% f / n", a * b); Break; Case '/': Printf ("% f / n", a / b); break; default: printf ("infut error / n");} This example Can be used for four operational requests. The Switch statement is used to determine the operator and then output an operation value. An error message is given when the input operator is not , -, *, / /. The cyclic structure program loop structure is a very important structure in the program. It is characterized in that a block is executed repeatedly when a given condition is established until the conditions are not established. A given condition is referred to as a circulating condition, and the program segment repeatedly executed is referred to as a cyclic body. The C language provides a variety of cyclic statements that can form a variety of different forms of loop structures. The general form of the While statement whose statement is: While (expression) statement; where the expression is a cycle condition, the statement is a cyclic body. The semantics of the While statement are: calculate the value of the expression, when the value is true (non-0), performs a cyclic body statement. Its execution can be represented by Figure 3-4. Statistics Enter the number of characters from the keyboard. #include void main () {int N = 0; Printf ("INPUT A String: / N"); while (getchar ()! = '/ n') N ; Printf ("% D", n);} int N = 0; Printf ("INPUT A String: / N"); while (getchar ()! = '/ n') N ; Printf ("% D", N); this program The cycle condition is getchar ()! = '/ N', its meaning is that as long as the characters entered from the keyboard are not the cycle. The cyclic body N completes the number count of the input character. Therefore, the program implements a number of characters that input a line character. Use the While statement to pay attention to the following: 1. The expression in the WHILE statement is generally a relationship expression or logical expression, as long as the value of the expression is true (non-0), it can continue loop. Void main () {Int a = 0, n; Printf ("/ n INPUT N:"); scanf ("% D", & n); while (n -) printf ("% d", A * 2) } int A = 0, N; Printf ("/ n INPUT N:"); scanf ("% d", & n); while (n -) printf ("% d", A * 2); this example The program will perform N cycles, each execution, N value minus 1. The cyclic body outputs the value of the expression A * 2. This expression is equivalent to (A * 2; A ) 2. The cyclic body, such as including more than one statement, must be enclosed in {}, constitutes a composite statement. 3. Pay attention to the choice of cycle conditions to avoid death cycles.

Void main () {Int a, n = 0; while (a = 5) Printf ("% D", n );} int A, n = 0; while (a = 5) Printf ("% d", n ); In this example, the cycle condition of the WHILE statement is assigning expression a = 5, so the value of the expression is always true, and there is no means for suspending cycles in the cyclic body, so the loop will endlessly do endlessly. Form a dead cycle. 4. Allow the cyclic body of the While statement to the While statement, thereby forming a dual cycle. Do-While Statement Do-While Statement is: DO statement; while (expressions); where statements are cyclicers, expressions are cyclic conditions. The semantics of the Do-While statement are: First execute the cyclic body statement once, and then discriminate the value of the expression, if it is true (non-0), continue the cycle, otherwise the loop is terminated. The difference between the Do-While statement and the While statement is that the do-while is executed before executing, so the do-while is at least one cycle. While is first judged, if the condition is not satisfied, the cyclic body statement is not executed. While statements and do-while statements generally rewrite each other. Void main () {Int a = 0, n; Printf ("/ n INPUT N:"); scanf ("% d", & n); do printf ("% d", A * 2); while (- n);} int A = 0, N; Printf ("/ n INPUT N:"); scanf ("% D", & n); do printf ("% d", A * 2); while (--n In this example, the cycle condition is changed to - N, otherwise the cycle will be executed. This is caused by the first execution. For the Do-While statement, you should also pay attention to the following points: 1. In the if statement, WHILE statement, both the expression cannot be added behind, and after the expression of the DO-WHILE statement must be added. 2. DO-While statement can also form multiple cycles, and can also be nested with the While statement. 3. When the cyclic body between DO and WHILE is composed of multiple statements, it must also be enclosed in {} to form a composite statement. 4. DO-while and while statements are replaced with each other, pay attention to modify the loop control. The FOR statement for statement is a more functionality provided by the C language and uses a broader cycle statement. Its general form is: for (Expression 1; Expression 2; Expression 3) statement; expression 1 is typically used to assign the cyclic variable, generally assigning expression. Allowed in the FOR statement to be transmitted to the initial value, and the expression can be omitted at this time. Expression 2 is typically a circulating condition, typically a relational expression or logical expression. Expression 3 is usually available to modify the value of the loop variable, typically an assignment statement. These three expressions can be a comma expression, that is, each expression can be composed of multiple expressions. Three expressions are optional, all can be omitted. The "statement" in general form is a cyclic body statement. The semantics of the for statement are: 1. First calculate the value of the expression 1. 2. Calculate the value of the expression 2, if the value is true (non-0), execute the cycler once, otherwise the loop is jumped out. 3. Then calculate the value of the expression 3, and turn it back to step 2.

During the entire FOR cycle, the expression 1 calculates only once, expressions 2 and expressions, 3 may calculate multiple times. The cyclic body may be executed multiple times or may not be executed once. The execution process of the for statement is shown in the figure. Void main () {INT N, S = 0; for (n = 1; n <= 100; n ) s = s n; printf ("s =% D / N", s);} Calculated with for statement s = 1 2 3 ... 99 100

INT N, S = 0; for (n = 1; n <= 100; n ) s = s n; Printf ("s =% D / N", S); Expression 3 in this effer statement is N , is actually an assignment statement, equivalent to n = n 1 to change the value of the cyclic variable. Void main () {Int a = 0, n; Printf ("/ n INPUT N:"); scanf ("% D", & n); for (; n> 0; A , n -) printf ("% D ", A * 2);} Use the for statement to modify the example. Starting from 0, N will be output from N. INT A = 0, N; Printf ("/ n INPUT N:"); scanf ("% d", & n); for (; n> 0; a , n -) Printf ("% d", a * 2); In this effer statement, the expression 1 has been omitted, and the initial value of the loop variable is obtained by the scanf statement before the FOR statement, and the expression 3 is a comma expression, from a , n - two expressions. composition. Each cycle is once again 1. N self-reduction 1. A change causes the output even increment, and the change in the change of N. In the use of the for statement, you should pay attention to the following points 1. The expression infor statement can be omitted, but the semicolon interval cannot be less. Such as: for (; expression; expression) eliminates the expression 1. FOR (expression; expression) eliminates the expression 2. FOR (expression; expression;) eliminates the expression 3. FOR (;;) saves all expressions. 2. When the cyclic variable has been assigned, the expression 1 can be omitted, as in Example 3.27, it belongs to this situation. Such as omnipulates 2 or Expression 3 will cause an infinite loop, then the cycle should be ended in the cyclic body. The example belongs to this situation. Void main () {INT A = 0, N; Printf ("/ n INPUT N:"); scanf ("% D", & n); for (; n> 0;) {a ; n -; printf "% d", a * 2);}} int A = 0, n; printf ("/ n INPUT N:"); scanf ("% d", & n); for (; n> 0;) {a , N -; Printf ("% D", A * 2);} In this example, the expression 1 and the expression 3 are omitted, and the N-state of the cycle is reduced by the N-statement in the cycle, to control the number of cycles . Void main () {INT A = 0, N; Printf ("/ n INPUT N:"); scanf ("% D", & n); for (;;) {a ; n -; printf ("% D) ", A * 2); if (n == 0) Break;}} int a = 0, n; printf (" / n INPUT N: "); scanf ("% d ", & n); for (;; ) {A ; N -; Printf ("% D", a * 2); if (n == 0) Break;} This example is all omitted. The decrease of cyclic variables and the judgment of the cycle variable are achieved by the statement in the cyclic body. When the n value is 0, the loop is aborted by the BREAK statement, and the procedure after the FOR is executed. In this case, the FOR statement has been equivalent to the While (1) statement. If there is no corresponding control method in the cyclic body, a dead cycle is caused. 3. The cyclic body can be a novel statement.

#include "stdio.h" void main () {int N = 0; Printf ("Input A String: / N"); for (; getchar ()! = '/ n'; n ); printf ("% D ", N);} In this example, the expression 1 of the FOR statement is eliminating, and the expression 3 is not used to modify the loop variable, but used as a count of input characters. In this way, the count that should be completed in the cyclic body is completed in the expression. Therefore, the cyclic body is an empty statement. It should be noted that the semicolon after empty statement is not less, such as lacking this semicolon, then executes the rear printf statement as a cycler. Conversely, if the cyclic body is not a null statement, it will never add a semicolon after the brackets of the expression, so that the cyclic body is empty and cannot be executed repeatedly. These are all common mistakes in programming, and they should pay very attention. 4.FOR statement can also be nest each other with while, do-while statement, constitute multiple cycles. The following is a legally nested nested. (1) for () {... while () {...} ...} (2) do {... for () {...} ...} while (); (3) while () {... for () {...} ...} (4) for () {... for () {...}} void main () {INT I, J, K; For (i = 1; i <= 3; i ) {for (j = 1; j <= 3-i 5; J ) Printf (""); for (k = 1; k <= 2 * i-1 5; k ) {IF (k <= 5) Printf (""); Else Printf "*");} Printf ("/ n");}} The statement in the transfer statement program is usually always performed in the order direction, or in the direction defined by the statement. If you need to change the normal flow of the program, you can use the transfer statement introduced in this section. Four transfer statements are available in C language: goto, break, continue, and return. The return statement can only appear in the modulated function, used to return to the primary, and we will introduce in the function chapter. This section describes the first three transfusion statements. 1.GOTO statement goto statement is also called unconditional transfer statement, its general format is as follows: goto statement label; where the statement reference is written according to the identifier, put it in front of a statement line, and the number is numbered (:) . The function of the statement is identified by the identifier, and uses the goto statement. Such as: Label: I ; loop: while (x <7); C language does not limit the number of times in the program, but the respective labels must not be renamed. The semantics of the GOTO statement are the statements that change the program flow direction and rotate the statement identified by the statement label. The GOTO statement is usually used with the conditional statement. Can be used to achieve conditional transfer, constitute a loop, and jump out of the cyclic body. However, in the structured programming, it is generally not advocated using a goto statement to avoid chaos of the program process, making it difficult to understand and debugging procedures. Statistics Enter the number of characters from the keyboard.

#include "stdio.h" void main () {int N = 0; Printf ("INPUT A String / N"); loop: if (getchar ()! = '/ n') {n ; goto loop;} printf ("% D", N);} int N = 0; Printf ("INPUT A String / N"); loop: IF (getchar ()! = '/ n') {n ; goto loop;} printf (" % D ", N); this example uses the IF statement and the GOTO statement to form a loop structure. When the input character is not '/ n', the N is executed, and then transfer to the IF statement cycle execution. The loop is stopped until the input character is '/ n'. BREAK statement BREAK statement can only be used in a switch statement or a loop statement, which is the role to jump out of the switch statement or jump out of this layer loop, and rotate the procedure after execution. Since the direction of transfer of the BREAK statement is clear, the statement label is not required to cooperate with it. The general form of the Break statement is: BREAK; the BREAK statement is used in the Switch statement and the FOR statement in the above example. Using the BREAK statement can make the loop speech with multiple exits, making programming more flexible and convenient under some occasions. Continue statement Continue statement can only be used in the cyclic body, its general format is: continue; its semantics is: End this loop, that is, the statement after the CONTINUE statement in the cyclic body is not executed, and the judgment of the next cycle condition is carried out. It should be noted that this statement only ends the cycle of this layer, does not jump out of the loop. Void main () {Int n; for (n = 7; n <= 100; n ) {if (n% 7! = 0) Continue; Printf ("% D", n);}} output 100 can be used 7 Take the number. INT N; for (n = 7; n <= 100; n ) {IF (n% 7! = 0) Continue; Printf ("% D", N);} In this example, each of 7 to 100 The number is tested. Only when the model is 0, the following printf statement can be performed, and the output can be removed by 7. #include "stdio.h" void main () {Char A, B; Printf ("Input A String: / N"); b = getchar (); while ((a = getchar ())! = '/ n' ) {if (a == b) {Printf ("Same Character / N"); Break;} B = a;}} Checking the same line in the input line. CHAR A, B; Printf ("Input A String: / N"); b = getchar (); while ((a = getchar ())! = '/ n') {if (a == b) {printf "Same Character / N"); Break;} b = a;} In this case, the first read character is sent to B.

Then enter the loop, read the next character into A, compare the A, B is equal, and if the phase is equal, the prompt string is output and the cycle is output. If it is not equal, the character in A is given to B, and the next cycle is input. The number of prime numbers within 100 is output. The number of prime is only 1 and itself. Use the exhaustive method to determine if a number is the number of prime. Void main () {INT N, I; for (n = 2; n <= 100; n ) {for (i = 2; i = n) Printf ("/ T% D", N);}} INT N, I; For (n = 2; n <= 100; n ) {for (i = 2; i = n) Printf ("/ t% d", n);} In this case, the first layer of cycle represents the 100 numbers of 1 to 100. Whether it is the number of prime, a total of 100 times, in the second layer cycle, the logs are removed by 2 to n-1, and if the except is except, the layer loop is jumped, and it is not the number of prime numbers. If all the numbers are ended, the cycle is ended, then the number of digits, there is I> = n, so the number of output probes can be determined by this. Then transfer to the next large cycle. In fact, all even numbers of 2 or more are not prime numbers, so that the step size of the cyclic variable can be changed to 2, i.e., each time it increases 2, and only the number of Number N is removed by 2 to n can determine whether the number is considered. This will greatly reduce the number of cycles and reduce program runtime. #include "math.h" void main () {INT N, I, K; for (n = 2; n <= 100; n = 2) {k = SQRT (N); for (i = 2; i < K; I ) IF (N% i == 0) Break; if (i> = k) Printf ("/ t% 2d", n);}} Summary 1. From the process of execution, the program can be divided For three most basic structures: sequential structure, branch structure, and loop structure 2. Execute some of the most basic units in the program are statements. The C language statement can be divided into five categories: (1) Expression statement, any expression, the semicolon can constitute an expression statement, the commonly used expression statement is an assignment statement. (2) Function call statement by function call plus the semicolon to form a function call statement. (3) The control statement is used to control the program process, consisting of a dedicated statement definition and the desired expression. The main condition is determined to execute a statement, a loop execution statement, a steering statement, and the like. (4) Composite statement encloses multiple stages to form a statement by {}. The composite statement is considered a single statement that can occur in all where the statement is allowed, such as cyclic body, and the like. (5) The empty statement is constructed only by the semicolon, no practical function. 3. The dedicated input output statement is provided in the language, all input and outputs are implemented by the input and output function in the quarant library function. The Scanf and getChar functions are input functions that receive input data from the keyboard. Scanf is a format input function that can be input to any type of data in the specified format. The getChar function is a character input function that can only receive a single character. The Printf and Putchar functions are output functions to output data to the display screen. PRINTF is a format output function that displays any type of data in the specified format. Putchar is a character display function that can only display a single character. 4. Relationships expressions and logical expressions are two important expressions, primarily for judging and cyclic execution of conditions.


New Post(0)