46
2 Introduction to C++ Programming —Aristophanes 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.

Introd to C++ Progr mming - CAS – Central Authentication ...my.fit.edu/~vkepuska/ece4553/courses/multi1/cpphtp5LM_02...Prelab Activities Name: Programming Output Chapter 2 Introduction

  • Upload
    hakiet

  • View
    221

  • Download
    2

Embed Size (px)

Citation preview

2Introductionto C++Programming

—Aristophanes

O B J E C T I V E SIn 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.

Chapter 2 Introduction to C++ Programming 3

Name: Date:

Section:

Assignment Checklist

Exercises Assigned: Circle assignments Date Due

Prelab Activities

Matching YES NO

Fill in the Blank 14, 15, 16, 17, 18, 19, 20, 21, 22,23, 24, 25

Short Answer 26, 27, 28, 29, 30, 31, 32

Programming Output 33, 34, 35, 36, 37, 38, 39

Correct the Code 40, 41, 42, 43, 44, 45

Lab Exercises

Exercise 1 — Sum, Average, Product, Smallest and Largest

YES NO

Follow-Up Questions and Activities 1, 2

Exercise 2 — Multiples YES NO

Follow-Up Questions and Activities 1, 2, 3, 4

Exercise 3 — Separating Digits YES NO

Follow-Up Questions and Activities 1, 2, 3

Debugging YES NO

Labs Provided by Instructor

1.

2.

3.

Postlab Activities

Coding Exercises 1, 2, 3, 4, 5, 6, 7

Programming Challenges 1, 2, 3

Chapter 2 Introduction to C++ Programming 5

Prelab Activities

Name: Date:

Section:

Matching

After reading Chapter 2 of C++ How to Program: Fifth Edition, answer the given questions. These questions areintended to test and reinforce your understanding of key concepts and may be done either before the lab or dur-ing the lab.

For each term in the column on the left, write the corresponding letter for the description that best matches itfrom the column on the right.

Term Description

D

H

I

G

A

L

J

E

B

C

M

K

F

1. Integer division

2. Stream extraction operator

3. return

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

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 itsresult.

e) Instruction that is performed before the program iscompiled.

f) Prevents a program from compiling.

g) An operation that yields the remainder after integerdivision.

h) >>.

i) One of several means to exit a function.

j) <<.

k) '\n'.

l) Text that documents programs and improves theirreadability.

m) Commonly formed by using equality operators andrelational operators.

Prelab Activities Name:

Fill in the Blank

Chapter 2 Introduction to C++ Programming 7

Name: Date:

Section:

Fill in the Blank

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 computer’s 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. cin represents the standard input stream.

22. cout represents the standard output stream.

23. The if statement allows a program to make a decision.

24. C++ evaluates arithmetic expressions in a precise sequence determined by the rules of operatorprecedence and associativity.

25. Equality operators and relational operators can be used in if conditions.

Prelab Activities Name:

Short Answer

Chapter 2 Introduction to C++ Programming 9

Name: Date:

Section:

Short Answer

In the space provided, answer each of the given questions. Your answers should be as concise as possible; aim fortwo 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 dis-play data on the screen. Stream extraction is used to extract characters and values from a stream, such as the stan-dard 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 accompaniedby error messages from the compiler to help the programmer locate and fix the incorrect code. The programcannot be executed until all syntax errors are corrected. Some examples of syntax errors include forgetting thesemicolon at the end of a statement, placing two variable identifiers next to each other without an interveningoperator 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 exe-cuting. A logic error will not be reported by the compiler. Some examples of logic errors include using the incor-rect variable in a calculation, using the assignment operator = instead of the equality operator == and spelling aword 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 exe-cute. For example, multiplication operations execute before addition operations, unless the addition operationsare enclosed within parentheses. Associativity is the order in which multiple operations with the same precedenceexecute. For example, addition operations are performed from left to right, while assignment operations are per-formed from right to left. Operator precedence and associativity determine the order in which operations executeand 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 execu-tion for the operations in that arithmetic expression. A programmer might use redundant parentheses to makethe order of execution of the expression more clear. For example, parentheses could be placed around the mul-tiplication operations in an arithmetic expression containing both multiplication and addition operations, eventhough the multiplication operations would be performed first anyway.

Prelab Activities Name:

Short Answer

10 Introduction to C++ Programming Chapter 2

31. Write an example of a preprocessor directive.

#include <iostream>

32. What is a variable? How are they used in computer programs?

A variable is a location in the computer’s memory. Variables enable a computer program to store values, possiblythe results of earlier calculations, for use later later in the program.

Prelab Activities Name:

Programming Output

Chapter 2 Introduction to C++ Programming 11

Name: Date:

Section:

Programming Output

For each of the given program segments, read the code and write the output in the space provided below eachprogram. [Note: Do not execute these programs on a computer.]

33. What is the output of the following program?

Your answer:

34. What is output by the following line of code?

Your answer:

