"c" functions, operations, flow control

Source: Internet
Author: User

First, function (a) what is a function

Any C language program is composed of one or more program segments (small programs), each of which has its own function, which we generally call "functions".

(ii) Definition of function

Purpose: To encapsulate a commonly used function to facilitate later invocation.

Step: Determine the function name, determine the function body, call

Format: Return value type function name (formal parameter list)

{function Body}

(c) Invocation of functionsExample:(d) Parameters of the function

①. Parameters: When defining a function, the arguments following the function name, such as NUM1 and num2

②. Arguments: When a function is called, the specific data of the descendant, such as A and b

③. The number of formal parameters and arguments must be equal

④. A variable with the same name as the parameter cannot be defined inside the function body

⑤. If the basic data type is a formal parameter, it is purely a value pass, and modifying the value of a function's internal parameter does not affect the value of the argument

⑥. A function can have no formal parameter, or it can have an infinite number of parameters

(v) return value of function

The role of 1.return:

①. Exit function

②. Returns a specific value to the caller of the function

2. Return value Use Note:

①. C is a weakly grammatical, weak type of language, very not strict

②. If the type of the return value is not written clearly, the default is int type

③. void represents no return value

④. Even if the return value type is explicitly declared, no value can be returned

⑤. C language By default, two functions with the same name are not allowed

(vi) Function use note

①. Duplicate function name not allowed by default

②. Functions are equal and cannot be nested defined

③. A function cannot be defined repeatedly, but can be declared repeatedly, as long as it is declared before the call, where it can be

④. function if the declaration is not defined, then the compilation succeeds, but the link is invalidated

(vii) Collaborative development of multiple people

#include <stdio.h> is a system header file.

#include <abc.txt> is equivalent to copying all content in the Abc.txt file to the current location in plain text mode.

"" indicates that the file is in the same path as the. c file, and you can use a relative path or an absolute path. The left side has an absolute path, and no/is a relative path.

Note: Custom files use "" and system files use <>.

If the function definition is called after the call and no corresponding declaration is made, the compiler will make an error.

Call function, no function declaration, compiler will not error, link times wrong, do not define the function instead of error.

Link: Combine the relevant. o Target files in the project with the C language libraries to generate the executable file.

Usually:

①. The definition of a function is placed in a. c file, and the declaration of the function is placed in the. h file

②. If you have a function defined in a. c file, you only need to include the. h file that corresponds to the. c file.

③. h file is born soy sauce is copied by others to contain, compile the link without writing

(eight) complement of functions

(1) Main function

The return value is returned to the operating system, 0 is normal exit, and the other value is abnormal exit.

(2) printf function

The return value is the number of characters. such as printf ("abc"); The return value is 3, if printf ("ABC man \ n"), the return value is 7 because a Chinese is 3 characters in the Mac OS X system.

(3) scanf function

①. # include <stdio.h> must be added before use.

②. When calling the scanf function, you need to pass in the address of the variable as a parameter, and the scanf function waits for input data and assigns the input data to the variable that corresponds to the address.

③. When you receive multiple values with the scanf function, the delimiter between the values is arbitrary.

Do not include \ n in the first parameter of ④.scanf, such as scanf ("%d\n", &a); This causes the SCANF function to not end.

Second, arithmetic operation (one)

There are 34 types of operators in C, including common subtraction operations

①. Addition: + can also indicate a plus sign

②. Subtraction:-can also represent a minus sign

③. Multiplication: * Non-mathematical meaning X

④. Division:/Note A value of 1/2 is 0, not One-second

⑤. Residual (modulo operation): the remainder after dividing two integers (note that both sides must be integers, and the positive and negative depend on the value of the left of%)

Attention:

①. int a = 10.8;//loss of precision. Result for 10--automatic type conversion

②. int a = (int) 10.8;//cast 10.8 to integral type--forced type conversion

③. Double C = 10.6 + 6//result is 16.600000. In the computer, take two numeric values for operation, and automatic type promotion if different types. That is, convert 6 to 6.000000 and then participate in the operation-automatic type promotion

