C Language Chapter 3

Source: Internet
Author: User
Article Directory

Foreword
First, the sequence structure
Second, select the structure 1-if statement
Third, select the structure 2-switch statement
Fourth, the loop structure 1-while loop
Five, loop structure 2-do while loop
Six, loop structure 3-for loop
Break and continue
Back to top Preface 1. The default operation process
By default, the program runs as follows: After running the program, the system executes each line of code in the program in the written order. For example, the following program

 1 #include <stdio.h>
 2 
 3 int main ()
 4 {
 5
 6 printf ("Hello-1 \ n");
 7 printf ("Hello-2 \ n");
 8 printf ("Hello-3 \ n");
 9     
10 return 0;
11}
After the program runs, the sixth, seventh, and eighth statements are executed in order, so the output is:

 

2. Other operating processes
But many times, we don't want to follow the default running process, for example, we want to execute a certain piece of code when a certain condition is met, otherwise we don't execute it. For example this interface:

If the user clicks the registration button, we execute the code of "jump to the registration interface"; if the user clicks the login button, we execute the code of "jump to the login interface". If the user does nothing, the two pieces of code mentioned above are not executed. To achieve this function, you must learn how to control the running process of the program.

 

3. Process structure
In order to make it easier for us to control the running process of the program, C language provides 3 kinds of process structures, and different process structures can realize different running processes. The three process structures are:

Sequence structure: The default process structure. Execute each statement in writing order.
Choose structure: judge the given conditions, and then decide which piece of code to execute based on the judgment results.
Loop structure: When a given condition is met, a certain piece of code is repeatedly executed.
The following is a flowchart of these three structures, which can be previewed roughly.

 

Back to top I. Sequence structure
The sequence structure is the simplest of the three structures, and it is also the default process structure: the statements in the program are executed in the written order. The code snippets listed at the beginning of the article are the sequential structure, so I won't introduce more here.

 

Back to top Second, select the structure 1-if statement
There are two ways to implement the choice structure in C language: if statements and switch statements. First look at the use of if statements, and there are many forms of if statements.

1.Form 1
Let's take a look at the simplest form of the if statement first.

1> Introduction
1 if (condition)
2 {
3 Statement 1;
4 statement 2;
5 ....
6}
If the condition in the parenthesis () to the right of if is true, that is, "true", the statements in the curly braces {} in lines 2 to 6 will be executed; if the condition is false, the curly braces {} will not be executed. Statement. Here if is a keyword.

2> Example
1 int a = 7;

3 if (a)
4 {
5 printf ("Condition a is true \ n");
6 printf ("The value of a is true");
7}
C language stipulates that all non-zero values are "true", and the value of a is 7, so the condition of the third line is satisfied, and then the fifth and sixth lines of code are executed. The output is as follows:

1 Condition a holds
2 a is true
If the value of a is changed to 0, then the condition in line 3 will not be satisfied, and the lines 5 and 6 will not be executed.

3> Omitting braces {}
If there is only one line of code in the braces {} after the if, the braces can be omitted. The form is as follows:

if (condition)
    Statement 1;
Note: If the condition is true, only the first statement after the if will be executed; if the condition is not true, the first statement after the if will not be executed.

1 int a = 7;

3 if (a> 9)
4 printf ("aaa");
5 printf ("bbb");
Because a> 9 in line 3 is not true, the code in line 4 will not be executed. The fifth line of code does not have any practice with the if statement, so the fifth line of code is executed as usual. Then you will see only output: on the screen.

Because the fifth line of code is not related to the if statement, it is generally written as follows:

1 int a = 7;

3 if (a> 9)
4 printf ("aaa");
5 printf ("bbb");
To keep the code readable, we don't recommend omitting braces! !! !!