1 #include <iostream>23 using std::cout;4 using std::endl;56 int main()7 {8 int x;9 int y;

1011 x = 30;12 y = 2;13 cout << x * y + 9 / 3 << endl;1415 return 0;1617 } // end main

63

1 cout << ( 8 * 4 * 2 + 6 ) / 2 + 4;

39

Prelab Activities Name:

Programming Output

12 Introduction to C++ Programming Chapter 2

For Programming Output Exercises 35 and 36, use the program in Fig. L 2.1.

35. What is output by the program in Fig. L 2.1? Assume that the user enters 5 for input.

Your answer:

36. What is output by the program in Fig. L 2.1? Assume that the user enters 7 for input.

Your answer:

1 #include <iostream>23 using std::cout;4 using std::cin;5 using std::endl;67 int main()8 {9 int input;

1011 cout << "Please enter an integer: ";12 cin >> input; 1314 if ( input != 7 )15 cout << "Hello" << endl;1617 if ( input == 7 )18 cout << "Goodbye" << endl;1920 return 0;2122 } // end main

Fig. L 2.1 | Program used for Programming Output Exercises 35 and 36.

Hello

Goodbye

Prelab Activities Name:

Programming Output

Chapter 2 Introduction to C++ Programming 13

For Programming Output Exercises 37 and 38, use the program in Fig. L 2.2.

37. What is output by the program in Fig. L 2.2? Assume the user enters 2 for input.

Your answer:

38. What is output by the program in Fig. L 2.2? Assume the user enters -2 for input.

Your answer:

1 #include <iostream>23 using std::cout;4 using std::cin;5 using std::endl;67 int main()8 {9 int input;

1011 cout << "Please enter an integer: ";12 cin >> input; 1314 if ( input >= 0 )15 cout << "Hello" << endl;1617 cout << "Goodbye" << endl;1819 return 0;2021 } // end main

Fig. L 2.2 | Program used for Programming Output Exercises 37 and 38.

HelloGoodbye

Goodbye

Prelab Activities Name:

Programming Output

14 Introduction to C++ Programming Chapter 2

39. What is output by the following program?

Your answer:

1 #include <iostream>23 using std::cout;4 using std::cin;5 using std::endl;67 int main()8 {9 int x = 3;

10 int y = 9;11 int z = 77;1213 if ( x == ( y / 3 ) )14 cout << "H";1516 if ( z != 77 )17 cout << "q";1819 if ( z == 77 )20 cout << "e";2122 if ( z * y + x < 0 )23 cout << "g";2425 if ( y == ( x * x ) )26 cout << "ll";2728 cout << "o!" << endl;2930 return 0;3132 } // end main

Hello!

Prelab Activities Name:

Correct the Code

Chapter 2 Introduction to C++ Programming 15

Name: Date:

Section:

Correct the Code

For each of the given program segments, determine if there is an error in the code. If there is an error, specifywhether it is a logic, syntax or compilation error, circle the error in the code and write the corrected code in thespace 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 pos-sible that a program segment may contain multiple errors.]

40. The following program should print an integer to the screen:

Your answer:

Errors:

• Line 1: There should not be a semicolon after a #include preprocessor directive. Compilation error.

• Lines 3–4: There should be semicolons after using directives. Compilation error.

1 #include <iostream>;23 using std::cout4 using std::endl56 int main()7 {8 int x = 30;9 int y = 2;

1011 cout << x * y + 9 / 3 << endl;1213 return 0;1415 } // end main

123 using std::cout4 using std::endl56 int main()7 {8 int x = 30;9 int y = 2;

1011 cout << x * y + 9 / 3 << endl;1213 return 0;1415 } // end main

#include <iostream>

;;

Prelab Activities Name:

Correct the Code

16 Introduction to C++ Programming Chapter 2

41. The following code should declare an integer variable and assign it the value 6.

Your answer:

Errors:

• Lines 1–2: Variable names cannot begin with digits. The name of the variable must be changed. Com-pilation 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.

Your answer:

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 int 1stPlace2 1stPlace = 6;

1 int2 = 6;

1 int x = 9;23 if ( x < = 9 )4 cout << "Less than or equal to.";

1 int x = 9;23 if ( x 9 )4 cout << "Less than or equal to.";

1 int q = 10;23 cout << "q is: " << q << endl;45 if ( q = 10 )6 cout << "q is equal to 10";

firstPlace;firstPlace

<=

Prelab Activities Name:

Correct the Code

Chapter 2 Introduction to C++ Programming 17

Your answer:

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 variable’s value is greater than zero anddisplay an appropriate message.

Your answer:

Error:

• Line 3: Placing a semicolon after the if statement’s condition causes the messsage "Greater than ze-

ro" to display even if the condition is false. Logic error.

1 int q = 10;23 cout << "q is: " << q << endl;45 if ( q 10 )6 cout << "q is equal to 10";

1 int x = 9;23 if ( x > 0 );4 cout << "Greater than zero";

