4.4 From statement to program
After understanding the various expressions and statements, it is equivalent to mastering the words and sentences to be used in writing, but only words and sentences can not constitute a meaningful article. To complete an article, the first need to determine the structure of this article is the first Division of the general, or progressive discussion. Set the structure and then according to the requirements of the structure of the words and sentences to the appropriate position, so as to write a meaningful sentence fluent article. Writing a program is like writing an article, and it is also necessary to determine the program's process control structure based on the transaction that needs to be processed, and then concatenate the fragmented statements together to describe a complete process of processing the transaction, thus organizing multiple fragmented statements into a complete program that can accomplish certain functions.
4.4.1 uses three process control structures to concatenate multiple statements into a program
According to the process of processing transactions, C + + has the following three kinds of program flow control structure:
1. Sequential structure
Sequential structure is the simplest and most commonly used process control structure in C + +. When this structure is executed, it executes the program's statements sequentially, from the top down. The order of execution does not change throughout the process. Therefore, it is often used to organize statements that simply need to be executed in a step-by-step sequence to complete the task. For example, a simple addition calculation process, from input to calculation to output, can only be done sequentially, so we use the sequential structure to take those responsible for input (cin>>a>>b;), calculation (int c = a + B;) and output (cout The statement of <<a<< "+" <<b<< "=" <<c<<endl;) is organized into a simple addition calculation program:
//An addition calculation program for sequential structure organizationintMain () {cout<<"Please enter a total of two integers:"<<Endl; intb; CIN>>a>>b;//input intc = a + B;//Calculationcout<<a<<" + "<<b<<" = "<<c<<endl;//Output return 0;}
At the time of execution, from entering the main () function, first execute the input statement (cin>>a>>b;), obtain the user input of two values A and B, and then execute the calculation statement (int c = a + B;), get the result of the calculation and save to the variable C, The output statement (cout<<a<< "+" <<b<< "=" <<c<<endl;) is then executed, and the resulting output is computed. In this way, each statement that is organized with a sequential structure requires only a sequential execution to complete the task.
2. Select structure
The real world is complex, and many problems are not solved by sequential steps alone. Or the above two number of the sum of the program as an example, if the required number of inputs must be greater than 0, that is, only more than 0 of the two number to calculate their sum. At this point it is necessary to determine whether the number of inputs is greater than 0, if the conditions are met, calculate the number of two and if not satisfied, the user is prompted to enter the number does not meet the conditions, can not be calculated. To express this process, which has different processing methods depending on the conditions, C + + provides a choice structure. The choice structure relies on the IF and other conditional statements, it can make judgments according to different conditions, choose different execution paths, and realize different processing processes. For example:
//An addition calculation program implemented by a selection structureinta,b;cin>>a>>b;//Select Structure, depending on the conditions, the path of execution is differentif(A >0&& B >0 ){ //If the user enters data that satisfies the criteria,//The result is calculated and output intc = A +b; cout<<a<<" + "<<b<<" = "<<c<<Endl;}Else{ //If the user enters data that does not meet the criteria,//the user is prompted to enter an errorcout<<"Please enter two numbers greater than 0. "<<Endl;}
Using the selection structure, we will organize the statements that meet the conditions to the If branch, organize the statements that do not satisfy the condition into the Else branch, so that when the program executes, it executes different code depending on whether the condition is met or not, and implements the "different processing methods according to different conditions" The expression.
3. Cyclic structure
Let's look at another more complex scenario: the sum of the 100 numbers that are required to be counted. If you use the sequential structure described earlier, you would define 100 variables, use 100 input statements to receive the data, and also require 100 plus and a statement to add them to the sum. This tedious calculation process is obviously unacceptable, so what can be done to simplify the calculation process?
It is found that this kind of calculation process has a rule: The calculation process of multiple input and add and calculate the code is similar, the input is to get input data from CIN to a variable, and the addition and calculation is to add the input data to a variable representing the sum. Because of this, the same code can be used to complete the second input and addition and calculation once the input and addition and calculation are completed. In this way, the entire calculation process is a process of inputting and adding and calculating repeated cycles. To express this type of computational process, C + + provides a looping structure. The loop structure relies on the for-loop statements to be implemented, and we use the statements that need to be repeated multiple times as loop body statements, which can be repeated multiple times during the loop to express the computational process that the same action needs to be executed repeatedly. Here, the statement that is responsible for the input (cin>>n;) and the addition and calculation (ntotal + = n;) is repeated several times, so we use it as the loop body statement for the For loop, and then we determine the start and end of the loop in the For loop, This is concatenated into a program that can enter and calculate a sum of 100 numbers:
//a program for continuous addition calculation using cyclic structure//A variable that represents a sumintNtotal =0;//loop structure for the For loop implementation for(inti =0; I < -; ++i) { intn =0; CIN>>n;//Input StatementNtotal + = n;//Add and Calculate statements}//Output Resultscout<<"The sum of the 100 numbers you have entered is:"<<nTotal<<endl;
In the case of a for loop, the input statements and the addition and calculation statements in the loop body are executed 100 times in a row, thus eliminating the tedious use of sequential structures and expressing the computational process that "an action needs to be executed repeatedly".
Sequential structure, selection structure and cyclic structure are the three most basic program control structures. These three structures can not only be used alone, but more often, we use a combination of various control structures to express those more complex computational processes. For example, in the example above, if we just want to calculate the sum of all the positive numbers of the input, we can embed a selection structure in the loop structure, organize the actions that need to be executed repeatedly, and each time the loop executes, the data is filtered by the selection structure. Only the qualifying number is added and calculated. The structure of loops and the nesting of selection structures can express this more complex computational process:
// looping structure and selection structure nesting use // looping structure, performing repetitive actions for (int i = 0 ; I < 100 ; ++i) { int n = 0 >>N; // Select the structure, filter the data, and calculate the data that matches the criteria if (n > 0 ) {Ntotal +=
n; }}
With the combination of these three control structures, it is possible to describe almost any complex program execution process. In other words, no matter what the program execution process is, none of these three structures or the combination of these three structures. And it is these three kinds of control structure will be scattered to implement simple operation of the sentence to organize, express a certain computational process, finally formed a certain function of the program.
The growth of 4.4.2 wage program: Using Arrays to process batch data and repeating actions with loop structures
I just saw "Hello, c++!." In the first few chapters, our "programmer" Xiao Chen felt that his C + + had mastered very well. Soon, he applied to a software company as a programmer.
On the first day of work, the boss assigned him a "big" task:
"Xiao Chen, although today is your first day of work, but the company now has a big task need you to complete." You know, our company is also a large company with nearly 100,000 employees. A program is now required to make statistics and inquiries about employee salaries. Statistics are the need to know the minimum wage, maximum wage and average wage for all employees. Query is the need can be based on the employee's ordinal query to get the employee's salary. Your C + + level so high, to complete such a payroll program should be no problem? ”
"No, no, not a bit of a problem." ”
Chen Yue more and more to hear, so far, although seen a few days, Hello, c++! , but he has never written such a complex C + + program, the heart is really not the end, had to promise to come down, and then go back to Reading to find a way. Until Xiao Chen will be "Hello, c++! Once again, he was pleasantly surprised to find that the knowledge needed to complete the payroll process had been discussed earlier in the book: to manage multiple batches of the same nature (nearly 100,000 payroll data), you could use an array; To repeat an action multiple times (input and query payroll data), You can use a looping structure to organize your statements, and to perform different actions according to different conditions (if you enter a special value of 1, this means that the payroll query ends; If you enter a sequence number beyond the ordinal range, the user is prompted to re-enter; If the serial number is within the ordinal range, the employee's wages are output) You can use the selection structure to implement different program execution paths. After simple analysis, Xiao Chen found that the program is a sequential structure in general: first input data, and then query the data, and each step is a loop structure: the use of the For loop multiple input data, the while loop multiple query data, while in the loop structure, and nested selection structure, Different actions are performed depending on the user input. According to the results of this analysis, Xiao Chen soon has the following payroll procedures:
//Payroll Procedure V1.0#include <iostream>#include<climits>//in order to use the integer maximum value macro int_max,int_minusing namespacestd;intMain () {//defines the maximum number of data elements for an array,//indicates that the program can handle up to 100,000 payroll data Const intMAX =100000; //defines an array and initializes it, which can contain 100,000 int type payroll data intArrsalary[max] = {0}; //define variables that record the gross, minimum, and maximum values of a payroll//because Min and Max are used to record minimum and maximum values,//so we initialize it to the maximum and minimum values of the int type data, respectively. intNtotal =0; intMin =Int_max; intMax =int_min; //the number of valid payroll data entered, the average wage calculated and the salary to be queried intNcount =0; //use the For loop structure to perform input actions repeatedly to complete input of multiple payroll data for(inti =0; i < MAX; ++i) {//Prompt for user inputcout<<"Please enter"<<i<<"Employee's salary (-1 means end of input):"<<Endl; //saves the input data to the first data element of the arrsalary arrayCin>>Arrsalary[i]; //use conditional structure to check if a special value is entered that represents the end if(-1==Arrsalary[i]) { //input end, output statistical resultscout<<"Payroll input ended, entered"<<nCount<<"payroll data. "<<Endl; //if the number of data entered is not 0, the output statistic if(0!=ncount) {cout<<"among them,"<<Endl; cout<<"The maximum value is"<<max<<Endl; cout<<"the minimum value is"<<min<<Endl; //Calculate average Salary floatFaver = (float) ntotal/ncount; cout<<"Average salary is"<<fAver<<Endl; } //End of input, ending the entire input loop with the break keyword Break; } //if it is normal input, general processing++ncount;//number of payroll data plus 1//Cumulative PayrollNtotal + =Arrsalary[i]; //update the maximum and minimum values for wages if(Arrsalary[i] < min)//if the newly entered value is smaller than the known min minmin = Arrsalary[i];//replace the old minimum value with the newly entered value if(Arrsalary[i] > Max)//Maximum similarity processingMax =Arrsalary[i]; } //end of input process, start query process//if the number of data is 0, indicating no input data, no longer query and end directly if(0==ncount) {cout<<"There is no payroll data and cannot be queried. Thanks for using! "<<Endl; return 0;//Direct End Program } //have payroll data, construct an infinite loop for payroll queries, and exit loops based on conditions in the loop while(true) { //number of employee entered intn =0; //Prompt for user inputcout<<"Please enter the number of employees to query (0-"<<ncount-1<<",-1 means end query):"<<Endl; //get the employee number entered by the user and save to nCin>>N; //Check for user input if(-1= = N)//whether to enter a special value that indicates the end { //End of query, end the entire query loop with the break keywordcout<<"Query finished, thanks for using! "<<Endl; Break; } Else if(N <0|| n >= ncount)//If the ordinal range is exceeded { //Prompt for user input errorcout<<"Enter the ordinal number"<<n<<"out of ordinal range 0-"<<ncount-1<<", please re-enter. "<<Endl; //Enter the sequence number out of range, end the cycle with continue, start the next cycle Continue; } //Enter a legal, output user-queried employee's salarycout<<"Employee Number:"<<n<<Endl; //Here we use the input employee number as an array subscript to get the payroll data in the corresponding position directly .cout<<"Employee Salary:"<<arrSalary[n]<<Endl; } return 0;}
After a few simple trials, Xiao Chen was satisfied with the salary process. So he hurried to take the program to the boss. The boss tried to find out that the Payroll program not only can handle enough payroll data, statistics and inquiries about payroll data, but also a very good user operation tips, even three-year-old children will use. The boss is very happy, grinning to small Chen: "Well done, next month, raise wages, ah ha haha ... "Hearing this, Xiao Chen in the heart of the flowers, the heart thought," Xin lost Hand has a "Hello, c++! ", the problem can be solved so smoothly. It seems that this is a studious and easy to use C + + reference book, go back after work must continue to look down ...
Hello, C + + (23) 4.4.2 Salary Program growth note: Use arrays to process batch data and perform repetitive actions with loop structures