C Language Programming-the 3rd simplest C programming-sequential programming

Source: Internet
Author: User
Tags bitwise operators goto mathematical functions square root uppercase letter

3.2 Representation of data and its operation

3.2.1 Constants and variables

1. Constants :

1) Integral type constant

2) Real constant. 1. Decimal decimal form, consisting of a number and a decimal point. 2. Exponential form

3) Character constants. 1. Ordinary characters, one character enclosed in a single apostrophe. 2. Escape character.

Escape character Character value Output results
\‘ A single apostrophe (') Characters with this octal code
\" A double apostrophe (") Output this character
\? A question mark (?) Output this character
\\ A backslash (\) Output this character
\a Warning (alert) produce sound or visual signals
\b BACKSPACE (BACKSPACE) Backs up the current position by one character
\f Page change (Form feed) Move the current position to the beginning of the next page
\ n Line break Moves the current position to the beginning of the next line
\ r Enter (carriage return) Move the current position to the beginning of the bank
\ t Horizontal tab Move the current position to the next tab position
\v Vertical tab Move the current position to the next Vertical tab alignment point
\o,\oo or \ooo
Where o represents an octal number
The ASCII character corresponding to the octal code The character that corresponds to the octal code
\xh[h]
where h represents a hexadecimal digit
The ASCII character corresponding to the hexadecimal code The character that corresponds to the hexadecimal code

4) string constants. Enclose several characters with a double apostrophe, and the string constant is all the characters in the double apostrophe (excluding the double apostrophe itself). A single apostrophe can contain only one character, and a double apostrophe may contain a string. ( this place and JS different, JS with a single pair can )

5) Symbolic constants. Use the # define directive to specify that a symbol name represents a constant.

#define PI 3.1416  //Note there is no semicolon at the end of the line

After the above designation, this file starts from this line all pi represents 3.1416. Before the program is compiled, the preprocessor first handles the PI, replacing all pi with 3.1416.

After precompilation, the symbolic constants have all become literal constants (3.14159).

The advantage of using symbolic constants is that the meaning is clear and "change the whole thing" when it needs to be changed.

Note: To distinguish between symbolic constants and variables, do not mistake symbolic constants for variables. Symbolic constants do not account for memory, only a temporary symbol, after the pre-compilation of this symbol does not exist, it is not possible to assign the symbol constant to the new value. To differentiate from variable names, the customary symbolic constants are denoted in uppercase.

2. Variables

A variable represents a storage unit with a name that has a specific attribute. It is used to store data, that is, the value of the variable. The value of the variable can be changed while the program is running.

Variables must be defined first and then used .

Specifies the name and type of the variable at the time of definition. A variable should have a name, For reference. Note the two different concepts of distinguishing variables from each other. The variable name is actually a storage address represented by a name. When you compile a connection to a program, each variable name is assigned a corresponding memory address by the compilation system. Taking a value from a variable is actually finding the appropriate memory address from the variable name. The data is read from the storage unit.

3. Constant Variables

Const int a=3;

Represents a is defined as an shaping variable, specifying its value to be 3, and its value cannot be changed during the existence of a variable.

The similarities and differences between constant variables and constants: Constant variables have the basic properties of a variable: there is a type, which is the storage unit, but it is not allowed to change its value. It can be said that the constant variable is a non-variable with a name, and the variable is an invariant with no name. It is easy to be quoted in a program.

4. identifiers

In a high-level computer language, a valid sequence of characters named for variables, symbolic constant names, functions, arrays, types, and so on, is collectively referred to as identifiers. An identifier is the name of an object.

The C language specifies that identifiers can only consist of letters, numbers, and underscores of 3 characters, and that the 1th character must be a letter or an underscore.

General variable names are lowercase, increasing readability, and capitalization is a different character.

3.2.2 Data types

The so-called type is the arrangement of the Data allocation storage unit, including the length of the storage unit (the number of bytes) and the storage form of the data. Different types are assigned different lengths and storage forms.