1 int x = 9;23 if ( x > 0 )4 cout << "Greater than zero";

==

Prelab Activities Name:

Correct the Code

18 Introduction to C++ Programming Chapter 2

45. The following program should print 302 to the screen:

Your answer:

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.

1 #include <iostream>23 using std::cout;4 using std::end;56 int ma in()7 {8 int x = 30;9 int y = 2;

1011 cout << y << x << endl;1213 return 0;1415 } // end main

1 #include <iostream>23 using std::cout;4 using std:: ;56 int ()7 {8 int x = 30;9 int y = 2;

1011 cout << << << endl;1213 return 0;1415 } // end main

endl

main

x y

Chapter 2 Introduction to C++ Programming 19

Lab Exercises

Name: Date:

Section:

Lab Exercise 1 — Sum, Average, Product, Smallest and Largest

This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. Theproblem 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 replacedwith 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 theprogram. Compare your output with the sample output provided. Then answer the follow-up questions. Thesource code for the template is available at www.deitel.com and www.prenhall.com./deitel.

Lab ObjectivesThis lab was designed to reinforce programming concepts from Chapter 2 of C++ How To Program: Fifth Edi-tion. 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.

The follow-up questions and activities also will give you practice:

• Comparing < to <=.

• Modifying existing code to perform the same task in a different manner.

Description of the ProblemWrite a program that inputs three integers from the keyboard, and prints the sum, average, product, smallestand largest of these numbers. The screen dialogue should appear as follows: [Note: 13, 27 and 14 are input bythe user.]

Sample Output

Input three different integers: 13 27 14Sum is 54Average is 18Product is 4914Smallest is 13Largest is 27

Lab Exercises Name:

Lab Exercise 1 — Sum, Average, Product, Smallest and Largest

20 Introduction to C++ Programming Chapter 2

Template

Problem-Solving Tips1. 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 as-sume number1 is the largest of the three values and assign it to largest. You will use if statements todetermine whether number2 or number3 are larger.

3. Using an if statement, compare largest to number2. If the content of number2 is larger, then store thevariable’s value in largest.

4. Using an if statement, compare largest to number3. If the content of number3 is larger, then store thevariable’s value in largest. At this point you are guaranteed to have the largest value stored in largest.

1 // Lab 1: numbercompare.cpp2 #include <iostream> // allows program to perform input and output34 using std::cout; // program uses cout5 using std::endl; // program uses endl6 using std::cin; // program uses cin78 int main()9 {

10 int number1; // first integer read from user11 int number2; // second integer read from user12 int number3; // third integer read from user13 int smallest; // smallest integer read from user14 int largest; // largest integer read from user1516 cout << "Input three different integers: "; // prompt17 /* Write a statement to read in values for number1, number2 and18 number3 using a single cin statement */1920 largest = number1; // assume first integer is largest2122 /* Write a statement to determine if number2 is greater than23 largest. If so assign number2 to largest */2425 /* Write a statement to determine if number3 is greater than26 largest. If so assign number3 to largest */2728 smallest = number1; // assume first integer is smallest2930 /* Write a statement to determine if number2 is less than31 smallest. If so assign number2 to smallest */3233 /* Write a statement to determine if number3 is less than34 smallest. If so assign number3 to smallest */3536 /* Write an output statement that prints the sum, average,37 product, largest and smallest */3839 return 0; // indicate successful termination4041 } // end main

Fig. L 2.3 | numbercompare.cpp.

Lab Exercises Name:

Lab Exercise 1 — Sum, Average, Product, Smallest and Largest

Chapter 2 Introduction to C++ Programming 21

5. Perform similar steps to those in Steps 2–4 to determine the smallest value.

6. Write a cout statement that outputs the sum, average, product (i.e., multiplication), largest and smallestvalues.

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 // Lab 1: numbercompare.cpp2 #include <iostream> // allows program to perform input and output34 using std::cout; // program uses cout5 using std::endl; // program uses endl6 using std::cin; // program uses cin78 int main()9 {

10 int number1; // first integer read from user11 int number2; // second integer read from user12 int number3; // third integer read from user13 int smallest; // smallest integer read from user14 int largest; // largest integer read from user1516 cout << "Input three different integers: "; // prompt17 cin >> number1 >> number2 >> number3; // read three integers1819 largest = number1; // assume first integer is largest2021 if ( number2 > largest ) // is number2 larger?22 largest = number2; // number2 is now the largest2324 if ( number3 > largest ) // is number3 larger?25 largest = number3; // number3 is now the largest2627 smallest = number1; // assume first integer is smallest2829 if ( number2 < smallest ) // is number2 smaller?30 smallest = number2; // number2 is now the smallest3132 if ( number3 < smallest ) // is number3 smaller?33 smallest = number3; // number3 is now the smallest3435 cout << "Sum is " << number1 + number2 + number3 36 << "\nAverage is " << ( number1 + number2 + number3 ) / 337 << "\nProduct is " << number1 * number2 * number338 << "\nSmallest is " << smallest39 << "\nLargest is " << largest << endl;4041 return 0; // indicate successful termination4243 } // end main

