This preview has intentionally blurred parts. Sign up to view the full document

View Full Document

Unformatted Document Excerpt

to 2 Introduction C++ Programming OBJECTIVES In this chapter you will learn: To write simple computer programs in C++. To write simple input and output statements. To use fundamental types. Basic computer memory concepts. To use arithmetic operators. The precedence of arithmetic operators. To write simple decision-making statements. Aristophanes 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 3 Assignment Checklist Name: Section: Date: Exercises Assigned: Circle assignments Date Due Prelab Activities Matching Fill in the Blank Short Answer Programming Output Correct the Code YES NO 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 26, 27, 28, 29, 30, 31, 32 33, 34, 35, 36, 37, 38, 39 40, 41, 42, 43, 44, 45 NO Lab Exercises Exercise 1 Sum, Average, Product, Smallest YES and Largest Follow-Up Questions and Activities Exercise 2 Multiples Follow-Up Questions and Activities Exercise 3 Separating Digits Follow-Up Questions and Activities Debugging 1, 2 YES YES 1, 2, 3 YES NO NO NO 1, 2, 3, 4 Labs Provided by Instructor 1. 2. 3. Postlab Activities Coding Exercises Programming Challenges 1, 2, 3, 4, 5, 6, 7 1, 2, 3 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 5 Prelab Activities Matching Name: Section: Date: After reading Chapter 2 of C++ How to Program: Fifth Edition, answer the given questions. These questions are intended to test and reinforce your understanding of key concepts and may be done either before the lab or during the lab. For each term in the column on the left, write the corresponding letter for the description that best matches it from the column on the right. Term D H I G A L J E B C M K F Description 1. Integer division 2. Stream extraction operator 3. return a) Holds whole number values. b) Outputs a newline and flushes the output buffer. c) Appears at the end of every statement. d) An operation that truncates any fractional part of its result. e) Instruction that is performed before the program is compiled. f) Prevents a program from compiling. g) An operation that yields the remainder after integer division. h) i) j) k) l) >>. 4. Modulus operator 5. A variable of type int 6. Comments 7. Stream insertion operator 8. Preprocessor directive 9. std::endl stream manipulator 10. Semicolon 11. Conditions in if statements 12. Newline escape sequence 13. Syntax error One of several means to exit a function. <<. '\n'. Text that documents programs and improves their readability. m) Commonly formed by using equality operators and relational operators. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 7 Prelab Activities Fill in the Blank Fill in the Blank Name: Name: Section: Date: Fill in the blanks in each of the following statements: 14. Both comments and white space are ignored by the C++ compiler. 15. A backslash is combined with the next character to form a(n) escape sequence . 16. A(n) variable is a location in the computers memory where a value can be stored for use by a program. 17. Output and input in C++ are accomplished with streams of characters. 18. Single-line comments begin with 19. main // . is the first function executed in a C++ program. 20. All variables in a C++ program must be declared before they are used. 21. 22. cin represents the standard input stream. represents the standard output stream. statement allows a program to make a decision. operator cout 23. The if 24. C++ evaluates arithmetic expressions in a precise sequence determined by the rules of precedence and associativity. 25. Equality operators and relational operators can be used in if conditions. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 9 Prelab Activities Short Answer Short Answer Name: Name: Section: Date: In the space provided, answer each of the given questions. Your answers should be as concise as possible; aim for two or three sentences. 26. What is the difference between stream insertion and stream extraction? What is each used for? Stream insertion is used to insert characters and values into a stream, such as the standard output stream to display data on the screen. Stream extraction is used to extract characters and values from a stream, such as the standard input stream to input data from the keyboard. 27. What is a syntax error? Give an example. A syntax error is a violation of C++s language rules in the program code. Syntax errors are normally accompanied by error messages from the compiler to help the programmer locate and fix the incorrect code. The program cannot be executed until all syntax errors are corrected. Some examples of syntax errors include forgetting the semicolon at the end of a statement, placing two variable identifiers next to each other without an intervening operator and not closing a parenthetical expression with a right parentheses. 28. What is a logic error? Give an example. A logic error is a mistake in the program code that causes the program to produce incorrect results while executing. A logic error will not be reported by the compiler. Some examples of logic errors include using the incorrect variable in a calculation, using the assignment operator = instead of the equality operator == and spelling a word incorrectly in a message to the user. 29. What are operator precedence and associativity? How do they affect program execution? Operator precedence is the order in which the operations in a statement containing multiple operations will execute. For example, multiplication operations execute before addition operations, unless the addition operations are enclosed within parentheses. Associativity is the order in which multiple operations with the same precedence execute. For example, addition operations are performed from left to right, while assignment operations are performed from right to left. Operator precedence and associativity determine the order in which operations execute and therefore affect the values that are used for each operation. 30. What are redundant parentheses? When might a programmer use them? Redundant parentheses are parentheses in a complex arithmetic expression that do not alter the order of execution for the operations in that arithmetic expression. A programmer might use redundant parentheses to make the order of execution of the expression more clear. For example, parentheses could be placed around the multiplication operations in an arithmetic expression containing both multiplication and addition operations, even though the multiplication operations would be performed first anyway. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 10 Introduction to C++ Programming Chapter 2 Prelab Activities Short Answer 31. Write an example of a preprocessor directive. #include <iostream> Name: 32. What is a variable? How are they used in computer programs? A variable is a location in the computers memory. Variables enable a computer program to store values, possibly the results of earlier calculations, for use later later in the program. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 11 Prelab Activities Programming Output Programming Output Name: Name: Section: Date: For each of the given program segments, read the code and write the output in the space provided below each program. [Note: Do not execute these programs on a computer.] 33. What is the output of the following program? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include <iostream> using std::cout; using std::endl; int main() { int x; int y; x = 30; y = 2; cout << x * y + 9 / 3 << endl; return 0; } // end main Your answer: 63 34. What is output by the following line of code? 1 cout << ( 8 * 4 * 2 + 6 ) / 2 + 4; Your answer: 39 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 12 Introduction to C++ Programming Chapter 2 Prelab Activities Programming Output For Programming Output Exercises 35 and 36, use the program in Fig. L 2.1. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #include <iostream> using std::cout; using std::cin; using std::endl; int main() { int input; cout << "Please enter an integer: "; cin >> input; if ( input != 7 ) cout << "Hello" << endl; if ( input == 7 ) cout << "Goodbye" << endl; return 0; } // end main Name: Fig. L 2.1 | Program used for Programming Output Exercises 35 and 36. 35. What is output by the program in Fig. L 2.1? Assume that the user enters 5 for input. Your answer: Hello 36. What is output by the program in Fig. L 2.1? Assume that the user enters 7 for input. Your answer: Goodbye 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 13 Prelab Activities Programming Output For Programming Output Exercises 37 and 38, use the program in Fig. L 2.2. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <iostream> using std::cout; using std::cin; using std::endl; int main() { int input; cout << "Please enter an integer: "; cin >> input; if ( input >= 0 ) cout << "Hello" << endl; cout << "Goodbye" << endl; return 0; } // end main Name: Fig. L 2.2 | Program used for Programming Output Exercises 37 and 38. 37. What is output by the program in Fig. L 2.2? Assume the user enters 2 for input. Your answer: Hello Goodbye 38. What is output by the program in Fig. L 2.2? Assume the user enters -2 for input. Your answer: Goodbye 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 14 Introduction to C++ Programming Chapter 2 Prelab Activities Programming Output 39. What is output by the following program? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 #include <iostream> using std::cout; using std::cin; using std::endl; int main() { int x = 3; int y = 9; int z = 77; if ( x == ( y / 3 ) ) cout << "H"; if ( z != 77 ) cout << "q"; if ( z == 77 ) cout << "e"; if ( z * y + x < 0 ) cout << "g"; if ( y == ( x * x ) ) cout << "ll"; cout << "o!" << endl; return 0; } // end main Name: Your answer: Hello! 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 15 Prelab Activities Correct the Code Correct the Code Name: Name: Section: Date: For each of the given program segments, determine if there is an error in the code. If there is an error, specify whether it is a logic, syntax or compilation error, circle the error in the code and write the corrected code in the space provided after each problem. If the code does not contain an error, write no error. For code segments, assume the code appears in main and that using directives are provided for cin, cout and endl. [Note: It is possible that a program segment may contain multiple errors.] 40. The following program should print an integer to the screen: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream>; using std::cout using std::endl int main() { int x = 30; int y = 2; cout << x * y + 9 / 3 << endl; return 0; } // end main Your answer: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> using std::cout; using std::endl; int main() { int x = 30; int y = 2; cout << x * y + 9 / 3 << endl; return 0; } // end main Errors: Line 1: There should not be a semicolon after a #include preprocessor directive. Compilation error. Lines 34: There should be semicolons after using directives. Compilation error. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 16 Introduction to C++ Programming Chapter 2 Prelab Activities Correct the Code Name: 41. The following code should declare an integer variable and assign it the value 6. 1 2 int 1stPlace 1stPlace = 6; Your answer: 1 2 int firstPlace; firstPlace = 6; Errors: Lines 12: Variable names cannot begin with digits. The name of the variable must be changed. Compilation error. Line 1: A variable declaration should be followed by a semicolon. Compilation error. 42. The following code should determine whether variable x is less than or equal to 9. 1 2 3 4 int x = 9; if ( x < = 9 ) cout << "Less than or equal to."; Your answer: 1 2 3 4 int x = 9; if ( x <= 9 ) cout << "Less than or equal to."; Errors: Line 3: Placing a space between < and = is a syntax error. 43. The following code should determine whether q is equal to 10. 1 2 3 4 5 6 int q = 10; cout << "q is: " << q << endl; if ( q = 10 ) cout << "q is equal to 10"; 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 17 Prelab Activities Correct the Code Your answer: 1 2 3 4 5 6 int q = 10; cout << "q is: " << q << endl; if ( q == 10 ) cout << "q is equal to 10"; Name: Error: Line 5: Testing for equality is performed with the equality operator ==, not the assignment operator =. Logic error. 44. The following code segment should determine whether an integer variables value is greater than zero and display an appropriate message. 1 2 3 4 int x = 9; if ( x > 0 ); cout << "Greater than zero"; Your answer: 1 2 3 4 int x = 9; if ( x > 0 ) cout << "Greater than zero"; Error: ro" Line 3: Placing a semicolon after the if statements condition causes the messsage "Greater to display even if the condition is false. Logic error. than ze- 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 18 Introduction to C++ Programming Chapter 2 Prelab Activities Correct the Code 45. The following program should print 302 to the screen: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> using std::cout; using std::end; int ma in() { int x = 30; int y = 2; cout << y << x << endl; return 0; } // end main Name: Your answer: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> using std::cout; using std::endl; int main() { int x = 30; int y = 2; cout << x << y << endl; return 0; } // end main Errors: Line 4: The stream manipulator endl is spelled incorrectly. Compilation error. Line 6: Placing a space in the middle of function name main is a syntax error. Line 11: To display 302, the value of x should be displayed, followed by the value of y. Logic error. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 19 Lab Exercises Lab Exercise 1 Sum, Average, Product, Smallest and Largest Name: Section: Date: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 2.3) 5. Problem-Solving Tips 6. Follow-Up Questions and Activities The program template represents a complete working C++ program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with C++ code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at www.deitel.com and www.prenhall.com./deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 2 of C++ How To Program: Fifth Edition. In this lab, you will practice: Using cout to output text and variables. Using cin to input data from the user. Using if statements to make decisions based on the truth or falsity of a condition. Using the arithmetic operators to perform calculations. Using relational operators to compare values. Comparing < to <=. Modifying existing code to perform the same task in a different manner. The follow-up questions and activities also will give you practice: Description of the Problem Write a program that inputs three integers from the keyboard, and prints the sum, average, product, smallest and largest of these numbers. The screen dialogue should appear as follows: [Note: 13, 27 and 14 are input by the user.] Sample Output Input three different integers: 13 27 14 Sum is 54 Average is 18 Product is 4914 Smallest is 13 Largest is 27 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 20 Introduction to C++ Programming Chapter 2 Lab Exercises Name: Lab Exercise 1 Sum, Average, Product, Smallest and Largest Template 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 // Lab 1: numbercompare.cpp #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::endl; // program uses endl using std::cin; // program uses cin int main() { int number1; // first integer read from user int number2; // second integer read from user int number3; // third integer read from user int smallest; // smallest integer read from user int largest; // largest integer read from user cout << "Input three different integers: "; // prompt /* Write a statement to read in values for number1, number2 and number3 using a single cin statement */ largest = number1; // assume first integer is largest /* Write a statement to determine if number2 is greater than largest. If so assign number2 to largest */ /* Write a statement to determine if number3 is greater than largest. If so assign number3 to largest */ smallest = number1; // assume first integer is smallest /* Write a statement to determine if number2 is less than smallest. If so assign number2 to smallest */ /* Write a statement to determine if number3 is less than smallest. If so assign number3 to smallest */ /* Write an output statement that prints the sum, average, product, largest and smallest */ return 0; // indicate successful termination } // end main numbercompare.cpp. Fig. L 2.3 | Problem-Solving Tips 1. Prompt the user to input three integer values. You will use a single cin statement to read all three values. 2. Sometimes it is useful to make an assumption to help solve or simplify a problem. For example, we assume number1 is the largest of the three values and assign it to largest. You will use if statements to determine whether number2 or number3 are larger. 3. Using an if statement, compare largest to number2. If the content of number2 is larger, then store the variables value in largest. 4. Using an if statement, compare largest to number3. If the content of number3 is larger, then store the variables value in largest. At this point you are guaranteed to have the largest value stored in largest. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 21 Lab Exercises Name: Lab Exercise 1 Sum, Average, Product, Smallest and Largest 5. Perform similar steps to those in Steps 24 to determine the smallest value. 6. Write a cout statement that outputs the sum, average, product (i.e., multiplication), largest and smallest values. 7. Be sure to follow the spacing and indentation conventions mentioned in the text. 8. If you have any questions as you proceed, ask your lab instructor for assistance. Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 // Lab 1: numbercompare.cpp #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::endl; // program uses endl using std::cin; // program uses cin int main() { int number1; // first integer read from user int number2; // second integer read from user int number3; // third integer read from user int smallest; // smallest integer read from user int largest; // largest integer read from user cout << "Input three different integers: "; // prompt cin >> number1 >> number2 >> number3; // read three integers largest = number1; // assume first integer is largest if ( number2 > largest ) // is number2 larger? largest = number2; // number2 is now the largest if ( number3 > largest ) // is number3 larger? largest = number3; // number3 is now the largest smallest = number1; // assume first integer is smallest if ( number2 < smallest ) // is number2 smaller? smallest = number2; // number2 is now the smallest if ( number3 < smallest ) // is number3 smaller? smallest = number3; // number3 is now the smallest cout << "Sum is " << number1 + number2 + number3 << "\nAverage is " << ( number1 + number2 + number3 ) / 3 << "\nProduct is " << number1 * number2 * number3 << "\nSmallest is " << smallest << "\nLargest is " << largest << endl; return 0; // indicate successful termination } // end main 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 22 Introduction to C++ Programming Chapter 2 Lab Exercises Name: Lab Exercise 1 Sum, Average, Product, Smallest and Largest Follow-Up Questions and Activities 1. Modify your solution to use three separate cin statements rather than one. Write a separate prompt for each cin. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // Lab 1: numbercompare.cpp #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::endl; // program uses endl using std::cin; // program uses cin int main() { int number1; // first integer read from user int number2; // second integer read from user int number3; // third integer read from user int smallest; // smallest integer read from user int largest; // largest integer read from user cout << "Input first integer: "; // prompt cin >> number1; // read an integer cout << "Input second integer: "; // prompt cin >> number2; // read a second integer cout << "Input third integer: "; // prompt cin >> number3; // read a third integer largest = number1; // assume first integer is largest if ( number2 > largest ) // is number2 larger? largest = number2; // number2 is now the largest if ( number3 > largest ) // is number3 larger? largest = number3; // number3 is now the largest smallest = number1; // assume first integer is smallest if ( number2 < smallest ) // is number2 smaller? smallest = number2; // number2 is now the smallest if ( number3 < smallest ) // is number3 smaller? smallest = number3; // number3 is now the smallest cout << "Sum is " << number1 + number2 + number3 << "\nAverage is " << ( number1 + number2 + number3 ) / 3 << "\nProduct is " << number1 * number2 * number3 << "\nSmallest is " << smallest << "\nLargest is " << largest << endl; return 0; // indicate successful termination } // end main 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 23 Lab Exercises Name: Lab Exercise 1 Sum, Average, Product, Smallest and Largest Input first integer: 13 Input second integer: 27 Input third integer: 14 Sum is 54 Average is 18 Product is 4914 Smallest is 13 Largest is 27 2. Does it matter whether < or <= is used when making comparisons to determine the smallest integer? Which did you use and why? In this program, it does not matter whether < or <= is used when making comparisons to determine the smallest integer. The only instance when using < as opposed to <= makes a difference is if smallest and the number it is being compared to are equal, in which case either value can be used as the smallest with the same result. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 25 Lab Exercises Lab Exercise 2 Multiples Lab Exercise 2 Multiples Name: Name: Section: Date: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 2.4) 5. Problem-Solving Tips 6. Follow-Up Questions and Activities The program template represents a complete working C++ program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with C++ code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at www.deitel.com and www.prenhall.com./deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 2 of C++ How To Program: Fifth Edition. In this lab, you will practice: Using cout to output text and values. Using cin to input data from the user. Using if statements to make decisions based on the truth or falsity of a condition. Using the modulus operator (%) to determine the remainder of an integer division operation. Understanding the modulus operator. Recognizing common mistakes with the if statement. Adapting a program to solve a similar problem. The follow-up questions and activities also will give you practice: Write a program that reads in two integers and determines and prints whether the first is a multiple of the second. [Hint: Use the modulus operator.] Description of the Problem Sample Output Enter two integers: 22 8 22 is not a multiple of 8 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 26 Introduction to C++ Programming Chapter 2 Lab Exercises Lab Exercise 2 Multiples Template 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Name: // Lab 2: multiples.cpp #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::endl; // program uses endl using std::cin; // program uses cin int main() { /* Write variables declarations here */ cout << "Enter two integers: "; // prompt /* Write a cin statement to read data into variables here */ // using modulus operator if ( /* Write a condition that tests whether number1 is a multiple of number2 */) cout << number1 << " is a multiple of " << number2 << endl; if ( /* Write a condition that tests whether number1 is not a multiple of number2 */ ) cout << number1 << " is not a multiple of " << number2 << endl; return 0; // indicate successful termination } // end main multiples.cpp. Fig. L 2.4 | Problem-Solving Tips 1. The input data consists of two integers, so you will need two int variables to store the input values. 2. Use cin to read the user input into the int variables. 3. Use an if statement to determine whether the first number input is a multiple of the second number input. Use the modulus operator, %. If one number divides into another evenly, the modulus operation results in 0. If the result is 0, display a message that indicating the first number is a multiple of the second number. 4. Use an if statement to determine whether the first number input is not a multiple of the second number input. If one number does not divide into another evenly, the modulus operation results in a non-zero value. If non-zero, display a message indicating that the first number is not a multiple of the second. 5. Be sure to follow the spacing and indentation conventions mentioned in the text. 6. If you have any questions as you proceed, ask your lab instructor for assistance. Solution 1 2 3 4 5 6 // Lab 2: multiples.cpp #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::endl; // program uses endl using std::cin; // program uses cin 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 27 Lab Exercises Lab Exercise 2 Multiples Name: 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 int main() { int number1; // first integer read from user int number2; // second integer read from user cout << "Enter two integers: "; // prompt cin >> number1 >> number2; // read two integers from user // using modulus operator if ( number1 % number2 == 0 ) cout << number1 << " is a multiple of " << number2 << endl; if ( number1 % number2 != 0 ) cout << number1 << " is not a multiple of " << number2 << endl; return 0; // indicate successful termination } // end main Follow-Up Questions and Activities 1. Can the modulus operator be used with non-integer operands? Can it be used with negative numbers? Assume that the user entered the sets of numbers in Fig. L 2.5. For each set, what does the expression in the third column output? If there is an error, explain why. Integer 1 73 0 100 3 9 16 Integer 2 22 100 0 3 4.5 2 Expression cout << 73 % 22; cout << 0 % 100; cout << 100 % 0; cout << -3 % 3; cout << 9 % 4.5; cout << 16 % 2; Output 7 0 error 0 error 0 Fig. L 2.5 | Determine the output of the cout statements in the third column. The modulus operator cannot be used with non-integer operands. It can be used with negative numbers. An error occurs in cout << 100 % 0; because you cannot divide by 0. An error occurs in cout << 9 % 4.5; because you cannot use modulus with a double value. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 28 Introduction to C++ Programming Chapter 2 Lab Exercises Lab Exercise 2 Multiples Name: 2. Place a semicolon at the end of the if statement in your solution that corresponds to the if statement in lines 1618 in the template. What happens? Explain. The line cout << number1 << " is a multiple of " << number2 << endl; always executes, even if number1 is not a multiple of number2, because the semicolon is treated as the empty statement and is considered to be the ifs body. The output statement is just another statement that will execute after the if statement executes. 3. Rewrite the cout statement in your solution that corresponds to the cout statement in line 18 in the template. This statement should now look as follows: cout << number1; cout << " is a multiple of "; cout << number2 << endl; Rerun the program and observe the differences. Why is the output different? The output is different because only the first cout statement is considered to be the if body. The second and third cout statements are now just regular statements that will be executed after the if statement is finished. 4. Modify the program to determine whether a number entered is even or odd. [Note: Now, the user needs to enter only one number.] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Lab 2: multiples.cpp #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::endl; // program uses endl using std::cin; // program uses cin int main() { int number; // integer read from user cout << "Enter an integer: "; // prompt cin >> number; // read an integer from user // using modulus operator if ( number % 2 == 0 ) cout << number1 << " is even" << endl; if ( number % 2 != 0 ) cout << number1 << " is odd" << endl; return 0; // indicate successful termination } // end main Enter an integer: 12 12 is even 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 29 Lab Exercises Lab Exercise 3 Separating Digits Lab Exercise 3 Separating Digits Name: Name: Section: Date: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 2.6) 5. Problem-Solving Tips 6. Follow-Up Questions and Activities The program template represents a complete working C++ program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with C++ code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at www.deitel.com and www.prenhall.com./deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 2 of C++ How To Program: Fifth Edition. In this lab, you will practice: Using the modulus operator (%) to determine the remainder of a division operation. Integer division, which differs from floating-point division because integer division truncates the decimal portion of the result. Using the division and modulus operators. Examining what happens during program execution when the user enters invalid input. Adapting a program to solve a similar problem. The follow-up questions and activities also will give you practice: Write a program that inputs a five-digit number, separates the number into its individual digits and prints the digits separated from one another by three spaces each. [Hint: Use integer division and the modulus operator.] For example, if the user inputs 42339, the program should print what is shown in the sample output. Problem Description Sample Output 4 2 3 3 9 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 30 Introduction to C++ Programming Chapter 2 Lab Exercises Lab Exercise 3 Separating Digits Template 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Name: // Lab 3: digits.cpp #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::endl; // program uses endl using std::cin; // program uses cin int main() { int number; // integer read from user cout << "Enter a five-digit integer: "; // prompt cin >> number; // read integer from user /* Write a statement to print the 5-digit number */ /* Write a statement that changes to 4-digits */ /* Write a statement to print the 4-digit number */ /* Write a statement that changes to 3-digits */ /* Write a statement to print the 3-digit number */ /* Write a statement that changes to 2-digits */ /* Write a statement to print the 2-digit number */ /* Write a statement that changes to 1-digit */ cout << number << endl; left-most digit of the number from 5-digits left-most digit of the number from 4-digits left-most digit of the number from 3-digits left-most digit of the number from 2-digits return 0; // indicate successful termination } // end main digits.cpp. Fig. L 2.6 | Problem-Solving Tips 1. The input data consists of one integer, so you will use an int variable (number) to represent it. Note that the description indicates that one five-digit number is to be inputnot five separate digits. 2. You will use a series of statements to break down the number into its individual digits using modulus (%) and division (/) calculations. 3. After the number has been input using cin, divide the number by 10000 to get the leftmost digit. Why does this work? Because the number input is five digits long, it is divided by 10000 to obtain the leftmost digit. In C++, dividing an integer by an integer results in an integer. For example, 42339 / 10000 evaluates to 4 because 10000 divides evenly into 42339 four times. The remainder 2339 is truncated. 4. Change the number to a 4-digit number using the modulus operator. The number modulus 10000 evaluates to the integer remainderin this case, the right-most four digits. For example, 42339 % 10000 results in 2339. Assign the result of this modulus operation to the variable that stores the five-digit number input. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 31 Lab Exercises Lab Exercise 3 Separating Digits Name: 5. Repeat this pattern of division and modulus reducing the divisor by a factor of 10 each time (i.e., 1000, 100, 10). After the number is changed to a four-digit number, divide/modulus by 1000. After the number is changed to a three-digit number, divide/modulus by 100. And so on. 6. Be sure to follow the spacing and indentation conventions mentioned in the text. 7. If you have any questions as you proceed, ask your lab instructor for assistance. Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Lab 3: digits.cpp #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::endl; // program uses endl using std::cin; // program uses cin int main() { int number; // integer read from user cout << "Enter a five-digit integer: "; // prompt cin >> number; // read integer from user cout << number / 10000 << " "; number = number % 10000; cout << number / 1000 << " "; number = number % 1000; cout << number / 100 << " "; number = number % 100; cout << number / 10 << " "; number = number % 10; cout << number << endl; return 0; // indicate successful termination } // end main Follow-Up Questions and Activities 1. What are the results of the following expressions? 24 / 5 = 18 % 3 = 13 % 9 = 13 / 2 % 2 = 4 0 4 0 2. What happens when the user inputs a number which has fewer than five digits? Why? What is the output when 1763 is entered? If the user inputs a number which has fewer than five digits, then the missing digits (the leftmost digits) are displayed as 0. This is because any number with fewer than five digits must be less than 10000 so dividing by 10000 will result in 0. Thus when 1763 is entered, the output is: 0 1 7 6 3. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 32 Introduction to C++ Programming Chapter 2 Lab Exercises Lab Exercise 3 Separating Digits Name: 3. The program you completed in this lab exercise inputs a number with multiple digits and separates the digits. Write the inverse program, a program which asks the user for three one-digit numbers and combines them into a single three-digit number. [Hint: Use multiplication and addition to form the three-digit number.] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // Lab 3: digits.cpp #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::endl; // program uses endl using std::cin; // program uses cin int main() { int number; int digit1; int digit2; int digit3; // // // // three-digit number hundred's digit ten's digit one's digit the hundred's digit: "; // prompt // read digit from user the ten's digit: "; // prompt // read digit from user the one's digit: "; // prompt // read digit from user cout << "Enter cin >> digit1; cout << "Enter cin >> digit2; cout << "Enter cin >> digit3; number = digit3; // start with just the one's digit number = number + digit2 * 10; // add the ten's digit * 10 number = number + digit1 * 100; // add the hundred's digit *100 cout << number << endl; return 0; // indicate successful termination } // end main Enter the hundreds digit: 4 Enter the tens digit: 2 Enter the ones digit: 7 427 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 33 Lab Exercises Debugging Debugging Name: Name: Section: Date: The program in this section does not run properly. Fix all the syntax errors so that the program will compile successfully. Once the program compiles, compare the output with the sample output, and eliminate any logic errors that may exist. The sample output demonstrates what the programs output should be once the programs code has been corrected. debugging02.cpp (Fig. L 2.7) is available at www.deitel.com and at www.prenhall.com/deitel. Sample Output Enter two integers to compare: 5 2 5 != 2 5 > 2 5 >= 2 Enter two integers to compare: 2 7 2 != 7 2 < 7 2 <= 7 Enter two integers to compare: 4 4 4 == 4 4 <= 4 4 >= 4 Broken Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // Debugging include <iostream> using std::cout; using std::endl; using std::cin; int main() { int number1; int number2; cout << "Enter two integers to compare: "; cout >> number1 >> number2; Fig. L 2.7 | debugging02.cpp. (Part 1 of 2.) 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 34 Introduction to C++ Programming Chapter 2 Lab Exercises Debugging Name: 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 if ( number1 == number2 ) cout << number1 << ' == ' << number2 << endl; if ( number1 <> number2 ) cout << number1 << " <> " << number2 << endl; if ( number2 < number1 ) cout << number1 << " < " << number2 << endl; if number1 > number2 ) cout << number1 << " > " << number2 << endl; if ( number1 < number2 ) cout << number1 << " <= " << number2 << endl; if ( number1 >= number2 ) cout << number1 << " >= " << number2 << endl return 0; } // end main debugging02.cpp. Fig. L 2.7 | (Part 2 of 2.) Debugging Solution 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // Debugging #include <iostream> using std::cout; using std::endl; using std::cin; int main() { int number1; int number2; cout << "Enter two integers to compare: "; cin >> number1 >> number2; if ( number1 == number2 ) cout << number1 << " == " << number2 << endl; if ( number1 != number2 ) cout << number1 << " != " << number2 << endl; if ( number1 < number2 ) cout << number1 << " < " << number2 << endl; if ( number1 > number2 ) cout << number1 << " > " << number2 << endl; if ( number1 <= number2 ) cout << number1 << " <= " << number2 << endl; 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 35 Lab Exercises Debugging Name: 31 32 33 34 35 36 37 if ( number1 >= number2 ) cout << number1 << " >= " << number2 << endl; return 0; } // end main Errors: Line 2: The program must #include the iostream header file. Line 15: Input from the keyboard requires the use of cin not cout. Line 18: A string literal must be enclosed with double-quotes ("); single-quotes (') can only be used for a single character literal. Lines 2021: The inequality operator is !=, not <>. Line 23: number2 and number1 were switched in the less than conditional expression. Line 26: The left parentheses in the if condition was missing. Line 29: The < should be <= to match the cout statement on the next line. Line 33: Every statement must end with a semicolon. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. 2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Chapter 2 Introduction to C++ Programming 37 Postlab Activities Coding Exercises Name: Section: Date: These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. They serve as a review after you have completed the Prelab Act...

cpphtp5LM_02_IM

End of Preview

Sign up now to access the rest of the document