The values of both the base type and the enumeration type variable are numeric values, collectively known as arithmetic types.

The arithmetic and pointer types are collectively known as a scalar type, because the value of the variable is represented by a number.

An enumeration type is an integer type defined by a user in a program.

Array types and struct types are collectively referred to as composite types, and the common body type does not attribute combination types because only one member has a value at the same time.

The function type is used to define a function, which describes the interface of a function, including the data type of the function return value and the type of the parameter.

Different types of data occupy a different length of storage units in memory.

3.2.3 Integral type data

1. Classification of integral type data

1) Basic integral type (int type)

The compilation system allocates 2 bytes or 4 bytes to the INT data. The storage unit is stored in the form of a complement of integers. A positive complement is the binary form of this number, and a negative complement is: first it is written in binary form, and then all the decimal digits behind it is reversed, plus 1.

In the storage unit where the integer is stored, the leftmost one is used to represent the symbol, if the bit is 0, indicating that the value is positive, and if the bit is 1, the value is negative.

2) Short integer type (shorter int)

The type is named short or shorter int. As with Visual C + + 6.0, the compilation system assigns 4 bytes to the int data, and 2 bytes for the integer.

3) Length integer (long int)

The type is named Long int or long. As with Visual C + + 6.0, the compilation system allocates 4 bytes of Long data.

4) Double-long Integer (Long long int)

The type is named long long int or long long. Typically 8 bytes are allocated, new types are added, and many C-compiled systems are not yet implemented.

The C standard does not specify the length of storage units used by various types of data, which is determined by the compilation system itself.

sizeof (short) <=sizeof (int) <=sizeof (long) <=sizeof (long Long)

sizeof is an operator that measures the length of a type or variable.

2. Symbol Properties for integer variables

Some data often has only positive values, you can define the variable as an "unsigned" type, preceded by the modifier unsigned, which indicates that the variable is "unsigned integer type." If you add the modifier signed, it is "signed type."

If neither is specified as signed and is not specified as unsigned, the default is signed type.

Description

1) only integer (including character type) data can be added signed or unsigned modifier, real data cannot be added.

2) output to unsigned integer data in "%u" format.%u represents the output in the format of unsigned decimal numbers.

After you define a variable as an unsigned integer, you should not give it a negative value, or you will get the wrong result.

3.2.4-character data

1. Character and character codes

Do not write a single character, the program can be recognized, can only use the system character set characters, large number system using the ASCII character set.

The glycol sets of various character sets include 127 characters, including: letters (uppercase, small English letters), digital 0~9, special symbols 29:! "# & ' () * +,-• / : ; < = >? [ \ ] ^ _ { | } ~, whitespace: space, Horizontal tab (tab), Vertical tab, wrap, page feed. Characters that cannot be displayed: empty (null) characters (denoted by ' \a '), a warning (denoted by ' \b '), a carriage return (denoted by ' \ R '), and so on.

All 127 characters can be represented in 7 binary, so in C, specify 1 bytes (8 bits) to store one character. At this point, the 1th bit in the byte is set to 0.

Note: The character ' 1 ' and the integer 1 are different concepts, the character ' 1 ' simply represents a symbol with a shape of ' 1 ', which is output as-is when needed, and is stored in memory in ASCII format, accounting for 1 bytes. The integer 1 is stored in integer (twos complement) storage, accounting for 2 bytes or 4 bytes.

2. Character variables

A character variable is a character variable that is defined with a type character char.

#include <stdio.h><stdlib.h>int  main () {    char c='  ? ' ;    printf ("%d%c\n", c,c);     return 0 ;}

Output 63?, '? ' The ASCII code is 63, the system assigns the integer 63 to the variable C.C is a character variable, essentially a byte shaping variable, because it is often used to hold characters, so called character variables. You can assign an integer between 0~127 to a character variable. When you output the value of a character variable, You can choose to output as a decimal integer or as a character.

3.2.5 Floating-point data