Lab Exercises Name:

Lab Exercise 1 — Sum, Average, Product, Smallest and Largest

22 Introduction to C++ Programming Chapter 2

Follow-Up Questions and Activities1. Modify your solution to use three separate cin statements rather than one. Write a separate prompt for each

cin.

1 // Lab 1: numbercompare.cpp2 #include <iostream> // allows program to perform input and output34 using std::cout; // program uses cout5 using std::endl; // program uses endl6 using std::cin; // program uses cin78 int main()9 {

10 int number1; // first integer read from user11 int number2; // second integer read from user12 int number3; // third integer read from user13 int smallest; // smallest integer read from user14 int largest; // largest integer read from user1516 cout << "Input first integer: "; // prompt17 cin >> number1; // read an integer18 cout << "Input second integer: "; // prompt19 cin >> number2; // read a second integer20 cout << "Input third integer: "; // prompt21 cin >> number3; // read a third integer2223 largest = number1; // assume first integer is largest2425 if ( number2 > largest ) // is number2 larger?26 largest = number2; // number2 is now the largest2728 if ( number3 > largest ) // is number3 larger?29 largest = number3; // number3 is now the largest3031 smallest = number1; // assume first integer is smallest3233 if ( number2 < smallest ) // is number2 smaller?34 smallest = number2; // number2 is now the smallest3536 if ( number3 < smallest ) // is number3 smaller?37 smallest = number3; // number3 is now the smallest3839 cout << "Sum is " << number1 + number2 + number3 40 << "\nAverage is " << ( number1 + number2 + number3 ) / 341 << "\nProduct is " << number1 * number2 * number342 << "\nSmallest is " << smallest43 << "\nLargest is " << largest << endl;4445 return 0; // indicate successful termination4647 } // end main

Lab Exercises Name:

Lab Exercise 1 — Sum, Average, Product, Smallest and Largest

Chapter 2 Introduction to C++ Programming 23

2. Does it matter whether < or <= is used when making comparisons to determine the smallest integer? Whichdid you use and why?

In this program, it does not matter whether < or <= is used when making comparisons to determine the smallestinteger. The only instance when using < as opposed to <= makes a difference is if smallest and the number it isbeing compared to are equal, in which case either value can be used as the smallest with the same result.

Input first integer: 13Input second integer: 27Input third integer: 14Sum is 54Average is 18Product is 4914Smallest is 13Largest is 27

Lab Exercises Name:

Lab Exercise 2 — Multiples

Chapter 2 Introduction to C++ Programming 25

Name: Date:

Section:

Lab Exercise 2 — Multiples

This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. Theproblem 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 replacedwith 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 theprogram. Compare your output with the sample output provided. Then answer the follow-up questions. Thesource code for the template is available at www.deitel.com and www.prenhall.com./deitel.

Lab ObjectivesThis lab was designed to reinforce programming concepts from Chapter 2 of C++ How To Program: Fifth Edi-tion. 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.

The follow-up questions and activities also will give you practice:

• Understanding the modulus operator.

• Recognizing common mistakes with the if statement.

• Adapting a program to solve a similar problem.

Description of the ProblemWrite 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.]

Sample Output

Enter two integers: 22 822 is not a multiple of 8

Lab Exercises Name:

Lab Exercise 2 — Multiples

26 Introduction to C++ Programming Chapter 2

Template

Problem-Solving Tips1. 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 numberinput. Use the modulus operator, %. If one number divides into another evenly, the modulus operationresults in 0. If the result is 0, display a message indicating that the first number is a multiple of the secondnumber.

4. Use an if statement to determine whether the first number input is not a multiple of the second numberinput. If one number does not divide into another evenly, the modulus operation results in a non-zerovalue. 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 // Lab 2: multiples.cpp2 #include <iostream> // allows program to perform input and output34 using std::cout; // program uses cout5 using std::endl; // program uses endl6 using std::cin; // program uses cin78 int main()9 {

10 /* Write variables declarations here */1112 cout << "Enter two integers: "; // prompt13 /* Write a cin statement to read data into variables here */1415 // using modulus operator16 if ( /* Write a condition that tests whether number1 is a multiple of17 number2 */)18 cout << number1 << " is a multiple of " << number2 << endl;1920 if ( /* Write a condition that tests whether number1 is not a multiple21 of number2 */ )22 cout << number1 << " is not a multiple of " << number2 << endl;2324 return 0; // indicate successful termination2526 } // end main

Fig. L 2.4 | multiples.cpp.

1 // Lab 2: multiples.cpp2 #include <iostream> // allows program to perform input and output34 using std::cout; // program uses cout5 using std::endl; // program uses endl6 using std::cin; // program uses cin

Lab Exercises Name:

Lab Exercise 2 — Multiples

Chapter 2 Introduction to C++ Programming 27

Follow-Up Questions and Activities1. Can the modulus operator be used with non-integer operands? Can it be used with negative numbers? As-

sume that the user entered the sets of numbers in Fig. L 2.5. For each set, what does the expression in thethird column output? If there is an error, explain why.

The modulus operator cannot be used with non-integer operands. It can be used with negative numbers. Anerror occurs in cout << 100 % 0; because you cannot divide by 0. An error occurs in cout << 9 % 4.5; becauseyou cannot use modulus with a double value.

78 int main()9 {

10 int number1; // first integer read from user11 int number2; // second integer read from user1213 cout << "Enter two integers: "; // prompt14 cin >> number1 >> number2; // read two integers from user1516 // using modulus operator17 if ( number1 % number2 == 0 )18 cout << number1 << " is a multiple of " << number2 << endl;1920 if ( number1 % number2 != 0 )21 cout << number1 << " is not a multiple of " << number2 << endl;2223 return 0; // indicate successful termination2425 } // end main

Integer 1 Integer 2 Expression Output

73 22 cout << 73 % 22; 7

0 100 cout << 0 % 100; 0

100 0 cout << 100 % 0; error

—3 3 cout << -3 % 3; 0

9 4.5 cout << 9 % 4.5; error

16 2 cout << 16 % 2; 0

Fig. L 2.5 | Determine the output of the cout statements in the third column.

Lab Exercises Name:

Lab Exercise 2 — Multiples

28 Introduction to C++ Programming Chapter 2

2. Place a semicolon at the end of the if statement in your solution that corresponds to the if statement inlines 16–18 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 state-ment and is considered to be the if’s body. The output statement is just another statement that will execute afterthe if statement executes.

3. Rewrite the cout statement in your solution that corresponds to the cout statement in line 18 in the tem-plate. 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 secondand 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 toenter only one number.]

1 // Lab 2: multiples.cpp2 #include <iostream> // allows program to perform input and output34 using std::cout; // program uses cout5 using std::endl; // program uses endl6 using std::cin; // program uses cin78 int main()9 {

10 int number; // integer read from user1112 cout << "Enter an integer: "; // prompt13 cin >> number; // read an integer from user1415 // using modulus operator16 if ( number % 2 == 0 )17 cout << number1 << " is even" << endl;1819 if ( number % 2 != 0 )20 cout << number1 << " is odd" << endl;2122 return 0; // indicate successful termination2324 } // end main

Enter an integer: 1212 is even

Lab Exercises Name:

Lab Exercise 3 — Separating Digits

Chapter 2 Introduction to C++ Programming 29

Name: Date:

Section:

Lab Exercise 3 — Separating Digits

This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. Theproblem 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 replacedwith 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 theprogram. Compare your output with the sample output provided. Then answer the follow-up questions. Thesource code for the template is available at www.deitel.com and www.prenhall.com./deitel.

Lab ObjectivesThis lab was designed to reinforce programming concepts from Chapter 2 of C++ How To Program: Fifth Edi-tion. 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 deci-mal portion of the result.

The follow-up questions and activities also will give you practice:

• 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.

Problem DescriptionWrite a program that inputs a five-digit number, separates the number into its individual digits and prints thedigits 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.

Sample Output

4 2 3 3 9

Lab Exercises Name:

Lab Exercise 3 — Separating Digits

30 Introduction to C++ Programming Chapter 2

Template

Problem-Solving Tips1. 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 input—not 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. Whydoes this work? Because the number input is five digits long, it is divided by 10000 to obtain the left-most 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 eval-uates to the integer remainder—in this case, the right-most four digits. For example, 42339 % 10000 re-sults in 2339. Assign the result of this modulus operation to the variable that stores the five-digit numberinput.

1 // Lab 3: digits.cpp2 #include <iostream> // allows program to perform input and output34 using std::cout; // program uses cout5 using std::endl; // program uses endl6 using std::cin; // program uses cin78 int main()9 {

10 int number; // integer read from user1112 cout << "Enter a five-digit integer: "; // prompt13 cin >> number; // read integer from user1415 /* Write a statement to print the left-most digit of the16 5-digit number */ 17 /* Write a statement that changes number from 5-digits 18 to 4-digits */19 /* Write a statement to print the left-most digit of the20 4-digit number */21 /* Write a statement that changes number from 4-digits22 to 3-digits */23 /* Write a statement to print the left-most digit of the24 3-digit number */25 /* Write a statement that changes number from 3-digits26 to 2-digits */27 /* Write a statement to print the left-most digit of the28 2-digit number */29 /* Write a statement that changes number from 2-digits 30 to 1-digit */31 cout << number << endl;3233 return 0; // indicate successful termination3435 } // end main

Fig. L 2.6 | digits.cpp.

Lab Exercises Name:

Lab Exercise 3 — Separating Digits