(ii) Assignment operations

①. Simple Assignment

int a = ten + 5;a = b = 10;//Right-to-left, left cannot be constant

②. Compound Assignment

A = a + 5; + A + = 5;

A = a * 5; = a *= 5;

A + = 5 * 6 + 4; + A = a + (5 * 6 + 4)

Tip: The order of operations depends on the precedence of the operators and the order in which they are combined.

(iii) Self-increase self-reduction

int a = 10;

There are four ways to add the value of a to 1:

①. A = a + 1;

②. A + = 1;

③. a++;

④. ++a;

Simple distinction between a++ and ++a.

int b;

int a = 10;

b = ++a; A = = 11,b = = 11;a First add a value of 1 to 11, and then assign a value to B

b = a++; A = = 11,b = = 10;a First copy the value 10 to b,a yourself plus 1 for 11

b = (a++) + (++a); A1 = = 10,a2 = = 12,b = 22

b = (++a) + (a++); A1 = = 11,a2 = = 11,b = 22

Note: int d = 10++;//is wrong because it makes no sense to self-add and decrement constants.

(d) sizeof

Function: The number of bytes of memory used to calculate a variable, constant, or a data type.

Basic form: sizeof (variable name | constant | data type), returns a value after completion.

①. Sizeof Variable | constant

②. Sizeof (Variable | constant)

③. Sizeof (data type)

Note: Data types must be enclosed in parentheses and cannot be written in the form of the sizeof data type.

(v) Relational operations

(1) Condition judgment

By default. The correct code for each sentence written in the program is executed, but many times we need to execute a certain piece of code, such as a login operation, in a condition that can be done using conditional statements.

(2) True and False

In C language, the condition is called "true", the condition is not established is called "false".

C language provisions, any value is true and false, any non-0 value is true, only 0 is False, no Boolean type.

(3) Comparison of relationships

The result of the relational operation is only two cases, if the condition is true, the value is 1, if the condition is false, the value is 0. There are 6 types of operators, namely: (1) < (2) <= (3) > (4) >= (5) = = (6)! =

(4) Use note

①. = = and! = have equal precedence, and the other four relational operators have equal precedence, and the precedence of the former is lower than the latter. such as 2 = = 3 > 1 should be calculated first 3 > 1

②. In relational operators, if the precedence is the same, then "left to right" is combined. For example, 4 > 3 < 2, calculate 4 > 3 First

③. The precedence of the relational operator is lower than the arithmetic operator. such as 3 + 4 > 8-2 equivalent (3 + 4) > (8-2)

④. Exercise 5! = 4 + 2 * 7 > 3 = = 10 Calculate First 5! = > 3 = = 10,5! = 1 = = 10,1 = = 10, False

(vi) Logical operation

The result of a logical operation is only two: true (0) and False (1)

①. Logic and && conditions 1 && Condition 2 only the condition 1 and Condition 2 are established, the true or false.

②. Logic or | | Condition 1 | | Condition 2 When one of the conditions 1 or Condition 2 is true, it is false when it is not established.

③. Logical Not! ! Conditional inversion

Note: When a logical operator is operating, the following conditions are ignored, as long as the integrity of the whole can be determined.

int a = b = 10;

int c = (A > 5) && (++b >= 11);//At this time a = = 10,b = = 11,c = 1

int C = (A < 5) && (++b >= 11);//At this time a = = 10,b = = 10,c = 0

Tip: You can use () when you are doing a logical operation, if you don't know the priority of each symbol.

(vii) Three mesh operation

Binocular: Requires two values to participate in the operation

Monocular: A numeric participation operation such as!5

Trinocular: Requires 3 values to participate

Format: Condition? Value 1: Value 2

Judge first? Before the conditions, if the condition is set to return a value of 1, if the condition is not established, return to the condition 2.

A and B are required to be compared, and the values are stored in c = a > B. A:b

Compares the value of the A,b,c three number and deposits the maximum value in D

int Abmax = (a > B)? A:B;

D = abmax > c:abmax:c;