4> statement nesting
If statements can be nested inside other if statements, such as the following example

 1 int a = 7;
 2 
 3 if (a> 0)
 4 {
 5 printf ("The value of a is greater than 0 \ n");
 6
 7 if (a <9)
 8     {
 9 printf ("The value of a is less than 9");
10}
11}
The a> 0 in the third line is true, so the code in the 4 ~ 11 braces will be executed in order. When execution reaches line 7, a <9 is also true, so line 9 code will be executed. Output results:

1 value of a is greater than 0
2 a value is less than 9
5> Use note 1
Some people are used to adding a semicolon ";" after writing a line of code, so when writing an if statement, they might write:

1 int a = 6;
2 if (a> 8);
3 {
4 printf ("a is greater than 8");
5}
If the semicolon at the end of line 2 is actually a semicolon, it is also a statement. This is called an "empty statement". The a> 8 in the second line is not true, so the following "empty statement" will not be executed. The following brace {} is not related to the if statement, so it will be executed normally, so you will see the output:

a is greater than 8
So be very careful not to add a semicolon after the parentheses in an if.

The content of lines 3 to 5 is a separate "code block":

1 {
2 printf ("a is greater than 8");
3}
6> Use note 2
The following is correct from a grammatical perspective:

int a = 10;

if (a = 0) {
    printf ("condition is true");
} else {
    printf ("condition does not hold");
}
The above code is perfectly reasonable, the compiler will not report an error, it is just a warning. Because a is 0, it is "false", and the output is: "condition is not true"

There are big pitfalls hidden here:

Suppose you originally wanted to determine whether a is 0, then you should write if (a == 0). If you mistakenly write if (a = 0), it will be a very terrible thing, because the compiler does not An error is reported, such a bug is hard to find. Therefore, an expression like a == 0 is best written as 0 == a. If you mistakenly write 0 = a, the compiler will directly report an error.

// Not recommended
if (a == 0) {
}

// recommended
if (0 == a) {
}
7> Use note 3
In C, the results of relational operations can be saved. Therefore, the following is legal:

1 int a = 10;
2 a> 10;
3 a == 0;
Here is another pitfall. Assuming that your intention is to assign a to 0, you should write a = 0 ;. If you mistakenly write a == 0 ;, then it will be a very difficult bug to find, because the compiler The device will not report an error at all. In 1993, this BUG almost made a hardware product worth US $ 20 million fail, because if this BUG is not resolved, the product cannot be used normally.

 

2.Form 2
if can also be used with the keyword else

1> Introduction
1 if (condition)
2 {
3 Statement 1;
4}
5 else
6 {
7 statement 2;
8 }
If the condition is true, the statement in the brace {} after the if is executed; if the condition is not true, the statement in the brace {} after the else is executed. In short, one of the two braces must be executed, and only one can be executed.

To reduce the number of lines of code, you can also write the following format:

1 if (condition) {
2 statement 1;
3} else {
4 statement 2;
5}
Of course, you can also omit the braces and write the following format:

1 if (condition)
2 statement 1;
3 else
4 statement 2;
If the condition is true, the first statement after the if is executed; if the condition is not true, the first statement after the else is executed. However, it is still not recommended to omit the braces {}.

2> Example
1 int a = 10;
2 if (a == 0) {
3 printf ("a equals 0");
4} else {
5 printf ("a is not equal to 0");
6}
A == 0 in the second line is not true, so the fifth line of code is executed, and the result is output:

a is not equal to 0
 

3.Form 3
if and else have a more complicated usage

1> Introduction
 1 if (condition 1)
 2 {
 3 Statement 1;
 4}
 5 else if (condition 2)
 6 {
 7 statement 2;
 8 }
 9 else if (condition 3)