Chapter 2 Introduction to C++ Programming 31

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 num-ber 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

Follow-Up Questions and Activities1. What are the results of the following expressions?

24 / 5 = 4

18 % 3 = 0

13 % 9 = 4

13 / 2 % 2 = 0

2. What happens when the user inputs a number which has fewer than five digits? Why? What is the outputwhen 1763 is entered?

If the user inputs a number which has fewer than five digits, then the missing digits (the leftmost digits) aredisplayed as 0. This is because any number with fewer than five digits must be less than 10000 so dividing by10000 will result in 0. Thus when 1763 is entered, the output is: 0 1 7 6 3.

1 // Lab 3: digits.cpp2 #include <iostream> // allows program to perform input and output34 using std::cout; // program uses cout5 using std::endl; // program uses endl6 using std::cin; // program uses cin78 int main()9 {

10 int number; // integer read from user1112 cout << "Enter a five-digit integer: "; // prompt13 cin >> number; // read integer from user1415 cout << number / 10000 << " ";16 number = number % 10000;17 cout << number / 1000 << " ";18 number = number % 1000;19 cout << number / 100 << " ";20 number = number % 100;21 cout << number / 10 << " ";22 number = number % 10;23 cout << number << endl;2425 return 0; // indicate successful termination2627 } // end main

Lab Exercises Name:

Lab Exercise 3 — Separating Digits

32 Introduction to C++ Programming Chapter 2

3. The program you completed in this lab exercise inputs a number with multiple digits and separates the dig-its. Write the inverse program, a program which asks the user for three one-digit numbers and combinesthem into a single three-digit number. [Hint: Use multiplication and addition to form the three-digit num-ber.]

1 // Lab 3: digits.cpp2 #include <iostream> // allows program to perform input and output34 using std::cout; // program uses cout5 using std::endl; // program uses endl6 using std::cin; // program uses cin78 int main()9 {

10 int number; // three-digit number11 int digit1; // hundred's digit12 int digit2; // ten's digit13 int digit3; // one's digit1415 cout << "Enter the hundred's digit: "; // prompt16 cin >> digit1; // read digit from user17 cout << "Enter the ten's digit: "; // prompt18 cin >> digit2; // read digit from user19 cout << "Enter the one's digit: "; // prompt20 cin >> digit3; // read digit from user2122 number = digit3; // start with just the one's digit23 number = number + digit2 * 10; // add the ten's digit * 1024 number = number + digit1 * 100; // add the hundred's digit *1002526 cout << number << endl;2728 return 0; // indicate successful termination2930 } // end main

Enter the hundred’s digit: 4Enter the ten’s digit: 2Enter the one’s digit: 7427

Lab Exercises Name:

Debugging

Chapter 2 Introduction to C++ Programming 33

Name: Date:

Section:

Debugging

The program in this section does not run properly. Fix all the syntax errors so that the program will compile suc-cessfully. Once the program compiles, compare the output with the sample output, and eliminate any logic errorsthat may exist. The sample output demonstrates what the program’s output should be once the program’s code hasbeen corrected. debugging02.cpp (Fig. L 2.7) is available at www.deitel.com and at www.prenhall.com/deitel.

Sample Output

Broken Code

Enter two integers to compare: 5 25 != 25 > 25 >= 2

Enter two integers to compare: 2 72 != 72 < 72 <= 7

Enter two integers to compare: 4 44 == 44 <= 44 >= 4

1 // Debugging2 include <iostream>34 using std::cout;5 using std::endl;6 using std::cin;78 int main()9 {

1011 int number1;12 int number2;1314 cout << "Enter two integers to compare: ";15 cout >> number1 >> number2;16

Fig. L 2.7 | debugging02.cpp. (Part 1 of 2.)

Lab Exercises Name:

Debugging

34 Introduction to C++ Programming Chapter 2

Debugging Solution

17 if ( number1 == number2 )18 cout << number1 << ' == ' << number2 << endl;1920 if ( number1 <> number2 )21 cout << number1 << " <> " << number2 << endl;2223 if ( number2 < number1 )24 cout << number1 << " < " << number2 << endl;2526 if number1 > number2 )27 cout << number1 << " > " << number2 << endl;2829 if ( number1 < number2 )30 cout << number1 << " <= " << number2 << endl;3132 if ( number1 >= number2 )33 cout << number1 << " >= " << number2 << endl3435 return 0; 3637 } // end main

1 // Debugging2 include <iostream>34 using std::cout;5 using std::endl;6 using std::cin;78 int main()9 {

1011 int number1;12 int number2;1314 cout << "Enter two integers to compare: ";15 >> number1 >> number2;1617 if ( number1 == number2 )18 cout << number1 << == << number2 << endl;1920 if ( number1 number2 )21 cout << number1 << " " << number2 << endl;2223 if ( < )24 cout << number1 << " < " << number2 << endl;2526 if number1 > number2 )27 cout << number1 << " > " << number2 << endl;2829 if ( number1 < number2 )30 cout << number1 << " <= " << number2 << endl;