Third, Process Control (i) Process Control structure

(1) Sequential structure: Each statement is executed in the written order.

(2) Select structure: Judge the given condition and decide which piece of code to execute according to the result of judgment.

(3) Loop structure: In the case of a given condition, repeated execution of a piece of code.

(ii) Selection structure-if

(1) If simple to use

1) The first type of structure:

If the condition is true, the following statement is executed, otherwise it is not executed.

if (condition)

{

Statement 1;

Statement 2;

......

}

2) The second type of structure:

If the condition is true, statement 1 is executed, otherwise statement 2 is executed.

if (condition)

{

Statement 1;

}

Else

{

Statement 2;

}

3) The third type of structure:

The first judgment condition 1, if set up executes the statement 1, other does not carry out, if the condition 1 does not establish, then examines the condition 2 ...

"Note" If condition 3 is set up, the preceding is not true. Only one of all statement blocks will be executed.

if (condition 1)

{

Statement 1;

}

else if (condition 2)

{

Statement 2;

}

else (condition 3)

{

Statement 3;

}

4) The fourth type of structure:

In this case, when the condition is true, only statement 1 is executed, statement 2 does not belong to the sub-conditional structure, but it is not recommended.

if (condition)

Statement 1;

Statement 2;

(2) If use note

①. It is recommended to use the IF (0==a) notation.

②. Note the assignment operator, do not write = =.

③. Do not add semicolons after the If (condition).

④. Note the scope of the problem, if you want to define a new variable after the IF, you must use curly braces.

(3) If practice

Enter an integer score to represent the score, based on the score output level (A-E)

a:90~100 b:80~89 c:70~79 d:60~69 e:0~60

1 #include <stdio.h> 2  3 int main () {4  5     //define variable store sub-value 6  7     int score; 8  9     //Prompt Input 10 11     printf ("Please enter a score: \ n");/     /Accept Input     scanf ("%d", &score); +/     /judgment level     (score> =90&&score<=100) printf (         "a\n"); (     score>=80) (         "b\n"); 26 27     else if (score>=70),         printf ("c\n"), and the other     if (score>=60),         printf ("d\n"); 34 35     else36 Notoginseng         printf ("e\n");     0;40 41}
(iii) SELECT structure-Switch

(1) Switch structure

switch (value)//is usually a variable

{

Case value 1:

Statement 1;

Break

Case Value 2:

Statement 2;

Break

Case Value 3:

Statement 3;

Break

Default:

Statement 4;

Break

}

Explanation: The structure compares the value to the value 1, and if it is equal, executes all subsequent statements until the break statement jumps out of the entire loop, and if none of the preceding conditions is satisfied, the statement following the default is executed. If the break statement is not written, subsequent statements are executed consecutively until the break statement is encountered or all statements are executed, and the subsequent judgment is ignored if the preceding conditions are true.

(2) Switch use note

Char c= ' A ';

Switch (c)

{

Case ' A ':

Statement 1;

Break

Case 65://cannot write this, because the ASCII value of ' A ' is 65, it will error

Statement 2;

Break

Case Value 3:

int a=10;

A's scope is not clear error, C language Check the scope of the variable according to {}, here you can add {}

Break

Default:

Statement 4;

Break

}

Note: If you want to define a variable in the statement following the case, you must enclose it in curly braces.

(3) Switch exercise

Enter an integer seore to represent the score, based on the fractional output level (A-E).

A 90-100 B 80-89 C 70-79 D 60-69 E 0-60

1 #include <stdio.h> 2  3 int main () 4 {5     //define a variable score, which stores the user input fraction of 6     int score; 7  8     printf ("Please Lose Into your score: "); 9     scanf ("%d", &score);/     /Use the switch statement to determine what level of user-entered score is     (SCORE/10) {case         10:// 100 minutes         9://90~99             printf ("rank is a \ n"),             break;18 case         8://80~89             ("grade is B \ n") );             break;21 case         7://70~79             ("rank is C \ n"),             break;24 case         6://60~69             printf ("rank is D \ n"),             break;27         default://0~59             ("rank is E \ n"),             break;30     }31     