10 {
11 statement 3;
12}
13 ...
14 else
15 {
16 other statements;
17}
If condition 1 is true, the content in the brace {} after condition 1 is executed: lines 2 ~ 4
If condition 1 does not hold, and condition 2 holds, the content in braces {} after condition 2 is executed: lines 6 to 8
If condition 1 and condition 2 are not satisfied, and condition 3 is satisfied, the content in the brace {} after the condition 3 is executed: lines 10-12
On line 13 means that there can be unlimited else if
If all the conditions are not met, the content in the braces {} after the else will be executed: lines 15 ~ 17
Note: With so many curly braces, only the code within the curly braces will be executed. As before, all braces can be omitted, but they are not recommended. When necessary, the last paragraph of the else (lines 14-17) can be omitted.

2> Example
1 int a = 10;
2 if (a == 0) {
3 printf ("a equals 0");
4} else if (a> 0) {
5 printf ("a is greater than 0");
6} else {
7 printf ("a is less than 0");
8 }
A == 0 in line 2 is not true, then line 4 is checked. A> 0 in line 4 holds, so line 5 is executed. Output results:

a is greater than 0
If the value of a is negative, then the conditions in lines 2 and 4 are not met, so the line 7 code is executed.

 

Back to top III. Select structure 2-switch statement 1. Form
First look at the use of the switch statement:

 1 switch (integer expression)
 2 {
 3 case value 1:
 4 Statement 1;
 5 break;
 6 case value 2:
 7 statement 2;
 8 break;
 9     ... ...
10 case value n:
11 statement n;
12 break;
13 default:
14 statements n + 1;
15 break;
16}
When the value of the integer expression is equal to "Value 1", "Statement 1" will be executed, and the subsequent break means to exit the entire switch statement, that is, jump directly to line 16;
When the value of the shaping expression is equal to "Value 2", "Statement 2" is executed; the rest are followed. If none of the values 1 to n is equal to the value of the integer expression, then the statement n + 1 in default is executed.
Since there is a break after all the cases, the switch statement will be exited directly after the execution of the statements in any case.
 

2. Examples
 1 int a = 10;
 2 
 3 switch (a) {
 4 case 0:
 5 printf ("This is a 0");
 6 break;
 7 case 5:
 8 printf ("This is a 5");
 9 break;
10 case 10:
11 printf ("This is a 10");
12 break;
13 default:
14 printf ("Nothing");
15 break;
16}
Because the value of a is exactly equal to 10 after the case on line 10, the line 11 code is executed and the result is output:

This is a 10
 

3.break
The role of the break keyword is to exit the entire switch statement. In the default format, there is a break after each case, so after executing the statements in the case, the switch statement will exit.

1> If there is no break after a case, it means that after the execution of the statements in this case, all subsequent cases and statements in default until break is encountered

 1 int a = 0;
 2 
 3 switch (a) {
 4 case 0:
 5 printf ("This is a 0 \ n");
 6 case 5:
 7 printf ("This is a 5 \ n");
 8 case 10:
 9 printf ("This is a 10 \ n");
10 break;
11 default:
12 printf ("Nothing \ n");
13 break;
14}
Since the value of the variable a is equal to 0 after the case in line 4, the line 5 code is definitely executed.
Since there is no break statement in case 0, the switch statement will not be exited and the code execution will continue.
Since the value of a is already equal to the value of the case in the fourth line, then it will not be judged whether the value of a is equal to the value of other cases, and the lines 7 and 9 are directly executed in order. There is a break on line 10, and then the switch statement will exit.
The output is:
1 this is a 0
2 this is a 5
3 this is a 10
If you change the value of a to 5, the output is:

1 this is a 5
2 this is a 10
 

