Bartleby Sitemap - Textbook Solutions

All Textbook Solutions for C++ Programming: From Problem Analysis to Program Design

1. Mark the following statements as true or false. a. The calculating device called the Pascaline could calculate sums up to eight figures long. (1) b. All programs must be loaded into the CPU before they can be executed and all data must be loaded into main memory before it can be manipulated. (2) c. Main memory is an ordered sequence of cells and each cell has a random location in main memory. (2) d. The program that loads first when you turn on your computer is called the operating system. (2) e. Analog signals represent information with a sequence of 0s and 1s. (3) f. The machine language is a sequence of 0s and 1s. (3) g. A Binary code is a sequence of 0s and 1s. (3) h. A sequence of eight bits is called a byte. (3) i. One GB is MB. (3) j. In ASCII, A is the 65th character. (3) k. The number system used by a computer is base 2. (3) l. An assembler translates the assembly language instructions into machine language. (4) m. A compiler translates the source program into an object program. n. In a program, statements that begin with the symbol are called preprocessor directives (7) o. An object program is the machine language version of a high-level language program. (9) p. All logical errors, such as division by 0, are reported by the compiler. (9) q. In object-oriented design (OOD), a program is a collection of interacting objects. (10) r. An object consists of data and operations on that data. (10) s. ISO stands for International Organization for Standardization. (11) 2SA3SA4SA5SA6SAIn a C++ program, preprocessor directives begin with which symbol? (8)8SA9SA10SA11SA12SADesign an algorithm to find the weighted average of four test scores. The four test scores and their respective weights are given in the following format: (9) testScore weightTestScore14SA15SA16. The dealer’s cost of a car is 85% of the listed price. The dealer would accept any offer that is at least $500 over the dealer’s cost. Design an algorithm that prompts the user to input the list price of the car and print the least amount that the dealer would accept for the car. (9) 17SA18. Tom and Jerry opened a new lawn service. They provide three types of services: mowing, fertilizing, and planting trees. The cost of mowing is $35.00 per 5,000 square yards, fertilizing is $30.00 per application, and planting a tree is $50.00. Write an algorithm that prompts the user to enter the area of the lawn, the number of fertilizing applications, and the number of trees to be planted. The algorithm then determines the billing amount. (Assume that the user orders all three services.) (9) 19. Jason typically uses the Internet to buy various items. If the total cost of the items ordered, at one time, is $200 or more, then the shipping and handling is free; otherwise, the shipping and handling is $10 per item. Design an algorithm that prompts Jason to enter the number of items ordered and the price of each item. The algorithm then outputs the total billing amount. Your algorithm must use a loop (repetition structure) to get the price of each item. (For simplicity, you may assume that Jason orders no more than five items at a time.) (9) 20SA21SAA student spends a majority of his weekend playing and watching sports, thereby tiring him out and leading him to oversleep and often miss his Monday 8 AM math class. Suppose that the tuition per semester is $25,000 and the average semester consists of 15 units. If the math class meets three days a week, one hour each day for 15 weeks, and is a four-unit course, how much does each hour of math class cost the student? Design an algorithm that computes the cost of each math class. (9)You are given a list of students names and their test scores. Design an algorithm that does the following: Calculates the average test scores. Determines and prints the names of all the students whose test scores are below the average test score. Determines the highest test score. Prints the names of all the students whose test scores are the same as the highest test score. (Each of the parts a, b, c, and d must be solved as a subproblem. The main algorithm combines the solutions of the subproblems.) (9)1. Mark the following statements as true or false. a. An identifier must start with a letter and can be any sequence of characters. (1) b. In C++, there is no difference between a reserved word and a predefined identifier. (1) c. A C++ identifier cannot start with a digit. (1) d. The collating sequence of a character is its preset number in the character data set. (2) e. Only one of the operands of the modulus operator needs to be of type int. (3) f. If ; and ;, then after the statement ; the value of b is erased. (6) g. If the input is 7 and x is a variable of type int, then the statement ; assigns the value 7 to x. (6) h. In an output statement, the newline character may be a part of the string. (10) i. In C++, all variables must be initialized when they are declared. (7) j. In a mixed expression, all the operands are converted to floating-point numbers. (4) k. Suppose . After the statement ; executes, y is 5 and x is 6. (9) i. Suppose . After the statement ; executes, the value of a is still 5 because the value of the expression is not saved in another variable. (9) 2MCWhich of the following is not a reserved word in C++? (1) int include double const cin bool4SA5. Are the identifiers quizNo1 and quiznol the same? (1) 6. Evaluate the following expressions. (3, 4) a. 25 + 4 - 7 b. 8/3 c. 13 / 3 * 6 - 10 d. 3 + 5 % 6 e. 28 / 4.0 f. 20 - 13 % 2 + 18 / 9 g. 42 % 36 - 6 + 36 / 7 * 4 h. 5 / 9 * (32.6 - 4.5) i. 13.5 + 2.0 * 4.0 / 4.0 If int x = 10;, int y = 7;, double z = 4.5;, and double w = 2.5;, evaluate each of the following statements, if possible. If it is not possible, state the reason. (3, 4) (x + y) % x x % y + w (z - y) / w (y + z) % x (x % y) * z x % y % 2 (x + y) % z (x % y + z) / w8CP9. Suppose that x, y, z, and w are int variables. What is stored in x, y, z, and w after the following statements execute? (3,6) x = 9; y = x - 4; z = (y + 7) % 6; w = (x * z) / y - 3; z = w + (x - y + 2) % x; 10SAWhich of the following are valid C++ assignment statements? Assume that i is an int variable, and x and percent are double variables. (6) x = 2 * i + 4; i++ = i; x = x + x * percent; percent% = 0.1;Write C++ statements that accomplish the following. (6, 7) Declare int variables x and y. Initialize x to 25 and y to 18. Declare and initialize an int variable temp to 10 and a char variable ch to 'A'. Update the value of an int variable x by adding 5 to it. Declare and initialize a double variable payRate to 12.50. Copy the value of an int variable firstNum into an int variable temp Num. Swap the contents of the int variables x and y. (Declare additional variables, if necessary.) Suppose x and y are double variables. Output the contents of x, y, and the expression x + 12 / y - 18. Declare a char variable grade and set the value of grade to 'A'. Declare int variables to store four integers. Copy the value of a double variable z to the nearest integer into an int variable x.Write each of the following as a C++ expression. (3, 4, 6) 9.0 divided by 5 times c plus 32. The integer value of the character +. Round the decimal number x to the nearest integer. Assign the string C++ Programming is exciting to the variable str. Assign the value of 12 times feet plus inches to totalInches. Increment the value of the int variable i by 1. v = 4/3(3.1416 r3). S = 2(3.1416 r2) + 2(3.1416r)h. a + (b-c)/d(ef - gh) (-b + (b2- 4ac)) / 2a14SASuppose x, y, and z are int variables and wandt are double variables. What value is assigned to each of these variables after the last statement executes? (4, 6) x = 8; y = x + 3; z = x + y + 2 * x; x = z - y % 4; w = 2.5 * z - x; t = w / 2 + 13 / 4 - y % 5;16. Suppose x, y, and z are int variables and x = 18, y = 5, and z = 4. What is the output of each of the following statements? (3, 4, 10) a. cout << "x = " << x << ", y = " << y << ", z = " << z << endl; b. cout << "5 * x - y = " << 5 * x - y << endl; c. cout << "Product of " < x << " and " << z << " is << x * z << endl; d. cout << "x - y / z = " << x - y / z << endl; e. cout << x << " square = " << x * x << endl; Suppose a and b are int variables, c is a double variable, and a = 25, b = 20, and c = 5.0. What is the output of the following statements? (3, 4, 10) cout a * 2 * b endl; cout a + b / 2.0 + 1.5 * c endl; cout a / static_castdouble (b) endl; cout 62 % 28 + a / c endl; cout static_castint(c) % 3 + 7 endl; cout 22.5 / 2 + 14.0 * 3.5 + 28 endl; cout 2 / (c - static_castint(c + 1.2)) endl;18. Write C++ statements that accomplish the following. (10) a. Outputs the newline character. b. Outputs the tab character. c. Outputs double quotation mark. Which of the following are correct C++ statements? (10) cout "Programming with C++!" endl; cout " Programming " " with " " C++" endl; cout " Programming" " with C++!" '\n'; cout "Programming with C++!' endl;Give meaningful identifiers for the following variables and write a proper C++ declaration and initialization to a reasonable value. (1, 6, 7) A variable to store the letter grade, (A, B, C, D, or F). A variable to store the sales tax price of an item. A variable to store the number of juice bottles sold. A variable to store the billing amount of a doctor's visit. A variable to store the grade point average (GPA).21. Write C++ statements to do the following. (7,8, 10) a. Declare int variables num1 and num2. b. Prompt the user to input two integers. c. Input the first number in num1 and the second number in num2. d. Output num1, num2, and 2 times num1 minus num2. Your output must identify each number and the expression. 22SAThe following program has syntax errors. Correct them. On each successive line, assume that any preceding error has been corrected. (12) const char = STAR = '*' const int PRIME = 71; int main { int count, sum; double x; count = 1; sum = count + PRIME; x = 25.67 newNum = count * ONE + 2; sum + count = sum; (x + sum) ++; x = x + sum * COUNT; sum += 3 ; cout " count = " count ", sum = " sum ", PRIME = " Prime endl; }24SA25SAPreprocessor directives begin with which of the following symbol: (12) * # $ ! None of these.27. Write equivalent compound statements if possible. (14) a. x = x + 5; b. x = 2 * x * y; c. totalPay = totalPay + current Pay; d. z = z * x + 2 * z; e. y = y 1 (x + 5); 28. Write the following compound statements as equivalent simple statements. (14) a. x += 5 - z; b. y *= 2 * x + 5 - z; c. w += 2 * z + 4; d. x - = z + y - t; e. sum + = num; 29. Suppose a, b, and c are int variables and a = 7 and b = 2. What value is assigned to each variable after each statement executes? If a variable is undefined at a particular statement, report UND (undefined). (6,9) a b c a = ++b + 5; ___ ___ ___ c = a + b -- + 1; ___ ___ ___ b = (a++) - (--c); ___ ___ ___ Suppose a, b, and sum are int variables and c is a double variable. What value is assigned to each variable after each statement executes? Suppose a = 6, b = 3, and c = 2.2. (14) a b c sum sum - static_castint(a + b + c); ___ ___ ___ ___ b + = c * a; ___ ___ ___ ___ c - = a; ___ ___ ___ ___ a * = 2 * b - c; ___ ___ ___ ___31SA32SA33SA34SA1. Write a program that produces the following output: In your program, substitute ??? with your own name. If necessary, adjust the positions and the number of the stars to produce a rectangle. 2PE3PE4. Repeat Programming Exercise 3 by declaring numl, num2, and num3, and average of type double. Store 75.35 into numl, -35.56 into num2, and 15.76 into num3. 5PE6PE7. Write a program that prompts the user to input a decimal number and outputs the number rounded to the nearest integer. 8PE9. Write a program that prompts the user to enter five test scores and then prints the average test score. (Assume that the test scores are decimal numbers.) 10. Write a program that prompts the user to input five decimal numbers. The program should then add the five decimal numbers, convert the sum to the nearest integer, and print the result. 11. Write a program that prompts the capacity, in gallons, of an automobile fuel tank and the miles per gallon the automobile can be driven. The program outputs the number of miles the automobile can be driven without refueling. 12. Write a C++ program that prompts the user to input the elapsed time for an event in seconds. The program then outputs the elapsed time in hours, minutes, and seconds. (For example, if the elapsed time is 9,630 seconds, then the output is 2:40:30.) 13. To make a profit, a local store marks up the prices of its items by a certain percentage. Write a C++ program that reads the original price of the item sold, the percentage of the marked up price, and the sales tax rate. The program then outputs the original price of the item, the percentage of the mark-up, the store's selling price of the item, the sales tax rate, the sales tax, and the final price of the item. (The final price of the item is the selling price plus the sales tax.) 14. (Hard drive storage capacity) If you buy a 40 GB hard drive, then chances are that the actual storage on the hard drive is not 40 GB. This is due to the fact that, typically, a manufacturer uses 1,000 bytes as the value of 1K bytes, 1,000 K bytes as the value of 1 MB, 1,000 MB as the value of 1 GB. Therefore, a 40 GB hard drive contains 40,000,000,000 bytes. However, in computer memory, as given in Table 1-1 (Chapter 1), 1 KB is equal to 1,024 bytes, and so on. So the actual storage on a 40 GB hard drive is approximately 37.25 GB. (You might like to read the fine print next time you buy a hard drive.) Write a program that prompts the user to enter the size of the hard drive specified by the manufacturer, on the hard drive box, and outputs the actual storage capacity of the hard drive. 15. Write a program to implement and test the algorithm that you designed for Exercise 15 of Chapter 1. (You may assume that the value of . In your program, declare a named constant PI to store this value.) 16. A milk carton can hold 3.78 liters of milk. Each morning, a dairy farm ships cartons of milk to a local grocery store. The cost of producing one liter of milk is $0.38, and the profit of each carton of milk is $0.27. Write a program that does the following: a. Prompts the user to enter the total amount of milk produced in the morning. b. Outputs the number of milk cartons needed to hold milk. (Round your answer to the nearest integer.) c. Outputs the cost of producing milk. d. Outputs the profit for producing milk. 17. Redo Programming Exercise 16 so that the user can also input the cost of producing one liter of milk and the profit on each carton of milk. 18PE19. Write a program that prompts the user to input the number of quarters, dimes, and nickels. The program then outputs the total value of the coins in pennies. 20. For each used car a salesperson sells, the commission is paid as follows: $20 plus 30% of the selling price in excess of the cost of the car. Typically, the minimum selling price of the car is the cost of the car plus $200 and the maximum selling price is the cost of the car and $2,000. Write a program that prompts the user to enter the salesperson's fixed commission, the percentage of the commission, the purchasing cost of the car, the minimum and maximum amount to be added to the purchasing cost to determine the minimum and maximum selling price, and outputs minimum and maximum selling price of the car and the salesperson's commission range. 21. Newton's law states that the force, , between two bodies of masses and is given by: in which is the gravitational constant and d is the distance between the bodies. The value of is approximately . Write a program that prompts the user to input the masses of the bodies and the distance between the bodies. The program then outputs the force between the bodies. 22. One metric ton is approximately 2,205 pounds. Write a program that prompts the user to input the amount of rice, in pounds, a bag can hold. The program outputs the number of bags needed to store one metric ton of rice. 23. Cindy uses the services of a brokerage firm to buy and sell stocks. The firm charges 1.5% service charges on the total amount for each transaction, buy or sell. When Cindy sells stocks, she would like to know if she gained or lost on a particular investment. Write a program that allows Cindy to input the number of shares sold, the purchase price of each share, and the selling price of each share. The program outputs the amount invested, the total service charges, amount gained or lost, and the amount received after selling the stock. 24. A piece of wire is to be bent in the form of a rectangle to put around a picture frame. The length of the picture frame is 1.5 times the width. Write a program that prompts the user to input the length of the wire and outputs the length and width of the picture frame. 25. Repeat Programming Exercise 24, but the wire is to be bent in the form of a circle. In this case, the user specifies the length of the wire and the program outputs the radius and area of the circle. (You may assume that . Also declare it as a named constant.) 26. A room has one door, two windows, and a built-in bookshelf and it needs to be painted. Suppose that one gallon of paint can paint 120 square feet. Write a program that prompts the user to input the lengths and widths of the door, each window, the bookshelf; and the length, width, and height of the room (in feet). The program outputs the amount of paint needed to paint the walls of the room. 27PE28. In an elementary school, a mixture of equal amounts of nuts and dried fruit is provided during lunch. Suppose that the number of calories in each pound of nuts is 0.70 times the number of calories in each pound of dried fruit. Write a program that prompts the user to input the number of students in the elementary school, the number of calories required for each student from the mixture, and the number of calories in each pound of nuts. The program outputs the amount of nuts and dried fruit needed for the students. (For simplicity, assume that each student requires the same amount of calories.) 29. A contractor orders, say, 30 cubic yards of premixed concrete to construct a patio that is to be, say, four inches thick. The length of the patio is to be, say, twice the width. Write a program that prompts the user to specify the amount of premixed concrete (in cubic yards) ordered, the thickness of the patio (in inches), and the ratio of length and width. The program then outputs the length and width of the patio (in feet). (1 cubic yard cubic feet.) (To find the square root of a decimal number, include the header file cmath using the statement #include <cmath>, in your program. The function sqrt, included in this header file, determines the square root of a decimal number. For example, sqrt .) Mark the following statements as true or false. An output stream is a sequence of characters from a computer to an output device. (1) To use cin and cout in a program, the program must include the header file iostream. (1, 2) Suppose pay is a variable of type double. The statement cin pay, requires the input of a decimal number. (2) The statement cin length; and length cin; are equivalent. (2) When the statement cin numl num2; executes, then after inputting a number into the variable numl the program skips all trailing whitespace characters. (2) To use the predefined function sqrt in a program, the program must include the header file cmath. (3) The statement cin.get (ch); inputs the next nonwhitespace character into the variable ch. (4) When the input stream enters the fail state, the program terminates with an error message. (5) To use the manipulators fixed and showpoint, the program does not require the inclusion of the header file iomanip. (6) The statement cin right; sets the input of only the next variable right-justified. (7) To input data from a file, the program must include the header file fstream. (10)2SA4SA5SA6SA7SAWhat does function sqrt do? Which header file must be included to use the function sqrt? (3)9SA10SA11. What is the purpose of the manipulator setw? Which header file must be included to use the function setw? (7) 12. What is the output of the following program? (2, 3, 6, 8) #include <iostream> #include <cmath> #include <string> #include <iomanip> using namespace std; int main() { double x, y; string str; x = 9.0; y = 3.2; cout << fixed << showpoint << setprecision (2); cout << x << "^" << y << " = " << pow(x, y) << endl; cout << "5.0^2.5 = " << pow(5.0, 2.5) << endl; cout << "sqrt (48.35) = " << sqrt (48.35) << endl; cout << "static_cast<int>(sqrt(pow (y, 4))) = " << static_cast<int>(sqrt(pow (y, 4))) << endl; str = "Predefined functions simplify programming code!"; cout << "Length of str = " << str.length() << endl; return 0; } 13SA14SASuppose that name is variable of type string. What is the effect of the following statement? (8) getline (cin, name);16. Write a C++ statement that uses the manipulator setfill to output a line containing 35 stars, as in the following line: (7) *********************************** 17SA18SA19. The following program is supposed to read the length and width of a rectangle from a file named input.txt and write the area and perimeter of the numbers to a file named output.txt. However, it fails to do so. Rewrite the program so that it accomplishes what it is intended to do. (Also, include statements to close the files.) (10) #include <iostream> using namespace std; int main() { double length, width; ofstream outfile; infile.open("input.txt"); infile >> length > > width; outfile << "Area = " << length * width <<", Perimeter = " << 2 * (length + width) << endl; return 0; } 20SA21SA22. Suppose that infile is an ifstream variable and employee.dat is a file that contains employees' information. Write the C++ statement that opens this file using the variable infile. (10) 23SA24. Suppose that infile is an 18stream variable and it is associated with the file that contains the following data: 27306 savings 7503.35. Write the C++ statement(s) that reads and stores the first input in the int variable acct Number, the second input in the string variable accountType, and the third input in the double variable balance. (10) 25SA1. Consider the following incomplete C++ program: #include <iostream> int main() { … } a. Write a statement that includes the header files fstream, string, and iomanip in this program. b. Write statements that declare inFile to be an ifstream variable and outFile to be an ofstream variable. c. The program will read data from the file inData.txt and write output to the file outData.txt. Write statements to open both of these files, associate inFile with inData.txt, and associate outFile with outData.txt. d. Suppose that the file inData.txt contains the following data: Giselle Robinson Accounting 5600 5 30 450 9 75 1.5 The first line contains a person's first name, last name, and the department the person works in. In the second line, the first number represents the monthly gross salary, the bonus (as a percent), and the taxes (as a percent). The third line contains the distance traveled and the traveling time. The fourth line contains the number of coffee cups sold and the cost of each coffee cup. Write statements so that after the program executes, the contents of the file outData.txt are as shown below. If necessary, declare additional variables. Your statements should be general enough so that if the content of the input file changes and the program is run again (without editing and recompiling), it outputs the appropriate results. Name: Giselle Robinson, Department: Accounting Monthly Gross Salary: $5600.00, Monthly Bonus: 5.00, Taxes: 30.000 Paycheck: $4116.00 Distance Traveled 450.00 miles, Traveling Time: 9.00 hours Average Speed: 50.00 miles per hour Number of coffee Cups Sold: 75, Cost: $1.50 per cup Sales Amount = $112.50 e. Write statements that close the input and output files. f. Write a C++ program that tests the statements in parts a through e. 2. Consider the following program in which the statements are in the incorrect order. Rearrange the statements so that the program prompts the user to input the height and the radius of the base of a cylinder and outputs the volume and surface area of the cylinder. Format the output to two decimal places. #include <iomanip> #include <cmath> int main() {} double height; cout << "Volume of the cylinder = " << PI * pow(radius, 2.0) * height << endl; cout << "Enter the height of the cylinder, "; cin >> radius; cout << endl; return 0; double radius; cout << "Surface area. " << 2 * PI * radius * height + 2 * PI * pow (radius, 2.0) << endl; cout << fixed << showpoint << setprecision (2), cout << "Enter the radius of the base of the cylinder: "; cin >> height; cout << endl; #include <iostream> conat double PI = 3.14159; using namespace std; Write a program that prompts the user to enter the weight of a person in kilograms and outputs the equivalent weight in pounds. Output both the weights rounded to two decimal places. (Note that 1 kilogram = 2.2 pounds.) Format your output with two decimal places.4. During each summer, John and Jessica grow vegetables in their backyard and buy seeds and fertilizer from a local nursery. The nursery carries different types of vegetable fertilizers in various bag sizes. When buying a particular fertilizer, they want to know the price of the fertilizer per pound and the cost of fertilizing per square foot. The following program prompts the user to enter the size of the fertilizer bag, in pounds, the cost of the bag, and the area, in square feet, that can be covered by the bag. The program should output the desired result. However, the program contains logic errors. Find and correct the logic errors so that the program works properly. // Logic errors. #include <iostream> #include <iomanip> using namespace std; int main() { double costs double area; double bagsize; cout << fixed << showpoint << setprecision (2); cout << "Enter the amount of fertilizer, in pounds, " << "in one bag: "; cin >> bagsize; cout << endl; cout << "Enter the cost of the << bagsize << pound fertilizer bag: "; cin >> cost; cout << endl; cout << "Enter the area, in square feet, that can be " << "fertilized by one bag: "; cin >> area; cout << endl; cout << "The cost of the fertilizer per pound is: $" << bagsize / cost << endl; cout << "The cost of fertilizing per square foot is: $" << area / cost << endl; return 0; } 5. Three employees in a company are up for a special pay increase. You are given a file, say ch3_Ex5Data.txt, with the following data: Miller Andrew 65789.87 5 Green Sheila 758 92.56 6 Sethi Amit 74900.50 6.1 Each input line consists of an employee's last name, first name, current salary, and percent pay increase. For example, in the first input line, the last name of the employee is Miller, the first name is Andrew, the current salary is 65789.87, and the pay increase is 54. Write a program that reads data from the specified file and stores the output in the file ch3_Ex50utput.dat. For each employee, the data must be output in the following form: firstName lastName updatedsalary. Format the output of decimal numbers to two decimal places. 6. Write a program that accepts as input the mass, in grams, and density, in grams per cubic centimeters, and outputs the volume of the object using the formula: volume mass / density. Format your output to two decimal places. Interest on a credit card's unpaid balance is calculated using the average daily balance. Suppose that netBalance is the balance shown in the bill, payment is the payment made, dl is the number of days in the billing cycle, and d2 is the number of days payment is made before billing cycle. Then, the average daily balance is: averageDailyBalance = (netBalance*d1 payment*d2)/d1 If the interest rate per month is, say, 0.0152, then the interest on the unpaid balance is: interest = averageDailyBalance*0.0152 Write a program that accepts as input netBalance, payment, d1, d2, and interest rate per month. The program outputs the interest. Format your output to two decimal places.8PEDairy Farm decided to ship milk in containers in the form of cubes rather than cylinders. Write a program that prompts the user to input the radius of the base and the height of a cylindrical container and outputs the side of the cube with the same volume as the cylindrical container.10. Paula and Danny want to plant evergreen trees along the back side of their yard. They do not want to have an excessive number of trees. Write a program that prompts the user to input the following: a. The length of the yard. b. The radius of a fully grown tree. c. The required space between fully grown trees. The program outputs the number of trees that can be planted in the yard and the total space that will be occupied by the fully grown trees. 11PE12PE1TF2SA3SA4SA5SA6SA7SA8SA9SA10SA11SA12SA13SA14SA15SA16SA17SA18SA19SA20SA21SA22SA23SA24SA25SA26SA27SA28SA29SA30SA31SA32SA33SA34SAWrite a program that prompts the user to input a number. The program should them output the number and a message saying whether the number is positive, negative, or zero.2PEWrite a program that prompts the user to output an integer between 0 and 35. If the number is less than or equal to 9, the program should output the number; otherwise, it should output A for 10, B for 11, C for 12, , and Z for 35. (Hint: Use the case operator, static_castchar(), for numbers = 10).4PEIn a right triangle, the square of the length of one side is equal to the sume of the squares of the lengths of the other two sides. Write a program that prompts the user to enter the lenghts of three sides of a triangle and then outputs a message indicating whether the triangle is a right triangle.6PE7PEWrite a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For division, if the denominator is zero, output an appropriate message.) Some sample outputs follow: 3 + 4 = 7 13 * 5 = 65Redo Exercise 8 to handle floating-point numbers. (Format your output to two decimal places.) 8. Which of the following are logical (Boolean) operators? (5) a. c. !d. e. <>10PE11PE12PEThe number of lines that can be printed on a paper depends on the paper size, the print size of each character in a line, whether lines are double-speced or single-spaced, the top and botto margin, and the left and right margins of the paper. Assume that all characters are of the same point size, and all lines are either single-spaced or double-spaced. Note that 1 inch = 72 points. Moreover, asume that the lines are printed along the width of the paper. For example, if the length of the paper is 11 inches and width is 8.5 inches, then the maximum length of a line is 8.5 inches. Write a program that calculates the number of lines that can be printed on a peper based on the following input from the user: The length and width, in inches, of the paper The top, bottom, left, and right margins The point size of a line If the lines are double-spaces, then double the point size of each character.The short-term, 0-24 hours, parking fee, F, at an international airport is given by the following formula: Where int(h + 1) is the integer value of h + 1. For example, int(3.2) = 3, int(4.8) = 4. Write a program that prompts the user to enter the number of hours a car is parked at the airport and outputs the parking fee. Write a program to implement the algorithm that you designed in Exercise 22 of Chapter 1. (Assume that the account balance is stored in the file Ch4_Ex15_Data.txt.) Your program should output account balance before and after withdrawal and service charges. Also save the account balance after withdrawal in the file Ch4_Ex15_Output.txt.16PESamantha and Vikas are looking to by a house in a new development. After looking at various modelsm the three models they like are colonial split-entry, and single-story. The builder gave them the base price and the finished area in square feet of the three models. The want to know the model(s) with the least price pler square foot. Write a program that accepts as input the base price and the finished area in square feet of the three models. The program outputs the model(s) with the least price per square foot.One way to determine how healthy a person is by measuring the body fat of the person. The formulas to determine the body fat for female and male are as follows: Body fat formula for women: A1 = (body weight x 0.732) + 8.987 A2 = wrist measurement (at fullest point)/3.140 A3 = waist measurement (at navel) x 0.157 A4 = hip measurement (at fullest point) x 0.249 A6 = forearm measurement (at fullest point) x 0.434 B = A1 + A2 A3 A4 + A5 Body fat = body weight - B Body fat percentage = body fat x 100/body weight Body fat formula for men: A1 = (Body weight x 1.082) + 94.42 A2 = wrist measurement x 4.15 B = A1 A2 Body fat = body weight B Body fat percentage = body fat x 100/body weight Write a program to calculate the body fat of a person.Ron bought several acres of farm to grow and sell vegetables. Suppose that Ron wants to grow a maximum of two types of vegetables. Write a program that prompts Ron or the user to do the following: Enter the total farm area in acres. The number of vegetables (one or two) that the user wants to grow. If the user wants to grow trwo types of vegetables, then specify the portion,as a percentage, of the farm land used for each type of vegetable. Enter the seed cost, plantation cose, fertilizing cost, labor cost, for each acre. Enter vegetable selling price per acre. Output the total revenue. Output the profit/loss.The cost of renting a room at a hotel is, say $100.00 per night. For special occasions, such as a wedding or conference, the hotel offers a special discount as follows: If the number of rooms booked at least 10, the discount is 10%; at least 20, the discount is 20%; and at least 30, the discount is 30%. Also if rooms are booked for at least three days, then there is an additional 5% discount. Write a program that prompts the user to enter the cost of renting one room, the number of rooms booked, the number of days the rooms are booked, and the sales tax (as a percent). The program outputs the cost of renting one room, the discount on each room as a percent, the number of rooms booked, the number of days the rooms are booked, the total cost of the rooms, the sales tax, and the total billing amount. Your program must use appropriate named constants to store special values such as various discounts.Let l be a line in the x-y plane. If l is a vertical line, its equation is x = a for some real number a. Suppose l is not a vertical line and its slope is m. Then the equation of l is y = mx + b, where b is the y-intercept. If l passes through the point (x0, y0), the equation of l can be written as y y0 = m(x x0). If (x0, y0) and (x2, y2) are two points in the x-y plane and x1 x2, the slope of line passing through these points is m = (y2 y1)/(x2 x1). Write a program that prompts the user two points in the x-y plane. The program outputs the equation of the line and used if statements to determine and output whether the line is vertical, horizontal, increasing, or decreasing, If l is a non-vertical line, output its equation in the form y = mx + b.The first 11 prime integers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, and 31. A positive integer between 1 and 1000 (inclusive), other than the first 11 prime integers, is prime if it is not divisible by 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, and 31. Write a program that prompts the user to enter a positive integer between 1 and 1000 (inclusive) and that outputs whether the number is prime. If the number is not prime, then output all the numbers, from the list of the first 11 prime integers, which divide the number.23PE1TF2SA3SA4SA5SA6SA7SA8SA9SA10SA11SA12SA13SA14SA15SA16SA17SAWhat type of loop, such as counter control or sentinel control, will you use in each of the following situations? (3) Sum the following series: 1 + (2 / l) + (3 / 2) + (4 / 3) + (5 / 4) + + (10 / 9) Sum the following numbers, except the last number: 17, 32, 62, 48, 58, -1 A file contains employees salary. Update employees salary.19SA20SA21SA22SA23SA24SA25SA26SA27SA28SA29SA30SA31SA32SA33SA34SA35SA36SA37SA38SA39SA40SA41SA42SA43SA44SA45SA46SAWrite a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6, output the individual digits of 8030 as 8 0 3 0, output the individual digits of 2345526 as 2 3 4 5 5 2 6, output the individual digits of 4000 as 4 0 0 0, and output the individual digits of -2345 as 2 3 4 5.2PE3PE4PE5PEWrite a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. (Note: An even number is prime if it is 2. An odd integer is prime if it is not divisible by any odd integer less than or equal to the square root of the number.)7PEWrite a program that uses while loops to perform the following steps: Prompt the user to input two integers: firstNumand secondNum (firstNummust be less than secondNum). Output all odd numbers between firstNumand secondNum. Output the sum of all even numbers between firstNumand secondNum. Output the numbers and their squares between 1 and 10. Output the sum of the square of the odd numbers between firstNum and secondNum. Output all uppercase letters.9PERedo Programming Exercise 8 using dowhile loops.The program in the Programming Example: Fibonacci Number does not check whether the first number entered by the user is less than or equal to the second number and whether both the numbers are non-negative. Also, the program does not check whether the user entered a valid value for the position of the desired number in the Fibonacci sequence. Rewrite that program so that it checks for these things.12PE13PE14PE15PE16PE17PE18PE19PEWhen you borrow money to buy a house, a car, or for some other purpose, you repay the loan by making periodic payments over a certain period of time. Of course, the lending company will charge interest on the loan. Every periodic payment consists of the interest on the loan and the payment toward the principal amount. To be specific, suppose that you borrow $1,000 at an interest rate of 7.2% per year and the payments are monthly. Suppose that your monthly payment is $25. Now, the interest is 7.2% per year and the payments are monthly, so the interest rate per month is 7.2/12 = 0.6%. The first months interest on $1,000 is 1000 0.006 = 6. Because the payment is $25 and the interest for the first month is $6, the payment toward the principal amount is 25 6 = 19. This means after making the first payment, the loan amount is 1,000 19 = 981. For the second payment, the interest is calculated on $981. So the interest for the second month is 981 0.006 = 5.886, that is, approximately $5.89. This implies that the payment toward the principal is 25 5.89 = 19.11 and the remaining balance after the second payment is 981 19.11 = 961.89. This process is repeated until the loan is paid. Write a program that accepts as input the loan amount, the interest rate per year, and the monthly payment. (Enter the interest rate as a percentage. For example, if the interest rate is 7.2% per year, then enter 7.2.) The program then outputs the number of months it would take to repay the loan. (Note that if the monthly payment is less than the first months interest, then after each payment, the loan amount will increase. In this case, the program must warn the borrower that the monthly payment is too low, and with this monthly payment, the loan amount could not be repaid.)21PE22PE23PE24PE25PE26PE27PE28PE29PE30PE31PE32PE33PEMark the following statements as true or false: a. To use a predefined function in a program, you need to know only the name of the function and how to use it. (1) b. A value-returning function returns only one value. (2, 3) c. Parameters allow you to use different values each time the function is called. (2, 7, 9) d. When a return statement executes in a user-defined function, the function immediately exits. (3, 4) e. A value-returning function returns only integer values. (4) f. A variable name cannot be passed to a value parameter. (3, 6) g. If a C++ function does not use parameters, parentheses around the empty parameter list are still required. (2, 3, 6) h. In C + + , the names of the corresponding formal and actual parameters must be the same. (3, 4, 6) i. A function that changes the value of a reference parameter also changes the value of the actual parameter. (7) j. Whenever the value of a reference parameter changes, the value of the actual parameter changes. (7) k. In C++, function definitions can be nested; that is, the definition of one function can be enclosed in the body of another function. (9) l. Using global variables in a program is a better programming style than using local variables, because extra variables can be avoided. (10) m. In a program, global constants are as dangerous as global variables. (10) n. The memory for a static variable remains allocated between function calls. (11) Determine the value of each of the following expressions. (1) a.staticcastchar(toupper('#'))b.staticcastchar(toupper('k'))c.staticcastchar(toupper('3'))d.staticcastchar(toupper('-'))e.staticcastchar(tolower('T'))f.staticcastchar(tolower(':'))g.staticcastchar(tolower('u'))h.staticcastchar(tolower(''))Determine the value of each of the following expressions. (For decimal numbers, round your answer to two decimal places.) (1) abs(-18) fabs(20.5) fabs(-87.2) pow(4, 2.0) pow(8.4, 3.5) sqrt(7.84) sqrt (196.0) sqrt (38.44)* pow(2.4, 2) / fabs(-3.2) floor(27.37) ceil(19.2) floor(12.45) + ceil(6.7) floor (-8.9) + ceil (3.45) floor(9.6) / ceil(3.7) pow(-4.0, 6.0) pow(10, -2.0) pow(9.2, 1.0 / 2)4SAConsider the following function definition. (4, 6) doublefuncTest(stringname, charu, intnum, doubley)WhichofthefollowingarecorrectfunctionprototypesofthefunctionfuncTest?a.doublefuncTest(string, char,int,double);b.doublefuncTest(stringn,charch,intx,doublet);c.doublefuncTest(name,u,num,y);d.intfuncTest(string, char,int,double)6SAConsider the following statements: Which of the following statements are valid? If they are invalid, explain why. (4) a. volume = box (length, width, height); b. volume = box (length, 3.8, height); c. cout << box(num1, num3, num2) << endl; d. cout << box (length, width, 7.0) << endl; e. volume = box (length, num1, height); f. cout << box(6.2, , height) << endl; g. volume = box (length + width, height) h. volume = box (num1, num2 + num3) ; 8SA9SAWhy do you need to include function prototypes in a program that contains user-defined functions? (5)11SA12SAConsider the following function: (4) intsecret(intm,intn)inttemp=n;for(inti=1;iabs(m);i++)temp=temp+n;if(m0)temp=-temp;returntemp; What is the output of the following C+ + statements? i.coutsecret(18,4)endl;ii.coutsecret(-10,20)endl; What does the function secret do?14SA15SAWhat is the output of the following program? (4) Write the definition of a function that takes as input two decimal numbers and returns first number to the power of the second number plus second number to the power of the first number. (4)18SAHow would you use a return statement in a void function? (6) Why would you want to use a return statement in a void function? (6)20SA21SAWhat is the output of the following program? (6) #includeiostreamusingnamespacestd;voidfunc1();voidfunc2();intmain()intnum;coutEnter1or2:;cinnum;coutendl;coutTake;if(num1)func1();elseif(num2)func2();elsecoutInvalidinput.Youmustentera1or2endl;return0;voidfunc1()coutProgrammingI.endl;voidfunc2()coutProgrammingII.endl; What is the output if the input is 1? What is the output if the input is 2? What is the output if the input is 3? What is the output if the input is -1?Write the definition of a void function that takes as input an integer and outputs two times the number if it is even; otherwise it outputs five times the number. (6, 7, 8) Write the definition of a void function that takes as input three decimal numbers. The function returns the sum and average of the three numbers. If the average is greater than or equal to 70, it returns "Pass"; otherwise it returns "Fail". (6, 7, 8) 25SA26SA27SA28SA29SA30SA31SA32SA33SA34SA35SA36SA37SA38SA1PE2PE3PE4PE
Page: [1][2][3]