Program structure in C language

Source: Internet
Author: User

There are three kinds of program structure in C language, namely sequential structure, selection structure and cyclic structure.

The program structure, which is executed according to the order of the statements, is called the sequential structure.

The following is an example of a triangle area, with the following code:

Example 1.1

1 #include <stdio.h> 2 int main () 3 {4       int width,height,s; 5       printf ("Please enter the base width of the triangle: \ n"); 6       scanf ("%d", &width); 7       printf ("Please enter the height of the triangle: \ n"), 8       scanf ("%d", &height), 9       s=width*height/2;10       printf ("The area of the triangle: s=%d\n ", s);       return 0;12  }

When the program executes, it is necessary to enter the bottom width of the triangle (6 lines), and then enter the height (8 lines), the program goes down, calculates the area of the triangle (9 rows), and finally shows the area (10 lines). This is done in the order in which the statements are executed.

Second, according to the establishment of a certain condition or not to adopt different procedures to deal with the structure of the program, called the selection structure.

Usually the choice structure has two branches, the condition is true, executes a program segment, otherwise executes the B program section. Sometimes, two branches do not fully describe the actual problem (for example, the student score is divided into a,b,c,d,e and other grades according to the scores), need to be divided into multiple branches, such a program structure called multi-branch selection structure.

1. If simple statement

Its grammatical form is as follows:

if (an expression)

{Statement 1}

Function: Evaluates the value of an expression, if true, executes statement 1, otherwise skips statement 1 and executes the next statement of the IF statement.

Example 2.1

1 #include <stdio.h> 2 int main () 3 {4       int age; 5       scanf ("%d", &age) 6       if (age>18) 7       {8             PR INTF ("You are already an adult!") "); 9       }10       re&turn 0;11  }

In the above program, the integer variable age is defined first, and after the value of age is entered, the age value is determined to determine whether it is an adult. When running the code, if the value entered is greater than 18 years old, then output "You are already an adult!" , or exit the program directly.

2. If-else statement

Its grammatical form is as follows:

if (an expression)

{Statement 1}

Else

{Statement 2}

Function: Calculate the value of the expression, if the value of the expression is "true" to execute statement 1, and Skip Statement 2, continue to execute the next statement of the If-else statement, if the expression is false, skip statement 1, execute Statement 2, and then continue to execute the next statement of the If-else statement.

Example 2.2

1 #include <stdio.h> 2 int main () 3 {4        int age; 5        scanf ("%d", &age), 6        if (age>18) 7        {   8
   PRINTF ("You are already an adult!") "); 9         }10        else11        {               PRINTFF ("You're still a minor! ");         }14      re&turn 0;15  }

The above procedure compares with example 2.1, one more statement. When running code, if the value entered is greater than 18 years old, then output "You are already an adult!" ", otherwise output" you are still a minor! “。

3. Nested IF statements

In the IF statement and the If-else statement form, Statement 1 or statement 2 can be any legitimate statement. If they are also if statements, they form nested IF statements. There are several types of nested forms, as described below.

Nested form 1 nested form 2 nested form 2

if (expression 1) if (expression 1) if (expression 1)

{{{statement 1}

if (expression 2) if (expression 2) else if (expression 2)

{Statement 1}                                  {Statement 1} {Statement 2}

else} else

{Statement 2} else {statement 3}

} {Statement 2}

Else

{Statement 3}

Example 2.3: Finding the following piecewise function

When X>0, y=x+1; when X=0, y=x; x<0 when y=x-1;

Using nested form 1:

1 #include <stdio.h> 2 int main () 3 {4       int x, y, 5       scanf ("%d", &x), 6       if (x>=0) 7       {8             if (X&G T;0) 9             {                    y=x+1;11             }12 else13 {+ y=x;15}16}17 else18       {19              y=x-1;20        }        printf ("x=%d,y=%d\n", X, y);        return 0;23}

Using nested form 2:

1 #include <stdio.h> 2  int main () 3 {4        int x, y, 5        scanf ("%d", &x), 6        y=x; 7        if (x>=0) 8
   {9              if (x>0)              {                     y=x+1;12              }13        }14        else15        {              y=x-1;17        }18 printf ("x=%d,y=%d\n", X, y);        return 0;20  }

Using nested form 3:

1 int Main () 2 {3       int x, y;       4       scanf ("%d", &x), 5       if (x>0) 6       {7             y=x+1; 8       } 9       else if (x=0)       {one             y=x ;       }13       else)       {             y=x-1;16       }17       printf ("x=%d,y=%d\n", X, y);       return 0;19}

4. Switch statement

The form is as follows:

Switch ()

{

case constant Expression 1: statement 1

Case constant Expression 2: statement 2

......

case constant Expression N: statement n

Default: Statement n+1

}

IDEA: A switch statement is often used with break, and the function of break is to terminate the switch statement where it is located.