2> At some point, we really don't need to add a break after each case. Here is an example: judge the grade of good and poor (100 points out of 100).

 1 int score = 77;
 2 
 3 switch (score / 10) {
 4 case 10:
 5 case 9:
 6 printf ("Excellent");
 7 break;
 8         
 9 case 8:
10 printf ("Good");
11 break;
12
13 case 7:
14 case 6:
15 printf ("medium");
16 break;
17
18 default:
19 printf ("Poor");
20 break;
twenty one }
When the score ranges from 90 to 100 and the score / 10 is 10 or 9, the sixth line of code is executed, and then the switch statement is exited;
When the range of score is 80 ~ 89, and the value of score / 10 is 8, the 10th line of code is executed, and then the switch statement is exited;
When the range of score is 60 ~ 79 and the value of score / 10 is 7 or 6, the 15th line of code will be executed and then the switch statement will be exited;
When the range of score is not 60 ~ 100 and the value of score / 10 is not in the range of 6 ~ 10, the 19th line of code will be executed and then the switch statement will be exited;
The value of score is 77, so the value of score / 10 is 7, and the output is: medium
 

4. Define variables in case
Sometimes, we may want to define some variables in the case. At this time, we must enclose all the statements in the case with braces {}.

 1 int a = 10;
 2 int b = 4;
 3
 4 char op = ‘-’;
 5
 6 switch (op)
 7 {
 8 case ‘+‘:
 9     {
10 int sum = a + b;
11 printf ("a + b =% d \ n", sum);
12 break;
13}
14
15 case ‘-‘:
16 {
17 int minus = a-b;
18 printf ("a-b =% d \ n", minus);
19 break;
20}
twenty one         
22 default:
23 printf ("Unrecognized symbol");
24 break;
25}
Define two variables at 10th and 17th respectively. Output results:

a-b = 6
 

Back to top IV. Loop structure 1-while loop
What would you do if you wanted to output Hello World repeatedly on the screen 10 times? Simple, just make 10 copies of the code below.

1 printf ("Hello World \ n");
That's right, writing the last code 10 times can really achieve the function. But such code is too garbage, there is a lot of duplicate code, which will make the code very bloated and low reuse rate. Therefore, this is not recommended.

The next time you encounter an operation that is repeated as above, the first thing to think of is the loop structure. The so-called loop is to repeatedly perform a certain operation. There are many ways to implement the loop structure in the C language. Let's take a look at the while loop first.

Form
1 while (condition)
2 {
3 Statement 1;
4 statement 2;
5 ....
6}
If the condition is true, the statement in the loop body is executed (the "loop body" is the content in the braces {} after the while). Then judge the condition again, repeat the above process, and end the while loop until the condition is not met
The characteristics of the while loop: If the condition in the while does not hold at the beginning, the statements in the loop body will never be executed
The braces {} can be omitted, but only the first statement after the while will be affected. Omitting braces is not recommended.

1 while (condition)
2 statement 1;
 

2. Examples
Repeat the output of Hello World on the screen 10 times, with a line break every time.

1 int count = 0;
2 while (count <10)
3 {
4 printf ("Hello World \ n");
5
6 count ++;
7}
If you omit count ++ in line 6 and count is always 0, then count <10 is always true. This while loop will fall into an "endless loop" and the line 4 code will be repeatedly executed.

 

3. Note
If written like this, the program will also enter an "endless loop"

1 int count = 0;

3 while (count <10);
4 {
5 printf ("Hello World \ n");
6
7 count ++;
8 }
Note on line 3, a semicolon is accidentally added after the while; a semicolon indicates an empty statement.
It can be seen that the while loop only affects the empty statement on line 3, and the code blocks on lines 4 to 8 are not affected by the while loop
Since count is 0, then count <10 is always true, and the program will repeatedly execute the empty statement on line 3, falling into an endless loop.
 

Back to top V. Loop structure 2-do while loop
The form is as follows:

1 do {
2 statement 1;
3 statement 2;
4 ...
5) while (condition);
Note the fifth line, followed by a semicolon;
When the do-while loop is executed, the statements in the loop body are executed first (the "loop body" is the content in the braces {} after do). Then judge the condition in while, and if the condition is true, execute the statement in the loop body. Then judge the condition again, repeat the above process, and end the while loop until the condition is not met
The characteristics of do-while loops: The statements in the loop body will be executed at least once, regardless of whether the conditions in the while are true.
In fact, the use of the do while loop is similar to that of the while loop, so no examples are given here.
 