Floating-point data is used to represent a real number with a decimal point. In the C language, the real numbers are stored in an exponential form in the storage unit. A real number can be expressed as an exponent without a form. Because the decimal position can float, the exponential form of the real numbers is called floating-point numbers.

Normalized exponential form: 0 before the decimal point, 1th digit after the decimal point is not 0.

Floating-point types include: float (single-precision floating-point type), double (double-precision floating-point), long double (longer dual-precision floating-point).

1) Float type. Allocates 4 bytes, and the values are stored in the storage unit in normalized binary exponent form. When stored, the system divides the real data into fractional parts and two parts of the exponent part. The float data can be 6 digits.

2) Double type. Allocate 8 bytes. You can get 15 digits of a valid number.

3) long double type. Different compilation systems have different distributions.

3.2.6 How to determine the type of a constant

The type can be determined from the representation of a constant. For character constants It is simple to see a single character or escape character enclosed by a single apostrophe as a character constant.

Integer constant. A numeric value without a decimal point is an integer constant, but you should be aware of its valid range.

Increasing the letter L or lowercase l at the end of an integer indicates that it is a long int.

Floating-point constants. Any real number that appears in decimal or exponential form is a floating-point constant that is stored in the memory as an exponent. The C compiler system assigns 8 bytes to the floating-point constant, which is handled by double precision.

You can force the type of a constant to be specified by adding a private character at the end of the constant.

Note: To differentiate between types and variables.

Each variable belongs to a certain type, and the type is an important property of the variable. A variable occupies a storage unit, is a concrete entity, and can store data in the storage unit it occupies. The type is the commonality of variables, is abstract, does not occupy the storage unit, cannot use to store the data.

3.2.7 Operators and expressions

1. Basic Arithmetic operators: + (plus sign operator, monocular operator) – (minus operator, monocular operator) */% + (add)-(minus)

The result of dividing two real numbers is a double-precision real number, and the result of dividing two integers is an integer. If a divisor or divisor has a value negative, the rounding method is not fixed.

The% operator requires an operand (that is, an operand) to participate in an operation as an integer, and the result is an integer.

The operand of an operator other than% can be any arithmetic type.

2. Self-increment, decrement operator

Note: The increment operator (+ +) and the decrement (--) can only be used for variables, not constants or expressions. The value of the constant cannot be changed.

The increment (subtract) operator is commonly used in loop statements to automatically add 1 to the loop variable, and also for pointer variables to point the pointer to the next address.

3. Precedence and binding of arithmetic expressions and operators

When an expression evaluates, it is performed in the order of precedence of the operator, and the same level is handled by the Union direction, and the algorithm operator is combined from left to right. The assignment operator is in right-to-left order.

4. Mixed operations between different types of data

If the data types on either side of an operator are different, type conversions are performed automatically, making them the same type and then operating.

1) +,-, The *,/operation has a number of float or double, the system will convert all float type data to double type first, the result is double.

2) if the int type and float type or double type data, the int and float data are converted to double type, and then the result is double type.

3) character (char) type data and integer data to run, that is, the character of the ASCII code and integer data operation. Character data can be directly calculated with integer data. If the character data is operated with the real data, the ASCII code of the character is converted to the double type data. And then perform the operation.

The above conversion is done automatically by the system.

Example 3.3 Given an uppercase letter, output in lowercase letters. The following is a lowercase output of uppercase a

 #include <stdio.h> #include  <stdlib.h> int   main () { char      c1,c2; C1  = " a   "    ;    C2  =c1+32  ; printf (  " %c\n   "    ,c2); printf (  " %d\n   "    ,c2);  return  0  ;}  

A character data can be output either as a character or as an integer.

5. Forcing type conversion operators

You can use the coercion type conversion operator to convert an expression to the desired type

(double) A

(int) (x+y)

(float) (5%3)

The general form is: (type name) (expression)

When you force a type conversion, you get intermediate data for the type you want, and the type of the original variable does not change.

6.C operator

1) arithmetic operator (+–*/% + +--)

2) relational operators (> < = = >= <=! =)