Fig. L 2.7 | debugging02.cpp. (Part 2 of 2.)

#

cin

" "

!=!=

number1 number2

(

=

Lab Exercises Name:

Debugging

Chapter 2 Introduction to C++ Programming 35

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 fora single character literal.

• Lines 20–21: 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.

3132 if ( number1 >= number2 )33 cout << number1 << " >= " << number2 << endl3435 return 0; 3637 } // end main

;

Chapter 2 Introduction to C++ Programming 37

Postlab Activities

Name: Date:

Section:

Coding Exercises

These coding exercises reinforce the lessons learned in the lab and provide additional programming experienceoutside the classroom and laboratory environment. They serve as a review after you have completed the PrelabActivities and Lab Exercises successfully.

For each of the following problems, write a program or a program segment that performs the specified action.

1. Write the preprocessor directive which includes the iostream file in a program. Also write the appropriateusing directives for cin, cout and endl.

2. Define a main function which declares three integer variables. Remember to terminate the main functionwith a return statement.

1 #include <iostream>23 using std::cin;4 using std::cout;5 using std::endl;

1 #include <iostream>23 using std::cin;4 using std::cout;5 using std::endl;67 int main()8 {9 int number1;

10 int number2;11 int number3;1213 return 0;14 } // end main function

Postlab Activities Name:

Coding Exercises

38 Introduction to C++ Programming Chapter 2

3. Write a single line of code that reads values into the three integer variables from Coding Exercise 2.

4. Write a line of code that prints all three integer values from Coding Exercise 3 separated by hyphens, -.

1 #include <iostream>23 using std::cin;4 using std::cout;5 using std::endl;67 int main()8 {9 int number1;

10 int number2;11 int number3;1213 cin >> number1 >> number2 >> number3;1415 return 0;16 } // end main function

1 #include <iostream>23 using std::cin;4 using std::cout;5 using std::endl;67 int main()8 {9 int number1;

10 int number2;11 int number3;1213 cin >> number1 >> number2 >> number3;1415 cout << number1 << "-" << number2 << "-" << number3 << endl;1617 return 0;18 } // end main function

Postlab Activities Name:

Coding Exercises

Chapter 2 Introduction to C++ Programming 39

5. Modify your solution to Coding Exercise 4 to write a C++ program that determines which variable’s value isthe largest. Use variable largest to store the largest value.

6. Modify your solution to Coding Exercise 5 to write a C++ program that determines which integer variable’svalue is the smallest. Use variable smallest to store the smallest value.

1 #include <iostream>23 using std::cin;4 using std::cout;5 using std::endl;67 int main()8 {9 int number1;

10 int number2;11 int number3;1213 cin >> number1 >> number2 >> number3;1415 cout << number1 << "-" << number2 << "-" << number3 << endl;1617 int largest;1819 largest = number1;2021 if ( number2 > largest )22 largest = number2;2324 if ( number3 > largest )25 largest = number3;2627 return 0;28 } // end main function

1 #include <iostream>23 using std::cin;4 using std::cout;5 using std::endl;67 int main()8 {9 int number1;

10 int number2;11 int number3;1213 cin >> number1 >> number2 >> number3;1415 cout << number1 << "-" << number2 << "-" << number3 << endl;1617 int largest;1819 largest = number1;20

Postlab Activities Name:

Coding Exercises

40 Introduction to C++ Programming Chapter 2

7. Modify your solution to Coding Exercise 6 to test if any of the variable’s values are equal and if so print thatthey are equal. For example, if two variables have the same value, 5, print “5 and 5 are equal.”

21 if ( number2 > largest )22 largest = number2;2324 if ( number3 > largest )25 largest = number3;2627 int smallest;2829 smallest = number1;3031 if ( number2 < smallest )32 smallest = number2;3334 if ( number3 < smallest )35 smallest = number3;3637 return 0;38 } // end main function

1 #include <iostream>23 using std::cin;4 using std::cout;5 using std::endl;67 int main()8 {9 int number1;

10 int number2;11 int number3;1213 cin >> number1 >> number2 >> number3;1415 cout << number1 << "-" << number2 << "-" << number3 << endl;1617 int largest;1819 largest = number1;20 if ( number2 > largest )21 largest = number2;22 if ( number3 > largest )23 largest = number3;2425 int smallest;2627 smallest = number1;28

Postlab Activities Name:

Coding Exercises

Chapter 2 Introduction to C++ Programming 41

29 if ( number2 < smallest )30 smallest = number2;3132 if ( number3 < smallest )33 smallest = number3;3435 if ( number1 == number2 )36 cout << number1 << " and " << number2 << " are equal." << endl;3738 if ( number1 == number3 )39 cout << number1 << " and " << number3 << " are equal." << endl;4041 if ( number2 == number3 )42 cout << number2 << " and " << number3 << " are equal." << endl;4344 return 0;45 } // end main function