"Compare" if with switch:

1. If statement is capable of completing functions, switch is sometimes not able to complete, such as judging if (a>100)

2. In some cases, the IF statement and the switch statement can be interchanged

3. The switch statement can complete the function, if statement can be completed

(iv) Cyclic structure-while

(1) While structure

while (condition)

{

Statement

}

Explanation: The judgment condition is set up, the execution code block is executed (judging condition----execution code block, judgment condition, ...). )

1. First determine the loop to perform the operation, 2. In determining the constraints, that is, how many times to cycle, 3. Define a variable to record the number of cycles.

Tip: Use If...break (jump out of the loop) or If...continue statement in the while loop (jump out of the loop to continue the next loop).

The operating principle of the while structure:

①. If the initial condition is not true, the loop body will never be executed.

②. If the condition is true, the loop body is executed once and the condition is determined once the execution is complete.

③. Break: Exits the entire loop directly.

④. Continue: Ends the current loop body, making the next round of cycle judgment.

(2) Use note

1) while (1) {...} is a dead loop

2) while (a<10); {...} A comma is followed by a condition to indicate that the loop body is an empty statement, not a {} part

3) The {} is recommended after the while condition statement, otherwise the loop body is only the first statement

4) Simplest dead loop while (1);//Always execute empty statement, let program crash

(3) While practice

A programming implementation that prompts for a positive integer n to calculate the value of the 1+2+3+...N.

1 #include <stdio.h> 2  3 int main () {4  5     //define variable save user input integer 6  7     int n; 8  9 while     (n<=0 ) {Ten         //Prompt for         printf ("Please enter a positive integer: \ n"); +/         /Accept Input         scanf ("%d", &n);     }20 21     int sum=0;22     int number=0;//Default added value of     (number<n) {         number++;28         sum= sum+number;30     }32     printf ("Calculated as:%d\n", sum);     return 0;36 37}
(v) Cyclic structure-do while

Do

{

Statement

}while (condition)

Features: A Do While loop performs at least one loop body

(vi) Cyclic structure-for

(1) Basic use

For (statement 1, condition, statement 2)

{

Loop body

}

Statement 1: Typically an initialization statement

Statement 2: Typically an incremental statement (a statement executed after the loop body is executed)

For loop principle:

1) The FOR Loop executes statement 1 at the beginning (the entire for loop executes only once)

2) Determine whether the condition is established, if established, then execute a loop body, and then execute the statement 2, again determine whether the condition is set up, if the condition is not established, the end cycle

3) The Order is: (statement 1, judging condition---loop body------sentence 2--... )

"Contrast" for and while:

On the performance, the for loop slightly better because the while loop can use only external variables, and for loops to recycle variables in a timely manner.

(2) for use note

①. Do not write a semicolon after the for statement, such as for (); {...}

②. Defining a variable's scope ambiguous error

for (int i = 0;i < 5;i++)

int a = 10; Compiler error, variable scope ambiguous

The simplest dead loop in a ③. For statement for (;;);

④. Need to be aware of the scope of variable definitions

int a = 10;

for (int i = 0,int A = 9;i < 5;i++)

{

int a = 10;

printf ("A =%d\n", a);//What is the value of a printed here?

}

(3) For loop nesting

To export content in a specific format, such as a list of QQ friends, to improve scalability.

for (In i = 0;i < 5;i++)

{

Number of loop control lines outside

printf ("Buddy list%d\n", i);

Internal loop control Number of columns

for (int j = 1;j< = 6;j++)

{

printf ("Friend%d\n", J);

}

}

(4) For practice

Use the For loop to output the 99 multiplication table. First control the number of rows, in the number of control columns

Code:

1 #include <stdio.h> 2  3 int main () 4  5 {6  7 for     (int i=1;i<=9;i++) 8  9     {Ten for         ( int j=1;j<=i;j++) ("             %dx%d=%d\t", i,j,i*j), and         }18         ("\ n");     }22 23     

"c" functions, operations, flow control

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.