3) logical operator (! && | |)

4) Bitwise operators (<< >> ~ |∧&)

5) assignment Operator (= and its extended assignment operator)

6) The conditional operator (?:)

7) comma operator (,)

8) pointer Operators (* and &)

9) Number of bytes operator (sizeof)

10) Coercion type conversion operator ((type))

11) member operators (.->)

12) subscript operator ([])

13) Other (such as function call operator ())

3.3 C Statements

A function consists of a declaration part and an execution part, and the execution part is composed of statements, and the corresponding operation is performed. A C statement is compiled to produce several machine instructions, the declaration part is not a statement, it does not produce machine instructions, but only the relevant data declaration.

The C statement is divided into the following 5 categories:

1) Control statements. C 9 Control statements: if () ..., while (), Else...,for (), Do...while (), continue (end this loop statement), Break (abort execution of switch or loop statement), switch (multi-branch SELECT statement), Return (from function return statement), Goto (Turn statement, basic no goto statement in a structured program)

2) Function call statement. A function call statement consists of a function call plus a semicolon.

3) expression statement. An expression statement consists of an expression and a semicolon.

A semicolon at the end of an expression is a statement. A statement must have a semicolon at the end, and a semicolon is an integral part of the statement, not a delimiter between two statements.

4) Empty statement. There is only one semicolon and nothing to do. can be used as a steering point for a process (where the flow goes from other parts of the program to this statement) or as a loop body in a looping statement (the loop body is an empty statement, which means that the loop body does nothing).

5) Compound statement. You can use {} to enclose some statements and declarations as compound statements (also called statement blocks). You can place a statement block switch position in a compound statement that is part of the declaration. The last semicolon in the last statement in a compound statement cannot be ignored.

3.3.2 Most basic statement-assignment statement

Example 3.4 gives the triangular three-side length, the triangular area

The following three-side assignment, to calculate the area

#include <stdio.h> #include <stdlib.h> #include <math.h>int main () {    double a,b,c,s,area;    a=3.68;    b=5.4;    c=6.21;    s= (A+B+C)/2;    Area=sqrt (s* (s-a) * (s-b) * (s-c));    printf ("a=%f\tb=%f\tc=%f\n", a,b,c);    printf ("area=%f\n", area);    return 0;}

The SQRT function is the square root function, because to call functions in the library of mathematical functions, there is a program beginning with a # include directive, the head file "MATH.H" included in the program.

' \ t ' is an escape character that jumps the output position to the next tab position.

Any function in a program that uses a library of mathematical functions should "contain" the MATH.H header file.

1. Assignment operator. 2. Compound assignment operator. 3. An assignment expression.

The expression that the assignment operator joins to one variable and one is called an assignment expression. Its general form is the variable assignment operator expression

The process of solving an assignment expression is to first evaluate the value of the expression on the right side of the assignment operator and assign it to the variable to the left of the operator. The left side of the assignment operator should be a modifiable value. A variable can be an lvalue, and an arithmetic expression cannot be an lvalue, and a constant cannot be an lvalue.

The expression in an assignment expression can also be an assignment expression.

An assignment expression cannot be a left-hand value.

An assignment expression can also appear in an output statement, a looping statement, and so on.

4. Type conversions during assignment

If the type on both sides of the assignment operator is the same, the assignment is made directly, and if it is inconsistent, but is an arithmetic type, the type conversion is performed at the time of assignment. Type conversions are performed automatically by the system, and the conversion rules are:

1) When assigning floating-point data to an shaping variable, the floating-point number is rounded first and then assigned to the shaping variable.

2) When assigning integer data to a single, double-precision variable, the value is the same, but stored in a variable as a floating-point number.

3) When assigning a double data to a float variable, the double is converted to a single precision, that is, only the 6~7 bit valid digits are stored in the 4 bytes of the float variable. Note that the size of the double value cannot exceed the value range of the float type variable.

When assigning a float data to a double variable, the value is unchanged, stored in memory in 8 bytes, and the number of significant digits is extended to 15 bits.