Postlab Activities Name:

Programming Challenges

Chapter 2 Introduction to C++ Programming 43

Name: Date:

Section:

Programming Challenges

The Programming Challenges are more involved than the Coding Exercises and may require a significant amountof time to complete. Write a C++ program for each of the problems in this section. The answers to these prob-lems are available at www.deitel.com and www.prenhall.com/deitel. Pseudocode, hints and/or sample outputsare provided to aid you in your programming.

1. Write a program that prints the numbers 1 to 4 on the same line with each pair of adjacent numbers sepa-rated by one space. Write the program using the following methods:

a) Using one output statement with one stream-insertion operator.

b) Using one output statement with four stream-insertion operators.

c) Using four output statements.

Hints:

• Use comments to separate your program into three clearly marked sections, one for each part (i.e., a–c)of the problem.

• For Part a) the entire output should be contained within one string.

• Use either endl or "\n" after each part to separate their output.

• Your output should look like:

Solution

1 2 3 41 2 3 41 2 3 4

1 // Programming Challenge 1: threeoutputs.cpp2 #include <iostream>34 using std::cin;5 using std::cout;6 using std::endl;78 int main()9 {

10 // part a - one output statement with one stream-insertion operator11 cout << "1 2 3 4\n";1213 // part b - one output statement with four stream-insertion operators14 cout << "1 " << "2 " << "3 " << "4\n";15

Postlab Activities Name:

Programming Challenges

44 Introduction to C++ Programming Chapter 2

2. Write a program that asks the user to enter two integers, obtains the numbers from the user, then prints thelarger number followed by the words “is larger.” If the numbers are equal, print the message “These num-

bers are equal.”

Hints:

• The user should input both integers at once, i.e., cin >> x >> y;

• Remember to print spaces after printing integers to the screen.

• A typical run of your program might look as follows:

Solution

16 // part c - four output statememts17 cout << "1 ";18 cout << "2 ";19 cout << "3 ";20 cout << "4\n";2122 return 0;23 } // end main function

Enter two integers: 5 35 is larger.

1 // Programming Challenge 2: larger.cpp2 #include <iostream>34 using std::cin;5 using std::cout;6 using std::endl;78 int main()9 {

10 int number1; // first input11 int number2; // second input1213 cout << "Enter two integers: "; // prompt14 cin >> number1 >> number2; // enter integers1516 if ( number1 > number2 ) // is number1 larger?17 cout << number1 << " is larger." << endl;1819 if ( number2 > number1 ) // is number2 larger?20 cout << number2 << " is larger." << endl;2122 if ( number1 == number2 ) // are they equal?23 cout << "These numbers are equal." << endl;2425 return 0;26 } // end main function

Postlab Activities Name:

Programming Challenges

Chapter 2 Introduction to C++ Programming 45

3. Write a program that reads in five integers and determines and prints the largest and the smallest integers inthe group. Use only the programming techniques you learned in Chapter 2 of C++ How to Program: FifthEdition.

Hints:

• This program requires seven variables: five for user input and two to store the largest and the smallest,respectively.

• As soon as the user inputs the values, assign the largest and smallest variables the value of the firstinput. If instead, largest was initially assigned to zero, this would be a logic error because negativenumbers could be input by the user.

• Ten separate if statements are required to compare each input to largest and smallest.

• A typical run of your program might look as follows:

Solution

Enter five integers: 2 4 -4 10 3Largest integer: 10Smallest integer: -4

1 // Programming Challenge 3: fiveintegers.cpp2 #include <iostream>34 using std::cin;5 using std::cout;6 using std::endl;78 int main()9 {

10 int number1; // first input11 int number2; // second input12 int number3; // third input13 int number4; // fourth input14 int number5; // fifth input15 int largest; // the largest integer16 int smallest; // the smallest integer1718 cout << "Enter five integers: "; // prompt19 cin >> number1 >> number2 >> number3 >> number4 >> number5; // read integers2021 largest = number1; // first assume that number1 is the largest22 smallest = number1; // first assume that number1 is the smallest2324 if ( number2 > largest ) // is number2 larger?25 largest = number2;2627 if ( number2 < smallest ) // is number2 smaller?28 smallest = number2;2930 if ( number3 > largest ) // is number3 larger?31 largest = number3;32

Postlab Activities Name:

Programming Challenges

46 Introduction to C++ Programming Chapter 2

33 if ( number3 < smallest ) // is number3 smaller?34 smallest = number3;3536 if ( number4 > largest ) // is number4 larger?37 largest = number4;3839 if ( number4 < smallest ) // is number4 smaller?40 smallest = number4;4142 if ( number5 > largest ) // is number5 larger?43 largest = number5;4445 if ( number5 < smallest ) // is number5 smaller?46 smallest = number5;4748 cout << "Largest integer: " << largest << endl;49 cout << "Smallest integer: " << smallest << endl;5051 return 0;52 } // end main function