Back to top VI. Loop structure 3-for loop 1. Form
 The for loop is the most complex of all loop structures.

1 for (statement 1; condition; statement 2) {
2 statement 3;
3 statement 4;
4 ...
5}
At the beginning of the for loop, statement 1 is executed first, and statement 1 is executed only once during the entire loop
Then judge the condition, if the condition is true, the statement in the loop body will be executed (the "loop body" is the content in the braces {} after the for)
After the execution of the loop body is completed, the next statement 2 is executed, then the condition is judged again, and the above process is repeated until the condition is not satisfied and the for loop ends
 

2. Examples
1 for (int i = 0; i <5; i ++)
2 {
3 printf ("% d", i);
4}
The output is:

0 1 2 3 4
It should be noted that the scope of the variable i is lines 1 to 4. Once out of this for loop, the variable i becomes invalid.

 

3. supplement
If the initialization statement of the for loop and the statement executed after the loop are composed of multiple statements, use a comma to separate them.

1 for (int x = 0, y = 0; x <3; x ++, y + = 2)
2 {
3 printf ("x =% d, y =% d \ n", x, y);
4}
Output results:

x = 0, y = 0
x = 1, y = 2
x = 2, y = 4
 

Back to top Seven, break and continue
Next, introduce two more important statements: break and continue.

1.break
Break has been used in the switch statement earlier, and its role is to jump out of the switch statement. It can also be used in loop structures, and its role at this time is to jump out of the entire loop statement.

1> Example
Here for example for loop, break can also be used in while loop, do-while loop.

1 for (int i = 0; i <5; i ++) {
2 printf ("i =% d \ n", i);
3
4 if (i> 2) {
5 break;
6}
7}
The above code means that when i> 2, it jumps out of the entire for loop, that is, ends the for loop, so the output is:

i = 0
i = 1
i = 2
i = 3
 

2> for loop nesting
First look at an example of for loop nesting. Nesting means: another for loop inside the for loop.

1 for (int x = 0; x <2; x ++) {
2 for (int y = 0; y <2; y ++) {
3 printf ("x =% d, y =% d \ n", x, y);
4}
5}
The output is:

1 x = 0, y = 0
2 x = 0, y = 1
3 x = 1, y = 0
4 x = 1, y = 1
 

At this time, if a break is added to the for loop, does this break break out of the for loop inside or outside?

1 for (int x = 0; x <2; x ++) {
2 for (int y = 0; y <2; y ++) {
3 printf ("x =% d, y =% d \ n", x, y);
4
5 break;
6}
7}
Note the break on line 5. The effect of this break is to jump out of the for loop inside, not the outer for loop. So the output is:

x = 0, y = 0
x = 1, y = 0
 

If you change the position of break

1 for (int x = 0; x <2; x ++) {
2 for (int y = 0; y <2; y ++) {
3 printf ("x =% d, y =% d \ n", x, y);
4}
5
6 break;
7}
Note the break in line 6. The purpose of this break is to jump out of the outer for loop, not the inner for loop. So the output is:

x = 0, y = 0
x = 0, y = 1
The rule is already obvious: break only affects the for loop it is in

 

2.continue
continue can only be used in a loop structure, its role is to skip this loop and directly enter the next loop.

Here for example for loop, continue can also be used in while loop, do-while loop.

1 for (int x = 0; x <10; x ++) {
2 if (x% 2 == 0) {
3 continue;
4}
5
6 printf ("x =% d \ n", x);
7}
Note that in the second line, when x% 2 == 0, that is, when x is a multiple of 2, the loop is skipped and the next line is directly executed without executing the statement in line 6. Output results:

1 x = 1
2 x = 3
3 x = 5
4 x = 7
5 x = 9
Like break, continue only affects the for loop it is in

c language chapter 3


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.