4) When the character data is assigned to the shaping variable, the ASCII code of the character is assigned to the shaping variable.

5) When assigning an integer-byte shape data to an integer-less shaped variable or character variable, only its low bytes are sent intact to the assigned variable (that is, "truncation" occurs).

To avoid assigning integer data with a lot of bytes to integer variables with fewer bytes, the value may be distorted after assignment.

The assignment between the real data and the integer and the real type is the first conversion (type) of the assignment value.

5. Assignment Expressions and Assignment statements

There is no semicolon at the end of an assignment expression, and a semicolon is required at the end of an assignment statement. You can include one or more assignment expressions in an expression, but you must never include an assignment statement.

6. Variable assignment initial value

You can assign a value to a variable with an assignment statement, or you can assign an initial value to a variable in a defined argument.

You can assign a value to a variable with an assignment statement, or you can assign an initial value to a variable when you define it. You can also assign an initial value to a part of a defined variable.

If the same initial value is assigned to several variables, it should be written as int a=3,b=3,c=3; and cannot be written as int a=b=c=3;

General variable initialization is not done during the compile phase (only when the initialization of static storage variables and external variables is done in the compilation phase), but rather when the program executes this function when the initial value is given, which is equivalent to executing an assignment statement.

3.4 Input and output of data

#include <stdio.h> #include <stdlib.h> #include <math.h>int main () {    double a,b,c,disc,x1,x2,p,q ;    scanf ("%lf%lf%lf", &a,&b,&c);    Disc=b*b-4*a*c;    p=-b/(2.0*a);    Q=SQRT (Disc)/(2.0*a);    X1=p+q;x2=p-q;    printf ("x1=%7.2f\nx2=%7.2f\n", x1,x2);    return 0;}

&a represents the address of variable a in memory. The SCANF function indicates that 3 data input from the terminal is sent to the storage unit with the address &a,&b,&c, which is assigned to the variable a,b,c. The double apostrophe is declared in the%LF format, indicating that the input is a double type real number .

When you enter data, two numbers are separated by a space , and if you use a different symbol (such as a comma), an error occurs.

In the printf function, a "7.2" is added to the front of the format letter F, indicating that when outputting x1,x2, the specified data occupies 7 columns, where the decimal number is 2 columns.

3.4.2 Concepts about data input and output

There is no point in a program that has no output.

The so-called input and output is based on the host computer. The C language itself does not provide input and output statements, and input and output operations are implemented by functions in the C standard function library.

When using the System library function, in the beginning of the program file with a preprocessing directive # # # to place the relevant header file in this program, such as # include <stdio.h> with precompiled Directive # # # to the desired "header file" Included in the user source file. The header file contains information about the function that you want to call. When using the standard input and output library functions, the information provided in the "Stdio.h" header file is used.

The stdio is an abbreviation for standard input & output, the "H" in the file suffix, which is the abbreviation for the header.

#include指令都放在程序文件的开头, so this type of file is called a header file.

#include <stdio.h> or #include "stdio.h"

In the form of angle brackets, the compilation system looks for the included files from the subdirectory of the C-compiled system, which is called the standard way. If you use double apostrophes, compile the system in the user's current directory (usually the user holds the subdirectory of the source program file) to include the file, if not found, and then the standard way to find.

Note: You should develop the habit of adding #include<stdio.h> directives whenever you use standard input and output library functions in this program file.

3.4.3 output data with the printf function

General format for 1.printf functions

printf (format control, output table column)

1) "Format Control" is a string enclosed in double apostrophes, "format string", which includes: a format declaration (consisting of "%" and a format character (such as%d,%f), a format that declares the problem by "%"), and a normal character (the character that needs to be output as-is).

2) "Output table column" is some data that the program needs to output, which can be a constant, a variable, or an expression.

printf (parameter 1, parameter 2, parameter 3,..., parameter n)

