Decision Making: making programs intelligent Have you heard of computers that beat chess champions or mimic experts? The decision making statement responsible for making a program an intelligent entity is known as the "if" statement. However, not using the proper decision-making can cause a program to fail or possibly become dumb. This is known as a computer error. An example of a program error is to print or display a paycheck for an employee who worked regular hours with a negative amount of money. MAKING THE DECISION If given an employee's salary, how would you determine the tax rate? If given the number of hours an employee worked, how would you determine the overtime hours? If you were asked whether you want to continue, or to stop what you were doing, what would you answer? If you were asked to enter your password and you typed either the right or the wrong password, what would you expect to happen? If given a menu with a list of items, how would you make a selection? These are a few examples of decision-making. They are used in a similar fashion in programming. HOW DO YOU MAKE A DECISION IN C/C++? In C/C++, decision making is done by using an if or a switch statement. The if statement uses the form shown in Figure 4.1. if( expression ){ //Body of if ( Runs only when the if expression is true ) }//IF else { // Body of else ( Runs only when the if expression is false ) }//ELSEFigure 4.1 - The if / else structure of C/C++. The expression after the if must evaluate to either true or false. If the expression evaluates to true, the "body of the if", which is the statement next to parentheses, will be executed. If the expression evaluates to false, the "body of the else" will be executed. If the body of if or the body of else contain more than one statement, then braces { } should be used. It is good practice to always use braces. LOOK AT THE FOLLOWING IF STATEMENTS IN C/C++ if( grosspay > 1000 ) taxrate = 0.20; else taxrate = 0.10;Figure 4.2a -Assign taxrate the value of 0.20 if grosspay is greater than 1000 otherwise assign taxrate the value of 0.10. if( hoursworked > 40) overtimehours = hoursworked-40; else overtimehours=0.0;Figure 4.2b - Assign overtimehours the value of hoursworked - 40 if hoursworked is greater than 40 otherwise assign the value of 0.0 to overtime hours. if( candidateInitial == ‘H’ ) hc=hc+1; else oc=oc+1;Figure 4.2c - If value of candidateInitial is equal to H then increment the counter named hc by the value of one (1) and assign the value back to hc. If the value of candidateInitial is anything other than H, then add one to the value of the counter named oc and assign the value back to oc. WHAT DOES THE EXPRESSION "IF" CONSIST OF ? The expression if, compares two values using the comparison operators of Table 4.1 listed below.
The result of the expression can be either true or false. In C/C++, anything besides zero is considered to be true. Therefore, the number zero is false and any other number is true. The expression if can be made more complex when making several evaluations or even an assignment statement. GENERAL SYNTAX OF AN IF STATEMENT The if statement syntax is illustrated by Figure 4.3a and 4.3b.
COMPARISON OF TWO NUMBERS: FIND THE MINIMUM In the example below, two numbers are compared to each other to determine whether the first number is less than the second number. If the answer is true the first statement will be executed; otherwise, the statement after the else will be executed. if( firstnumber < secondnumber ) cout<< " THE FIRST NUMBER IS THE MINIMUM."; else cout<< " THE SECOND NUMBER IS THE MINIMUM.";Figure 4.4 - if statement conditional checking for the minimum. What happens if the two numbers are equal? In the above statement the else part will be executed because the RESULT OF THE STATEMENT firstnumber < secondnumber is not true. Therefore, the statement THE SECOND NUMBER IS THE MINIMUM will be displayed. To avoid displaying the second number is the minimum, it is possible to use an assignment to set the minimum value and then display the minimum value at the end. In this case, both are evaluated as the minimum. if ( firstnumber < secondnumber ) minimum = firstnumber; else minimum = secondnumber;Figure 4.5 - Making the first and the second number the minimum. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int firstnumber, secondnumber, minimum; 5. cout << "ENTER TWO NUMBERS: "; 6. cin >> firstnumber >> secondnumber; 7. if( firstnumber < secondnumber ) 8. minimum = firstnumber; 9. else 10. minimum = secondnumber; 11. cout << "THE MINIMUM IS " << minimum << endl; 12. return 0;Figure 4.6a - Program that discovers the minimum value of two integer variables. ENTER TWO NUMBERS: 12 20 THE MINIMUM IS 12 ENTER TWO NUMBERS: 106 211 THE MINIMUM IS 106 ENTER TWO NUMBERS: 501 312 THE MINIMUM IS 312Figure 4.6b -Sample output of Figure 4.6a for example variables. FIND THE MINIMUM OF TWO NUMBERS: CASE WHERE BOTH ARE EQUAL When finding the minimum of two numbers and the numbers are equal; we do not want to display either as the minimum. Therefore, we need to include an additional if statement to the program of figure 4.6a to evaluate it if the numbers are equal, as illustrated in figure 4.7a. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int firstnumber, secondnumber, minimum; 5. cout << "ENTER TWO NUMBERS: "; 6. cin >> firstnumber >> secondnumber; 7. if( firstnumber < secondnumber ) 8. minimum = firstnumber; 9. else 10. minimum = secondnumber; 11. if ( firstnumber = = secondnumber ) 12. cout << "BOTH NUMBERS ARE EQUAL." << endl; 13. else 14. cout << " THE MINIMUM IS "<< minimum << endl; 15. return 0; 16. }//MAINFigure 4.7a - Program that finds the minimum of two variables and evaluates the possibility that the first and the second number are equal. ENTER TWO NUMBERS: 51 22 THE MINIMUM IS 22 ENTER TWO NUMBERS: 23 45 THE MINIMUM IS 23 ENTER TWO NUMBERS: 33 33 BOTH NUMBERS ARE EQUAL.Figure 4.7b - Output of Figure 4.7a for sample data input variables. IF WITH A COMPOUND STATEMENT An if statement may contain more than one statement whether its condition is true or false. Braces that make up the compound statement surround each group of statements; however, braces aren’t necessary when only one statement is placed after the condition of if or else. if( expression ){ statement 1; statement 2; //etc. }//IF else { statement3; statement4; //etc. }//ELSEFigure 4.8 - if statement syntax when more than one statement is used for an if / else block. FIND THE MINIMUM AND MAXIMUM OF TWO NUMBERS: USE OF A COMPOUND STATEMENT In the example shown in figure 4.9a, the body of if and else contain more than one statement, this represents a compound statement. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int firstnumber, secondnumber, min, max; 5. cout << "ENTER TWO NUMBERS: "; 6. cin >> firstnumber >> secondnumber; 7. if( firstnumber < secondnumber ){ 8. min = firstnumber; 9. max = secondnumber; }//IF 10. else { 11. min = secondnumber; 12. max = firstnumber; }//ELSE 13. if ( firstnumber == secondnumber ) 14. cout << "BOTH ARE EQUAL." << endl; 15. else { 16. cout << "MIN IS " << min << endl; 17. cout << "MAX IS " << max << endl; }//ELSE 18. return 0; 19. }//MAINFigure 4.9a - Program containing compound statements within an if / else construction. ENTER TWO NUMBERS: 67 12 MIN IS 12 MAX IS 67 ENTER TWO NUMBERS: 28 103 MIN IS 28 MAX IS 103 ENTER TWO NUMBERS: 56 56 BOTH ARE EQUAL.Figure 4.9b -The output of Figure 4.9a for two sample variables. FIND MAXIMUM OF THREE NUMBERS: PLAYING IN TOURNAMENT 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int firstnumber, secondnumber, thirdnumber, max; 5. cout << "ENTER THREE NUMBERS: "; 6. cin >> firstnumber >> secondnumber >> thirdnumber; 7. if( firstnumber > secondnumber ) 8. max = firstnumber; 9. else 10. max = secondnumber; 11. if( thirdnumber > max) 12. max = thirdnumber; 13. else 14. max = max; 15. if( firstnumber == secondnumber ){ 16. max = firstnumber; 17. if( max == thirdnumber ) 18. cout << "ALL THREE NUMBERS ARE EQUAL." << endl; 19. else 20. if( thirdnumber > max ) max = thirdnumber; 21. }//IF 22. cout << "MAXIMUM IS " << max << endl; 23. return 0; 24. }//MAINFigure 4.10a - Program that finds the maximum of three numbers. ENTER THREE NUMBERS: 10 20 30 MAXIMUM IS 30 ENTER THREE NUMBERS: 20 15 62 MAXIMUM IS 62 ENTER THREE NUMBERS: 15 15 15 ALL THREE NUMBERS ARE EQUAL MAXIMUM IS 15Figure 4.10b - Output of Figure 4.10a, the maximum of three numbers. NESTED IF An if statement that contains other if statements as part of its body, this is called a "nested if". For example, there are situations where more than one test is needed for an action to be performed. An example of a nested if is illustrated in figure 4.11. For clarity, the below numbering convention below has been adopted. if ( expression 1 ) if( expression 2 ) statement 12; else if( expression 13 ) if ( expression 134 ) statement 134; else statement 135; else statement 16; else statement7; else statement 8;Figure 4.11 - Complex Nested if / else expressions. WHICH ELSE GOES WITH WHICH IF Every else must match with its if. When there are multiple ifs and else, every else corresponds with its nearest if. This may look uncertain, but the compiler’s rules have been set and ambiguities have been resolved. For clarity, we use indentations to match every else with its corresponding if. By default, one statement belongs to the body of an if and one statement belongs to the body of an else. If there is more than one statement, you must put the statements within braces. Also, for clarity, you may use braces for any of the above. PAYROLL PROGRAM: VARIABLE TAX RATE The payroll program of figure 4.12a, on the next page, computes an employee’s tax rate based on the amount of gross pay according to the following parameters:
When it comes to programming and problem solving, the word "algorithm" is frequently used. At first glance, most people associate the word algorithm with a mathematical term such as Logarithm. In programming, algorithm refers to the problem solving steps that are needed to find a solution to a problem, such as finding the shortest path from one city to another or computing employee wages. Where does the word algorithm come from? It came from the Persian scientist Alkharazmi who wrote a book around 825 A.D. called "Algebr and Moghabeleh" which translates to "Reduction and Calculation". 1. #include<iostream> 2. using namespace std; 3. main(){ 4. int hw, empid; 5. float hr, gp, np, taxrate, taxamt; 6. while( cin >> empid >> hw >> hr ){ 7. gp = hw * hr; 8. if( gp > 1000 ) taxrate = 0.30; 9. else if( gp > 800 ) taxrate = 0.20; 10. else if( gp > 500 ) taxrate = 0.10; 11. else taxrate = 0.0; 12. taxamt = gp * taxrate; 13. np = gp - taxamt; 14. cout << "EMPLOYEE ID IS " << empid << endl; 15. cout << "HOURS WORKED ARE " << hw << endl; 16. cout << "HOURLY RATE IS " << hr << endl; 17. cout << "GROSS PAY IS " << gp << endl; 18. cout << "TAX AMOUNT IS " << taxamt << endl; 19. cout << "NET PAY IS " << np << endl << endl; 20. }//WHILE 21. return 0; 22. }//MAINFigure 4.12a - Payroll program that includes multiple tax rates using the if /else structure highlighted in violet above. Also notice the green highlight indicating the while loop. The program above contains the three basic programming constructs: sequence, selection, and repetition. The data file used for the program can be found in Figure 4.12b. 1645 10 9.99 8932 40 20.00 7104 20 15.99 2816 15 50.00 5387 30 6.99Figure 4.12b - Input for the PayrollPprogram of Figure 4.12a. The name of the file is payroll.in. EMPLOYEE ID IS 1645 HOURS WORKED ARE 32 HOURLY RATE IS 31.5 GROSS PAY IS 1008 TAX AMOUNT IS 302.4 NET PAY IS 705.6 EMPLOYEE ID IS 8932 HOURS WORKED ARE 40 HOURLY RATE IS 40 GROSS PAY IS 1600 TAX AMOUNT IS 480 NET PAY IS 1120 EMPLOYEE ID IS 7104 HOURS WORKED ARE 20 HOURLY RATE IS 42.5 GROSS PAY IS 850 TAX AMOUNT IS 170 NET PAY IS 680 EMPLOYEE ID IS 2816 HOURS WORKED ARE 15 HOURLY RATE IS 50 GROSS PAY IS 750 TAX AMOUNT IS 75 NET PAY IS 675 EMPLOYEE ID IS 5387 HOURS WORKED ARE 30 HOURLY RATE IS 15.99 GROSS PAY IS 479.7 TAX AMOUNT IS 47.97 NET PAY IS 431.73Figure 4.12c - The output of the Payroll Program of Figure 4.12a. FIND THE MAXIMUM OF MANY NUMBERS: ALGORITHM EXPLANATION How would you find the maximum of several numbers? You already learned how to find the maximum of three numbers in different ways. One thing we want to avoid is using several variables, one for each number. In fact, we want to use only two variables: one variable to hold the incoming input and another variable to hold the current maximum value, which eventually will be the final maximum. We are going to use the tournament strategy to compare every incoming number with the variable holding the current maximum. If the current number is greater than current maximum then we will reassign the maximum to the current number. We will continue to loop until all the numbers are finished. When the loop is finished, the maximum has been determined and we will display the maximum value. There is one problem that needs to be addressed: what value should the maximum contain before starting the loop and reading the input number? One solution is to initialize the maximum to the lowest possible number so that the first incoming input becomes the maximum on the first round. The steps discussed above explain the Algorithm for finding the maximum number. PROGRAM TO FIND THE MAXIMUM OF SEVERAL NUMBERS Figure 4.13a, illustrates a program that finds the maximum of many numbers. Observe that the program for finding the maximum of three numbers and the program for finding the maximum of 1000 numbers or more does not differ much in the size of the program or even in the logic. 1. #include<iostream> 2. using namespace std; 3. main(){ 4. int number, max; 5. max = -9999; // the smallest number possible not in the data 6. while( cin >> number ){ 7. if( number > max ) 8. max = number; 9. }//WHILE 10. cout << "THE MAXIMUM IS " << max << endl; 11. return 0; 12. }//MAINFigure 4.13a - The Program will find the maximum of many numbers. Note: Pressing the Esc key provides the best results for the stopping the while loop. 12 35 62 3 € THE MAXIMUM IS 62Figure 4.13b - Sample output from the program of Figure 4.13a. Caution: You can initialize the maximum value to 0 to start, but be sure that your data does not contain negative numbers. A different approach (algorithm) would be to initialize the maximum value by the first input data, and then start the loop by reading the next input and its comparison with current maximum value. See Figure 4.14a to view this different approach. 1. #include <iostream> 2. using namespace std; 3 main(){ 4. int number, max; 5. cin >> number; 6. max = number; 7. while( cin >> number ){ 8. if( number > max ) max = number; 9. }//WHILE 10. cout << "THE MAXIMUM IS " << max << endl; 11. return 0; 12. }//MAINFigure 4.14a - A different approach to the program of Figure 4.13a that finds the maximum of many numbers. Note: Pressing the Esc key provides the best results for the stopping the while loop. 32 96 103 21 € THE MAXIMUM IS 103Figure 4.14b - Sample output from the program of Figure 4.14a. LOGICAL IF: "AND OR NOT" Table 4.2 illustrates the logical operators (AND, OR, NOT) that can be used in a program. Logical expressions, also known as Boolean expressions, result to either true or false.
LEAP YEAR: LOGICAL IF, Y2K Many people mistakenly consider every four years to be a leap year. However, this is not the case. A leap year is any year that is divisible by 4 and not divisible by 100, or any year that is divisible by 400. The confusion arises as every 100 is divisible by 4 and every 400 is divisible by 4 and 100. Figure 4.15a shows the if condition is needed to test for a leap year. 1. #include<iostream> 2. using namespace std; 3. main(){ 4. int year; 5. cout << "Enter a year: "; 6. cin >> year; 7. if( ( year % 4 == 0 ) && ( year % 100 != 0 ) || ( year % 400 == 0 ) ) 8. cout << "LEAP YEAR.\n"; 9. else 10. cout << "NOT LEAP YEAR.\n"; 11. return 0; 12. }//MAINFigure 4.15a - The if condition to check for a leap year. At first, the above "logical if" can be difficult to comprehend. However, over time it becomes easier and preferable in comparison to a simple "if else" statement as illustrated below. • • • if( year % 400 == 0 ) cout << "LEAP YEAR"; else if( year % 100 == 0 ) cout << "NOT LEAP YEAR"; else if (year % 4 ==0) cout << "LEAP YEAR "; else cout << "NOT LEAP YEAR "; •Figure 4.15b - Series of if statements to determine leap year What would be the output if you run the program from Figure 4.15a with the following data? 1900 1994 1998 1999 2000 2001 2100 The year 2000 is a leap year, and a special one because it belongs to a category that occurs every 400 years. In addition to the fact that the year 2000 is a leap year, the problem of the two-digit format of the year (66 versus 1966) must be tackled. Output for the above data is shown in figure 4.15c. Enter a year: 1900 NOT LEAP YEAR. Enter a year: 1994 NOT LEAP YEAR. Enter a year: 1998 NOT LEAP YEAR. Enter a year: 1999 NOT LEAP YEAR. Enter a year: 2000 LEAP YEAR. Enter a year: 2001 NOT LEAP YEAR. Enter a year: 2100 NOT LEAP YEAR.Figure 4.15c - Output to the leap year program of Figure 4.15a. FIND MINIMUM OF THREE NUMBERS: USING LOGICAL IF 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int number1, number2, number3, max; 5. cout << "Enter Three Different Numbers: "; 6. cin >> number1 >> number2 >> number3; 7. if( ( number1 > number2 ) && ( number1 > number3 ) ) 8. max = number1; 9. if( ( number2 > number1 ) && ( number2 > number3 ) ) 10. max = number2; 11. if( ( number3 > number1 ) && ( number3 > number2 ) ) 12. max = number3; 13. cout << "THE MAXIMUM IS " << max << endl; 14. return 0; 15. }//MAINFigure 4.16a - Finding the minimum of three numbers using the if construct only. The program of Figure 4.16a can be optimized with the use of an else. The result is the program of 4.16b. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int number1, number2, number3, max; 5. cout << "Enter Three Different Numbers: "; 6. cin >> number1 >> number2 >> number3; 7. if( ( number1 > number2 ) && ( number1 > number3 ) ) 8. max = number1; 9. else if( number2 > number3 ) 10. max = number2; 11. else 12. max = number3; 13. cout << "THE MAXIMUM IS "<< max << endl; 14. return 0; 15. }//MAINFigure 4.16b - Finding the minimum of three numbers using the if / else construct. In the program of Figure 4.16b, at the time the first "if statement" has failed and we are at the else, this implies that the number1 is not the maximum. Therefore, it can be excluded from further testing. Figure 4.16c shows sample input and output for the programs of 4.16a and 4.16b. Enter Three Different Numbers: 85 21 30 THE MAXIMUM IS 85 Enter Three Different Numbers: 45 95 30 THE MAXIMUM IS 95Figure 4.17c - The input and output of both Figure 4.16a and 4.16b. ERROR CHECKING: BULLET PROOF BUT NO SILVER BULLET What happens when you look at the output of the payroll program and you see the net pay is a negative amount? Obviously something is wrong. A resolution is used to place an if statement within the program code that displays an error message rather than the incorrect amount. The following line of code accomplishes this task. if( netpay < 0 ) cout << "NET PAY ERROR: ";There is also a possibility that errors occurred at an earlier stage within the program, such as a computation error of the tax rate. For example, the tax rate was mistakenly written as the following statement, which made the net pay negative. if ( grosspay > 1000 ) taxrate =30.0;The taxrate variable should be assigned a value of 0.30 not 30.00. Also, the error could have stemmed from an earlier stage of data entries. Therefore, a data entry check for data validity should be included. The following segment of code addresses this issue. • • • if( ( hoursworked < 0 ) || ( hourlyrate < 0 ) ) cout << "ERROR - Input again" << endl; else{ // rest of calculations… }//ELSEHow would you determine the correct range for input data that has been entered? It is not easy to test every single case of input data to make a program foolproof, especially when you write a general program without knowing your audience. A user may interact with a program in an unexpected manner. For example, instead of entering numbers, the user enters letters and the program crashes. There can be serious errors that may not be detected until the program is tested in the field and then needs to be debugged. One thing a programmer can do is to consider the lower and the upper bounds of each data element. For example, the upper bound for hours worked would be 168 hours per week (seven days) working non-stop for 24 hours. Obviously every business has its own regulation regarding the upper and lower bound settings. For example, working 5 days a week and 12 hours each of those days provides an upper bound 60 hours. AN EXPERIENCED PROGRAMMER MAKES MISTAKES TOO The program of Figure 4.18a intends to find the maximum and minimum of a series of numbers. However, there is a small bug that makes the program to do something unexpected. At first glance, even an experienced programmer may not notice the error. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int number, max, min; 5. max = -9999; //setting to a dummy value that replaces right away 6. min = 9999; 7. while( cin >> number ){ 8. if ( number > max ) 9. max = number; 10. else 11. min = number; 12. }//WHILE 13. cout << "MINIMUM IS " << min << endl; 14. cout << "MAXIMUM IS " << max << endl; 15. return 0; 16. }//MAINFigure 4.18a -Incorrect algorithm to check for minimum and maximum. What is the minimum for the following input: 3 7 5 4 6. The minimum for the above input data is 3. However, due to an incorrect if and else statement, only the max value will be reset and the value of min will be skipped over. As a result the output is incorrect. 3 7 5 4 6 € MINIMUM IS 6 MAXIMUM IS 7Figure 4.18b - The incorrect output of the program of Figure 4.18a, finding the minimum and maximum of input data. One solution to the above problem is to use two separate if statements, and eliminate the else to find the minimum and maximum. For example, lines 9 through 12 of figure 4.18a could be replaced with the following four lines of code: if( number > max ) max = number; if( number < min ) min = number;Adding the four new lines of code produces the correct output as seen in Figure 4.18c. 3 7 5 4 6 € MINIMUM IS 3 MAXIMUM IS 7Figure 4.18c - The correct output of the program of Figure 4.18a, finding the minimum and maximum output of input data. DO NOT SUBSTITUTE LOGICAL "AND" FOR LOGICAL "OR" Let us look at the following: a manager says to a programmer "We want to shut down the system when the temperature exceeds 212 degrees Fahrenheit and goes below 32 Fahrenheit." The programmer translates the above instruction into the following code segment: • • • if( ( temperature > 212 ) && ( temperature < 32 ) ) cout << "Ready to shut down, take the appropriate action here."; else cout << "Follow the normal operation here.";What is wrong with the above segment? The logical && requires both statements to be true, in order for the statements to perform (execute). The question that arises is how could the temperature GREATER THAN 212 and at the same time be LESS THAN 32? Obviously, the intention was to use the logical "OR" ( || ) as illustrated in figure 4.19a. 1. #include <iostream> 2. using namespace std; 3. int main(){ 4. int temperature; 5. cout << "Enter a temperature: "; 6. cin >> temperature; 7. if( ( temperature > 212 ) || ( temperature < 32 ) ) 8. cout << "Ready to shut down. Take the appropriate action here.\n"; 9. else 10. cout << "Follow the normal operation here.\n"; 11. return 0; 12. }//MAINFigure 4.19a - Using the correct logical operator to shut down a system. Enter a temperature: 225 Ready to shut down. Take the appropriate action here. Enter a temperature: 30 Ready to shut down. Take the appropriate action here. Enter a temperature: 100 Follow the normal operation here.Figure 4.19b - Sample input and output for the program of Figure 4.19a. ANALYSIS OF AN ALGORITHM: SPEED, SPACE, AND COMPLICATION There may be more than one algorithm (approach) to solve a problem. In choosing an algorithm to solve a problem and writing the program, the criteria of speed and space have always been a concern. Another concern and important measurement is whether the program is easy to write and understand. There are situations when time is crucial and the speed of the program is very important. Also there are situations where due to the lack of available memory there is a space shortage. Obviously, programs should be user-friendly, as well as easy to write and maintain. While it may not be possible to satisfy all of the above criteria, programmers should attempt to make the program as efficient as possible. PROGRAM SPEED: WHY IS IT IMPORTANT? Can you imagine waiting for your credit card to clear, or withdrawing money from the bank? Likewise, waiting for your travel agent to find a seat on an immediate flight. How long can you wait? To determine a weather forecast, thousands of computations are required because several parameters, such as wind speed and moisture need to be considered. The above are real time applications that are examples of functions of time, and each has a deadline. A programmer must choose an algorithm that fits, runs faster, and avoids unnecessary code. SAVING MEMORY: WHY IS IT IMPORTANT? In the early days of computing, a gigantic mainframe computer had less memory capacity than today’s personal computer. As a result of the memory limitations, a large program could not be executed all at once. A programmer had to use extra effort to solve the problem with less memory usage. As memory locations are accessed back and forth the processing time is hindered. The designs of block structured programming languages were intended to conserve memory. Even though today’s computers have enormous memory space and virtual memory, adequate use of memory is still crucial because programs are becoming proportionally larger and larger. SAVING MEMORY YIELDS TO SPEED AND EFFICIENCY The proper use of memory in a program can lead to a faster and more efficient program. For example, in C/C++ an integer value can utilize a data type that uses less memory. Several data types are provided, and each holds a different range of integer values. Table 4.3 shows the different types of integer values.
A programmer can take advantage of the above variations and select the proper type. The proper selection of a data type results in saving memory, better error checking (out of range), and speeds up operations. Moreover, one bit of the above data type holds the sign (sign bit) as to whether the number is negative (1) or positive (0). Therefore, when the data is negative it is referred to as an unsigned integer. The number of bytes for the various integer data types is machine or compiler dependent. sizeof() OPERATOR : BYTE DETERMINATION You can use the sizeof( ) operator to determine the number of bytes assigned for each different data type by the compiler. The following line of code will return the number of bytes the data type uses. cout << sizeof( long ) << endl;The output may display either 4 or 8, depending on the computer or the compiler. Y2K PROBLEM: SAVINGS PROBLEM In the early days of computing data was punched in eighty column cards, and read into a computer with a small memory and with slower processing time. Therefore, saving time and memory was a crucial issue and any possibility was taken into consideration. This trend continued from generation to generation, creating a new problem with each generation. The major problem of the year 2000 compliance is attributed to saving memory. For example, a year was entered as two digits (55) instead of four digits (1955). Ironically, the memory saving of the past has become today’s problems. GROSSPAY WITH OVERTIME: IF ELSE WITH COMPOUND STATEMENT 1. #include <iostream> 2. using namespace std; 3. int main(){ 4. int empid, hoursworked, overtimehours; 5. float hourlyrate, regularpay, overtimepay, grosspay; 6. 7. while( cin >> empid >> hoursworked >> hourlyrate ){ 8. if ( hoursworked > 40 ){ 9. overtimehours = hoursworked - 40; 10. overtimepay = overtimehours * hourlyrate * 1.5; 11. regularpay = 40 * hourlyrate; 12. }//IF 13. else{ 14. overtimehours = 0; 15. overtimepay = 0; 16. regularpay = hoursworked * hourlyrate; 17. }//ELSE 18. 19. grosspay = regularpay + overtimepay; 20. cout << "EMPLOYEE ID " << empid << endl; 21. cout << "GROSS PAY IS " << grosspay << endl << endl; 22. }//WHILE 23. return 0; 24. }//MAINFigure 4.20a - The Payroll Program with compounded if / else statements. Figure 4.20a - The Payroll Program with compounded if / else statements.
switch STATEMENT An alternative to the if statement is the switch statement. When there are multiple if statements, one after the other, the switch statement makes the program more legible and neater. switch STATEMENT SYNTAX The switch statement uses the following general syntax where the expression is evaluated to a value. This value (integer or character) is matched against the appropriate case and the required actions will be taken upon succession. At the end the default will be executed when there is no matching case for the value. The switch statement is not the same as the "nested if and else". To achieve the same effect of if with else, you need to use the break keyword after the completion of each case. Figure 4.21 shows the syntax of the switch statement. switch( expression ){ case intvalue 1: statement(s); break; case intvalue 2: statement(s); break; • • • case intvalue n: statements(s); break; default: statement(s); }//SWITCHFigure 4.21 - Syntax of the switch statement. switch STATEMENT EXAMPLE: MENU 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int choice; 5. cout << " CHOOSE ONE FROM THE FOLLOWING MENU" << endl; 6. cout << " 1. Deposit \n 2. Withdraw \n 3. Balance \n "; 7. cout << " 4. Transfer \n Any Number for Help \n"; 8. cin >> choice; 9. switch( choice ){ 10. case 1: 11. cout << " DEPOSIT UNDER CONSTRUCTION. " << endl; 12. break; 13. case 2: 14. cout << " WITHDRAW UNDER CONSTRUCTION." << endl; 15. break; 16. case 3: 17. cout << " FIND BALANCE UNDER CONSTRUCTION." << endl; 18. break; 19. case 4: 20. cout << " TRANSFER UNDER CONSTRUCTION." << endl; 21. break; 22. default: 23. cout << " HELP ON THE WAY." << endl; 24. }//SWITCH 25. return 0;Figure 4.22a - Menu Program using the switch statement rather than the if / else construct. CHOOSE ONE FROM THE FOLLOWING MENU 1. Deposit 2. Withdraw 3. Balance 4. Transfer Any Number for Help 2 WITHDRAW UNDER CONSTRUCTION.Figure 4.22b - Output of the Menu Program of Figure 4.22a. EXCEPTION HANDLING: DIVIDE BY ZERO Consider the following statement: average = sum / n;What would the average be when the value of n is zero? Division by zero is not allowed; therefore, a test should be done in advance to disallow the division by zero. The code snippet of figure 4.23 displays an error message when n is equal to zero. • • • if( n == 0 ) cout << " ERROR- DIVIDE BY ZERO."; else{ average = sum / n; cout << " THE AVERAGE IS " << average << endl; }//ELSE • • •Figure 4.23 - Capturing division by zero error. break THE switch The switch statement is similar to the if statement but is different than a set of if and else statements in that all cases will be tested regardless of previous matches. In situations where you want to exit the switch, a break can be used to bypass testing the rest of the cases. The candidate election count program of figure 4.24a illustrates this situation. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. char candidateinitial; 5. int rcount, hcount, gcount, ocount; 6. rcount = hcount = gcount = ocount = 0; 7. cout << " ENTER THE CANDIDATE INITIAL: "; 8. cin >> candidateinitial; 9. switch( candidateinitial ){ 10. case 'R': 11. rcount = rcount + 1; 12. break; 13. case 'H': 14. hcount = hcount + 1; 15. break; 16. case 'G': 17. gcount = gcount +1; 18. break; 19. default: 20. ocount = ocount + 1; 21. }//SWITCH 22. cout << " CANDIDATE \t\t NUMBER OF VOTES\n"; 23. cout << " R \t "<< rcount << endl; 24. cout << " H \t "<< hcount << endl; 25. cout << " G \t "<< gcount << endl; 26. cout << " O \t "<< ocount << endl; 27. return 0; 28. }//MAINFigure 4.24a - Illustrates the use of the break to evaluate only one case. ENTER THE CANDIDATE INITIAL: H CANDIDATE NUMBER OF VOTES R 0 H 1 G 0 O 0Figure 4.24b - Sample output of the program of Figure 4.24a. break THE LOOP The termination test of the while and for loops is at the top of the loop. The termination test of the do while is at the bottom of the loop. There are situations where one wants to terminate the loop from within the body of the loop, and the keyword break does the job. The example of Figure 4.25 counts the number of characters per word. The loop terminates when a blank or a new line is reached. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. char ch; 5. int nc = 0; 6. cout << "Enter a word( End word with: # ): " << endl; 7. while( 1 ){ 8. cin >> ch; 9. if( ch == ‘#’ ) 10. break; 11. else 12. nc++; 13. }//WHILE 14. cout << " The length of the word is " << nc << endl; 15. return 0; 16. }//MAINFigure 4.25a - Counting the number of letters in a word. Enter a word( End word with: # ): ebrahimi# The length of the word is 8Figure 4.25b - Output of the number of letters in a word from Figure 4.25a. CONTINUE TO LOOP Normally when control flow reaches the bottom of the loop, it starts over again at the top of the loop. By using the keyword continue the control flow will be redirected back to the top of the loop. An example of continue, is to further the loop if the criteria has not been met. The program of Figure 4.26 will take a number as input, and determine whether the number is even or odd. However, only odd numbers are processed (e.g. looking for prime), and the even numbers are discarded and the loop continues. 1. #include< iostream> 2. using namespace std; 3. main(){ 4. int number; 5. cout << "Enter a number ( Ctrl + Z to END ): "; 6. while( cin >> number ){ 7. if( number % 2 == 0 ){ 8. cout << "Enter a number ( Ctrl + Z to END ): "; 9. continue; 10. }//IF 11. else{ 12. cout << " The number is ODD."; 13. // process further for prime number 14. }//ELSE 15. cout << "\nEnter a number ( Ctrl + Z to END ): "; 16. }//WHILE 17. return 0; 18. }//MAINFigure 4.26a - Initial Shell for processing prime numbers using the continue keyword. Enter a number ( Ctrl + Z to END ): 1 The number is ODD Enter a number ( Ctrl + Z to END ): 2 Enter a number ( Ctrl + Z to END ): 3 The number is ODD Enter a number ( Ctrl + Z to END ): 4 Enter a number ( Ctrl + Z to END ): 5 The number is ODD Enter a number ( Ctrl + Z to END ):Figure 4.26b - Sample output for program of Figure 4.26a. if WITH goto: TO GET OUT 1. #include <iostream> 2. using namespace std; 3. main(){ 4. long int i, j, k; 5. int long code; 6. for( i = 0 ; i < 32767 ; i++ ){ 7. for( j = 0 ; j < 32767 ; j++ ){ 8. for( k = 0 ; k < 32767 ; k++ ){ 9. cout << "i = " << i << " j = " << j << " k = " << k << endl; 10. if( i + j + k == code) 11. goto OUT; 12. } // end k 13. } // end j 14. } // end i 15. OUT: if ( i != 32767) 16. cout << " CODE HAS BEEN FOUND" << code << endl; 17. return 0; 18. }//MAINFigure 4.27a - Using goto to end a loop. i = 0 j = 0 k = 0 i = 0 j = 0 k = 1 i = 0 j = 0 k = 2 • • • CODE HAS BEEN FOUND 3435973836Figure 4.27b - Output of Figure 4.27a. A SIMPLE SEARCH PROGRAM: GIVEN THE ID FIND THE PRICE The program of Figure 4.28a illustrates a simple search program. The program shares the same fundamentals of a complicated search program. The program searches for an item’s id, and upon finding a match displays the item’s price. The input data for the program is previously created and saved in a file named itmprice.in. To illustrate the power of the operating system, the file is linked to the program using the MS-DOS command line and the indirection operator. The use of the operating system to link programs to a specific data file was discussed in the section Program And Data File Linkage: The Operating System in Chapter 3. There is a drawback to Figure 4.28a’s program. Each time you need to search for another id, you must change the value of searchid within the program, and recompile to create another executable file that can run from the command line. To solve the problem, Figure 4.29a’s program reads the searchid as the first data element from the data file named itmprice2.in. Notice that itmprice2.in is the same data file as listed in itmprice.in used for figure 4.28a’s input, except for the first data element within the file. Although this is a step in the correct direction, it is not the final answer to solving the problem of creating a totally interactive program. After all, if you were going to search for a value, you would not want to add the value your searching for to the top of a data file. Instead, you would want to be able to search a file interactively by typing in a search parameter through the keyboard. If the reader looks closer, there is another problem with the programs of Figure 4.28a and 4.29a. What happens if no match is found for the searchid? The program is not very user friendly in the case of not finding a match. A user would receive a blank screen. Figure 4.30a illustrates how to solve the no match problem, as well as create an interactive program by the explicit use of naming the file to be searched. Adding line 21 of figure 4.30a solves the issue of not finding a match. The only time the line will be displayed is when the entire file is searched and there is no data element that matches the searchid. Also, the program becomes interactive with the use of the explicit opening of the file named itmprice.in. Notice line 8: ifstream fin( "itmprice.in");The line might look a bit strange but it is very powerful. The declaration of an input file stream variable named fin is created and the file named itmprice.in is opened. Also, notice the next line ( line 9 ): while( fin >> id >> price )The line looks very similar to both of the previous programs, except for the user defined file input ( fin ) variable. The variable fin assumes the role of cin, and reads information from the file named itmprice.in until the end of file is reached. After file usage is complete, it is important to close an opened file. Line 13 and 17 indicate the proper file usage house keeping by closing the file named itmprice.in. fin.close( );In order to accomplish the file reading notice line 1 of Figure 4.30a. The header file fstream.h ( meaning file stream header ) must be used. You may be asking, why did the file header iostream.h disappear? That is a good question to ask. For now, you must trust the header fstream.h when using a file. In Chapter 9, File Handling, we will discuss the fstream.h header file and many more file related tasks in greater detail. 1. #include <iostream> 2. using namespace std; 3. main(){ 4. const long int searchid = 876590123; 5. long int id; 6. float price; 7. while (cin>>id>>price){ 8. if( id == searchid ){ 9. cout << "ITEM ID IS " << id << endl; 10. cout << "PRICE IS " <<price << endl; 11. }//IF 12. }//WHILE 13. return 0; 14. }//MAINFigure 4.28a - Fixed search program.
1. #include <iostream> 2. using namespace std; 3. main(){ 4. long int searchid; 5. long int id; 6. float price; 7. cout << "ENTER THE SEARCH ID: "; 8. cin >> searchid; 9. cout << searchid; 10. while( cin >> id >> price ){ 11. if( id == searchid ){ 12. cout << "\nITEM ID IS " << id << endl; 13. cout << "PRICE IS " << price <<endl; 14. break; 15. }//IF 16. }//WHILE 17. return 0; 18. }//MAINFigure 4.29a - Search Program where the user enters the searchid as the first data element of the input file named itmprice2.in. NOTE: Notice that the value to be searched for is entered into the top of the data file.
1. #include <iostream> 2. #include
The logical AND operator && has higher priority over the logical OR || operator just as the arithmetic multiplication has higher priority over addition. Use parenthesis whenever it is necessary to avoid confusion, since parentheses has the highest precedence. if( a || b && c ) cout << "This is a test."; if( a || ( b && c) ) cout << "This is the same test.";OPERATOR IF: A SHORTHAND IF In addition to the if and switch statements, the operator if ( ? ) or conditional expression is another form of decision making. The operator if,as its name suggests, is involved in an operation where the result can be assigned to a variable, or the output can be used with a return. The operator if can use the following form: condition ? result of if : result of else;The above can be viewed as if and else statement. When the test is true, the statement right after the question mark ( ? ) will be executed, and when the test is false the statement right after : sign will be executed. max = ( num1 > num2 ) ? num1 : num2;The above operator if can be expressed as an if else statement as shown below, however, operator if is a shortcut. if( num1 > num2 ) max = num1; else max = num2; 1. #include <iostream> 2. using namespace std; 3. main(){ 4. int num1,num2; 5. cout << "Enter two numbers: "; 6. cin >> num1 >> num2; 7. cout << (( num1 > num2 ) ? num1: num2 ); 8. cout << " IS THE MAXIMUM "; 9. return 0; 10. }//MAINFigure 4.31a - Finding the maximum of two numbers using the if operator. Enter two numbers: 20 30 30 IS THE MAXIMUM Enter two numbers: 50 10 50 IS THE MAXIMUMFigure 4.31b - Sample output of the maximum of two numbers program Another way the operator if is used is with the return statement. return num1 > num2 ? num1 : num2;FORMAT YOUR OUTPUT: MAKE IT PRESENTABLE It is desirable to control the output of a program to make it presentable. Until now blank spaces, tabs, and new lines are inserted in output routines to achieve presentability. You may have already encountered situations where the output was not how you wanted it to look. For example, when looking at the output of the payroll program you may have realized that the net pay contains more than two digits after the decimal point (e.g. $ 12345.996531) and there are spaces between the $ and the amount. This is not the output you wanted. The setting is done by the default rule. You can reverse this by using format routines, known as manipulators. While there are various formatting styles and manipulators, only a few of these routines are frequently used. C++ OUTPUT FORMAT MANIPULATOR In C++, using the following manipulators in conjunction with cout can format the output. To access these manipulators it is necessary to use the include <iomanip.h> header file.
1. #include <iostream> 2. #includeFigure 4.32a - Smaller version of Payroll program demonstrating formatted output. ENTER HOURS WORKED AND HOURLY RATE: 25 30.10 THE GROSS PAY IS $752.50Figure 4.32b - Formatted output of Payroll program in Figure 4.32a. OUPUT FORMATTING IN C The C language equivalent of cout is printf, which stands for print formatted. However, the C programmer needs to provide the format for each output indicating whether the output belongs to the integer, float, or character data type. The printf has the following form: printf ( " %d %f %c", age, salary, gender );The output data types are indicated by the following symbols:
A C programmer may find the C++ output formatting a little cumbersome because you must type the manipulators in order to format output. In addition, the header file named #include<iostream.h> is necessary for C++ manipulators to be accessed. The header file #include<stdio.h> is needed for C output formatting. Table 4.3 illustrates some of the differences between C and C++ regarding displaying and formatting output.
RAINFALL PROBLEM The program of figure 4.33a finds the sum, average, minimum, and maximum amounts of rainfall. The program will detect the end of file (e.g. link a data file through the operating system or interactively enter (CTRL/Z, or CTRL/D for Unix) to end the file). Alternatively a data type mismatch, such as typing STOP, will terminate the loop. The rainfall values greater than 100 and less than 0 are considered invalid and will be disregarded. 1. // RAINFALL PROGRAM - CHECK INVALID DATA- 2. //FIND SUM, MIN, MAX OF RAINFALLS 3. #include <iostream> 4. #includeFigure 4.33a - Rainfall Program that determines the sum, average, minimum, and maximum rainfall. Enter a rainfall amount ( Ctrl + Z to end ): 2.09 Enter a rainfall amount ( Ctrl + Z to end ): 3.85 Enter a rainfall amount ( Ctrl + Z to end ): 1.11 Enter a rainfall amount ( Ctrl + Z to end ): 4.00 Enter a rainfall amount ( Ctrl + Z to end ): 0.50 Enter a rainfall amount ( Ctrl + Z to end ): SUM OF RAINFALLS 11.55 AVERAGE OF RAINFALLS 2.31 MINIMUM OF RAINFALL IS 0.50 MAXIMUM OF RAINFALLS IS 4.00Figure 4.33b - Output of Rainfall Program of Figure 4.33a with NO errors. Enter a rainfall amount ( Ctrl + Z to end ): 10.00 Enter a rainfall amount ( Ctrl + Z to end ): 20.00 Enter a rainfall amount ( Ctrl + Z to end ): 102.50 ERROR - RAINFALL TOO HIGH Enter a rainfall amount ( Ctrl + Z to end ): 30.00 Enter a rainfall amount ( Ctrl + Z to end ): 40.00 Enter a rainfall amount ( Ctrl + Z to end ): SUM OF RAINFALLS 100.00 AVERAGE OF RAINFALLS 25.00 MINIMUM OF RAINFALL IS 10.00 MAXIMUM OF RAINFALLS IS 40.00Figure 4.33c - Output of Rainfall Program of Figure 4.33a with high output error. Enter a rainfall amount ( Ctrl + Z to end ): 15.00 Enter a rainfall amount ( Ctrl + Z to end ): 25.00 Enter a rainfall amount ( Ctrl + Z to end ): -1.00 ERROR - RAINFALL TOO LOW Enter a rainfall amount ( Ctrl + Z to end ): 35.00 Enter a rainfall amount ( Ctrl + Z to end ): 45.00 Enter a rainfall amount ( Ctrl + Z to end ): SUM OF RAINFALLS 120.00 AVERAGE OF RAINFALLS 30.00 MINIMUM OF RAINFALL IS 15.00 MAXIMUM OF RAINFALLS IS 45.00Figure 4.33d - Output of Rainfall Program of Figure 4.33a with low output error. CLOSING REMARKS AND LOOKING AHEAD One way to build an intelligent program is to utilize appropriate decision-making. Moreover, by not using proper decision-making, the program can become vulnerable and prone to errors that may cause extreme problems. Just think of a payroll program that does not check for taxes based on total income, or, even worse, does not take out any taxes at all. It sounds good now, but wait until April 15th and try to explain these problems to the IRS! There are a variety of "if" statements, such as the nested "if" and the "if" with logical conditions. When there are several choices that can be made related to one condition, the "switch" and "case" is a better choice than the "if" statements. The C/C++ "if" and "else" construct represent the last of the three basic programming constructs. After Chapter 4, the reader should understand sequence, repetition, and selection. These three constructs enable any programmer to write comprehensive and meaningful programs that interact with the user, as well as with a data file. The next three chapters focus on the organization of data and programming codes. Chapter 5 starts the process by introducing an array, which allows the programmer the ability to store data of the same type and kind using the same variable name. |