Example 2.4 According to the high and low level of student performance, the code is as follows:

1 #include <stdio.h> 2 int main () 3 {4      int x; 5      printf ("Please enter student score: \ n"), 6      scanf ("%d", &x); 7      SWITC H (X/10) 8      {9 Case            10:10 case            9:11                  printf ("A"), break;13 case            8:14                  printf ("B"); 15                  break;16 case            7:17                  printf ("C"),                  break;19 case            6:20                  printf ("D");                  break;22 Case            5:23 Case 4:24 Case 3:25 Case 2:26 Case 1:27 case            0:28                  printf ("E");                  break;30            default:31                  printf ("Invalid data! ");      }33      return 0;34}

In the above program, first define an integer variable x, after entering the value of x, according to the scope of x, determine the grade of the score. When you run the code, if you enter 85, the output is "B", which indicates that the student grade is B. If there is no break statement in the switch statement, the program continues executing the following statement, outputting B, C, D, E.

Third, control a block of code execution multiple times, know that a condition is satisfied with the program structure, called the loop structure.

In the C language, the while statement, the Do-while statement, and the FOR statement are circular statements that directly control the looping process.

1. While statement

Its grammatical form is as follows:

while (expression)

{Loop Body Statement}

Function: The value of the expression is evaluated first, if true, the loop body statement is executed, after execution, the value of the expression is evaluated, and if it is still true, the loop body statement is executed repeatedly. Until the value of the expression is false, end execution of the while statement and continue executing the statement following the while statement.

In order to 1+2+3+......+100 and for example, the use of the while Loop statement is explained.

Example 3.1

1 #include <stdio.h> 2 int main () 3 {4       int s,i; 5       s=0; 6       I=1; 7 while       (i<=100) 8       {9             s=s+i ;             i++;11       }12       return 0;13}

2. Do-while statement

Its grammatical form is as follows:

Do

{Loop Body Statement}

while (expression);

Function: The loop body statement is executed first, then the value of the loop control condition expression is detected, and if true, the loop body statement is executed repeatedly, otherwise the loop is exited.

In order to 1+2+3+......+100 and as an example, explain the use of Do-while loop statement.

Example 3.2

1 #include <stdio.h> 2 int main () 3  {4        int s,i; 5        s=0,i=1; 6 do        7        {8             s=s+i; 9             I++;10
   }while (i<=100);        return 0;12  }                            

3. For statement

Its grammatical form is as follows:

for (expression 1; expression 2; expression 3)

{Loop Body Statement}

Function: The value of expression 1 is evaluated first, then the value of expression 2 is detected, and if it is true, the loop body statement is executed, and after completion, Expression 3 is evaluated. Then, test whether the value of expression 2 is true, and if true, resumes execution of the loop body statement and, if False, terminates the loop.

The following is an example of 1+2+3+......+100 and illustrates the use of a For loop statement.

Example 3.3

1 #include <stdio.h> 2 int main () 3 {4       int i,s; 5       s=0; 6 for       (i=1;i<=100;i++) 7       {8             i++; 9
   
    }10       return 0;11}
   

From examples 3.1, 3.2 and 3.3, it can be seen that three circular statements can be converted to each other. But they also have their own focus, should be based on different needs, choose the appropriate statement.

    • The while statement and the for statement belong to the "type" loop, which is "first judged, then executed, and the Do-while statement belongs to the" until "loop, i.e." execute first, then judge ".
    • In practice, the For statement is more useful for the problem of clear cycle times, but it is not possible to determine the number of loops by using a while statement or Do-while statement.
    • There are several changes to the three expressions for the for statement, such as omitting some or all of the expressions, or even writing the loop body into expression 3, the loop body is an empty statement to satisfy the syntax requirements of the circular statement.

4. Loop nesting

The loop body statement of a looping structure can be any valid C statement. If the loop body of a loop structure contains another loop statement, it forms a loop nesting, called a multiple loop.

The following is an example of using a * output rectangle to illustrate the use of circular nesting.

Example 3.4

1 #include <stdio.h> 2 int main () 3 {4       int i,j; 5       int width,height; 6       printf ("Length and width of input rectangle: \ n"); 7       scanf ("%d%d", &width,&height); 8       for (i=1;i<=width;i++)          //i Control Rectangle length 9       {Ten for             (j=1;j<=height;j++)  //j control Rectangle width by             {12                  printf ("*");             printf ("\ n");                 Line * Output after newline       }16       return 0;17}

In the above procedure, four variables are applied first, i,j,width and height respectively. Both I and J are used as cyclic control variables to control the width and height of the rectangle respectively, and when the values of width and height are entered, the width of the rectangle is determined, and finally the rectangle is output with a for statement.

If width=5,height=2, the output is as follows:

*****

*****

Program structure in C language

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.