Parameter 1 is the format control string, and the parameter 2~ parameter n is the data that needs to be output. When you execute the printf function, the parameter 2~ parameter n is output in the format specified by parameter 1. Parameter 1 is required, and parameter 2~n is optional.

2. Format characters

1) d format character. Used to output a signed decimal integer. You can specify the field width (the number of columns) of the output data in the format declaration, such as "%5d", specifying the output data as 5 columns, and the output data displayed to the right of this 5 column area.

2) C format character. Used to output a character. You can also specify a field width.

3) s format character. Used to output a string.

4) F format character. Used to output real numbers (including single, double, long double), output in decimal form. basic type, with%f. Specify the data width and scale, using%M.NF, the output data is aligned to the left, with%-m.nf

Note: When using%f output, it is important to note that the data itself can provide valid numbers, such as float type data storage unit can only guarantee 6 digits. Double type data can guarantee 15 digits. Do not assume that all the numbers that are output by the computer are absolutely accurate and efficient.

5) e format character. The format declaration%e specifies that the real number is output as an exponent.

There are also I format characters, o format characters (output as octal integers), x format characters (integers are output as hexadecimal numbers), U-format characters, and G-format characters.

The general form of a format declaration can be expressed as:

% additional character format characters

In addition to x,e,g, other format characters must be in lowercase letters.

If you want to output the character "%", you should indicate a connection of two "%" in the format control string.

3.4.4 entering data with the scanf function

General format: scanf (Format control, Address table column)

The format declaration also begins with%, ending with a format character, in which additional characters can be inserted in the middle.

Note: the "format control" should be followed by the variable address, not the variable name.

If there are other characters in the format control string other than the format declaration, they should be entered in the corresponding position at the time the data is entered.

3.4. Input and output of 5 character data

1. Use the Putchar function to output one character

Format:Putchar (c)

Example 3.8 Output Boy three characters

#include <stdio.h> #include <stdlib.h>int main () {    char a= ' B ', b= ' O ', c= ' Y ';    Putchar (a);    Putchar (b);    Putchar (c);    Putchar (' \ n ');    return 0;}

The following results are the same as above

#include <stdio.h> #include <stdlib.h>int main () {    int a=66,b=79,c=89;    Putchar (a);    Putchar (b);    Putchar (c);    Putchar (' \ n ');    return 0;}

The Putchar function is a function of the output character, which outputs a character and cannot output an integer.

C in Putchar (c) can be a character constant, an integer constant, a character variable, or an integer variable.

2. Enter a character with the GetChar function

Format:getchar ()

The GetChar function does not have parameters, it is to enter a character from the computer terminal, that is, the computer obtains a character. The GetChar function can only receive one character, and multiple GetChar functions are necessary if you want to enter more than one character.

Example 3.9 Enter BOY3 characters from the keyboard and then output them to the screen.

#include <stdio.h> #include <stdlib.h>int main () {    char a,b,c;    A=getchar ();    B=getchar ();    C=getchar ();    Putchar (a);    Putchar (b);    Putchar (c);    Putchar (' \ n ');    return 0;}

1. If our gross domestic product is growing at an annual rate of 10%, calculate the percentage of GDP growth in 10 compared with the present.

The computer formula is:, R is the annual growth rate, n is the number of years, p is the multiples compared with the present.

#include <stdio.h><stdlib.h><math.h>int  main () {      float  p,r,n;    R=0.1;    n=ten;    P=pow (1+r,n);    printf ("p=%f\n", p);     return 0 ;}

6. Please compile the program to translate "China" into a password, the password rule is: replace the original letter with the 4th letter after the original letter.

#include <stdio.h> #include <stdlib.h>int main () {    char c1= ' C ', c2= ' h ', c3= ' i ', c4= ' n ', c5= ' a ';    c1=c1+4;    c2=c2+4;    c3=c3+4;    c4=c4+4;    c5=c5+4;    printf ("Password is%c%c%c%c%c\n", c1,c2,c3,c4,c5);    return 0;}

C Language Programming-the 3rd simplest C programming-sequential programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.