Hello, C ++ (23) 4.4.2 salary program growth Note: Use arrays to process batch data, and use a loop structure to execute repeated actions, an array of 4.4.2

Source: Internet
Author: User

Hello, C ++ (23) 4.4.2 salary program growth Note: Use arrays to process batch data, and use a loop structure to execute repeated actions, an array of 4.4.2
4.4 from statement to program

After learning about various expressions and statements, you can understand the words and sentences used to write the compositions. However, only words and sentences cannot constitute a meaningful article. To complete an article, you must first determine the structure of this article, whether it is first described and then summarized, or further discussed. After the structure is determined, words and sentences can be arranged to appropriate positions according to the structure requirements so that a meaningful article can be written. Writing a program is like writing an article. You also need to determine the process control structure of the program based on the transaction to be processed, then, we concatenate the scattered statements to describe a complete transaction processing process, and then organize multiple scattered statements into a complete program that can complete certain functions.

4.4.1 concatenate multiple statements into a program using three process control structures

Depending on the transaction process, C ++ mainly has the following three program process control structures:

1. Ordered Structure

The sequential structure is the simplest and most commonly used process control structure in C ++. When executing this structure, it executes program statements one by one in the order from top to bottom. The execution sequence does not change throughout the process. Therefore, it is usually used to organize statements that can complete tasks by step-by-step execution. For example, a simple addition computing process, from input to computing to output, can be completed by sequential execution, therefore, we use the sequential structure to separate the input (cin> a> B;) and calculation (int c = a + B ;) and the output Statement (cout <a <"+" <B <"=" <c <endl, it becomes a simple addition computing program:

// The addition calculation program int main () {cout <"Please enter two integers:" <endl; int a, B; cin> a> B; // enter int c = a + B; // calculate cout <a <"+" <B <"=" <c <endl; // return 0 ;}

During execution, from entering the main () function, first run the input statement (cin> a> B;) to obtain the two values a and B entered by the user, then execute the calculation Statement (int c = a + B;) sequentially to obtain the calculation result and save it to the variable c, next, run the output Statement (cout <a <"+" <B <"=" <c <endl;) to output the calculation result. In this way, you can complete the tasks by executing the statements in sequence.

2. Select Structure

The real world is complex, and many problems cannot be solved simply by sequential steps. For example, if you want to calculate the sum of two numbers, the sum of the input numbers must be greater than 0, that is, only two numbers greater than 0 can calculate their sum. In this case, you must first determine whether the input number is greater than 0. If the condition is met, the sum of the two numbers is calculated. If the condition is not met, the system prompts that the number entered by the user does not meet the condition and cannot be calculated. To express the process of having different processing methods based on different conditions, C ++ provides a selection structure. The selection structure is implemented by conditional statements such as if. It can be determined based on different conditions, and different execution paths can be selected to implement different processing processes. For example:

// Use the addition calculation program int a, B; cin> a> B; // select the structure based on different conditions, the execution path is also different if (a> 0 & B> 0) {// if the data entered by the user meets the conditions, // calculates the result and outputs int c = a + B. cout <a <"+" <B <"=" <c <endl ;} else {// if the data entered by the user does not meet the conditions, // The system prompts the user to enter an incorrect cout <". Please enter two numbers greater than 0. "<Endl ;}

Using the selection structure, we organize the statements that meet the conditions to the if branch, and organize the statements that do not meet the conditions to the else branch, in this way, the program will execute different code based on whether the conditions are met, and realize the expression of "having different processing methods according to different conditions.

3. Loop Structure

Let's look at another more complex scenario: We need to input 100 numbers and then calculate their sum. If we use the sequence structure described above, we need to define 100 variables, use 100 input statements to receive data, and add 100 addition statements to the sum. Such a complicated computing process is obviously unacceptable. What method can be used to simplify this computing process?

People have found that this type of computing process has a rule that multiple inputs are similar to the Code for addition and calculation. The inputs are obtained from the cin input data to a variable, the addition and calculation also accumulate the input data to a variable that represents the sum. Because of this, you can use the same code to complete the second input and addition calculation after completing an input and addition calculation. In this way, the entire computing process is a process of Repeated input and Addition and calculation. To express this type of computing process, C ++ provides a cyclic structure. The loop structure is implemented by loop statements such as for. We use the statements that need to be repeatedly executed multiple times as the loop body statement, so that we can get repeated executions in the loop process, to express the computing processes that need to be executed repeatedly for the same action. Here, the statements responsible for inputting (cin> n;) and adding and calculating (nTotal + = n;) need to be executed multiple times, so we use it as the loop body statement of the for loop, and then determine the starting and ending points of the loop in the for loop, so as to concatenate a program that can input and calculate the sum of the 100 numbers:

// The continuous addition computing program implemented by the cyclic structure // The variable int nTotal representing the sum = 0; // for the cyclic structure for (int I = 0; I <100; ++ I) {int n = 0; cin> n; // input statement nTotal + = n; // Add and calculate the statement} // output result cout <"the sum of the 100 numbers you input is:" <nTotal <endl;

When executing a for loop, the input statements and Addition and calculation statements in the loop body are executed 100 times in a row, saving the hassle of using the sequence structure, A good expression of the computing process of "An action needs to be executed multiple times.

Sequence Structure, selection structure, and cyclic structure are the three most basic program control structures. These three structures can be used separately. More often, we use multiple control structures to express more complex computing processes. For example, in the preceding example, if we only want to calculate the sum of all input positive numbers, we can embed a selection structure in the loop structure, the cyclic structure is used to organize the actions that need to be executed multiple times. During each cyclic execution, the data is filtered by the selected structure first, and only the qualified number is used for addition and calculation. The nested loop structure and selection structure can express this more complex computing process:

// Use the loop structure and nested selection structure // use the loop structure to execute repeated actions for (int I = 0; I <100; ++ I) {int n = 0; cin> n; // select the structure, filter the data, and calculate the Qualified Data if (n> 0) {nTotal + = n ;}}

By combining these three control structures, you can describe almost any complicated program execution process. In other words, no matter what program execution process, it is almost a combination of these three structures or these three structures. It is these three control structures that organize scattered statements that implement simple operations and express certain computing processes that ultimately form a program that implements certain functions.

4.4.2 wage program growth Note: Processes batch data using arrays and performs repeated actions in a cyclic structure

I just read Hello, C ++! In the previous chapters, our "programmer" Xiao Chen felt that his C ++ had a good grasp. Soon, he hired a software company as a programmer.

On the first day of work, the boss assigned him a "big" task:

"Xiao Chen, today is the first day of your work, but the company now has a big task to complete. You know, our company is also a large company with nearly 100000 employees. Now we need a program to make statistics and query on employees' salaries. Statistics are the minimum wage, maximum wage, and average wage of all employees. You can query the employee's serial number to obtain the employee's salary. Your C ++ level is so high that it should be okay to complete such a wage process ?"

"No, no, no problem at all ."

Chen Yue is more and more surprised. So far, although I have read "Hello, C ++!" for a few days, However, he has never written such a complex C ++ program. He has no idea, so he has to promise it first and then go back to the book to find a solution. Wait until Chen sends "Hello, C ++!" After reading it carefully again, he was pleasantly surprised to find that the knowledge required to complete the Wage Program has been discussed in the book: to manage multiple batch data of the same nature (nearly 100000 wage data), you can use an array. To repeat an action multiple times (enter and query wage data ), you can use the cyclic structure to organize statements. You need to execute different actions based on different conditions (if you enter a special value-1, the salary query ends; if the input number exceeds the serial number range, prompt the user to re-enter the serial number. If the Input Serial number is within the serial number range and the employee's salary of the corresponding serial number is output), you can use the selected structure to implement different program execution paths. After a simple analysis, Xiao Chen found that the program is in a sequential structure: First input data and then query the data. Each step is a circular structure: the for loop is used to input data multiple times and the while loop is used to query data multiple times. Meanwhile, in the loop structure, the nested selection structure is used to execute different actions based on the user input. According to this analysis, Xiao Chen quickly had the following salary program:

// Payroll V1.0 # include <iostream> # include <climits> // to use the largest integer macro INT_MAX, INT_MINusing namespace std; int main () {// defines the maximum number of data elements in the array, // indicates that this program can process a maximum of 100000 wage data const int MAX = 100000; // defines the array and initializes it, this array can contain 100000 int-type wage data int arrSalary [MAX] = {0 }; // defines the variables that record the total wage value, minimum value, and maximum value. // because min and max are used to record the minimum and maximum values, // Therefore, we initialize the maximum and minimum values of int type data to int nTotal = 0; int min = INT_MAX; int max = INT_MIN; // The number of valid wage data input, calculate the average salary and query the salary Int nCount = 0; // use the for loop structure to repeat the input action to complete the input of multiple wage data for (int I = 0; I <MAX; ++ I) {// prompt the user to enter cout <"enter" <I <"employee's salary (-1 indicates that the input is complete):" <endl; // Save the input data to the I-th data element of the arrSalary array cin> arrSalary [I]; // use the condition structure, check whether a special value (if (-1 = arrSalary [I]) indicating the end is input {// The end is input, and the output result is cout <"the wage input ends, A total of <nCount <"salary data are entered. "<Endl; // if the number of input data is not 0, the output statistical information if (0! = NCount) {cout <"where," <endl; cout <"maximum value is" <max <endl; cout <"minimum value is" <min <endl; // calculates the average wage float fAver = (float) nTotal/nCount; cout <"average salary is" <fAver <endl;} // enter the end and use the break keyword to end the entire input loop break;} // If the input is normal, then perform regular processing + + nCount; // The number of wage data plus 1 // the total accumulated wage nTotal + = arrSalary [I]; // update the maximum and minimum values of the salary if (arrSalary [I] <min) // if the new value is smaller than the known minimum value min = arrSalary [I]; // replace the old minimum value if (arrSalary [I]> max) with the new input value // ma for maximum value similarity Processing X = arrSalary [I];} // The input process ends and the query process starts. // if the number of data entries is 0, no data is input, if (0 = nCount) {cout <"no wage data is returned when no query is performed. Thank you! "<Endl; return 0; // directly terminate the program} // has the wage data, constructs an infinite loop for wage query, and exits the loop according to the condition in the loop while (true) {// enter employee No. int n = 0; // Prompt User enter cout <"Enter employee No. to query (0-" <nCount-1 <", -1 indicates the end of the query.): "<endl; // obtain the employee ID and save it to n cin> n; // check user input if (-1 = n) // whether a special value indicating end is input {// query ends, use the break keyword to end the entire query cycle cout <". Thank you for using it! "<Endl; break;} else if (n <0 | n> = nCount) // whether the serial number range exceeded {// Prompt user input error cout <"Input Serial Number" <n <"beyond the serial number range 0-" <nCount-1 <", enter again. "<Endl; // The input sequence number is out of the range. Use continue to end the loop and start the next loop.} // The input is valid, output the employee salary cout queried by the user <"Employee serial number:" <n <endl; // enter the employee serial number as the array subscript, get the wage data cout <"Employee Salary:" <arrSalary [n] <endl ;}return 0 ;}

After a few simple trials, Chen was satisfied with the salary program. So he quickly handed over the program to the boss. The boss tried to find that this wage program can not only process enough wage data, but also collect statistics and query wage data. At the same time, there are also good user operation tips, it can be used by even three-year-olds. The boss was very happy and said with a smile to Xiao Chen: "It's a good job. Next month, I will raise my salary. Haha ...... "When I heard this sentence, Xiao Chen spent some time in his heart and thought," Hello, C ++! ", The problem can be solved so smoothly. It seems that this is really a studious and useful C ++ reference book. After you get back from work, you must continue reading ......

Related Article

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.