Introduction to Programming with C++ Student Lecture Workbook Andi Toce Last update: Sunday 26th March, 2023 Contents I Part One - MAC 101 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.1 What is Computer Science? 1.2 What is Programming? 10 1.3 Getting Started with C++ 11 1.4 Practice Questions 14 2 Numbers at Different Bases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.1 Storing Information in the Computer 17 2.2 Converting Binary, Octal and Hexadecimal to Decimal 18 2.3 Converting Decimal Numbers to Other Bases 20 2.4 Conversion Between Binary, Octal and Hexadecimal 21 2.5 Addition and Subtraction of Numbers at Different Bases 22 2.6 Practice Questions 24 3 Data Types and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3.1 C++ Syntax Tokens 27 3.2 Primitive Data Types 29 3.3 Arithmetic Operations 31 3.4 Practice Questions 34 9 4 Selection Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.1 Relational and Comparison Operators 43 4.2 if and if-else Statements 43 4.3 The Nested if-else Statements 46 4.4 The switch Statement 47 4.5 Logical Operators 49 4.6 Practice Questions 51 5 Repetitions Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 5.1 C++ Loops. The while and do. . . while Statement. 59 5.2 The for loop 61 5.3 The break and continue Statements 64 5.4 Practice Questions 65 6 Functions and Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 6.1 What are Functions? 75 6.2 Passing a Parameter by Value or by Reference 80 6.3 Default Function Arguments 82 6.4 Function Overloading 83 6.5 Practice Questions 84 7 Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 7.1 Local and Global Variables 93 7.2 Default and Static Variables 94 7.3 Pre-defined Functions 95 7.4 Practice Questions 98 8 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 8.1 What are Arrays 101 8.2 Initializing Arrays 102 8.3 Array Size 105 8.4 Passing Arrays to Functions 106 8.5 Characters, Strings and Arrays of Strings 108 8.6 Multi-Dimensional Arrays 109 8.7 Practice Questions 111 9 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 9.1 What are Pointers? 121 9.2 Arrays and Pointer Arithmetic 122 10 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 10.1 What are Structures? 125 10.2 Structure Composition 127 10.3 Arrays of Structures 128 10.4 Passing Structures to Functions 129 11 Introduction to Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 11.1 Objects 131 11.2 Classes 132 11.3 The First Example 132 12 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 12.1 How C++ Stores Text? 135 12.2 C-style String Functions 137 12.3 The <string> Class 138 13 Basic Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 13.1 Sorting Algorithms II 143 Part Two - MAC 125 14 Classes and Objects (continued...) . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 14.1 Constructors 150 14.2 Destructors 152 14.3 Separating Content in Different Files 153 14.4 Constant Objects 155 14.5 Member Initializers 156 14.6 Class Composition 157 15 Classes, Pointers, and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 15.1 Pointers Revisited 159 15.2 Pointers and Some Special Operators 160 15.3 Arrays and Pointers 160 15.4 The this Keyword 162 15.5 Operator Overloading 163 16 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 16.1 Recursive Functions 165 16.2 More on Recursion 169 16.3 Practice Questions 172 17 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 17.1 Inheritance 177 17.2 Inheritance and Constructors 180 17.3 Inheriting Functionality 182 17.4 Multiple Inheritance 184 17.5 Multilevel Inheritance 185 18 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 18.1 Polymorphism and Virtual Functions 187 18.2 Abstract Classes 191 19 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 19.1 Background 193 19.2 Function Templates 195 19.3 Class Templates 197 20 Linked Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 20.1 Linked Lists 199 20.2 Linked Lists using Classes 201 20.3 Adding and Removing Nodes 202 21 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 21.1 Basic Exception Handling 205 21.2 Multiple Throws and Catches 208 21.3 Throwing an Exception in a Function 209 22 Standard Template Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 22.1 Iterators 211 22.2 Vectors 212 22.3 Queue Iterator Example 213 Part Three - Other Topics III 23 File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 23.1 Stream Objects A Answers to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 A.1 Chapter 1 225 A.2 Chapter 3 226 A.3 Chapter 3 228 221 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 I Part One - MAC 101 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2 Numbers at Different Bases . . . . . . . . . . . 17 3 Data Types and Operators . . . . . . . . . . . 27 4 Selection Statements . . . . . . . . . . . . . . . . 43 5 Repetitions Statements . . . . . . . . . . . . . . . 59 6 Functions and Parameters . . . . . . . . . . . 75 7 Variable Scope . . . . . . . . . . . . . . . . . . . . . . 93 8 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 9 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 10 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . 125 11 Introduction to Classes . . . . . . . . . . . . . . 131 12 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 13 Basic Sorting Algorithms . . . . . . . . . . . . 143 1. Introduction 1.1 What is Computer Science? Different sources give different definitions of Computer Science. Below are examples taken from two university websites. George Washington University: http://www.seas.gwu.edu/ simhaweb/misc/cscareers.html What exactly is Computer Science? Computer Science is the science of using computers to solve problems. Mostly, this involves designing software (computer programs) and addressing fundamental scientific questions about the nature of computation but also involves many aspects of hardware and architecting the large computer systems that form the infrastructure of commercial and government enterprises. Computer scientists work in many different ways: pen-and-paper theoretical work on the foundations and fundamentals, programming work at the computer and collaborative teamwork in doing research and solving problems. What Computer Science is not ... Computer Science is not about using software, such as spreadsheets (like Excel), word processors (like Word) or image tools (like Photoshop). Many software packages are complicated to master (such as Photoshop or Excel) and it is true that many jobs depend on expertise in using such tools, but computer science is not about using the tools. It is not about expertise in computer games, it is not about writing content in websites, and it is not about not about assembling computers or knowing which computers are best buys. Edsger Dijkstra, a famous award-winning computer scientist once said, "Computer Science is no more about computers than Astronomy is about telescopes". Computer Science is about the principles behind building the above software packages, about the algorithms used in computer games, about the technology behind the Internet and about the architecture of computing devices. Michigan Technological University: http://www.cs.mtu.edu/ john/whatiscs.html 10 Chapter 1. Introduction Computer science is a discipline that spans theory and practice. It requires thinking both in abstract terms and in concrete terms. The practical side of computing can be seen everywhere. Nowadays, practically everyone is a computer user, and many people are even computer programmers. Getting computers to do what you want them to do requires intensive hands-on experience. But computer science can be seen on a higher level, as a science of problem solving. Computer scientists must be adept at modeling and analyzing problems. They must also be able to design solutions and verify that they are correct. Problem solving requires precision, creativity, and careful reasoning. 1.2 What is Programming? What is programming? What is a programming language? Hierarchical layers of programming languages 1.3 Getting Started with C++ 1.3 11 Getting Started with C++ Why C++ ? • • • • • Popular Object-oriented language Concise clear language Is a good language to first learn programming Portable C++ IDEs (Integrated Development Environment): • • • • • Eclipse C++ CodeBlocks Microsoft Visual C++ CLion xCode (Apple devices) Online Compilers (This should only be temporary. You need to use an IDE): • C++ Shell. (cpp.sh). Only C++. • JDoodle. (www.jdoodle.com). Various languages. Installing C++ in your computer: 1. Choose a C++ editor: While I recommend using Eclipse, you can choose any C++ editor that you feel comfortable with. 2. Install your chosen editor: For Eclipse, you can find installation guides on the internet. Search for "Install Eclipse for C++" on YouTube, and choose a video that suits the specifications of your computer. Follow the directions to complete the installation process. Link (Cave of Programming) Intro discussion on pros and cons of C++, compilers and IDEs. Running the first program: • Open Eclipse (or other C++ editors like CodeBlocks, Microsoft Visual C++) • Create a new C++ project • Create a new “HelloWorld.cpp” file • Compile and run the file Chapter 1. Introduction 12 Code 1.1: First C++ program 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 c o u t << " H e l l o World " ; 6 return 0; 7 } Link (Cave of Programming) Hello World program. Link (Cave of Programming) Outputting text. What happens when we build a C++ program? Code 1.2: A simple input-output C++ program 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 i n t main ( ) { 6 s t r i n g mystr ; 7 c o u t << " What ’ s y o u r name ? " ; 8 g e t l i n e ( cin , mystr ) ; 9 c o u t << " H e l l o " << m y s t r << " . \ n " ; 10 return 0; 11 } 1.3 Getting Started with C++ Testing, revising and optimizing a program 13 Chapter 1. Introduction 14 1.4 Practice Questions 1. What is the meaning of the following in the context of Computer Science? (a) programming language: (b) compiler: (c) source code: (d) algorithm: (e) syntax and semantics: (f) syntax error and logic error: (g) debugging: 1.4 Practice Questions Write a program that prints two lines of text with an empty line in between as shown below. Desired output: 2. This is the first line. This is the second line. Click here for answer. (Try to code it first yourself!) Write a program that prints two lines of text with an empty line in between as shown below. Desired output: 3. one two three Click here for answer. (Try to code it first yourself!) Write a program that produces the output shown below. Desired output: 4. * ** *** **** Click here for answer. (Try to code it first yourself!) Write a program that produces the output shown below. 5. Desired output: * *** ***** ******* Write a program that allows the user to input his/her age and prints the age on the screen. 6. Sample output: Enter your age: 25 You are 25 years old Click here for answer. (Try to code it first yourself!) 15 Chapter 1. Introduction 16 Write a C++ program that allows the user to input his/her name and prints a greeting on the screen. 7. Sample output: Enter your name: John Hello John! Have a wonderful day! 2. Numbers at Different Bases 2.1 Storing Information in the Computer In computing, the smallest unit of information storage is the bit. A bit can take on only two values, 0 or 1, and all information in a computer is stored as a sequence of bits. To make it easier to talk about larger amounts of information, we use multiples of bits. The most common multiples are: • Byte: a unit of 8 bits. It is the basic building block of most computer systems. • Kilobyte (KB): a unit of a thousand bytes, or 103 bytes. • Megabyte (MB): a unit of a million bytes, or 106 bytes. • Gigabyte (GB): a unit of a billion bytes, or 109 bytes. • Terabyte (TB): a unit of a trillion bytes, or 1012 bytes. Convert 1110012 to a decimal number. Understanding bit multiples is important for understanding the capacity and performance of computer systems. Chapter 2. Numbers at Different Bases 18 2.2 Converting Binary, Octal and Hexadecimal to Decimal The base of a number system corresponds to the digits used by the system. Base 2 8 10 16 Digits Used 0,1 0,1,2,3,4,5,6,7 0,1,2,3,4,5,6,7,8,9 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F Name Binary Octal Decimal Hexadecimal Example 1012 468 10910 2A316 Decimal Equivalent 5 38 109 675 <— Watch this video to better understand why we use the binary system. <— .... and another video. In mathematics, we use different number bases or number systems to represent numbers. The most commonly used number system is the decimal or base-10 system, which uses ten digits (0 to 9) to represent numbers. However, there are other number systems as well, such as the binary (base-2), octal (base-8), and hexadecimal (base-16) systems. Understanding how different number bases work is important in computer science and engineering. Consider the decimal number 2365 . Thousands 2 103 2000 Hundreds 3 102 300 Tens 6 101 60 Ones 5 100 5 Sum = 2365 Consider the binary number 10011012 . Find the equivalent decimal number. 1 26 64 0 25 0 0 24 0 1 23 8 1 22 4 0 21 0 1 20 1 Sum = 77 10011012 = 1 × 26 + 0 × 25 + 0 × 24 + 1 × 23 + 1 × 22 + 0 × 21 + 1 × 20 = 64 + 0 + 0 + 8 + 4 + 0 + 1 = 77 10 Therefore, the equivalent decimal number of the binary number 10011012 is 7710 . 2.2 Converting Binary, Octal and Hexadecimal to Decimal Consider the octal number 4278 . Find the equivalent decimal number. 4 82 256 2 81 16 7 80 7 Sum = 279 4278 = 7 × 80 + 2 × 81 + 4 × 82 = 7 × 1 + 2 × 8 + 4 × 64 = 7 + 16 + 256 = 279 10 Therefore, the equivalent decimal number of the octal number 4278 is 27910 . Convert 1110012 to a decimal number. Convert 37718 to a decimal number. Convert 2B516 to a decimal number. 19 Chapter 2. Numbers at Different Bases 20 2.3 Converting Decimal Numbers to Other Bases To convert a decimal number to a different base, we use the method of repeated division by the base, while keeping track of the remainders. The remainders, read in reverse order, give us the corresponding digits in the new base. This process can be better understood through the following examples. Example: convert 4310 to binary. Divide by 2 43 / 2 21 / 2 10 / 2 5/2 2/2 1/2 Quotient 21 10 5 2 1 0 Remainder 1 1 0 1 0 1 Take the binary digits in reverse order: 4310 = 1010112 Convert 9410 to binary. Convert 34210 to the octal equivalent. Divide by 8 342/8 42/8 5/8 Quotient 42 5 0 Remainder 6 2 5 34210 = 5268 Convert 18910 to octal. Convert 54210 to hexadecimal. 2.4 Conversion Between Binary, Octal and Hexadecimal 2.4 21 Conversion Between Binary, Octal and Hexadecimal Converting between binary, octal, and hexadecimal is easier than converting to and from decimal. Can you tell why? Example: Convert 10110102 to octal and hexadecimal. Octal 1 1 011 3 010 2 Binary 10110102 = Grouped 001, 011, 010 = Octal 1328 Therefore, the binary number 10110102 is equivalent to the octal number 1328 . Hexadecimal 101 5 1010 A 10110102 = 1328 = 5A16 Convert 36178 to binary and hexadecimal. Convert 11100012 to octal and hexadecimal. Chapter 2. Numbers at Different Bases 22 2.5 Addition and Subtraction of Numbers at Different Bases In this section, we will explore the addition and subtraction of numbers at different bases, focusing on the techniques and strategies used to perform these operations efficiently and accurately. Addition First, a closer look at the addition of decimal values: 352410 + 69210 Let’s add the binary numbers 10011 and 11010: 1 Now try: 10111012 + 101102 Add 11001102 and 11110102 35A16 + E716 35278 + 7268 1 1 0 0 1 0 0 0 1 1 1 0 1 0 1 2.5 Addition and Subtraction of Numbers at Different Bases Subtraction First, a closer look at the subtraction of decimal values: 193210 − 28110 Now we subtract 110012 from 11100112 11010012 − 1011102 35A16 − E716 35278 − 7268 23 Chapter 2. Numbers at Different Bases 24 2.6 Practice Questions 1. Consider the binary number 110110012 . Find the equivalent decimal number. 2. Consider the octal number 2748 . Find the equivalent decimal number. 3. Consider the hexadecimal number AC716 . Find the equivalent decimal number. 4. Convert 28310 to the octal equivalent. 5. Convert 19810 to the corresponding hexadecimal number. 6. Convert 101100112 to octal and hexadecimal. 7. Convert 45718 to binary and hexadecimal. 8. Convert 100110112 to octal and hexadecimal. 9. Add 111001012 and 1110101102 10. Subtract 1101001012 - 10101102 2.6 Practice Questions 11. Find 35A16 + E716 12. Find 35A16 - E716 13. Find 35278 + 7268 14. Find 35278 - 7268 25 3. Data Types and Operators 3.1 C++ Syntax Tokens In C++, tokens are the smallest individual units of a program that the compiler can understand. Each token has a specific meaning for the compiler, and C++ has a variety of different types of tokens, including keywords, identifiers, operators, literals, and punctuation. Understanding the different types of C++ tokens is essential for writing correct and efficient code, as well as for debugging errors that may arise during the compilation process. Chapter 3. Data Types and Operators 28 Keywords in C++ Keywords are reserved words that have a specific meaning in a programming language, such as C++. They are used to define the syntax and structure of the language, and cannot be used for any other purpose. In C++, keywords are an essential component of the language, and it is important for developers to have a good understanding of their usage. The following table lists some of the most commonly used keywords in C++: Identifiers Identifiers are typically used to name different components of a program such as variables and objects. Rules for choosing identifiers: • The first character of the name must be a letter or an underscore. • You can only use letters, digits, or underscores in the rest of the name. • You can’t use spaces to separate words in a function name - instead, you can either use underscores to separate words or capitalize the first letter of words after the first word. • ou can’t use C++ keywords as identifier names. Which of the following is not a valid C++ identifier? Select all that apply. (a) (b) (c) (d) (e) (f) (g) (h) firstInteger first integer first_integer 1st_integer double 3ge4k2 $dollar My#one 3.2 Primitive Data Types 3.2 29 Primitive Data Types When you write a computer program or algorithm, you need to use and manipulate data. This data can take different forms, such as numbers or text, and needs to be stored in a specific location in the computer’s memory. This is where variables come in - they provide a way to store and access information throughout the program. To use variables effectively, you need to understand the different data types that can be stored. Here are some of the most commonly used data types, along with their descriptions: Type Integer Floating point Character String Keyword int float double char string Size at least 32 bits at least 32 bits at least 64 bits at least 8 bits varies Example int i=23; float f = 23.7; double d = 243.2; char c = ’g’; string s = "hello"; Code 3.1: Example of different data types and their maximum capacity. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 c o u t << " S i z e o f c h a r : " << s i z e o f ( c h a r ) << e n d l ; 6 char c = ’g ’ ; 7 c o u t << " Example c h a r a c t e r t y p e : " << c << e n d l ; 8 9 c o u t << " S i z e o f i n t : " << s i z e o f ( i n t ) << e n d l ; 10 i n t i = 12; 11 c o u t << " Example i n t e g e r t y p e : " << i << e n d l ; 12 13 c o u t << " S i z e o f f l o a t : " << s i z e o f ( f l o a t ) << e n d l ; 14 float f = 22.3; 15 c o u t << " Example f l o a t i n g p o i n t t y p e : " << f << e n d l ; 16 17 c o u t << " S i z e o f d o u b l e : " << s i z e o f ( d o u b l e ) << e n d l ; 18 double d = 125.345; 19 c o u t << " Example d o u b l e p r e c i s i o n t y p e : " << d << e n d l ; 20 21 return 0; 22 } <— Click here for an extended version of this program. 30 Chapter 3. Data Types and Operators Code 3.2: An input-output program with integers. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 int i ; 6 c o u t << " P l e a s e e n t e r an i n t e g e r v a l u e : " ; 7 c i n >> i ; 8 c o u t << " The v a l u e you e n t e r e d i s " << i ; 9 return 0; 10 } Enter different numeric and non-numeric values of different sizes as input. What do you notice? What is the largest unsigned integer that can be represented with 32 bits? What is the largest unsigned integer that can be represented with 64 bits? <— Video Link (Cave of Programming) Variables. <— Video Link (Cave of Programming) User Input. <— Video Link (Cave of Programming) Integer Variables. <— Video Link (Cave of Programming) Floating Point Variables. 3.3 Arithmetic Operations 3.3 31 Arithmetic Operations Basic C++ arithmetic binary operators: Operation Addition Subtraction Multiplication Division Modulus Parenthesis C++ Operator + * / % () Example H+3 A-B 3*D 7/5 10 % 3 (a + 2) - 5 Code 3.3: A program that adds two numbers: 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t n1 , n2 , sum ; 6 7 c o u t << " E n t e r f i r s t i n t e g e r : " ; 8 c i n >> n1 ; 9 10 c o u t << " E n t e r s e c o n d i n t e g e r : " ; 11 c i n >> n2 ; 12 13 sum = n1 + n2 ; 14 c o u t << "Sum i s " << sum << e n d l ; 15 16 return 0; 17 } (From book) Write a program that reads a four-digit integer, such as 1998, and then displays it, one digit per line. Your prompt should tell the user to enter a four-digit integer. You can then assume that the user follows directions. Hint: Use the division and remainder operators. Desired output: Enter a four-digit number: 1998 1 9 9 8 32 Chapter 3. Data Types and Operators Code 3.4: A program that finds the average of two numbers 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 d o u b l e d1 ; 7 c o u t << " E n t e r t h e f i r s t number : " ; 8 c i n >> d1 ; 9 10 d o u b l e d2 ; 11 c o u t << " E n t e r t h e s e c o n d number : " ; 12 c i n >> d2 ; 13 14 c o u t << " The a v e r a g e v a l u e i s " << ( d1+d2 ) / 2 ; 15 16 return 0; 17 } Code 3.5: A program using characters 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 c h a r myChar = ’A ’ ; 7 c o u t << " The i n i t i a l c h a r a c t e r v a l u e i s : " << myChar << e n d l ; 8 9 myChar = myChar + 1 ; 10 c o u t << " The c h a r a c t e r v a l u e i s now : " << myChar ; 11 12 return 0; 13 } 3.3 Arithmetic Operations Basic C++ compound operators: Expresion x+=5; x-=y; x*= y+2; x/=2; Equivalent to x=x+5; x=x-y; x=x*(y+2); x=x/2; Increment and decrement operators: Expresion ++x; x++ - -x; x- -; Similar to x=x+1; x=x+1; x=x-1; x=x-1; Code 3.6: Unary increment example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 int x, y; 6 7 c o u t << " Unary P r e f i x Example : " << e n d l ; 8 x = 5; 9 y = ++x ; 10 c o u t << " x i s : " << x << e n d l ; 11 c o u t << " y i s : " << y << e n d l << e n d l ; 12 13 c o u t << " Unary S u f f i x Example : " << e n d l ; 14 x = 5; 15 y = x ++; 16 c o u t << " x i s : " << x << e n d l ; 17 c o u t << " y i s : " << y << e n d l ; 18 19 return 0; 20 } <— Get code and some explanations here. 33 Chapter 3. Data Types and Operators 34 3.4 Practice Questions 1. What is the meaning of the following in the context of Computer Science? (a) variable: (b) identifier: (c) keyword: (d) statement: (e) declaring a variable: (f) initializing a variable: (g) assignment statement: Click here for answer. 3.4 Practice Questions 35 2. True-False questions – circle your choice. (a) All variables must be declared before being used. ( True - False ) (b) C++ considers the variable number and NUMBER to be identical. ( True - False ) (c) The arithmetic operators *, /, +, and – have the same level of precedence. ( True - False ) (d) The statement cout « “a = 5;” ; is a typical assignment statement. ( True - False ) (e) The statements n +=2; and n = n+2; have the exact same outcome. ( True - False ) (f) The size of the int data type is guaranteed to be 4 bytes on all platforms. ( True - False ) (g) The double data type can hold larger values than the float data type. ( True - False ) (h) C++ has a built-in data type for representing Boolean values. (True - False) (i) The "sizeof" operator in C++ returns the number of bytes occupied by a variable. ( True - False ) Click here for answer. 3. Assuming that x is equal to 6, which of the following statements will not result in y containing the value 7 after execution? Select ALL that apply. (a) y = 7; (b) y = ++x; (c) y = x++; (d) y = x + 1; (e) y = x + 8 / 2; (f) y = (x + 8) / 2; 4. Which of the following is not a valid C++ identifier? Choose all that apply. (a) myNumber (b) my number (c) my_number (d) 1st_number Chapter 3. Data Types and Operators 36 (e) float (f) w3e5r6t7 (g) &number (h) my+number 5. A variable that can have values only in the range 0 to 65535 is a: (a) four – byte integer (b) four – byte unsigned integer (c) two – byte integer (d) two – byte unsigned integer Click here for answer. 6. Given the algebraic expression 2x2 − 5x + 2, which of the following is (are) correct C++ statements for the equation. Circle all that apply. (a) y = 2 * x * x – 5 * x + 2 (b) y = 2 * x * x – 5 * (x + 2) (c) y = (2 * x * x )– (5 * x) + 2 (d) y = 2 * x * (x – 5) * x + 2 7. What is the largest unsigned integer that can be represented with 32 bits and 64 bits? Click here for answer. 8. What is the largest signed integer that can be represented with 32 bits and 64 bits? 9. Which of the following is NOT a valid C++ data type? Circle your choice clearly. (a) (b) (c) (d) int char double number 3.4 Practice Questions 37 10. Write four different C++ statements that each adds one to variable x. Embed the statements in a small c++ program for testing. Click here for answer. 11. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t x = 13; 6 i n t y = 3; 7 c o u t << " Summary o f R e s u l t s : " << e n d l ; 8 c o u t << x + y << e n d l ; 9 c o u t << x − y << e n d l ; 10 c o u t << x / y << e n d l ; 11 c o u t << x * y << e n d l ; 12 c o u t << x % y << e n d l ; 13 14 return 0; 15 } Write exact output here: Chapter 3. Data Types and Operators 38 12. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t x = 7 , y =10; 6 c o u t << x++ << " " << ++y << e n d l ; 7 c o u t << x << " " << y << e n d l ; 8 c o u t <<x−− << " " << −−y << e n d l ; 9 c o u t << x << " " << y << e n d l ; 10 c o u t << x / y << e n d l ; 11 c o u t << x % y << e n d l ; 12 13 return 0; 14 } Write exact output here: 13. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 c o u t << " S i z e o f c h a r : " << s i z e o f ( c h a r ) << e n d l ; 6 c o u t << " S i z e o f i n t : " << s i z e o f ( i n t ) << e n d l ; 7 c o u t << " S i z e o f f l o a t : " << s i z e o f ( f l o a t ) << e n d l ; 8 c o u t << " S i z e o f d o u b l e : " << s i z e o f ( d o u b l e ) << e n d l ; 9 10 return 0; 11 } Write exact output here: 3.4 Practice Questions 39 14. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) 5 { 6 int x, y; 7 8 c o u t << " Unary P r e f i x 9 x = 11; 10 y = −−x ; 11 c o u t << " The v a l u e o f 12 c o u t << " The v a l u e o f 13 14 c o u t << " Unary S u f f i x 15 x = 11; 16 y = x − −; 17 c o u t << " The v a l u e o f 18 c o u t << " The v a l u e o f 19 20 return 0; 21 } Write exact output here: Example : " << e n d l ; x i s : " << x << e n d l ; y i s : " << y << e n d l << e n d l ; Example : " << e n d l ; x i s : " << x << e n d l ; y i s : " << y << e n d l ; Chapter 3. Data Types and Operators 40 15. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 i n t x = 11; 7 double y = 6 , z = 2; 8 y = x / z; 9 x = 3 * y; 10 c o u t << " y = " << y << e n d l ; 11 c o u t << " x = " << x << e n d l ; 12 13 return 0; 14 } Write exact output here: 16. Write a program that allows the user to input a temperature value in Celsius and prints the corresponding temperature in Fahrenheit. Use the following conversion formula: Fahrenheit = Celsius * 1.8 + 32. Desired output: Enter the temperature in Celsius: 30 The corresponding temperature in Fahrenheit is: 86 17. Write a program that allows the user to input a temperature value in Fahrenheit and prints the corresponding temperature in Celsius. Desired output: Enter the temperature in Fahrenheit: 86 The corresponding temperature in Celsius is: 30 3.4 Practice Questions 41 18. Write a program that allows the user to input two integers, one for the length of the rectangle and one for the width. The program then prints the value for the area of the rectangle. Desired output: Enter a number for the length: 5 Enter a number for the width: 4 The area of the rectangle is: 20 19. Write a program that allows the user to input a number for the side of a cube and prints the value for the volume of the cube. Desired output: Enter a number for the side of the cube: 2.0 The volume of the cube is: 8.0 20. Write a C++ program that allows the user to input an integer value n and prints the sum of the five consecutive integers starting with n. For example if the user enters 2 then the program prints the sum = 20 since 2+3+4+5+6 = 20. Desired output: Enter the first integer value: 2 The sum is: 20 21. Write a C++ program that allows the user to input separately the number of years, months and days for a given time period and prints the total number of days for the same time period. For this exercise assume all months have 30 days. Desired output: Enter the number of years: 2 Enter the number of months: 5 Enter the number of days: 10 The time period you entered is equivalent to 880 days Chapter 3. Data Types and Operators 42 22. Write a program that prompts the user to enter a five-digit integer and displays the sum of its digits. Your program should also verify that the input is a valid five-digit integer. Desired output: Enter a five-digit number: 12345 The sum of the digits in 12345 is 15. 23. Write a C++ program that takes two integers as input and swaps their values. The program should print on the screen the values of each variable before and after swapping. Sample output: Enter two integers: 7 9 Before swapping: x=7 y=9 After swapping: x=9 y=7 24. What is the largest signed decimal integer that can be represented with 16 bits? 25. What is the largest unsigned decimal integer that can be represented with 16 bits? 26. What is the minimum number of bits needed to represent the decimal value 1000? 4. Selection Statements Very often we need to make a decision whether to execute one or more statements based on criteria that need to be satisfied. 4.1 Relational and Comparison Operators In C++ we use relational or comparison operators to compare two expressions. The result of the comparison is either true or false. The table below lists these operators. Operator == != < Comparison Equal to Not equal to Less than Operator > <= >= Comparison Greater than Less or equal to Greater or equal to 4.2 if and if-else Statements The if statement format if (condition) statement: executed if condition is true; Chapter 4. Selection Statements 44 Code 4.1: C++ if statement example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t x = 5; 6 i n t y = 5; 7 8 i f ( x==y ) 9 c o u t << " x and y a r e e q u a l " << e n d l ; 10 11 c o u t << " Done ! " ; 12 return 0; 13 } Change the value of x and run the program. <— Video Link (Cave of Programming) If Statements. The compound if statement format if (condition){ statement1; statement2; statement3; } Code 4.2: C++ compound if statement example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t x = 5; 6 i n t y = 5; 7 8 i f ( x == y ) { 9 c o u t << " x and y a r e e q u a l \ n " ; 10 c o u t << " x i s " << x << " and y i s " << y << e n d l ; 11 } 12 c o u t << " Done ! " ; 13 return 0; 14 } Remove the curly brackets at the beginning and the end of the if statement and run the program. 4.2 if and if-else Statements 45 Write a program that allows the user to input three integers (not necessarily distinct) and prints the largest of the three values. Desired output: Enter three integers: 5 2 1 The largest integer is: 5 The compound if-else statement format if (condition) statement1: executed if condition is true; else statement2: executed if condition is false; Code 4.3: C++ if-else statement example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t x = 5; 6 i n t y = 6; 7 8 i f ( x == y ) 9 c o u t << " x and y a r e e q u a l \ n " ; 10 else 11 c o u t << " x and y a r e n o t e q u a l \ n " ; 12 13 c o u t << " Done ! " ; 14 return 0; 15 } <— Video Link (Cave of Programming) If Else Statements. Write a program that inputs an integer and prints if the number is even or odd. Desired output: Enter an integer: 7 The number you entered is odd. Chapter 4. Selection Statements 46 4.3 The Nested if-else Statements Code 4.4: C++ nested if-else statement example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t sco re =0; 6 c o u t << " E n t e r S c o r e : " ; 7 c i n >> s c o r e ; 8 9 c o u t << " The Grade i s : " ; 10 i f ( s c o r e >= 90 ) 11 c o u t << "A" ; 12 e l s e i f ( s c o r e >= 80 ) 13 c o u t << "B" ; 14 e l s e i f ( s c o r e >= 70 ) 15 c o u t << "C" ; 16 e l s e i f ( s c o r e >= 60 ) 17 c o u t << "D" ; 18 else 19 c o u t << " F " ; 20 21 return 0; 22 } <— Get code here. Code 4.5: An alternative to if-else statement (using the ?: operator) 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t s c o r e = 0 ; / / s c o r e on exam 6 c o u t << " E n t e r S c o r e : " ; 7 c i n >> s c o r e ; 8 9 c o u t << ( s c o r e >= 60 ? " P a s s e d " : " F a i l e d " ) ; 10 return 0; 11 } 4.4 The switch Statement 4.4 47 The switch Statement The switch statement is an alternative to if-else. It is commonly used if we have several condition cases. It is easier to write and read. Example switch statement compared to the equivalent if-else statement. Code 4.6: Switch statement example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t day = 0 ; 6 c o u t << " E n t e r a number b e t w e e n 1 and 7 : " ; 7 c i n >> day ; 8 9 s w i t c h ( day ) { 10 c a s e 1 : c o u t << " Monday " ; 11 break ; 12 c a s e 2 : c o u t << " T u e s d a y " ; 13 break ; 14 c a s e 3 : c o u t << " Wednesday " ; 15 break ; 16 c a s e 4 : c o u t << " T h u r s d a y " ; 17 break ; 18 c a s e 5 : c o u t << " F r i d a y " ; 19 break ; 20 c a s e 6 : c o u t << " S a t u r d a y " ; 21 break ; 22 c a s e 7 : c o u t << " Sunday " ; 23 break ; 24 d e f a u l t : c o u t << " Not a v a l i d e n t r y " ; 25 break ; 26 } 27 return 0; 28 } <— Get code here. Remove the first 3 break statements and then enter 1 as an input. What do you notice? Remove the default case. Does the program work? What can you conclude? Write a program that does the same work as the switch example above but using a nested if statement instead. Chapter 4. Selection Statements 48 Characters share some similar features with integers. Characters are saved in memory as numbers. We can use the same relational operators to compare characters. See example below. Code 4.7: Example comparing characters 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 char f i r s t = ’b ’ ; 6 char second = ’b ’ ; 7 8 i f ( f i r s t < second ) 9 c o u t << " I t l o o k s l i k e " 10 << " comes b e f o r e " 11 e l s e i f ( second < f i r s t ) 12 c o u t << " I t l o o k s l i k e " 13 << " comes b e f o r e " 14 else 15 c o u t << f i r s t << " and " 16 << " a r e t h e same . " 17 18 return 0; 19 } << f i r s t << s e c o n d << e n d l ; << s e c o n d << f i r s t << e n d l ; << s e c o n d << e n d l ; Change the value of ’first’ and ’second’ and test the program. 4.5 Logical Operators 4.5 49 Logical Operators Operator Logical Operation Example ! NOT !(2==2) // evaluates to FALSE && AND ( 2==2) && (2==3) //evaluates to FALSE || OR (2==2) || (2==3) //evaluates to TRUE A TRUE TRUE FALSE FALSE B TRUE FALSE TRUE FALSE A && B TRUE FALSE FALSE FALSE A TRUE TRUE FALSE FALSE B TRUE FALSE TRUE FALSE A || B TRUE TRUE TRUE FALSE Code 4.8: || (OR) operator example. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 char agree ; 6 c o u t << " Would you l i k e t o meet ? ( y / n ) : " ; 7 c i n >> a g r e e ; 8 9 i f ( a g r e e == ’ y ’ | | a g r e e == ’Y ’ ) 10 c o u t << " G r e a t ! ! ! " << e n d l ; 11 e l s e i f ( a g r e e == ’ n ’ | | a g r e e == ’N ’ ) 12 c o u t << " S o r r y t o h e a r t h a t ! ! ! " << e n d l ; 13 else 14 c o u t << " What d i d you s a y ? " << e n d l ; 15 16 return 0; 17 } Chapter 4. Selection Statements 50 Code 4.9: && (AND) operator example. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t number ; 6 c o u t << " I o n l y l i k e numbers b e t w e e n 10 and 2 0 . " << e n d l ; 7 c o u t << " E n t e r an i n t e g e r : " ; 8 c i n >> number ; 9 10 i f ( number >= 10 && number <= 2 0 ) 11 c o u t << " You e n t e r e d " << number << " . I am happy ! " ; 12 else 13 c o u t << " I don ’ t l i k e t h e number you e n t e r e d ! " ; 14 15 return 0; 16 } Determine whether the following expressions are true or false. Use a computer program to verify your answers. (a) (b) (c) (d) (e) (f) (4 == 4) && (4 >= 3) = (4 == 4) || (10 < 5) = !(4 == 4) || (10 < 5) = !(4 == 4) || !(10 < 5) = (3 != 4) && (10 < 15) || (4 == 5) = (3 != 4) && (10 < 15) && (4 == 5) = Here is a C++ program that can be used to verify the answer to each question. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 c o u t << b o o l a l p h a << 6 c o u t << b o o l a l p h a << 7 c o u t << b o o l a l p h a << 8 c o u t << b o o l a l p h a << 9 c o u t << b o o l a l p h a << 10 c o u t << b o o l a l p h a << 11 12 return 0; 13 } ( ( 4 == 4 ) && ( ( 4 == 4 ) | | ( ! ( 4 == 4 ) | | ( ! ( 4 == 4 ) | | ( ( 3 ! = 4 ) && ( ( 3 ! = 4 ) && ( 4 >= 3 ) ) << e n d l ; ( 1 0 < 5 ) ) << e n d l ; ( 1 0 < 5 ) ) << e n d l ; ! ( 1 0 < 5 ) ) << e n d l ; ( 1 0 < 1 5 ) | | ( 4 == 5 ) ) << e n d l ; ( 1 0 < 1 5 ) && ( 4 == 5 ) ) << e n d l ; 4.6 Practice Questions 4.6 51 Practice Questions 1. What is the meaning of the following in the context of Computer Science? (a) optimizing a program / algorithm: (b) C++ is case sensitive: (c) unsigned and signed integer: (d) A program is scalable: 2. Determine whether the following expressions are true or false. Assume x=3 and y=5. Use a computer program to verify your answers. (a) (x <= 5) && (y == 5) = (b) (x == y) || (y < 10) = (c) !(x == 3) || (y != 5) = (d) ((x % 3) == 1) || (y == 3) = (e) (3 != 4) && (x < 2) || (y == 5) Chapter 4. Selection Statements 52 3. What the following statements print? Assume i=1, j=2, k=3 and m=2. (a) cout « (j == 1) « endl; (b) cout « (j >= 1 && j < 4) « endl; (c) cout « (j >= i || k == m) « endl; (d) cout « (k + m < j || 3-j >= k) « endl; (e) cout « (!(j - m)) « endl; 4. Which of the following is a selection statement? Clearly circle your answer. (a) for (b) if...else (c) do...while (d) while 5. True-False questions – Circle your choice (a) (b) (c) (d) (e) (f) (g) (h) (i) (j) (k) (l) (m) (n) (o) (p) (q) The AND (&&) operator stops after finding one condition to be false. ( True - False ) The OR (||) operator stops after finding one condition to be false. ( True - False ) The default portion is REQUIRED in a switch statement . ( True - False ) A switch statement can use a string as the expression to be evaluated. (False - True) The logical NOT operator (!) can only be used with boolean values. (True - False) The switch statement can only be used with integer and character types. (True - False) The AND (&&) operator has higher precedence than the OR (||) operator. (True - False) The if statement is a selection statement. (True - False) The if-else statement is a conditional statement. (True - False) The switch statement is a selection statement. (True - False) The break statement is used to exit a switch statement. (True - False) The AND (&&) operator evaluates both conditions even if the first condition is false. (False - True) The OR (||) operator evaluates both conditions even if the first condition is true. (False True) The ?: operator can be used in place of an if-else statement. (True - False) The AND (&&) operator can be used with integer values. (False - True) The OR (||) operator can be used with integer values. (False - True) The if-else statement can be nested within another if-else statement. (True - False) 4.6 Practice Questions 53 6. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) 5 { 6 i n t number1 = 5 ; 7 i n t number2 = 1 2 ; 8 i n t number3 = 7 ; 9 i n t myChoice = 0 ; 10 11 myChoice = number1 ; 12 13 i f ( number2 < myChoice ) myChoice = number2 ; 14 i f ( number3 < myChoice ) myChoice = number3 ; 15 16 c o u t << "My C h o i c e i s : " << myChoice ; 17 return 0; 18 } 7. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t year = 2000; 6 7 i f ( ( y e a r % 4 == 0 && y e a r % 100 ! = 0 ) | | ( y e a r % 400 == 0 ) ) 8 c o u t << y e a r << " i s a l e a p y e a r " ; 9 else 10 c o u t << y e a r << " i s n o t a l e a p y e a r " ; 11 12 return 0; 13 } Chapter 4. Selection Statements 54 8. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t num1 = 5 , num2 = −3; 6 7 i f ( num1 > 0 && num2 > 0 ) 8 c o u t << " The sum i s " << num1 + num2 ; 9 e l s e i f ( num1 <= 0 | | num2 <= 0 ) 10 c o u t << " I n v a l i d i n p u t " ; 11 else 12 c o u t << " The d i f f e r e n c e i s " << num1 − num2 ; 13 14 return 0; 15 } 9. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) 5 { 6 i n t x = 5; 7 i n t y = 3; 8 i n t z = 7; 9 10 i f ( x<=y && y<= z ) 11 c o u t << "My C h o i c e i s : " << y ; 12 i f ( y<=x && x<= z ) 13 c o u t << "My C h o i c e i s : " << x ; 14 i f ( x<= z && z <=y ) 15 c o u t << "My C h o i c e i s : " << z ; 16 17 return 0; 18 } 4.6 Practice Questions 55 10. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) 5 { 6 i n t x = 6; 7 i n t y = 6; 8 9 i f ( x >= y ) 10 c o u t << " H e l l o " << e n d l ; 11 else 12 c o u t << " Goodbye " << e n d l ; 13 c o u t << " Done ! " ; 14 return 0; 15 } 11. Convert the following switch-statement into the equivalent if-else-statement. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 switch (x ) { case 1 : n =1; break ; case 2 : n =2; break ; case 3 : n =3; break ; default : n =10; break ; } Chapter 4. Selection Statements 56 12. Convert the following switch-statement into the equivalent if-else-statement. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 / / Choose day o f week p r o g r a m 5 i n t main ( ) 6 { 7 i n t day = 0 ; / / day o f t h e week 8 c o u t << " E n t e r a number b e t w e e n 1 and 7 f o r t h e day o f t h e week : " ; 9 c i n >> day ; 10 11 i f ( day == 1 ) c o u t << " Monday " ; 12 e l s e i f ( day == 2 ) c o u t << " T u e s d a y " ; 13 e l s e i f ( day == 3 ) c o u t << " Wednesday " ; 14 e l s e i f ( day == 4 ) c o u t << " T h u r s d a y " ; 15 e l s e i f ( day == 5 ) c o u t << " F r i d a y " ; 16 e l s e i f ( day == 6 ) c o u t << " S a t u r d a y " ; 17 e l s e i f ( day == 7 ) c o u t << " Sunday " ; 18 e l s e c o u t << " Not a v a l i d e n t r y " ; 19 20 return 0; 21 } 13. Write a program that allows the user to input three integers (not necessarily distinct) and prints the largest of the three values. Desired output: Enter three integers: 2 5 1 The largest integer is: 5 14. Write a program that allows the user to input three integers (not necessarily distinct) and prints the median of the three values. Desired output: Enter three integers: 2 7 1 The median is: 2 4.6 Practice Questions 57 15. Write a program that inputs an integer and prints if the number is even or odd. Desired output: Enter an integer: 7 The number you entered is odd. 16. Write a C++ program that allows the user to input two integers and prints the sum, difference, product, quotient, and remainder of the two values. Desired output: Enter two integers: 17 5 Sum: 22 Difference: 12 Product: 85 Quotient: 3 Remainder: 2 17. Write a C++ program that inputs a grade percentage and prints the corresponding letter grade according to the following scale: A for percentages 90-100, B for 80-89, C for 70-79, D for 60-69, and F for percentages below 60. Desired output: Enter grade percentage: 83 Letter grade: B 18. Write a C++ program that inputs a number and checks if it is a palindrome (i.e., the number reads the same forwards and backwards). Desired output: Enter a number: 12321 12321 is a palindrome. 19. Write a program that inputs a number between 1 and 12 inclusive and prints the corresponding month of the year. If a different value is entered the program prints: “Not a valid entry!”. Use the switch statement. As an alternative you can also write a different version of the program using the if statement. Sample output: Enter a number between 1 and 12 for the month of the year: 2 The month you selected is: February 5. Repetitions Statements 5.1 C++ Loops. The while and do. . . while Statement. Loops are a very important and powerful component of any programming language. It allows the repetition of one or more statements as long as a condition is satisfied. One of the most basic loop structures in C++ is the while statement. The while statement format The while statement format while (condition) statement; while (condition){ statement1; statement2; statement3; } Code 5.1: Program using a loop to print numbers from 1 to 10 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t number = 1 ; 6 7 w h i l e ( number <= 1 0 ) { 8 c o u t << number << e n d l ; 9 number ++; 10 } 11 return 0; 12 } Chapter 5. Repetitions Statements 60 Remove the statement number++; from the previous program and run it. What do you notice? Write a program that allows the user to enter an integer value n and prints all the positive integers starting with n, in decreasing order. Desired output: Enter a positive integer: 7 The numbers in decreasing order are: 7 6 5 4 3 2 1 Write a program that allows the user to enter an integer value n and prints all the positive even integers smaller or equal to n, in decreasing order. Desired output: Enter a positive integer: 7 The even numbers in decreasing order are: 6 4 2 The do. . . while statement. Is similar to the while statement. The list of statements is executed before the condition is checked. So, the do. . . while statement is executed at least once. The do...while statement format do { } statement1; statement2; statement3; while(condition); 5.2 The for loop 61 Code 5.2: Example do...while statement 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t number = 1 ; 6 7 do { 8 c o u t << number << e n d l ; 9 number ++; 10 } w h i l e ( number <= 1 0 ) ; 11 return 0; 12 } 5.2 The for loop Let’s start by saying that everything that can be done using the for loop can also be done using the while loop. However the for statement is more concise and more commonly used. The for statement format for(initializer; condition; increment){ statement1; statement2; } Comparison for and while loops: 62 Chapter 5. Repetitions Statements Code 5.3: Printing 1 to 10 using the for loop 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 f o r ( i n t number = 1 ; number <=10; number ++) { 6 c o u t << number << e n d l ; 7 } 8 return 0; 9 } The next program calculates the factorial of a given number. What is the factorial of a number? Code 5.4: Using a nested for loop to calculate the factorial of a number 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 int factorial ; 6 i n t n = 10; 7 8 c o u t << "N \ t F a c t o r i a l o f N \ n " ; 9 10 f o r ( i n t i = 1 ; i <=n ; ++ i ) { 11 f a c t o r i a l =1; 12 f o r ( i n t j = 1 ; j <= i ; ++ j ) 13 f a c t o r i a l *= j ; 14 c o u t << i << ’ \ t ’ << f a c t o r i a l << e n d l ; 15 } 16 return 0; 17 } Can we optimize the code in Factorial.cpp? Do we need a nested for loop? <— Click here for an improved version of the factorial program with explanations. Try to answer the question above first before visiting this link. 5.2 The for loop 63 Write a program that prints the shape below using only the following print statements: cout « “*”; and cout « endl; Desired output: * ** *** **** ***** ****** ******* ******** Write a program that prints the following diamond shape. You may use output statements that print a single asterisk (cout « “*”;) a single blank (cout « “ ”;) or new line (cout « endl;). Maximize your use of repetition (with nested for structures) and minimize the number of output statements. Desired output: * *** ***** ******* ********* ******* ***** *** * Chapter 5. Repetitions Statements 64 5.3 The break and continue Statements The break statement when executed within any of the loop statements it causes the immediate exit from the loop statement. Code 5.5: Example break statement. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 f o r ( i n t number = 1 ; number <=10; number ++) { 7 i f ( number == 5 ) 8 break ; 9 c o u t << number << e n d l ; 10 } 11 return 0; 12 } The continue statement when used within any of the loop statements it causes the remaining statements in the body of the loop to be skipped. The loop then continues with the next iteration. Code 5.6: Example continue statement. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 f o r ( i n t number = 1 ; number <=10; number ++) { 7 i f ( number == 5 ) 8 continue ; 9 c o u t << number << e n d l ; 10 } 11 return 0; 12 } 5.4 Practice Questions 5.4 Practice Questions 1. What is the meaning of the following in the context of Computer Science? (a) iteration: (b) sentinel: (c) initializer: (d) Nested loop: (e) increment / decrement: 2. Which of the following is a C++ repetition statement? (a) if (b) if...else (c) do...while (d) switch (e) repeat 65 Chapter 5. Repetitions Statements 66 3. What is wrong with the following while loop? Explain. 1 2 3 i n t x =5; w h i l e ( x <= 1 0 ) x −=2; 4. The following code should output all even integers from 2 to 100 inclusive. Find and fix the errors. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 counter = 2; 7 8 do { 9 c o u t << c o u n t e r << e n d l ; 10 c o u n t e r +=2; 11 } While ( c o u n t e r < 1 0 0 ) ; 12 13 return 0; 14 } 5.4 Practice Questions 67 5. The following code should output all powers of 2 between 1 and 100 (as shown in the desired output column). Find and fix the errors. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 counter = 1; 6 do { 7 c o u n t e r +=2; 8 c o u t << c o u n t e r << e n d l ; 9 } while ( counter < 100); 10 11 return 0; 12 } Desired output: 2 4 8 16 32 64 6. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) 5 { 6 f o r ( i n t i = 1 ; i <=2; i = i + 1 ) 7 f o r ( i n t j = 1 ; j <= 3 ; j = j + 1 ) 8 c o u t << i << " − " << j << e n d l ; 9 10 return 0; 11 } Chapter 5. Repetitions Statements 68 7. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) 5 { 6 f o r ( i n t number = 1 ; number <10; number ++) { 7 i f ( number % 3 ! = 0 ) 8 continue ; 9 c o u t << number << e n d l ; 10 } 11 return 0; 12 } 8. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) 5 { 6 i n t number = 1 ; 7 w h i l e ( number < 1 0 ) { 8 c o u t << number << e n d l ; 9 number +=3; 10 } 11 return 0; 12 } 5.4 Practice Questions 9. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t i = 0 , j = 1 , k = 1 , sum = 0 ; 6 7 while ( i < 10){ 8 c o u t << j << e n d l ; 9 sum= j +k ; 10 j =k ; 11 k=sum ; 12 i ++; 13 } 14 } 10. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 f o r ( i n t i = 1 ; i <=3; ++ i ) { 6 f o r ( i n t j = 1 ; j <=3; ++ j ) { 7 f o r ( i n t k = 1 ; k <=3; ++k ) 8 c o u t << ’ * ’ ; 9 c o u t << e n d l ; 10 } 11 c o u t << e n d l ; 12 } 13 return 0; 14 } 69 70 11. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) 5 { 6 i n t number = 1 5 ; 7 8 do { 9 c o u t << number << e n d l ; 10 number ++; 11 } w h i l e ( number <= 1 0 ) ; 12 return 0; 13 } Chapter 5. Repetitions Statements 5.4 Practice Questions 71 12. Make only one change to the program below so that the current output changes to the desired output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 int y; 6 f o r ( i n t i = 1 ; i <= 9 ; i ++ ) { 7 y =0; 8 f o r ( i n t j = 1 ; j <= i ; j ++ ) { 9 y += 1 ; 10 c o u t << i << " " ; 11 } 12 c o u t << e n d l ; 13 } 14 return 0; 15 } Current output: 1 22 333 4444 55555 666666 7777777 88888888 999999999 Desired output: 1 12 123 1234 12345 123456 1234567 12345678 123456789 Chapter 5. Repetitions Statements 72 13. Write a C++ program that uses a nested loop to print the multiplication table for numbers from 1 to 10 as shown below. Desired output: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 14. Write a program that allows the user to enter an integer value n and prints all the positive integers starting with n, in decreasing order. Sample output: Enter a positive integer: 7 The numbers in decreasing order are: 7 6 5 4 3 2 1 15. Write a program that allows the user to enter an integer value n and prints all the positive even integers smaller or equal to n, in decreasing order. Sample output: Enter a positive integer: 7 The even numbers in decreasing order are: 6 4 2 16. Write a program that allows the user to enter an integer value n and prints all the positive odd integers smaller or equal to n, in decreasing order. Sample output: Enter a positive integer: 7 The odd numbers in decreasing order are: 7 5 3 1 5.4 Practice Questions 73 17. Write a program that allows the user to enter a positive integer value n and prints all the integers from 1 to n and back down to 1. Sample output: Enter a positive integer: 5 The numbers are: 1 2 3 4 5 4 3 2 1 18. Write a program that has the output shown below and uses only one for loop. Hint: The numbers in the second column are the factorials of the numbers in the first column. Desired output: 1 2 3 4 5 6 1 2 6 24 120 720 6. Functions and Parameters 6.1 What are Functions? Functions are important building blocks of computer programs. Functions are also referred to as procedures, subroutines or methods. Each function is a group of statements that accomplish a specific task. We will use a number of predefined functions available with C++ and we will also design our own functions. Components of a function return_type } function_name (argument_list) { statements ....... return statement; (if applicable) 76 Chapter 6. Functions and Parameters Code 6.1: A program that defines and tests a function that calculates the average of two numbers. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 / / F u n c t i o n must be d e c l a r e d b e f o r e b e i n g u s e d . 5 double average ( double x , double y ) ; 6 7 i n t main ( ) { 8 9 double a = 0 . 0 ; 10 double b = 0 . 0 ; 11 12 c o u t << " E n t e r f i r s t number : " ; 13 c i n >> a ; 14 c o u t << " E n t e r s e c o n d number : " ; 15 c i n >> b ; 16 17 / / Call the function average ( ) . 18 c o u t << " A v e r a g e i s : " << a v e r a g e ( a , b ) << e n d l ; 19 20 return 0; 21 22 } / / end main ( ) 23 24 / / Average −number f u n c t i o n d e f i n i t i o n 25 d o u b l e a v e r a g e ( d o u b l e x , d o u b l e y ) { 26 27 d o u b l e avg = ( x + y ) / 2 ; 28 r e t u r n avg ; 29 30 } / / end a v e r a g e ( ) f u n c t i o n 6.1 What are Functions? Code 6.2: A program that defines and tests a factorial function. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 int factorial ( int x ); 5 6 i n t main ( ) { 7 8 i n t number ; 9 10 c o u t << " E n t e r an i n t e g e r : " ; 11 c i n >> number ; 12 13 c o u t << number << " ! = " << f a c t o r i a l ( number ) << e n d l ; 14 15 return 0; 16 } / / end main ( ) 17 18 i n t f a c t o r i a l ( i n t x ) { 19 20 i n t f =1; 21 22 f o r ( i n t i = 2 ; i <=x ; i ++){ 23 f *= i ; 24 } 25 26 return f ; 27 28 } / / end f a c t o r i a l ( ) 77 Chapter 6. Functions and Parameters 78 Code 6.3: A program that defines and tests a function that prints the first n integers. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void p r i n t A l l I n t e g e r s ( i n t x ) ; 5 6 i n t main ( ) { 7 8 int n; 9 c o u t << " E n t e r an i n t e g e r : " ; 10 c i n >> n ; 11 12 c o u t << " The f i r s t " << n << " p o s i t i v e i n t e g e r s a r e : " << e n d l ; 13 printAllIntegers (n ); 14 15 return 0; 16 17 } / / end main ( ) 18 19 v o i d p r i n t A l l I n t e g e r s ( i n t x ) { 20 21 f o r ( i n t i = 1 ; i <=x ; i ++){ 22 c o u t << i << e n d l ; 23 } 24 25 } / / end p r i n t A l l I n t e g e r s ( ) Write a C++ program that defines and tests a function largest(. . . .) that takes as parameters any three integers and returns the largest of the three integers. Your output should have the same format and should work for any integers a user enters. Desired output: Enter three integers: 6 15 8 The largest integer is: 15 6.1 What are Functions? 79 Code 6.4: A program that checks whether a number is prime. 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 # include <iostream > # i n c l u d e <cmath > u s i n g namespace s t d ; bool prime ( i n t ) ; i n t main ( ) { int n; while ( t r u e ) { c o u t << " E n t e r number ( 0 = e x i t ) : " ; c i n >> n ; i f ( n == 0 ) break ; i f ( prime ( n ) ) c o u t << n << " i s p r i m e " << e n d l ; else c o u t << n << " i s n o t p r i m e " << e n d l ; } return 0; } / / end main bool prime ( i n t x ) { f o r ( i n t i = 2 ; i < x ; i ++) i f ( x % i == 0 ) r e t u r n f a l s e ; return true ; } / / end p r i m e ( ) <— Click here for a version of this program. Optimize the prime-number function. Can we reduce the current number of operations? Chapter 6. Functions and Parameters 80 Rewrite main so that it tests all the numbers from 2 to 10 (inclusive) and prints out the results, each on a separate line. (Hint: Use a for loop, with i running from 2 to 10.) Desired output: 2 is prime 3 is prime 4 is not prime 5 is prime 6 is not prime 7 is prime 8 is not prime 9 is not prime 10 is not prime Write a C++ program that defines and tests a function power(base, exponent) that takes two integers b and x and returns bx by using only multiplication. Design your own function. Do not use the built in in function pow().Your output should have the same format as shown below and should work for any integers. Desired output: Enter base: 2 Enter exponent: 3 2 to the power 3 is 8 6.2 Passing a Parameter by Value or by Reference There are two ways to pass arguments to a function (by value or by reference). What we have done so far is to pass the value of the parameter. We illustrate both possibilities via examples. 6.2 Passing a Parameter by Value or by Reference 81 Code 6.5: Passing by value example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t addOne ( i n t ) ; 5 6 i n t main ( ) { 7 8 i n t n = 3; 9 10 c o u t << " n b e f o r e c a l l i n g addOne ( ) : " << n << e n d l ; 11 c o u t << " V a l u e r e t u r n e d by addOne ( ) : " << addOne ( n ) << e n d l ; 12 c o u t << " n a f t e r c a l l i n g addOne ( ) i s : " << n << e n d l ; 13 } 14 15 i n t addOne ( i n t v a l u e ) { 16 v a l u e ++; 17 return value ; 18 } Code 6.6: Passing by reference example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t addOne ( i n t & ) ; 5 6 i n t main ( ) { 7 8 i n t n = 3; 9 10 c o u t << " n b e f o r e c a l l i n g addOne ( ) : " << n << e n d l ; 11 c o u t << " V a l u e r e t u r n e d by addOne ( ) : " << addOne ( n ) << e n d l ; 12 c o u t << " n a f t e r c a l l i n g addOne ( ) i s : " << n << e n d l ; 13 } 14 15 i n t addOne ( i n t &v a l u e ) { 16 v a l u e ++; 17 return value ; 18 } What are the pros and cons of each method? Chapter 6. Functions and Parameters 82 6.3 Default Function Arguments It is possible to assign default values to each of the function arguments. This allows the caller to omit argument values. If the value is not specified by the caller, the default value will be used. See examples below. Code 6.7: Default arguments example - Rectangle area 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 # include <iostream > u s i n g namespace s t d ; i n t rArea ( i n t l e n g t h = 2 , i n t width = 1 ) ; i n t main ( ) { c o u t << " D e f a u l t a r e a : " << r A r e a ( ) << e n d l ; c o u t << " l e n g t h =10 and d e f a u l t w i d t h : " << r A r e a ( 1 0 ) << e n d l ; c o u t << " l e n g t h =10 and w i d t h = 5 : " << r A r e a ( 1 0 , 5 ) << e n d l ; return 0; } i n t rArea ( i n t length , i n t width ){ r e t u r n l e n g t h * width ; } Can we assign a default value to only length or only width? Code 6.8: Additional Example - Interest 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 # include <iostream > u s i n g namespace s t d ; double i n t e r e s t ( double p = 1000 , double r = 0 . 0 5 , double t = 1 ) ; i n t main ( ) { c o u t << << c o u t << c o u t << c o u t << " i n t e r e s t (3000 , 0.015 , 5 ) : " i n t e r e s t ( 3 0 0 0 , 0 . 0 1 5 , 5 ) << e n d l ; " i n t e r e s t ( 3 0 0 0 , 0 . 0 1 5 ) : " << i n t e r e s t ( 3 0 0 0 , 0 . 0 1 5 ) << e n d l ; " i n t e r e s t ( 3 0 0 0 ) : " << i n t e r e s t ( 3 0 0 0 ) << e n d l ; " i n t e r e s t ( ) : " << i n t e r e s t ( ) << e n d l ; return 0; } double i n t e r e s t ( double p , double r , double t ){ r e t u r n p* r * t ; } 6.4 Function Overloading 6.4 83 Function Overloading It is possible to declare different functions using the same function identifier. These functions however have different signatures, typically different data types. The C++ compiler will select the version of the function that matches with the signature. Code 6.9: Function overloading example 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 # include <iostream > u s i n g namespace s t d ; i n t addNumbers ( i n t , i n t ) ; d o u b l e addNumbers ( d o u b l e , d o u b l e ) ; i n t main ( ) { i n t xInt = 5; i n t yInt = 7; d o u b l e xDouble = 3 . 3 ; d o u b l e yDouble = 2 . 4 ; cout cout cout cout << << << << " Calling "Sum i s : " Calling "Sum i s : t h e i n t e g e r v e r s i o n . " << e n d l ; " << addNumbers ( x I n t , y I n t ) << e n d l << e n d l ; t h e d o u b l e v e r s i o n . " << e n d l ; " << addNumbers ( xDouble , yDouble ) << e n d l ; return 0; } i n t addNumbers ( i n t f i r s t , i n t s e c o n d ) { c o u t << " I n s i d e t h e i n t e g e r v e r s i o n . " << e n d l ; r e t u r n f i r s t + second ; } d o u b l e addNumbers ( d o u b l e f i r s t , d o u b l e s e c o n d ) { c o u t << " I n s i d e t h e d o u b l e v e r s i o n . " << e n d l ; r e t u r n f i r s t + second ; } <— Get here a similar version of the program. Can we overload a function by changing the number of arguments? Can we overload a function by only changing the return type? Chapter 6. Functions and Parameters 84 6.5 Practice Questions 1. What is the meaning of the following in the context of Computer Science? (a) function return type: (b) pre-defined and user-defined functions: (c) function arguments / parameters: (d) function call: (e) void return type: (f) passing an argument by value or by reference: (g) function overloading: (h) default function values: 6.5 Practice Questions (i) function header and function body: (j) function declaration / function prototype: 2. True-False questions – Circle your choice (a) All arguments to C++ function calls are passed by value. ( True - False ) (b) A C++ function must always return a value when called. ( True - False ) 3. If an argument to a function is declared as const, then ... (a) Function can modify the argument (b) Function can’t modify the argument (c) const argument to a function is not possible (d) None of the above 85 Chapter 6. Functions and Parameters 86 4. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 int f ( int b, int e ); 5 6 i n t main ( ) { 7 i n t n1 = 2 , n2 = 6 ; 8 c o u t << n1 << " ^ " << n2 << " = " << f ( n1 , n2 ) << e n d l ; 9 return 0; 10 } / / end main 11 12 i n t f ( i n t b , i n t e ) { 13 i n t r e s u l t =1; 14 f o r ( i n t i = 1 ; i <= e ; i ++) 15 r e s u l t *= b ; 16 return result ; 17 } 5. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t re c ta ng le A re a ( i n t l e n g t h = 2 , i n t width = 1 ) ; 5 6 i n t main ( ) { 7 c o u t << " F i r s t R e c t a n g l e : " << r e c t a n g l e A r e a ( ) << e n d l ; 8 c o u t << " Second R e c t a n g l e : " << r e c t a n g l e A r e a ( 5 ) << e n d l ; 9 c o u t << " T h i r d R e c t a n g l e : " << r e c t a n g l e A r e a ( 1 0 , 2 ) << e n d l ; 10 return 0; 11 } 12 13 i n t r e c t a n g l e A r e a ( i n t l e n g t h , i n t w i d t h ) { 14 r e t u r n l e n g t h * width ; 15 } 6.5 Practice Questions 6. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t myFunction ( i n t ) ; 5 6 i n t main ( ) { 7 i n t number = 5 ; 8 c o u t << number << e n d l ; 9 c o u t << m y F u n c t i o n ( number ) << e n d l ; 10 c o u t << number << e n d l ; 11 } 12 13 i n t m y F u n c t i o n ( i n t v a l u e ) { 14 value *=5; 15 return value ; 16 } 7. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t myFunction ( i n t &); 5 6 i n t main ( ) { 7 i n t number = 5 ; 8 c o u t << number << e n d l ; 9 c o u t << m y F u n c t i o n ( number ) << e n d l ; 10 c o u t << number << e n d l ; 11 } 12 13 i n t m y F u n c t i o n ( i n t &v a l u e ) { 14 value *=5; 15 return value ; 16 } 87 Chapter 6. Functions and Parameters 88 8. Write a program that defines and tests function factorial(). Use a for loop for this function. Sample output is given. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 int factorial ( int x ); 5 6 i n t main ( ) { 7 i n t number ; 8 c o u t << " E n t e r an i n t e g e r f o r t h e d e s i r e d f a c t o r i a l : " ; 9 c i n >> number ; 10 c o u t << number << " ! = " << f a c t o r i a l ( number ) << e n d l ; 11 return 0; 12 } 13 14 i n t f a c t o r i a l ( i n t x ) { 15 16 17 18 19 20 21 } Sample output: Enter an integer for the desired factorial: 5 5! = 120 6.5 Practice Questions 89 9. Write a program that defines and tests a function that prints the first n positive integers followed by their sum. Use a while loop for this function. Sample output is given. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void p r i n t A l l I n t e g e r s ( i n t x ) ; 5 6 i n t main ( ) { 7 i n t number ; 8 c o u t << " E n t e r an I n t e g e r : " ; 9 c i n >> number ; 10 c o u t << " The f i r s t " << number << " i n t e g e r s a r e l i s t e d below : " << e n d l ; 11 p r i n t A l l I n t e g e r s ( number ) ; 12 return 0; 13 } / / end main ( ) f u n c t i o n 14 15 v o i d p r i n t A l l I n t e g e r s ( i n t x ) { 16 17 18 19 20 21 22 23 } Sample output: Enter an Integer: 6 The first 6 positive integers are listed below: 1 2 3 4 5 6 Sum = 21 Chapter 6. Functions and Parameters 90 10. Write a C++ program that defines and tests a function largest(. . . .) that takes as parameters any three integers and returns the largest of the three integers. Sample output: Enter three integers: 6 15 8 The largest integer is: 15 11. Write a C++ program that defines and tests a function absoluteValue(. . . .) that takes as a parameter a floating point number and returns its absolute value. Sample output: Enter a number: -4.25 The absolute value is: 4.25 12. Write a C++ program that defines a function reverseInt(int n) that takes as an argument a positive integer and returns an integer with digits in reverse order. Print n before and after reversing the digits. Your output should have the same format and should work for any integer a user enters. Sample output: The value before reverse is: 425 The value after reverse is: 524 13. Write a C++ program that defines and tests a function multiplyNumbers(m,n) that takes two positive integers m and n, computes m * n by using only addition, and returns the product. Hint: Use iteration and notice for example that 3*2=2 +2 +2 Sample output: Enter m: 2 Enter n: 3 2*3 = 6 6.5 Practice Questions 91 14. Write a C++ program that defines and tests a function power(base, exponent) that takes two integers b and x and returns bx by using only multiplication. Design your own function. Do not use the built in function pow(). Sample output: Enter base: 2 Enter Exponent: 3 2 to the power 3 = 8 15. Write a boolean function divisibleBySeven(. . . ) definition that takes as an input an integer and returns true if the integer is divisible by 7, false if not. Make sure you use the proper function return type and argument list. Just write the function definition. You do not need to write a complete C++ program. 16. Write a function isDigit(. . . ) definition that takes one argument of type char and returns a bool value. The function returns true if the argument is a decimal digit; otherwise it returns false. Make sure you use the proper function return type and argument list. Just write the function definition. You do not need to write a complete C++ program. 17. Write a function multiple(. . . ) definition that determines for a pair of integers whether the second integer is a multiple of the first. The function should take two integer arguments and return true if the second is a multiple of the first, false otherwise. . Make sure you use the proper function return type and argument list. Just write the function definition. You do not need to write a complete C++ program. 7. Variable Scope 7.1 Local and Global Variables A variable is local if it is declared inside a function. A global variable is declared outside of all functions including main. Global variables are typically declared at the very beginning of the program. Local variables are better choices unless there is a specific need for a global variable shared by multiple functions. Chapter 7. Variable Scope 94 Code 7.1: Global vs. local variables example 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 # include <iostream > u s i n g namespace s t d ; i n t i = 1; void f i r s t F u n c t i o n ( ) ; void secondFunction ( ) ; void t h i r d F u n c t i o n ( ) ; i n t main ( ) { i n t i = 2; c o u t << " I n s i d e main ( ) : i = " << i << e n d l ; firstFunction (); secondFunction ( ) ; thirdFunction (); return 0; } void f i r s t F u n c t i o n ( ) { i n t i = 3; c o u t << " I n s i d e f i r s t F u n c t i o n ( ) : i = " << i << e n d l ; } void secondFunction ( ) { c o u t << " I n s i d e s e c o n d F u n c t i o n ( ) : i = " << i << e n d l ; } void t h i r d F u n c t i o n ( ) { i n t i = 4; c o u t << " I n s i d e t h i r d F u n c t i o n ( ) : i = " << : : i << e n d l ; } <— Get a version of the code here. 7.2 Default and Static Variables The ‘lifetime’ of a variable is determined by the storage category it belongs. The most commonly used categories are auto (default choice) and static. An auto local variable is assigned memory space automatically during the execution of a function. Once the function returns, the variable’s memory space is released and made available to other processes. A static variable continues to ‘exist’ during the entire execution of the program. 7.3 Pre-defined Functions 95 Code 7.2: Example auto variable 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void t e s t ( ) ; 5 6 i n t main ( ) { 7 8 f o r ( i n t i = 1 ; i <=3; i ++) 9 test (); 10 11 return 0; 12 } / / end main ( ) 13 14 v o i d t e s t ( ) { 15 16 i n t number = 0 ; 17 c o u t << " number i s : " << number << e n d l ; 18 number ++; 19 20 return ; 21 } / / end t e s t ( ) Change the local variable ‘number’ to static and run the program. What do you observe? 7.3 Pre-defined Functions A number of pre-defined functions are already available for programmers to use. These functions are grouped in collections called libraries. In order for the user to have access to these functions the program should include the given library. <cmath> is an example of a library. The following program illustrates some of its functions. Chapter 7. Variable Scope 96 Code 7.3: Using functions from the cmath library 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # include <iostream > # i n c l u d e <cmath > # i n c l u d e <iomanip > u s i n g namespace s t d ; i n t main ( ) { cout cout cout cout cout cout cout << << << << << << << f i x e d << s e t p r e c i s i o n ( 2 ) ; " s q r t ( 1 2 . 0 ) = " << s q r t ( 1 2 . 0 ) << e n d l ; " exp ( 1 . 0 ) = " << s e t p r e c i s i o n ( 3 ) << exp ( 1 . 0 ) << e n d l ; " l o g ( 8 . 3 2 ) = " << l o g ( 8 . 3 2 ) << e n d l ; " l o g ( exp ( 8 . 2 3 ) ) = " << l o g ( exp ( 8 . 2 3 ) ) << e n d l ; " pow ( 2 , 3 ) = " << pow ( 2 , 3 ) << e n d l ; " c o s ( 9 0 ) = " << s e t p r e c i s i o n ( 1 5 ) << c o s ( 9 0 ) << e n d l ; return 0; } <— Get code here. Code 7.4: Random number generator 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # include <iostream > # i n c l u d e <cmath > # include <cstdlib > # i n c l u d e <ctime > u s i n g namespace s t d ; i n t main ( ) { int n, r ; s r a n d ( t i m e (NULL ) ) ; c o u t << "How many numbers do you want ? " ; c i n >> n ; f o r ( i n t i = 1 ; i <= n ; i ++) { r = rand ( ) % 9 + 1; c o u t << r << " " ; } return 0; } What is the range of numbers generated by the program? 7.3 Pre-defined Functions 97 Modify the program to generate numbers in the range [5,10]. Modify the program to generate numbers in the range [-3,25]. Modify the program to allow the user to specify the range of values to be generated. Modify the program to display a frequency distribution of the values and graph the results. Sample output: How many number do you want? 20 22632341434554333342 Value 1 2 3 4 5 6 Freq 1 4 7 5 2 1 Graph * **** ******* ***** ** * Chapter 7. Variable Scope 98 7.4 Practice Questions 1. What is the meaning of the following in the context of Computer Science? (a) local and global variables: (b) Stack: (c) scope of a variable: (d) static variable: 2. True-False questions – Circle your choice (a) A variable is local if it is declared inside the main function. ( True - False ) (b) A variable declared within a function is said to be local to the function. ( True - False ) 3. The statement n = rand(); assigns to variable n a value between 0 and a very large positive integer. Change the statement to assign to n a value in the following ranges. (a) [1, 5] (b) [5, 100] (c) [−3, 18] 7.4 Practice Questions 99 4. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t myFunction ( ) ; 5 6 i n t main ( ) { 7 c o u t << m y F u n c t i o n ( ) << e n d l ; 8 c o u t << m y F u n c t i o n ( ) << e n d l ; 9 c o u t << m y F u n c t i o n ( ) << e n d l ; 10 return 0; 11 } 12 13 i n t m y F u n c t i o n ( ) { 14 i n t number = 0 ; 15 r e t u r n number ++; 16 } 5. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t myFunction ( ) ; 5 6 i n t main ( ) { 7 c o u t << m y F u n c t i o n ( ) 8 c o u t << m y F u n c t i o n ( ) 9 c o u t << m y F u n c t i o n ( ) 10 return 0; 11 } 12 13 i n t m y F u n c t i o n ( ) { 14 s t a t i c i n t number = 15 r e t u r n number ++; 16 } << e n d l ; << e n d l ; << e n d l ; 0; Chapter 7. Variable Scope 100 6. Write the exact output for the following code. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 char myFunction ( ) ; 5 6 i n t main ( ) { 7 c o u t << m y F u n c t i o n ( ) << 8 c o u t << m y F u n c t i o n ( ) << 9 c o u t << m y F u n c t i o n ( ) << 10 return 0; 11 } 12 13 c h a r m y F u n c t i o n ( ) { 14 s t a t i c char character = 15 r e t u r n c h a r a c t e r ++; 16 } endl ; endl ; endl ; ’a ’ ; 7. Write the exact output. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 # include <iostream > u s i n g namespace s t d ; i n t i = 7; void f i r s t F u n c t i o n ( ) ; void secondFunction ( ) ; i n t main ( ) { i n t i = 2; c o u t << " I n s i d e main ( ) : i = " << i << e n d l ; firstFunction (); secondFunction ( ) ; return 0; } void f i r s t F u n c t i o n ( ) { i n t i = 5; c o u t << " I n s i d e f i r s t F u n c t i o n ( ) : i = " << i << e n d l ; } void secondFunction ( ) { c o u t << " I n s i d e s e c o n d F u n c t i o n ( ) : i = " << i << e n d l ; } 8. Arrays 8.1 What are Arrays An array is an ordered collection (potentially very large) of items. Arrays are indexed to allow easier access to its elements. Arrays are powerful structures that allow the user to store multiple data values of the same type without having to declare as many variables. Assume we want to store 5 double data values for further processing (example find their average). One way is to declare 5 different double variables, one for each value. This is not an efficient way of storing data. Imagine we have to do this for a lot more data values. The following program uses an array to store the data values and calculate the average of all these values. Chapter 8. Arrays 102 Code 8.1: Example using arrays 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 d o u b l e myArray [ 5 ] ; 7 8 c o u t << " E n t e r v a l u e s : " << e n d l ; 9 10 f o r ( i n t i = 0 ; i < 5 ; i ++) 11 c i n >> myArray [ i ] ; 12 13 d o u b l e sum = 0 ; 14 f o r ( i n t i = 0 ; i < 5 ; i ++) 15 sum += myArray [ i ] ; 16 17 c o u t << " The A v e r a g e i s : " << sum / 5 << e n d l ; 18 return 0; 19 } 8.2 Initializing Arrays Arrays follow the same principles regarding initialization as variables. Global numerical variables (arrays) are all initialized to zero by default if the user does not specify any values. Local variables must be initialized by the user otherwise they will be possibly assigned random values. 8.2 Initializing Arrays 103 Code 8.2: Initializing global and local arrays 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 int globalArray [6]; 5 6 i n t main ( ) { 7 8 int localArray [8]; 9 10 c o u t << " G l o b a l A r r a y v a l u e s b e f o r e i n i t i a l i z i n g . " << e n d l ; 11 f o r ( i n t i = 0 ; i < 6 ; i ++) 12 c o u t << g l o b a l A r r a y [ i ] << " " ; 13 14 c o u t << e n d l << e n d l ; 15 16 c o u t << " L o c a l A r r a y v a l u e s b e f o r e i n i t i a l i z i n g . " << e n d l ; 17 f o r ( i n t i = 0 ; i < 8 ; i ++) 18 c o u t << l o c a l A r r a y [ i ] << " " ; 19 20 c o u t << e n d l << e n d l ; 21 22 int initializedLocalArray [5] = {3 ,4 ,6 ,2 ,4}; 23 24 c o u t << " I n i t i a l i z e d L o c a l A r r a y v a l u e s . " << e n d l ; 25 f o r ( i n t i = 0 ; i < 5 ; i ++) 26 c o u t << i n i t i a l i z e d L o c a l A r r a y [ i ] << " " ; 27 28 return 0; 29 } <— Get code here. Modify the following code to use an array instead of the individually declared variables. Does this approach improve code writing and code readability? <— Get code here. Chapter 8. Arrays 104 Code 8.3: Random number simulator with statistics 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 48 49 50 51 52 53 54 55 56 57 # include <iostream > # include <cstdlib > # i n c l u d e <ctime > u s i n g namespace s t d ; void keepRecord ( i n t ) ; void d i s p l a y S t a t i s t i c s ( ) ; i n t n1 , n2 , n3 , n4 , n5 ; i n t main ( ) { int n , r ; s r a n d ( t i m e (NULL ) ) ; c o u t << "How many numbers do you want : " ; c i n >> n ; f o r ( i n t i = 1 ; i <= n ; i ++) { r = r a n d ( ) \% 5 + 1 ; c o u t << r << " " ; keepRecord ( r ) ; } c o u t << e n d l << e n d l ; displayStatistics (); return 0; } void keepRecord ( i n t value ){ switch ( value ){ c a s e 1 : n1 ++; b r e a k ; c a s e 2 : n2 ++; b r e a k ; c a s e 3 : n3 ++; b r e a k ; c a s e 4 : n4 ++; b r e a k ; c a s e 5 : n5 ++; b r e a k ; } } void d i s p l a y S t a t i s t i c s ( ) { c o u t << " V a l u e \ t " << " F r e q \ t " << " Graph " << e n d l << e n d l ; c o u t << " 1 \ t " << n1 << " \ t " ; f o r ( i n t i = 0 ; i <n1 ; i ++) c o u t << " * " ; c o u t << e n d l ; c o u t << " 2 \ t " << n2 << " \ t " ; f o r ( i n t i = 0 ; i <n2 ; i ++) c o u t << " * " ; c o u t << e n d l ; c o u t << " 3 \ t " << n3 << " \ t " ; f o r ( i n t i = 0 ; i <n3 ; i ++) c o u t << " * " ; c o u t << e n d l ; c o u t << " 4 \ t " << n4 << " \ t " ; f o r ( i n t i = 0 ; i <n4 ; i ++) c o u t << " * " ; c o u t << e n d l ; c o u t << " 5 \ t " << n5 << " \ t " ; f o r ( i n t i = 0 ; i <n1 ; i ++) c o u t << " * " ; c o u t << e n d l ; } 8.3 Array Size 8.3 105 Array Size It is a good practice to declare a constant integer for the size of the array and use it during the program as needed. Code 8.4: Using constant array size example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 c o n s t i n t myArraySize = 5 ; 7 i n t myArray [ m y A r r a y S i z e ] = { 3 , 4 , 6 , 2 , 4 } ; 8 9 c o u t << " Number o f e l e m e n t s : " << m y A r r a y S i z e << e n d l ; 10 c o u t << " L i s t o f e l e m e n t s : " ; 11 f o r ( i n t i = 0 ; i < m y A r r a y S i z e ; i ++) 12 c o u t << myArray [ i ] << " " ; 13 14 return 0; 15 } Another way of getting the array size. Code 8.5: Calculating number of array elements 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 i n t myArray [ 5 ] = { 3 , 4 , 6 , 2 , 4 } ; 7 8 c o u t << " A r r a y s i z e i n b y t e s : " << s i z e o f ( myArray ) << e n d l ; 9 c o u t << " F i r s t e l e m e n t s i z e : " << s i z e o f ( myArray [ 0 ] ) << e n d l ; 10 i n t s i z e = s i z e o f ( myArray ) / s i z e o f ( myArray [ 0 ] ) ; 11 c o u t << " The number o f e l e m e n t s i s : " << s i z e << e n d l ; 12 c o u t << " E l e m e n t s i n t h e a r r a y s a r e : " ; 13 f o r ( i n t i = 0 ; i < s i z e ; i ++) 14 c o u t << myArray [ i ] << " " ; 15 16 return 0; 17 } <— Get code here. Chapter 8. Arrays 106 8.4 Passing Arrays to Functions In C++ arrays are passed to functions by reference. Individual elements from the array are passed by value. See example below. Code 8.6: Passing Arrays to Functions Example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void modifyArray ( i n t [ ] , i n t ) ; 5 6 i n t main ( ) { 7 8 const i n t arraySize = 5; 9 i n t myArray [ a r r a y S i z e ] = { 3 , 4 , 6 , 2 , 8 } ; 10 11 c o u t << " E l e m e n t s i n t h e o r i g i n a l a r r a y a r e : " << e n d l ; 12 f o r ( i n t i = 0 ; i < a r r a y S i z e ; i ++) 13 c o u t << myArray [ i ] << " " ; 14 c o u t << e n d l << e n d l ; 15 16 m o d i f y A r r a y ( myArray , a r r a y S i z e ) ; 17 18 c o u t << " E l e m e n t s i n t h e m o d i f i e d a r r a y a r e : " << e n d l ; 19 f o r ( i n t i = 0 ; i < a r r a y S i z e ; i ++) 20 c o u t << myArray [ i ] << " " ; 21 c o u t << e n d l ; 22 23 return 0; 24 } / / end main 25 26 v o i d m o d i f y A r r a y ( i n t a [ ] , i n t s i z e O f A r r a y ) { 27 f o r ( i n t i = 0 ; i < s i z e O f A r r a y ; i ++) 28 a [ i ]++; 29 } / / end m o d i f y A r r a y ( ) <— Get code here. Add another value to the number set 3,4,6,2,8, in PassingArraysToFunctions.cpp, compile and run the program. Does the program run? What do you observe? What can you conclude? Change the function signature to read void modifyArray(const int a[], int sizeOfArray). Compile and run the program. What do you notice? Add a ’cout’ statement that prints myArray[5]. Does it work? What do you think is happening? 8.4 Passing Arrays to Functions 107 Write a program that uses a function largestValue(int[], int) that takes as an argument an array of integers and the size of the array and returns the largest value in the array. Part of the code is given. Complete the remaining code (function definition) to produce the desired output. Desired output format: The largest value is: 25 Code 8.7: Class code activity 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 int largestValue ( int [] , int ); 5 6 i n t main ( ) { 7 8 const i n t arraySize = 10; 9 i n t myArray [ a r r a y S i z e ] = { 3 , 4 , 6 , 2 1 , 8 , 1 3 , 2 5 , 1 , 7 , 1 1 } ; 10 11 c o u t << " The l a r g e s t i n t e g e r i s : " ; 12 c o u t << l a r g e s t V a l u e ( myArray , a r r a y S i z e ) ; 13 14 return 0; 15 } / / end main 16 17 i n t l a r g e s t V a l u e ( i n t a [ ] , i n t s i z e O f A r r a y ) { 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 } / / end l a r g e s t V a l u e ( ) Chapter 8. Arrays 108 8.5 Characters, Strings and Arrays of Strings Code 8.8: Example illustrating different char arrays. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 char f i r s t A r r a y [ 8 ] ; 7 8 f o r ( i n t i = 0 ; i < 8 ; i ++) 9 f i r s t A r r a y [ i ]= ’ d ’ ; 10 11 c o u t << " P r i n t f i r s t A r r a y u s i n g f o r l o o p : " << e n d l ; 12 f o r ( i n t i = 0 ; i < 7 ; i ++) 13 c o u t << f i r s t A r r a y [ i ] ; 14 15 f i r s t A r r a y [7]= ’ \0 ’ ; 16 c o u t << e n d l ; 17 18 c o u t << " P r i n t f i r s t A r r a y u s i n g i d e n t i f i e r : " << e n d l ; 19 c o u t << f i r s t A r r a y << e n d l ; 20 21 c h a r s e c o n d A r r a y [ ] = { ’H ’ , ’ e ’ , ’ l ’ , ’ l ’ , ’ o ’ , ’ \ 0 ’ } ; 22 c o u t << " P r i n t s e c o n d A r r a y u s i n g f o r l o o p : " << e n d l ; 23 f o r ( i n t i = 0 ; i < 6 ; i ++) 24 c o u t << s e c o n d A r r a y [ i ] ; 25 c o u t << e n d l ; 26 27 char thirdArray [ ] = " Test " ; 28 c o u t << " P r i n t t h i r d A r r a y u s i n g f o r l o o p : " << e n d l ; 29 f o r ( i n t i = 0 ; i < 4 ; i ++) 30 c o u t << t h i r d A r r a y [ i ] ; 31 c o u t << e n d l ; 32 33 c o u t << " C h a n g i n g one d i g i t i n t h i r d a r r a y : " << e n d l ; 34 t h i r d A r r a y [ 0 ] = ’N ’ ; 35 c o u t << " P r i n t t h i r d A r r a y u s i n g f o r l o o p : " << e n d l ; 36 f o r ( i n t i = 0 ; i < 4 ; i ++) 37 c o u t << t h i r d A r r a y [ i ] ; 38 39 return 0; 40 } <— Get code here. Comment out the statement firstArray[7]=’\0’; . What changes do you see in the output? 8.6 Multi-Dimensional Arrays 109 Code 8.9: Array of Strings Example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 c h a r * weekDays [ 7 ] = { " Monday " , " T u e s d a y " , " Wednesday " , 7 " T h u r s d a y " , " F r i d a y " , " S a t u r d a y " , " Sunday " } ; 8 9 f o r ( i n t i = 0 ; i < 7 ; i ++) 10 c o u t << weekDays [ i ] << e n d l ; 11 12 return 0; 13 } 8.6 Multi-Dimensional Arrays C++ allows creation of arrays with 2 or more dimensions. Below is an example of declaring, initializing and printing a 2-dimensional array of numbers. Code 8.10: Example 2D Array 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 c o n s t i n t columns = 6 ; 6 c o n s t i n t rows = 4 ; 7 i n t my2DArray [ rows ] [ c o l u m n s ] ; 8 9 f o r ( i n t i = 0 ; i < rows ; i ++){ 10 f o r ( i n t j = 0 ; j < c o l u m n s ; j ++) 11 my2DArray [ i ] [ j ] = i + j ; 12 } 13 14 f o r ( i n t i = 0 ; i < rows ; i ++){ 15 f o r ( i n t j = 0 ; j < c o l u m n s ; j ++) 16 c o u t << my2DArray [ i ] [ j ] << " " ; 17 c o u t << e n d l ; 18 } 19 return 0; 20 } Chapter 8. Arrays 110 Code 8.11: Another 2D Array Example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void p ri n t Ar r a y ( const i n t [ ] [ 3 ] ) ; 5 c o n s t i n t rows = 2 ; 6 c o n s t i n t columns = 3 ; 7 8 i n t main ( ) { 9 i n t a r r a y 1 [ rows ] [ c o l u m n s ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } } ; 10 i n t a r r a y 2 [ rows ] [ c o l u m n s ] = { 1 , 2 , 3 , 4 , 5 } ; 11 i n t a r r a y 3 [ rows ] [ c o l u m n s ] = { { 1 , 2 } , { 4 } } ; 12 13 c o u t << " V a l u e s i n a r r a y 1 a r e : " << e n d l ; 14 printArray ( array1 ) ; 15 16 c o u t << " V a l u e s i n a r r a y 2 a r e : " << e n d l ; 17 printArray ( array2 ) ; 18 19 c o u t << " V a l u e s i n a r r a y 3 a r e : " << e n d l ; 20 printArray ( array3 ) ; 21 22 return 0; 23 } 24 25 v o i d p r i n t A r r a y ( c o n s t i n t a [ ] [ c o l u m n s ] ) { 26 f o r ( i n t i = 0 ; i < rows ; i ++){ 27 f o r ( i n t j = 0 ; j < c o l u m n s ; j ++) 28 c o u t << a [ i ] [ j ] << " " ; 29 c o u t << e n d l ; 30 } 31 } <— Get code here. 8.7 Practice Questions 8.7 111 Practice Questions 1. What is the meaning of the following in the context of Computer Science? (a) array index: (b) array length / size: 2. True-False questions – Circle your choice (a) The same array can store different types of values. ( True - False ) (b) The statement s[4] refers to the fourth element of array s. ( True - False ) (c) The statement array[5][6] reads the value of the array element in row 5 and column 6. ( True - False ) (d) In C++ all arrays are passed as arguments to a function by value. ( True - False ) (e) The elements of the same C++ array can be of different data types. ( True - False ) 3. Fill in the blanks. (a) The number used to refer to a specific element in an array is called its . (b) A 5 x 3 array contains rows, columns and elements. 4. Given the array declaration, int a[20]; The first element of this array is written as: (a) (b) (c) (d) (e) a[1] a[0] a a[19] a[20] Chapter 8. Arrays 112 5. Fix the errors in the code to obtain the desired output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void modifyArray ( i n t [ ] , i n t ) ; 5 6 i n t main ( ) { 7 8 const i n t arraySize = 5; 9 i n t myArray [ a r r a y S i z e ] = { 3 , 4 , 6 , 2 , 8 , 9 } ; 10 11 m o d i f y A r r a y ( myArray , a r r a y S i z e ) ; 12 13 return 0; 14 } / / end main 15 16 v o i d m o d i f y A r r a y ( c o n s t i n t a [ ] ) { 17 f o r ( i n t i = 0 ; i < s i z e O f A r r a y ; i ++){ 18 a [ i ]++; 19 c o u t << a [ i ] << e n d l ; 20 } 21 } Desired output: 4 5 7 3 9 10 8.7 Practice Questions 6. Fix the errors in the following code. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 c h a r weekDays [ ] = { " Monday " , " T u e s d a y " , " Wednesday " , 7 " T h u r s d a y " , " F r i d a y " , " S a t u r d a y " , " Sunday " } ; 8 9 f o r ( i n t i = 0 ; i < 7 ; i ++){ 10 c o u t << weekDays [ i ] << e n d l ; 11 } 12 return 0; 13 } 113 114 Chapter 8. Arrays 7. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void p ri n t Ar r a y ( const i n t [ ] [ 3 ] ) ; 5 c o n s t i n t rows = 2 ; 6 c o n s t i n t columns = 3 ; 7 8 i n t main ( ) { 9 i n t a r r a y 1 [ rows ] [ c o l u m n s ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } } ; 10 i n t a r r a y 2 [ rows ] [ c o l u m n s ] = { 1 , 2 , 3 , 4 , 5 } ; 11 i n t a r r a y 3 [ rows ] [ c o l u m n s ] = { { 1 , 2 } , { 4 } } ; 12 13 c o u t << " V a l u e s i n a r r a y 1 a r e : " << e n d l ; 14 printArray ( array1 ) ; 15 16 c o u t << " V a l u e s i n a r r a y 2 a r e : " << e n d l ; 17 printArray ( array2 ) ; 18 19 c o u t << " V a l u e s i n a r r a y 3 a r e : " << e n d l ; 20 printArray ( array3 ) ; 21 22 return 0; 23 } 24 25 v o i d p r i n t A r r a y ( c o n s t i n t a [ ] [ c o l u m n s ] ) { 26 f o r ( i n t i = 0 ; i < rows ; i ++){ 27 f o r ( i n t j = 0 ; j < c o l u m n s ; j ++) 28 c o u t << a [ i ] [ j ] << " " ; 29 c o u t << e n d l ; 30 } 31 } 8.7 Practice Questions 8. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 i n t myArray [ 6 ] = { 3 , 4 , 6 , 2 , 4 , 7 } ; 7 8 c o u t << s i z e o f ( myArray ) << e n d l ; 9 c o u t << s i z e o f ( myArray [ 0 ] ) << e n d l ; 10 11 return 0; 12 } 9. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 c o n s t i n t columns = 4 ; 6 c o n s t i n t rows = 3 ; 7 i n t my2DArray [ rows ] [ c o l u m n s ] ; 8 9 f o r ( i n t i = 0 ; i < rows ; i ++){ 10 f o r ( i n t j = 0 ; j < c o l u m n s ; j ++) 11 my2DArray [ i ] [ j ] = 6− i + j ; 12 } 13 14 f o r ( i n t i = 0 ; i < rows ; i ++){ 15 f o r ( i n t j = 0 ; j < c o l u m n s ; j ++) 16 c o u t << my2DArray [ i ] [ j ] << " " ; 17 c o u t << e n d l ; 18 } 19 return 0; 20 } 115 116 Chapter 8. Arrays 10. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 i n t my2DArray [ 3 ] [ 3 ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; 7 8 c o u t << my2DArray [ 1 ] [ 0 ] << e n d l ; 9 c o u t << my2DArray [ 2 ] [ 1 ] << e n d l ; 10 c o u t << my2DArray [ 1 ] [ 2 ] << e n d l ; 11 12 return 0; 13 } 8.7 Practice Questions 117 11. Make only one change to the program below so that the current output changes to the desired output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 c h a r * weekDays [ 7 ] = { " Monday " , " T u e s d a y " , 7 " Wednesday " , " T h u r s d a y " , " F r i d a y " , " S a t u r d a y " , " Sunday " } ; 8 9 f o r ( i n t i = 0 ; i < 7 ; i ++){ 10 c o u t << weekDays [ i ] << e n d l ; 11 } 12 13 return 0; 14 } Current output: Monday Tuesday Wednesday Thursday Friday Saturday Sunday Desired output: M T W T F S S Chapter 8. Arrays 118 12. Make only one change to the program below so that the current output changes to the desired output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 c h a r * weekDays [ 7 ] = { " Monday " , " T u e s d a y " , 6 " Wednesday " , " T h u r s d a y " , " F r i d a y " , " S a t u r d a y " , " Sunday " } ; 7 8 f o r ( i n t i = 0 ; i < 7 ; i ++){ 9 c o u t << weekDays [ 0 ] [ i ] << e n d l ; 10 } 11 12 return 0; 13 } Current output: M o n d a y Desired output: Monday onday nday day ay y 8.7 Practice Questions 119 13. Complete the program below so that it prints the content of My2Darray as shown in the output column. Use a nested for loop to print the values. Use the tab feature to print the values in distinct columns as shown. 1 ## i n c l u d e < i o s t r e a m > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 c o n s t i n t columns = 3 ; 6 c o n s t i n t rows = 4 ; 7 i n t my2DArray [ rows ] [ c o l u m n s ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 1 0 , 1 1 , 1 2 } ; 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 return 0; 25 } Desired output: 1 4 7 10 2 5 8 11 3 6 9 12 Chapter 8. Arrays 120 14. Assume we want to store 5 double data values for further processing (example find their average). Write a program that allows the user to input 5 numerical values and uses an array to store the data values and calculate the average of all these values. Desired output: Enter value: 5 6 8 2.3 3.2 The Average is: 4.9 15. Write a function definition LinearSearch(. . . .) to perform a linear search of an array. The function should receive an integer array and the size of the array as arguments, and the key. If the search key is found, return the array index; otherwise, return -1. Make sure you use the proper function return type and argument list. Just write the function definition. You do not need to write a complete C++ program. 16. Write the function void rotateRight (int n, char a[]) which moves each of the n characters one position to the right, but moves the last character to the first position. For example, if a contained n = 4 characters, ABCD, then when the function is finished, it would contain DABC. Make sure you use the proper function return type and argument list. Just write the function definition. You do not need to write a complete C++ program. 17. Write a function definition largestIndex(. . . ) that returns the index of the largest element of a global integer array myArray of length 100. Make sure you use the proper function return type and argument list. Just write the function definition. You do not need to write a complete C++ program. 18. Write a function averageValue(. . . ) that returns the average of all the elements in a global array myArray of double values. (hint: the number of elements in array a must be passed to the function.) Make sure you use the proper function return type and argument list. Just write the function definition. You do not need to write a complete C++ program. 9. Pointers 9.1 What are Pointers? Pointers are a powerful feature of C++. They allow the user to pass-by-reference which in turn allows manipulation of more complex, dynamic data structures. Pointers will be extensively used in later more advanced topics. Code 9.1: Pointers first example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 i n t x = 5; 7 i n t * x P o i n t e r = &x ; 8 9 c o u t << " A d d r e s s o f x : " << &x << e n d l ; 10 c o u t << " V a l u e o f x P o i n t e r : " << x P o i n t e r << e n d l << e n d l ; 11 12 c o u t << " A d d r e s s o f x P o i n t e r : " << &x P o i n t e r << e n d l << e n d l ; 13 14 c o u t << " V a l u e o f x : " << x << e n d l ; 15 c o u t << " V a l u e o f * x P o i n t e r : " << * x P o i n t e r << e n d l ; 16 17 return 0; 18 } <— Get code here. Chapter 9. Pointers 122 Code 9.2: Another example using pointers 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void doubleValue ( i n t *p ) ; 5 6 i n t main ( ) { 7 8 i n t myInt = 5 ; 9 c o u t << " m y I n t b e f o r e d o u b l i n g : " << m y I n t << e n d l ; 10 d o u b l e V a l u e (& m y I n t ) ; 11 c o u t << " m y I n t a f t e r d o u b l i n g : " << m y I n t << e n d l ; 12 13 return 0; 14 } / / end main ( ) 15 16 v o i d d o u b l e V a l u e ( i n t * p ) { 17 *p = *p * 2 ; 18 } / / end d o u b l e V a l u e ( ) Write a C++ program that swaps the values of two integer variables a and b. Use a function swap1(*p1, *p2). Print a and b before and after swapping. Your output should have the same format and should work for any integer a user enters. Use pointers. Desired output format: The value of a before swapping is: 4 The value of b before swapping is: 7 The value of a after swapping is: 7 The value of b after swapping is: 4 9.2 Arrays and Pointer Arithmetic Arrays store values in consecutive memory locations. Pointer can be very useful when processing arrays. The example below illustrates some of the array properties and the use of pointers. 9.2 Arrays and Pointer Arithmetic 123 Code 9.3: Arrays and pointers example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 const i n t arraySize = 5; 7 i n t myArray [ a r r a y S i z e ] = { 2 , 4 , 7 , 9 , 1 } ; 8 i n t * p = myArray ; 9 10 c o u t << " I n d e x \ t V a l u e \ t A d d r e s s " << e n d l << e n d l ; 11 12 f o r ( i n t i = 0 ; i < a r r a y S i z e ; i ++){ 13 c o u t << i << " \ t " ; 14 c o u t << myArray [ i ] << " \ t " ; 15 c o u t << &myArray [ i ] << " \ t " << e n d l ; 16 } 17 c o u t << e n d l ; 18 19 c o u t << " p i s p o i n t i n g a t a d d r e s s : " << p << e n d l ; 20 c o u t << " The v a l u e o f * p i s : " << * p << e n d l << e n d l ; 21 22 c o u t << " Moving p t o t h e n e x t memory a d d r e s s . " << e n d l ; 23 p = p +1; 24 25 c o u t << " p i s p o i n t i n g a t a d d r e s s : " << p << e n d l ; 26 c o u t << " The v a l u e o f * p i s : " << * p << e n d l ; 27 28 return 0; 29 } <— Get code here. Change myArray from an array of integers to a double array. Run the program, compare any two consecutive addresses. What do you notice? Change line 8 from int *p = myArray; to int *p = &myArray[0]. Is there any difference in the output? Why? Chapter 9. Pointers 124 Code 9.4: Using pointers to work with strings 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 5 c h a r * m y S t r i n g s [ 4 ] = { " one " , " two " , " t h r e e " , " f o u r " } ; 6 7 i n t main ( ) { 8 9 c o u t << " P r i n t i n g t h e a r r a y c o n t e n t . " << e n d l ; 10 f o r ( i n t i = 0 ; i < 4 ; i ++) 11 c o u t << m y S t r i n g s [ i ] << e n d l ; 12 c o u t << e n d l ; 13 14 c o u t << " P r i n t i n g t h e a d d r e s s o f e a c h s t r i n g . " << e n d l ; 15 f o r ( i n t i = 0 ; i < 4 ; i ++) 16 c o u t << &m y S t r i n g s [ i ] << e n d l ; 17 c o u t << e n d l ; 18 19 c o u t << " P r i n t i n g s u b s t r i n g s o f t h e t h i r d s t r i n g . " << e n d l ; 20 f o r ( i n t i = 0 ; i < 5 ; i ++) 21 c o u t << &m y S t r i n g s [ 2 ] [ i ] << e n d l ; 22 c o u t << e n d l ; 23 24 c o u t << " P r i n t i n g t h e v a l u e where p o i n t e r s a r e . " << e n d l ; 25 f o r ( i n t i = 0 ; i < 4 ; i ++) 26 c o u t << * m y S t r i n g s [ i ] << e n d l ; 27 c o u t << e n d l ; 28 29 return 0; 30 } <— Get code here. 10. Structures 10.1 What are Structures? We have used variables that allow us to store information in the computer. Variable types such as int, char, etc. allow us to save information of a single type. Structures allow us to organize information as collections of values that belong to the same entity and are connected to one another in a meaningful way. Understanding structures is a helpful step to better understand classes and objects which we will discuss in the next chapter. Code 10.1: Structure example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 s t r u c t Course { 5 i n t courseNumber ; 6 char grade ; 7 }; 8 9 i n t main ( ) { 10 11 C o u r s e myCourse ; 12 myCourse . c o u r s e N u m b e r = 1 0 1 ; 13 myCourse . g r a d e = ’A ’ ; 14 15 c o u t << " I t o o k MAC " << myCourse . c o u r s e N u m b e r ; 16 c o u t << " and I g o t a ( n ) " << myCourse . g r a d e << e n d l ; 17 18 return 0; 19 } 126 Chapter 10. Structures Add a new structure to the program above named Exam, which has two member variables, examNumber and grade. Assign values from main() to both variables, then print the results similar to what we did with the Course structure. Is it working? Is there a problem using the same name (grade) for both structures? Code 10.2: Alternative way of initializing structures 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 s t r u c t Course { 5 i n t courseNumber ; 6 char grade ; 7 }; 8 9 i n t main ( ) { 10 11 C o u r s e myCourse = { 1 0 1 , ’A ’ } ; 12 13 c o u t << " I t o o k MAC " << myCourse . c o u r s e N u m b e r ; 14 c o u t << " and I g o t a ( n ) " << myCourse . g r a d e << e n d l ; 15 16 return 0; 17 } Swap the values 101 and ’A’. Does it work? What do you notice? 10.2 Structure Composition 10.2 127 Structure Composition It is possible to have a structure be a member of another structure. Code 10.3: Structure composition example 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 s t r u c t Course { 6 i n t courseNumber ; 7 char grade ; 8 }; 9 10 s t r u c t S t u d e n t { 11 s t r i n g studentName ; 12 Course s t u d e n t C o u r s e ; 13 } ; 14 15 i n t main ( ) { 16 17 Student st1 ; 18 s t 1 . s t u d e n t N a m e = " Bob " ; 19 s t 1 . s t u d e n t C o u r s e . courseNumber = 101; 20 s t 1 . s t u d e n t C o u r s e . g r a d e = ’A ’ ; 21 22 c o u t << s t 1 . s t u d e n t N a m e ; 23 c o u t << " t o o k MAC " << s t 1 . s t u d e n t C o u r s e . c o u r s e N u m b e r ; 24 c o u t << " and g o t a ( n ) " << s t 1 . s t u d e n t C o u r s e . g r a d e << e n d l ; 25 26 return 0; 27 } <— Get code here. Chapter 10. Structures 128 10.3 Arrays of Structures Multiple structures of the same type can be stored using an array. Code 10.4: Example storing structures in an array 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 s t r u c t Course { 5 i n t courseNumber ; 6 char grade ; 7 }; 8 9 i n t main ( ) { 10 c o n s t i n t numberOfCourses = 4 ; 11 Course c o u r s e L i s t [ numberOfCourses ] = { 12 { 1 0 1 , ’A ’ } , 13 { 1 2 5 , ’B ’ } , 14 { 1 9 0 , ’C ’ } , 15 { 2 8 6 , ’A ’ } 16 }; 17 18 c o u t << " C o u r s e l i s t : " << e n d l ; 19 f o r ( i n t i = 0 ; i < n u m b e r O f C o u r s e s ; i ++){ 20 c o u t << c o u r s e L i s t [ i ] . c o u r s e N u m b e r ; 21 c o u t << " " << c o u r s e L i s t [ i ] . g r a d e << e n d l ; 22 } 23 24 return 0; 25 } <— Get code here. What are the similarities and differences between structures and arrays? 10.4 Passing Structures to Functions 10.4 129 Passing Structures to Functions Structures can also serve as arguments for function parameters, much like any primitive data types. By default structures are passed by value. Code 10.5: Passing a structure to function example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 s t r u c t Course { 5 i n t courseNumber ; 6 char grade ; 7 }; 8 9 void p r i n t C o u r s e ( Course ) ; 10 11 i n t main ( ) { 12 c o n s t i n t numberOfCourses = 4 ; 13 Course c o u r s e L i s t [ numberOfCourses ] = { 14 { 1 0 1 , ’A ’ } , 15 { 1 2 5 , ’B ’ } , 16 { 1 9 0 , ’C ’ } , 17 { 2 8 6 , ’A ’ } 18 }; 19 20 c o u t << " C o u r s e l i s t : " << e n d l ; 21 f o r ( i n t i = 0 ; i < n u m b e r O f C o u r s e s ; i ++) 22 printCourse ( courseList [ i ] ) ; 23 24 return 0; 25 } 26 27 v o i d p r i n t C o u r s e ( C o u r s e c ) { 28 c o u t << c . c o u r s e N u m b e r ; 29 c o u t << " " << c . g r a d e << e n d l ; 30 } 1. Change the previous program to pass each structure to the function by reference. The program should produce the same output. 2. Similarly change the program to give the function a pointer to each structure. 11. Introduction to Classes 11.1 Objects C++ is an object-oriented programming language that provides a powerful paradigm for developing software applications. With its support for OOP, C++ enables programmers to create custom data types that closely mirror real-life scenarios, making the code more intuitive, organized, and reusable. This approach to programming results in software that is easy to understand, maintain, and extend, and ultimately results in higher-quality applications. What is an object? What sets two objects apart? Do different objects have anything in common? Chapter 11. Introduction to Classes 132 11.2 Classes Until now for the most part we have used primitive data types such as int or char to process information. Following the OOP principles, a programmer can specify his/her own type based on what objects he/she intends to work with. To enable creation of such objects a programmer needs to identify common characteristics and behavior of these objects and create a class using this information. A class is a blueprint (template) which is used when we create an object. A class describes collectively characteristics and behavior of the same type of objects. We can create multiple objects from the same class. Each object is unique but they all share common features of all other objects derived from the same class. An object created from a class is referred to as an instance of the class. The process of creating an object is called instantiation. 11.3 The First Example Code 11.1: First example of a class 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 class Rectangle { 5 public : 6 i n t width , l e n g t h ; 7 } ; / / end R e c t a n g l e c l a s s 8 9 i n t main ( ) { 10 Rectangle r1 ; 11 r1 . width =3; 12 r1 . l e n g t h =5; 13 c o u t << " r 1 i s a " << r 1 . w i d t h ; 14 c o u t << " x " << r 1 . l e n g t h << " r e c t a n g l e . " << e n d l ; 15 16 return 0; 17 } / / end main ( ) Remove the public keyword and run the program. What do you notice? What happens if we do not initialize class members? 11.3 The First Example 133 Code 11.2: Adding class member functions 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 class Rectangle { 5 public : 6 i n t width , l e n g t h ; 7 void printArea ( ) { 8 c o u t << " Area = " << w i d t h * l e n g t h << e n d l ; 9 } 10 } ; / / end R e c t a n g l e c l a s s 11 12 i n t main ( ) { 13 Rectangle r1 ; 14 r1 . width =3; 15 r1 . l e n g t h =5; 16 r1 . printArea ( ) ; 17 return 0; 18 } / / end main ( ) Code 11.3: Access specifiers, data hiding and encapsulation 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 class Rectangle { 5 private : 6 i n t width , l e n g t h ; 7 public : 8 v o i d s e t ( i n t w, i n t l ) { w i d t h = w ; l e n g t h = l ; } 9 i n t getWidth ( ) { r e t u r n width ;} 10 i n t getLength ( ) { return length ;} 11 12 void printArea ( ) { 13 c o u t << " Area = " << w i d t h * l e n g t h << e n d l ; 14 } 15 } ; / / end R e c t a n g l e c l a s s 16 17 i n t main ( ) { 18 Rectangle r1 ; 19 r1 . s e t ( 4 , 7 ) ; 20 c o u t << " D i m e n s i o n s : " << r 1 . g e t W i d t h ( ) ; 21 c o u t << " x " << r 1 . g e t L e n g t h ( ) << e n d l ; 22 r1 . printArea ( ) ; 23 return 0; 24 } 12. Strings 12.1 How C++ Stores Text? All information in the computer is stored using 0s and 1s. Therefore, all data is stored as a number. When it comes to text, each character is stored using the corresponding ASCII number. Each character gets one byte of memory space. How many different characters can be represented with one byte of memory space? Chapter 12. Strings 136 Code 12.1: Example displaying the ASCII value of a char variable. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 # include <iostream > # include <bitset > # i n c l u d e <iomanip > u s i n g namespace s t d ; i n t main ( ) { char c ; c o u t << " E n t e r any c h a r a c t e r : " ; c i n >> c ; c o u t << " The c h a r a c t e r you e n t e r e d i s : " << c << e n d l ; c o u t << " I t s ASCII c o d e ( d e c i m a l ) i s : " << ( i n t ) c << e n d l ; b i t s e t <8> x ( c ) ; c o u t << " I t s ASCII c o d e ( b i n a r y ) i s : " << x << e n d l ; c o u t << " I t s ASCII c o d e ( h e x a d e c i m a l ) i s : " ; c o u t << s e t w ( 2 ) << s e t f i l l ( ’ 0 ’ ) << hex << ( i n t ) c << e n d l ; return 0; } Code 12.2: Example converting ascii value to char. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # include <iostream > # include <bitset > # i n c l u d e <iomanip > u s i n g namespace s t d ; i n t main ( ) { int ascii ; c o u t << " E n t e r an i n t e g e r b e t w e e n 0 and 2 5 5 : " ; c i n >> a s c i i ; c o u t << " The i n t e g e r you e n t e r e d i s : " << a s c i i << e n d l ; c o u t << " The ASCII c h a r a c t e r i s : " << ( c h a r ) a s c i i << e n d l ; return 0; } 12.2 C-style String Functions 137 Write a program that uses a for loop to print all the ASCII characters and their corresponding decimal values in tabular format. See the sample output for some of the characters below: Desired output format: ... ... 35 # 36 $ 37 % ... ... 12.2 C-style String Functions C++ has a number of pre-defined functions inherited from C that help the programmer manipulate arrays of characters or strings. The example below illustrates some of these functions. Code 12.3: Example using cstring functions. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 char s [ 8 0 ] ; 6 s t r c p y ( s , " One " ) ; 7 s t r c a t ( s , "Two" ) ; 8 s t r c a t ( s , " Three " ) ; 9 c o u t << " The s t r i n g c r e a t e d i s : " << s << e n d l ; 10 c o u t << " The l e n g t h o f t h e s t r i n g i s : " << s t r l e n ( s ) ; 11 12 return 0; 13 } There is something missing in the above program which may prevent the program from running. Can you fix it? Chapter 12. Strings 138 Code 12.4: Reading string input example. 1 # include <iostream > 2 # include <cstring > 3 u s i n g namespace s t d ; 4 5 i n t main ( ) { 6 char s [ 8 0 ] ; 7 c o u t << " E n t e r s t r i n g : " ; 8 c i n >> s ; 9 c o u t << " The s t r i n g e n t e r e d i s : " << s << e n d l ; 10 c o u t << " The l e n g t h o f t h e s t r i n g i s : " << s t r l e n ( s ) ; 11 12 return 0; 13 } Enter a string consisting of more than one word. Does it work? Substitute the line cin » s; with the line cin.getline(s,79); Run the program and input the string “Hello World”. What changed? Now input a long string of more than 80 characters. What do you notice? 12.3 The <string> Class The <string> class makes it easier for programmers to manipulate strings. A string derived from this class is an object, but it has similarities to primitive data types such as int or char. We will discuss classes and objects in more detail in the upcoming chapters. 12.3 The <string> Class 139 Code 12.5: Different ways to initialize a string object. 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 i n t main ( ) { 6 7 s t r i n g myString1 ; 8 s t r i n g m y S t r i n g 2 = " H e l l o MAC101 c l a s s ! " ; 9 s t r i n g myString3 ( " Using P a r e n t h e s i s " ) ; 10 s t r i n g myString4 ( myString3 ) ; 11 s t r i n g myString5 ( myString2 , 6 ) ; 12 s t r i n g myString6 ( myString2 , 6 , 6 ) ; 13 14 c o u t << " 1 : " << m y S t r i n g 1 << e n d l ; 15 c o u t << " 2 : " << m y S t r i n g 2 << e n d l ; 16 c o u t << " 3 : " << m y S t r i n g 3 << e n d l ; 17 c o u t << " 4 : " << m y S t r i n g 4 << e n d l ; 18 c o u t << " 5 : " << m y S t r i n g 5 << e n d l ; 19 c o u t << " 6 : " << m y S t r i n g 6 << e n d l ; 20 21 return 0; 22 } Code 12.6: String input and concatenation example. 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 i n t main ( ) { 6 s t r i n g s t r , name , a d d r ; 7 8 c o u t << " E n t e r name : " ; 9 g e t l i n e ( c i n , name ) ; 10 c o u t << " E n t e r a d d r e s s : " ; 11 g e t l i n e ( cin , addr ) ; 12 13 s t r = "My name i s " + name + " . " + " I l i v e i n " + a d d r + " . " ; 14 c o u t << s t r << e n d l ; 15 16 return 0; 17 } Chapter 12. Strings 140 Code 12.7: Comparing strings example. 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 i n t main ( ) { 6 7 s t r i n g s t r i n g 1 = " one " ; 8 s t r i n g s t r i n g 2 ( " one " ) ; 9 string string3 ( " five " ); 10 s t r i n g string4 ( " ten " ) ; 11 12 i f ( s t r i n g 1 == s t r i n g 2 ) 13 c o u t << " The s t r i n g s a r e t h e same " << e n d l ; 14 else 15 c o u t << " The s t r i n g s a r e d i f f e r e n t " << e n d l ; 16 17 i f ( ! s t r i n g 1 . compare ( s t r i n g 2 ) ) 18 c o u t << " The s t r i n g s a r e t h e same " << e n d l ; 19 else 20 c o u t << " The s t r i n g s a r e d i f f e r e n t " << e n d l ; 21 c o u t << s t r i n g 1 . compare ( s t r i n g 2 ) ; 22 23 return 0; 24 } 12.3 The <string> Class 141 Code 12.8: Working with strings additional example. 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 i n t main ( ) { 6 7 s t r i n g c i t y = "New" ; 8 c o u t << " I n i t i a l s t r i n g : " << c i t y << e n d l ; 9 10 c i t y . append ( " c i t y ! " ) ; 11 c o u t << " A f t e r a p p e n d i n g : " << c i t y << e n d l ; 12 13 c i t y [ 4 ] = ’C ’ ; 14 c o u t << " A f t e r c h a r c h a n g e : " << c i t y << e n d l ; 15 16 s t r i n g s 2 = " York " ; 17 c i t y . i n s e r t ( 4 , s2 ) ; 18 c o u t << " A f t e r i n s e r t : " << c i t y << e n d l ; 19 20 city . erase (8 , 5); 21 c o u t << " A f t e r e r a s e : " << c i t y << e n d l ; 22 23 f o r ( i n t i = 0 ; i < c i t y . s i z e ( ) ; i ++){ 24 f o r ( i n t j = 0 ; j < i ; j ++) 25 c o u t << " " ; 26 c o u t << c i t y [ i ] << e n d l ; 27 } 28 return 0; 29 } Write a C++ program that takes a string as an input and prints the string in reverse order. Use a loop for this program, do not use any built-in function to reverse the string. Desired output format: Enter a string: Hello World The string you entered in reverse order is: dlroW olleH Chapter 12. Strings 142 Write a C++ program that takes as an input two strings from the user and determines whether the first string is a substring of the second. If yes, also print at what position the substring starts. Desired output format 1: Enter first string: Hello World Enter second string: World "World" is a substring of "Hello World". It starts at position 6 Desired output format 2: Enter first string: Hello World Enter second string: apple "apple" is NOT a substring of "Hello World". 13. Basic Sorting Algorithms 13.1 Sorting Algorithms Very often we need to arrange (sort) data for searching or other purposes. There is a large variety of sorting algorithms. We will only discuss here the simplest algorithms. Chapter 13. Basic Sorting Algorithms 144 Code 13.1: Bubble Sort example. 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 # include <iostream > # i n c l u d e <iomanip > u s i n g namespace s t d ; i n t myArray [ ] = { 7 , 2 , 4 , 2 , 9 , 5 , 6 , 1 , 5 } ; i n t a r r a y S i z e = s i z e o f ( myArray ) / s i z e o f ( myArray [ 0 ] ) ; void BubbleSort ( ) ; v o i d swap ( i n t one , i n t two ) ; void printMyArray ( int , i n t ) ; i n t main ( ) { c o u t << " A r r a y v a l u e s b e f o r e s o r t i n g : " << e n d l ; printMyArray ( −1 , −1); BubbleSort ( ) ; c o u t << " \ nThe a r r a y h a s b e e n s o r t e d . " ; return 0; } / / end main void BubbleSort ( ) { f o r ( i n t i = 0 ; i < a r r a y S i z e ; i ++) f o r ( i n t j = 0 ; j < a r r a y S i z e −1− i ; j ++){ i f ( myArray [ j ] > myArray [ j + 1 ] ) swap ( j , j + 1 ) ; } } / / end B u b b l e S o r t v o i d swap ( i n t one , i n t two ) { i n t temp = myArray [ one ] ; myArray [ one ] = myArray [ two ] ; myArray [ two ] = temp ; s t a t i c i n t swapCount = 1 ; c o u t << " Swap " << s e t w ( 2 ) << swapCount ++ << " : p r i n t M y A r r a y ( one , two ) ; } / / end swap v o i d p r i n t M y A r r a y ( i n t one , i n t two ) { f o r ( i n t j = 0 ; j < a r r a y S i z e ; j ++) i f ( j == one o r j ==two ) c o u t << " ( " << myArray [ j ] << " ) " ; else c o u t << " " << myArray [ j ] << " " ; c o u t << e n d l ; } / / end p r i n t M y A r r a y ( ) <— Get code here. "; 13.1 Sorting Algorithms 145 Code 13.2: Selection sort example. 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 # include <iostream > # i n c l u d e <iomanip > u s i n g namespace s t d ; i n t myArray [ ] = { 7 , 2 , 4 , 2 , 9 , 5 , 6 , 1 , 5 } ; i n t a r r a y S i z e = s i z e o f ( myArray ) / s i z e o f ( myArray [ 0 ] ) ; void S e l e c t i o n S o r t ( ) ; v o i d swap ( i n t one , i n t two ) ; void printMyArray ( int , i n t ) ; i n t main ( ) { c o u t << " A r r a y v a l u e s b e f o r e s o r t i n g : " << e n d l ; printMyArray ( −1 , −1); SelectionSort (); c o u t << " \ nThe a r r a y h a s b e e n s o r t e d . " ; return 0; } / / end main void S e l e c t i o n S o r t ( ) { i n t min ; f o r ( i n t i = 0 ; i < a r r a y S i z e − 1 ; i ++){ min= i ; f o r ( i n t j = i + 1 ; j < a r r a y S i z e ; j ++) i f ( myArray [ j ] < myArray [ min ] ) min= j ; swap ( i , min ) ; } } / / end S e l e c t i o n S o r t v o i d swap ( i n t one , i n t two ) { i n t temp = myArray [ one ] ; myArray [ one ] = myArray [ two ] ; myArray [ two ] = temp ; s t a t i c i n t swapCount = 1 ; c o u t << " Swap " << s e t w ( 2 ) << swapCount ++ << " : p r i n t M y A r r a y ( one , two ) ; } / / end swap v o i d p r i n t M y A r r a y ( i n t one , i n t two ) { f o r ( i n t j = 0 ; j < a r r a y S i z e ; j ++) i f ( j == one o r j ==two ) c o u t << " ( " << myArray [ j ] << " ) " ; else c o u t << " " << myArray [ j ] << " " ; c o u t << e n d l ; } / / end p r i n t M y A r r a y ( ) <— Get code here. "; Chapter 13. Basic Sorting Algorithms 146 Code 13.3: Insertion sort example. 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 # include <iostream > u s i n g namespace s t d ; i n t myArray [ ] = { 7 , 2 , 4 , 2 , 9 , 5 , 6 , 1 , 5 } ; i n t a r r a y S i z e = s i z e o f ( myArray ) / s i z e o f ( myArray [ 0 ] ) ; void I n s e r t i o n S o r t ( ) ; void printMyArray ( int , i n t ) ; i n t main ( ) { c o u t << " A r r a y v a l u e s b e f o r e s o r t i n g : " << e n d l ; printMyArray ( −1 , −1); InsertionSort (); c o u t << " \ nThe a r r a y h a s b e e n s o r t e d . " ; return 0; } / / end main ( ) void I n s e r t i o n S o r t ( ) { i n t h e r e , n e x t , temp ; printMyArray ( −1 , 1 ) ; f o r ( n e x t = 1 ; n e x t < a r r a y S i z e ; n e x t ++){ temp=myArray [ n e x t ] ; here = next ; w h i l e ( h e r e >0 && myArray [ h e r e −1] >= temp ) { myArray [ h e r e ] = myArray [ h e r e − 1 ] ; h e r e − −; } myArray [ h e r e ] = temp ; printMyArray ( here , next +1); } / / end f o r } / / end I n s e r t i o n S o r t ( ) void printMyArray ( i n t i n s e r t e d , i n t nextValue ) { f o r ( i n t j = 0 ; j < a r r a y S i z e ; j ++){ i f ( j == n e x t V a l u e ) c o u t << " <−− S o r t e d | U n s o r t e d −−> " ; i f ( j == i n s e r t e d ) c o u t << " ( " << myArray [ j ] << " ) " ; else c o u t << " " << myArray [ j ] << " " ; } c o u t << e n d l ; } / / end p r i n t M y A r r a y ( ) <— Get code here. II Part Two - MAC 125 14 Classes and Objects (continued...) . . 149 15 Classes, Pointers, and Arrays . . . . . . . . 159 16 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . 165 17 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . 177 18 Polymorphism . . . . . . . . . . . . . . . . . . . . . . 187 19 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . 193 20 Linked Data Structures . . . . . . . . . . . . . . 199 21 Exception Handling . . . . . . . . . . . . . . . . . 205 22 Standard Template Library . . . . . . . . . . 211 150 Chapter 14. Classes and Objects (continued...) 14. Classes and Objects (continued...) 14.1 Constructors Code 14.1: Adding constructors 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 class Rectangle { 5 private : 6 i n t width , l e n g t h ; 7 public : 8 Rectangle () { 9 width =1; l e n g t h =2; 10 c o u t << " H e l l o w o r l d ! ! ! " << e n d l ; 11 } 12 v o i d s e t ( i n t w, i n t l ) { w i d t h = w ; l e n g t h = l ; } 13 i n t getWidth ( ) { r e t u r n width ;} 14 i n t getLength ( ) { return length ;} 15 16 void printArea ( ) { 17 c o u t << " Area = " << w i d t h * l e n g t h << e n d l ; 18 } 19 } ; / / end R e c t a n g l e c l a s s 20 21 i n t main ( ) { 22 Rectangle r1 ; 23 r1 . printArea ( ) ; 24 return 0; 25 } 14.1 Constructors 151 Add another constructor that takes two parameters and assigns those values to width and length. What can we conclude regarding constructor overloading in C++? Can we call the constructor explicitly, say: r1.Rectangle(3,5); Always include a default constructor. 152 14.2 Chapter 14. Classes and Objects (continued...) Destructors Code 14.2: Adding destructors 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 class Rectangle { 5 private : 6 i n t width , l e n g t h ; 7 public : 8 Rectangle () { 9 width =1; l e n g t h =2; 10 c o u t << " H e l l o w o r l d ! ! ! " << e n d l ; 11 } 12 ~Rectangle (){ 13 c o u t << " Goodbye e v e r y o n e ! ! ! " << e n d l ; 14 } 15 v o i d s e t ( i n t w, i n t l ) { w i d t h = w ; l e n g t h = l ; } 16 i n t getWidth ( ) { r e t u r n width ;} 17 i n t getLength ( ) { return length ;} 18 19 void printArea ( ) { 20 c o u t << " Area = " << w i d t h * l e n g t h << e n d l ; 21 } 22 } ; / / end R e c t a n g l e c l a s s 23 24 i n t main ( ) { 25 Rectangle r1 ; 26 r1 . printArea ( ) ; 27 return 0; 28 } 14.3 Separating Content in Different Files 14.3 153 Separating Content in Different Files It is common practice to separate the declaration and definition of each class into separate files. First comes the header file ClassName.h then the source / implementation file ClassName.cpp. Next, we create separate files to achieve the results from the previous example. Code 14.3: Rectangle.h 1 # i f n d e f RECTANGLE_H_ 2 # d e f i n e RECTANGLE_H_ 3 4 class Rectangle { 5 private : 6 i n t width , l e n g t h ; 7 protected : 8 public : 9 Rectangle ( ) ; 10 R e c t a n g l e ( i n t w, i n t l ) ; 11 ~Rectangle ( ) ; 12 void setWidth ( i n t ) ; 13 void setLength ( i n t ) ; 14 i n t getWidth ( ) ; 15 i n t getLength ( ) ; 16 void printArea ( ) ; 17 } ; 18 19 # e n d i f / * RECTANGLE_H_ * / Chapter 14. Classes and Objects (continued...) 154 Code 14.4: Rectangle.cpp 1 # include " Rectangle . h" 2 # include <iostream > 3 u s i n g namespace s t d ; 4 5 Rectangle : : Rectangle ( ) { width = 1; l e n g t h = 2;} 6 7 R e c t a n g l e : : R e c t a n g l e ( i n t w, i n t l ) { w i d t h = w ; l e n g t h = l ; } 8 9 Rectangle ::~ Rectangle (){} 10 11 v o i d R e c t a n g l e : : s e t W i d t h ( i n t w) { w i d t h = w; } 12 13 v o i d R e c t a n g l e : : s e t L e n g t h ( i n t l ) { l e n g t h = l ; } 14 15 i n t R e c t a n g l e : : g e t W i d t h ( ) { r e t u r n w i d t h ; } 16 17 i n t R e c t a n g l e : : g e t L e n g t h ( ) { r e t u r n l e n g t h ; } 18 19 v o i d R e c t a n g l e : : p r i n t A r e a ( ) { c o u t << " Area = " << w i d t h * l e n g t h ; } Code 14.5: Main program 1 # include " Rectangle . h" 2 # include <iostream > 3 u s i n g namespace s t d ; 4 5 i n t main ( ) { 6 Rectangle r1 ; 7 r1 . printArea ( ) ; 8 return 0; 9 } Write a class named Person that has data members name and age. Include a default and a parameterized constructor, a destructor and a public member function named sayHello() that that prints “Hello! I am “, followed by the name of the person on the screen. 14.4 Constant Objects 14.4 155 Constant Objects Similar to primitive data types we can set objects as constant to prevent any changes to the object during the execution of a program. Code 14.6: Rectangle class example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 / * *********** D e c l a r a t i o n S e c t i o n ***************** * / 4 class Rectangle { 5 private : 6 i n t width , l e n g t h ; 7 public : 8 Rectangle ( ) ; 9 R e c t a n g l e ( i n t w, i n t l ) ; 10 ~Rectangle ( ) ; 11 void setWidth ( i n t ) ; 12 void setLength ( i n t ) ; 13 i n t getWidth ( ) ; 14 i n t getLength ( ) ; 15 void printArea ( ) ; 16 } ; 17 / * *********** I m p l e m e n t a t i o n S e c t i o n ***************** * / 18 R e c t a n g l e : : R e c t a n g l e ( ) { w i d t h = 1 ; l e n g t h = 2 ; } 19 R e c t a n g l e : : R e c t a n g l e ( i n t w, i n t l ) { w i d t h = w ; l e n g t h = l ; } 20 R e c t a n g l e : : ~ R e c t a n g l e ( ) { } 21 v o i d R e c t a n g l e : : s e t W i d t h ( i n t w) { w i d t h = w; } 22 v o i d R e c t a n g l e : : s e t L e n g t h ( i n t l ) { l e n g t h = l ; } 23 i n t R e c t a n g l e : : g e t W i d t h ( ) { r e t u r n w i d t h ; } 24 i n t R e c t a n g l e : : g e t L e n g t h ( ) { r e t u r n l e n g t h ; } 25 v o i d R e c t a n g l e : : p r i n t A r e a ( ) { c o u t << " Area = " << w i d t h * l e n g t h ; } 26 / * **************** Main S e c t i o n ******************** * / 27 i n t main ( ) { 28 Rectangle r1 ; 29 r1 . printArea ( ) ; 30 return 0; 31 } <— Get code here. Consider the example above. Make the following changes and run the program. 1. Declare Rectangle r1 as constant. What do you observe? 2. Change the printArea() function to constant. 3. Change the Rectangle r1 back to non-constant. What can you conclude? Chapter 14. Classes and Objects (continued...) 156 14.5 Member Initializers C++ offers an alternative syntax for initializing member variable via the constructor. Below is an example using both alternatives. Consider the program below: Code 14.7: Class example. 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 # include <iostream > u s i n g namespace s t d ; / * *********** D e c l a r a t i o n S e c t i o n ***************** * / class Rectangle { private : i n t width , l e n g t h ; public : Rectangle ( ) ; R e c t a n g l e ( i n t w, i n t l ) ; void printArea ( ) ; }; / * *********** I m p l e m e n t a t i o n S e c t i o n ***************** * / Rectangle : : Rectangle (){ width = 1 , l e n g t h = 2; c o u t << " H e l l o t h e r e ! My i d i s " << t h i s << e n d l ; } R e c t a n g l e : : R e c t a n g l e ( i n t w, i n t l ) { w i d t h = w, l e n g t h = l ; c o u t << " H e l l o t h e r e ! My i d i s " << t h i s << e n d l ; } void Rectangle : : printArea ( ) { c o u t << " Area o f " << t h i s << " = " << w i d t h * l e n g t h << e n d l ; } / * **************** Main S e c t i o n ******************** * / i n t main ( ) { R e c t a n g l e r1 , r 2 ( 5 , 7 ) ; r1 . printArea ( ) ; r2 . printArea ( ) ; return 0; } <— Get code here. Change the implementation section using the code below: Code 14.8: Using initializers code 1 2 3 4 5 6 7 8 9 10 / * *********** I m p l e m e n t a t i o n S e c t i o n ***************** * / Rectangle : : Rectangle ( ) : width ( 1 ) , l e n g t h ( 2 ) { c o u t << " H e l l o t h e r e ! My i d i s " << t h i s << e n d l ; } R e c t a n g l e : : R e c t a n g l e ( i n t w, i n t l ) : w i d t h (w) , l e n g t h ( l ) { c o u t << " H e l l o t h e r e ! My i d i s " << t h i s << e n d l ; } void Rectangle : : printArea ( ) { c o u t << " Area o f " << t h i s << " = " << w i d t h * l e n g t h << e n d l ; } 14.6 Class Composition 14.6 157 Class Composition A class can have as a member an object from another class. Code 14.9: Class composition example 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 / * ************** B i r t h d a y C l a s s ******************* * / 5 class Birthday { 6 private : 7 i n t month , day , y e a r ; 8 public : 9 B i r t h d a y ( i n t m, i n t d , i n t y ) 10 : month (m) , day ( d ) , y e a r ( y ) {} 11 12 void p r i n t D a t e ( ) { 13 c o u t <<month << " / " << day << " / " << y e a r << e n d l ; 14 } 15 } ; 16 / * ************** P e r s o n C l a s s ******************* * / 17 c l a s s P e r s o n { 18 p r i v a t e : 19 s t r i n g name ; 20 Birthday dateOfBirth ; 21 p u b l i c : 22 Person ( s t r i n g n , Birthday b ) 23 : name ( n ) , d a t e O f B i r t h ( b ) { } 24 25 void p r i n t I n f o ( ) { 26 c o u t << name << " was b o r n on : " ; 27 dateOfBirth . printDate ( ) ; 28 } 29 } ; 30 / * ************** Main ******************* * / 31 i n t main ( ) { 32 B i r t h d a y bDate ( 1 2 , 1 1 , 1 8 8 2 ) ; 33 Person peopleObj ( " F i o r e l l o H. LaGuardia " , bDate ) ; 34 peopleObj . p r i n t I n f o ( ) ; 35 } <— Get code here. 1. Create a Major class with two private attributes, major name, and number of credits and a public member function displayMajorInfo(). 2. Create a Student class with private attributes, student name, age major and a public member function displayStudentInfo(). 15. Classes, Pointers, and Arrays 15.1 Pointers Revisited IMPORTANT: First please review the material from chapter 9 on page 121. Quick facts: • A pointer is a variable that holds the address of another variable. • The operator & provides the address of a variable. • We use * when declaring a pointer. After declaration the operator * is used to get the value from the variable the pointer is pointing to. Code 15.1: Simple pointer example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 i n t a = 5; 7 i n t * aP = &a ; 8 c o u t << " a = " << a << e n d l ; 9 c o u t << " * aP = " << * aP << e n d l ; 10 11 return 0; 12 } Chapter 15. Classes, Pointers, and Arrays 160 15.2 Pointers and Some Special Operators Code 15.2: Pointer example using some special operators 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 i n t * one = new i n t ; 7 c o u t << " * one = " << 8 9 * one = 5 ; 10 c o u t << " * one = " << 11 12 * one = NULL ; 13 c o u t << " * one = " << 14 15 * one += 1 ; 16 c o u t << " * one = " << 17 18 i n t * two = n u l l p t r ; 19 20 two = one ; 21 c o u t << " * two = " << 22 23 return 0; 24 } * one << e n d l ; * one << e n d l ; * one << e n d l ; * one << e n d l ; * two << e n d l ; Can we have 2 pointers point at the same address? Show an example. 15.3 Arrays and Pointers In chapter 9 we discussed some examples of using pointers when working with arrays. Quick Facts: 1. Array variables are just pointers. 2. When we declare an array, we declare a pointer to its first element. 3. When we pass an array to a function, we pass a pointer to the first element instead of the array values. 15.3 Arrays and Pointers Code 15.3: Example of a dynamic array 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 6 const i n t sizeOne = 5; 7 i n t arrayOne [ sizeOne ] ; 8 9 f o r ( i n t i = 0 ; i < s i z e O n e ; i ++) 10 arrayOne [ i ]= i +1; 11 12 c o u t << " C o n t e n t o f a r r a y O n e : " ; 13 f o r ( i n t i = 0 ; i < s i z e O n e ; i ++) 14 c o u t << a r r a y O n e [ i ] << " " ; 15 16 c o u t << e n d l ; 17 18 c o n s t i n t sizeTwo = 5 ; 19 i n t * a r r a y T w o = new i n t [ s i z e T w o ] ; 20 21 f o r ( i n t i = 0 ; i < s i z e T w o ; i ++) 22 arrayTwo [ i ]= i +1; 23 24 c o u t << " C o n t e n t o f a r r a y T w o : " ; 25 f o r ( i n t i = 0 ; i < s i z e T w o ; i ++) 26 c o u t << a r r a y T w o [ i ] << " " ; 27 28 return 0; 29 } <— Get code here. What are the differences between arrayOne and arrayTwo? Can we remove the const keyword from sizeOne? Why? 161 162 15.4 Chapter 15. Classes, Pointers, and Arrays The this Keyword The special keyword this is used to allow an object to refer to itself, meaning to have access (point) at its own address. Code 15.4: this pointer example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 / * ****** C l a s s D e c l a r a t i o n & D e f i n i t i o n ********** * / 5 c l a s s MyClass { 6 public : 7 MyClass ( i n t a ) : m y I n t ( a ) {} 8 void p rintV alues ( ) { 9 c o u t << m y I n t << e n d l ; 10 c o u t << t h i s −> m y I n t << e n d l ; 11 c o u t << ( * t h i s ) . m y I n t << e n d l ; 12 } 13 p r i v a t e : 14 i n t myInt ; 15 } ; 16 17 / * **************** Main S e c t i o n ****************** * / 18 i n t main ( ) { 19 MyClass o b j ( 1 0 0 ) ; 20 obj . printValues ( ) ; 21 } 15.5 Operator Overloading 163 Code 15.5: Another example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 / * *********** D e c l a r a t i o n S e c t i o n ***************** * / 5 c l a s s BankAccount { 6 private : 7 double balance ; 8 public : 9 BankAccount ( ) ; 10 BankAccount ( d o u b l e b a l a n c e ) ; 11 BankAccount& d e p o s i t ( d o u b l e money ) ; 12 v o i d w i t h d r a w ( d o u b l e money ) ; 13 double getBalance ( ) ; 14 } ; 15 16 / * *********** I m p l e m e n t a t i o n S e c t i o n ***************** * / 17 BankAccount : : BankAccount ( ) { b a l a n c e = 0 . 0 0 ; } 18 BankAccount : : BankAccount ( d o u b l e money ) { b a l a n c e = money ; } 19 BankAccount& BankAccount : : d e p o s i t ( d o u b l e money ) { 20 b a l a n c e += money ; 21 return * this ; 22 } 23 v o i d BankAccount : : w i t h d r a w ( d o u b l e money ) { b a l a n c e −= money ; } 24 d o u b l e BankAccount : : g e t B a l a n c e ( ) { r e t u r n b a l a n c e ; } 25 26 / * **************** Main S e c t i o n ******************** * / 27 i n t main ( ) { 28 BankAccount myAccount ; 29 c o u t << " I n i t i a l b a l a n c e = " << myAccount . g e t B a l a n c e ( ) << e n d l ; 30 31 myAccount . d e p o s i t ( 5 0 ) ; 32 c o u t << " B a l a n c e 1 = " << myAccount . g e t B a l a n c e ( ) << e n d l ; 33 34 myAccount . d e p o s i t ( 3 0 ) . d e p o s i t ( 5 0 ) . d e p o s i t ( 2 0 ) ; 35 c o u t << " B a l a n c e 2 = " << myAccount . g e t B a l a n c e ( ) << e n d l ; 36 37 return 0; 38 } 15.5 Operator Overloading Most C++ operators can be overloaded. Overloading an operator means to define a new function/use for the operator as compared to the original built-in function. Chapter 15. Classes, Pointers, and Arrays 164 Code 15.6: Operator overloading example 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 # include <iostream > u s i n g namespace s t d ; / * *********** D e c l a r a t i o n S e c t i o n ***************** * / class Rectangle { private : i n t width , l e n g t h ; public : Rectangle ( ) ; R e c t a n g l e ( i n t w, i n t l ) ; void printArea ( ) ; void d i s p l a y I n f o ( ) ; R e c t a n g l e o p e r a t o r + ( R e c t a n g l e& r ) ; }; / * *********** I m p l e m e n t a t i o n S e c t i o n ***************** * / Rectangle : : Rectangle ( ) { width = 1 , l e n g t h = 2; } R e c t a n g l e : : R e c t a n g l e ( i n t w, i n t l ) { w i d t h = w, l e n g t h = l ; } void Rectangle : : printArea ( ) { c o u t << " Area o f " << t h i s << " = " << w i d t h * l e n g t h << e n d l ; } void Rectangle : : d i s p l a y I n f o ( ) { c o u t << " I am a " << w i d t h << " x " << l e n g t h << " r e c t a n g l e " << " w i t h i d " << t h i s << e n d l ; } R e c t a n g l e R e c t a n g l e : : o p e r a t o r + ( R e c t a n g l e& r ) { R e c t a n g l e temp ; temp . w i d t h = t h i s −> w i d t h + r . w i d t h ; temp . l e n g t h = t h i s −> l e n g t h + r . l e n g t h ; r e t u r n temp ; } / * **************** Main S e c t i o n ******************** * / i n t main ( ) { R e c t a n g l e r1 , r 2 ( 5 , 7 ) , r 3 ; r1 . d i s p l a y I n f o ( ) ; r2 . d i s p l a y I n f o ( ) ; r3 . d i s p l a y I n f o ( ) ; r3=r1+r2 ; r3 . d i s p l a y I n f o ( ) ; r1 . printArea ( ) ; r2 . printArea ( ) ; r3 . printArea ( ) ; return 0; } Change the + operator overload to work with a rectangle object and an integer (e.g r1+2) ch will add the integer to both the width and the length of the rectangle. 16. Recursion 16.1 Recursive Functions Recursion is a technique when a function calls itself. To avoid infinite loops each recursive function has a mechanism of ending the recursion. Each recursive function has a base case. Example: Recall the program 5.4 that defines and tests a factorial function using a for loop. Here we change the factorial function to a recursive function. 166 Chapter 16. Recursion Code 16.1: Using recursion to calculate the factorial of a number 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 int factorial ( int ); 5 6 i n t main ( ) { 7 8 i n t number = 5 ; 9 10 c o u t << number << " ! = " << f a c t o r i a l ( number ) << e n d l ; 11 12 return 0; 13 } / / end main ( ) 14 15 i n t f a c t o r i a l ( i n t x ) { 16 17 i f ( x==0 | | x ==1) 18 return 1; 19 else 20 return x * f a c t o r i a l (x −1); 21 22 } / / end f a c t o r i a l ( ) During recursion, a special area of memory called the stack is utilized to store the information as the multiple function calls are executed. Values that are stored in the stack follow the last in – first out (LIFO) order. The following picture illustrates the factorial recursive process. Which of the two approaches (iterative or recursive) is better in this case? 16.1 Recursive Functions 167 Write a program that uses a function sum(int) that takes as an argument a positive integer n and returns the sum of the first n positive integers. Use a while loop. Then write a recursive function that performs the same task. Desired output: Enter a positive integer: 5 The sum of the first 5 positive integers is: 15 Try using n=50,000 for each of the programs. What do you notice? Which version is a better choice for this example? Can we further optimize the code? Additional example: The Fibonacci series. What is the Fibonacci series? 168 Chapter 16. Recursion Code 16.2: Fibonacci example using iteration 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 int fibonacci ( int x ); 5 6 i n t main ( ) { 7 i n t number = 6 ; / / <−− E n t e r t e r m h e r e 8 c o u t << " The " << number << " − t h F i b o n a c c i i s : " ; 9 c o u t << f i b o n a c c i ( number ) << e n d l ; 10 return 0; 11 } / / end main ( ) 12 13 i n t f i b o n a c c i ( i n t x ) { 14 i n t i = 0 , j = 1 , k = 1 , sum = 0 ; 15 while ( i < x −1){ 16 sum= j +k ; 17 j =k ; 18 k=sum ; 19 i ++; 20 } 21 return j ; 22 } / / end f i b o n a c c i ( ) Code 16.3: Fibonacci example using recursion 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 int fibonacci ( int x ); 5 6 i n t main ( ) { 7 i n t number = 6 ; / / <−− E n t e r t e r m h e r e 8 c o u t << " The " << number << " − t h F i b o n a c c i i s : " ; 9 c o u t << f i b o n a c c i ( number ) << e n d l ; 10 return 0; 11 } / / end main ( ) 12 13 i n t f i b o n a c c i ( i n t x ) { 14 i f ( x==1 | | x ==2) 15 return 1; 16 else 17 r e t u r n f i b o n a c c i ( x −1) + f i b o n a c c i ( x − 2 ) ; 18 } / / end f i b o n a c c i ( ) 16.2 More on Recursion 169 Write a program that uses a function power(base,exponent) which when invoked returns baseexponent . Desired output: Enter base: 5 Enter exponent: 3 5 to the power 3 is: 125 Example: Print the prime factorization of a given number. Code 16.4: Prime factorization of a number 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void g e t _ d i v i s o r s ( i n t n ) ; 5 6 i n t main ( ) { 7 i n t n = 0; 8 c o u t << " E n t e r an i n t e g e r : " ; 9 c i n >> n ; 10 get_divisors (n ); 11 return 0; 12 } / / end main 13 14 v o i d g e t _ d i v i s o r s ( i n t n ) { 15 f o r ( i n t i = 2 ; i < n ; i ++) 16 i f ( n \% i == 0 ) { 17 c o u t << i << " , " ; 18 get_divisors (n/ i ); 19 return ; 20 } 21 c o u t << n ; 22 } / / end g e t _ d i v i s o r s ( ) <— Get code here. 16.2 More on Recursion IMPORTANT: First please review the material from chapter ?? on page ??. Quick Facts: 1. Recursion is a technique that solves a problem by first finding the solution for a smaller, simpler problem and use the information to build up to the final answer. 2. In C++, like many other languages, we implement a recursive solution by allowing a function to call itself. Chapter 16. Recursion 170 3. Each recursive function has two components, the base case and the recursive step. 4. Both void functions and those returning a value can be recursive. Code 16.5: Example void recursive function - Convert to Binary 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void toBinary ( i n t ) ; 5 6 i n t main ( ) { 7 i n t number = 5 ; 8 c o u t << " D e c i m a l : " << number << e n d l ; 9 c o u t << " B i n a r y : " ; 10 t o B i n a r y ( number ) ; 11 return 0; 12 } 13 14 v o i d t o B i n a r y ( i n t n ) { 15 i f ( n == 0 ) 16 return ; 17 18 toBinary (n / 2 ) ; 19 c o u t << n%2; 20 return ; 21 } Write an iterative version of the ’covert to binary’ program. Can we generalize this algorithm to convert to other bases? 16.2 More on Recursion Code 16.6: Iterative program to reverse the digits of an integer 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 void printReverse ( i n t ) ; 5 6 i n t main ( ) { 7 i n t number = 1 2 3 4 5 ; 8 c o u t << " O r i g i n a l : " << number << e n d l ; 9 c o u t << " R e v e r s e d : " ; 10 p r i n t R e v e r s e ( number ) ; 11 return 0; 12 } 13 14 v o i d p r i n t R e v e r s e ( i n t x ) { 15 while ( x !=0){ 16 c o u t << x %10; 17 x=x / 1 0 ; 18 } 19 } Write a recursive version of the ’reverse digits’ program. 171 Chapter 16. Recursion 172 Code 16.7: Determine if string is a palindrome - recursive 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 # include <iostream > # include <string > u s i n g namespace s t d ; bool isPalindrome ( s t r i n g ) ; i n t main ( ) { s t r i n g mystr ; c o u t << " E n t e r a s t r i n g : " ; g e t l i n e ( cin , mystr ) ; i f ( isPalindrome ( mystr ) ) c o u t << m y s t r << " i s a p a l i n d r o m e \ n " ; else c o u t << m y s t r << " i s n o t a p a l i n d r o m e \ n " ; } bool isPalindrome ( s t r i n g s t r ){ int length = str . length ( ) ; i f ( l e n g t h <= 1 ) return true ; i f ( s t r [ 0 ] == s t r [ l e n g t h − 1 ] ) return isPalindrome ( s t r . substr (1 , ( length − 2 ) ) ) ; return false ; } <— Get code here (recursive version). <— Get code here (iterative version). 16.3 Practice Questions 1. What is the meaning of the following in the context of Computer Science? (a) recursion base case: (b) recursive step: 16.3 Practice Questions 173 (c) iteration vs recursion: 2. True-False questions – Circle your choice (a) The main reason we use recursion is because it typically uses less memory than iteration. ( True - False ) 3. The following program should print the sum of the first n positive integers. Find and fix the errors in the code. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t number ; 6 c o u t << " E n t e r a P o s i t i v e I n t e g e r : " ; 7 c i n >> number ; 8 c o u t << " The sum o f t h e f i r s t " << number ; 9 c o u t << " i n t e g e r s i s : " << sum ( number ) << e n d l ; 10 return 0; 11 } / / end main ( ) f u n c t i o n 12 13 i n t sum ( i n t x ) { 14 i f ( x == 1 ) 15 return 1; 16 else 17 r e t u r n x + sum ( x ) ; 18 } Sample output: Enter a Positive Integer: 5 The sum of the first 5 integers is: 15 174 4. Write the exact output. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 int f ( int x ); 5 6 i n t main ( ) { 7 i n t number = 5 ; 8 c o u t << f ( number ) ; 9 return 0; 10 } / / end main ( ) f u n c t i o n 11 12 i n t f ( i n t x ) { 13 i f ( x < 2) 14 return 1; 15 else 16 r e t u r n f ( x −1) * f ( x −2) + 1 ; 17 } Chapter 16. Recursion 16.3 Practice Questions 175 5. The following program should print the prime factorization of a number entered by the user. Fix all the errors and make the necessary changes so that the code produces the desired output. Sample output is provided. 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 # include <iostream > # i n c l u d e <cmath > u s i n g namespace s t d ; void g e t _ d i v i s o r s ( i n t n ) ; i n t main ( ) { i n t n = 0; c o u t << " E n t e r an i n t e g e r : " ; c i n >> n ; c o u t << e n d l ; return 0; } void g e t _ d i v i s o r s ( i n t n ) { int i ; f o r ( i = 2 ; i <= s q r t _ o f _ n ; i ++) i f ( n % i == 5 ) { c o u t << i << " , " ; get_divisors (n \ i ); return ; } c o u t << n ; } Sample output: Enter an integer: 24 2,2,2,3 6. Write a program that uses a recursive function power(base,exponent) which when invoked returns basee xponent. Sample output: Enter the Base: 5 Enter the Exponent: 3 5 to the power 3 = 125 Chapter 16. Recursion 176 7. Write a program that uses a function sum(int) that takes as an argument a positive integer n and returns the sum of the first n positive integers. Use a while loop. Then write a recursive function that performs the same task. . Sample output: Enter a positive integer: 5 The sum of the first 5 positive integers is: 15 8. Write a program that uses a function gcf(int,int) that takes as arguments two positive integers and returns their GCF (Greatest Common Factor) sum of the first n positive integers. First use a loop. Then write a recursive function that performs the same task. Sample output: Enter first integer: 50 Enter second integer: 30 Their gcf is: 10 17. Inheritance 17.1 Inheritance Inheritance is a key feature of object oriented programming. It allows new classes to adopt attributes and functionality from existing classes. The original class is called the base class and the new class is the derived class. Chapter 17. Inheritance 178 Code 17.1: Simple inheritance example 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 c l a s s Person { 6 public : 7 s t r i n g name ; 8 i n t age ; 9 }; 10 11 c l a s s S t u d e n t : p u b l i c P e r s o n { 12 p u b l i c : 13 d o u b l e gpa ; 14 } ; 15 16 i n t main ( ) { 17 Student st1 ; 18 s t 1 . name = " Bob " ; 19 s t 1 . age = 20; 20 s t 1 . gpa = 3 . 5 5 ; 21 22 c o u t << s t 1 . name ; 23 c o u t << " i s a " << s t 1 . a g e << " y e a r o l d s t u d e n t " ; 24 c o u t << " w i t h a gpa o f " << s t 1 . gpa << e n d l ; 25 return 0; 26 } Which one is the base class and which one the derived class? Alternatively the terms parent class and child class are also used. Which one they are in our example? Substitute the keyword public with protected inside the Person class. Does it work? Repeat using the keyword private. 17.1 Inheritance 179 Code 17.2: Simple inheritance example with added components 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 c l a s s Person { 6 public : 7 s t r i n g name ; 8 i n t age ; 9 }; 10 11 c l a s s S t u d e n t : p u b l i c P e r s o n { 12 p r i v a t e : 13 d o u b l e gpa ; 14 p u b l i c : 15 Student ( s t r i n g n , i n t a , double g ){ 16 name = n ; 17 age = a ; 18 gpa = g ; 19 } 20 21 void p r i n t I n f o ( ) { 22 c o u t << name ; 23 c o u t << " i s a " << a g e << " y e a r o l d s t u d e n t " ; 24 c o u t << " w i t h a gpa o f " << gpa << e n d l ; 25 } 26 } ; 27 28 i n t main ( ) { 29 S t u d e n t s t 1 ( " Bob " , 2 0 , 3 . 5 5 ) ; 30 st1 . printInfo ( ) ; 31 return 0; 32 } Substitute the keyword public with protected inside the Person class. Does it work this time? Repeat using the keyword private. If any of the attempts does not work what can we do to fix it? Chapter 17. Inheritance 180 17.2 Inheritance and Constructors Constructors and destructors are not inherited from the base class to the derived class. Code 17.3: Constructors in inheritance example 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 c l a s s Person { 6 protected : 7 s t r i n g name ; 8 i n t age ; 9 public : 10 P e r s o n ( ) { c o u t << "New p e r s o n c r e a t e d . " << e n d l ; } 11 ~ P e r s o n ( ) { c o u t << " P e r s o n d e l e t e d . " << e n d l ; } 12 13 } ; 14 15 c l a s s S t u d e n t : p u b l i c P e r s o n { 16 p r i v a t e : 17 d o u b l e gpa ; 18 p u b l i c : 19 Student ( s t r i n g n , i n t a , double g ){ 20 c o u t << "New s t u d e n t c r e a t e d . " << e n d l ; 21 name = n ; 22 age = a ; 23 gpa = g ; 24 } 25 26 ~ S t u d e n t ( ) { c o u t << " S t u d e n t d e l e t e d . " << e n d l ; } 27 28 void p r i n t I n f o ( ) { 29 c o u t << name ; 30 c o u t << " i s a " << a g e << " y e a r o l d s t u d e n t " ; 31 c o u t << " w i t h a gpa o f " << gpa << e n d l ; 32 } 33 } ; 34 35 i n t main ( ) { 36 S t u d e n t s t 1 ( " Bob " , 2 0 , 3 . 5 5 ) ; 37 st1 . printInfo ( ) ; 38 return 0; 39 } Run the program. What do you notice about the order in which constructors and destructors are executed? What can we conclude regarding the relation betwen the base and derived constructors and destructors? 17.2 Inheritance and Constructors Code 17.4: Constructors in inheritance example - Explicit constructor call 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 c l a s s Person { 6 protected : 7 s t r i n g name ; 8 i n t age ; 9 public : 10 P e r s o n ( ) : name ( " " ) , a g e ( 0 ) 11 { c o u t << "New p e r s o n c r e a t e d . " << e n d l ; } 12 P e r s o n ( s t r i n g n , i n t a ) : name ( n ) , a g e ( a ) 13 { c o u t << "New p e r s o n c r e a t e d . " << e n d l ; } 14 ~ P e r s o n ( ) { c o u t << " P e r s o n d e l e t e d . " << e n d l ; } 15 } ; 16 17 c l a s s S t u d e n t : p u b l i c P e r s o n { 18 p r i v a t e : 19 d o u b l e gpa ; 20 p u b l i c : 21 S t u d e n t ( ) : P e r s o n ( ) , gpa ( 0 . 0 ) 22 { c o u t << "New s t u d e n t c r e a t e d . " << e n d l ; } 23 S t u d e n t ( s t r i n g n , i n t a , d o u b l e g ) : P e r s o n ( n , a ) , gpa ( g ) 24 { c o u t << "New s t u d e n t c r e a t e d . " << e n d l ; } 25 ~ S t u d e n t ( ) { c o u t << " S t u d e n t d e l e t e d . " << e n d l ; } 26 27 void p r i n t I n f o ( ) { 28 c o u t << name ; 29 c o u t << " i s a " << a g e << " y e a r o l d s t u d e n t " ; 30 c o u t << " w i t h a gpa o f " << gpa << e n d l ; 31 } 32 } ; 33 i n t main ( ) { 34 S t u d e n t s t 1 ( " Bob " , 2 0 , 3 . 5 5 ) ; 35 st1 . printInfo ( ) ; 36 return 0; 37 } What are the advantages of calling a constructor explicitly? Is it best to keep attributes protected or private? 181 Chapter 17. Inheritance 182 17.3 Inheriting Functionality Member functions are inherited similar to member attributes. Code 17.5: Inheriting member functions 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 c l a s s Person { 6 protected : 7 s t r i n g name ; 8 i n t age ; 9 public : 10 P e r s o n ( ) : name ( " " ) , a g e ( 0 ) 11 { c o u t << "New p e r s o n c r e a t e d . " << e n d l ; } 12 Person ( s t r i n g n , i n t a ) 13 : name ( n ) , a g e ( a ) 14 { c o u t << "New p e r s o n c r e a t e d . " << e n d l ; } 15 void sayHello ( ) { 16 c o u t << " H e l l o I am " << name << " . " ; 17 c o u t << " I am a p e r s o n . " << e n d l ; 18 } 19 ~ P e r s o n ( ) { c o u t << " P e r s o n d e l e t e d . " << e n d l ; } 20 } ; 21 22 c l a s s S t u d e n t : p u b l i c P e r s o n { 23 p r i v a t e : 24 d o u b l e gpa ; 25 p u b l i c : 26 S t u d e n t ( ) : P e r s o n ( ) , gpa ( 0 . 0 ) 27 { c o u t << "New s t u d e n t c r e a t e d . " << e n d l ; } 28 Student ( s t r i n g n , i n t a , double g ) 29 : P e r s o n ( n , a ) , gpa ( g ) 30 { c o u t << "New s t u d e n t c r e a t e d . " << e n d l ; } 31 ~ S t u d e n t ( ) { c o u t << " S t u d e n t d e l e t e d . " << e n d l ; } 32 } ; 33 34 i n t main ( ) { 35 S t u d e n t s t 1 ( " Bob " , 2 0 , 3 . 5 5 ) ; 36 st1 . sayHello ( ) ; 37 return 0; 38 } 17.3 Inheriting Functionality 1 2 3 4 183 void sayHello ( ) { c o u t << " H e l l o I am " << name << " . " ; c o u t << " I am a s t u d e n t . " << e n d l ; } Add the above function definition to the Student class definition and run the program. What change do you observe? 1 2 3 4 v o i d s a y H e l l o ( s t r i n g mood ) { c o u t << " H e l l o I am " << name << " . " ; c o u t << " I am a " << mood << " s t u d e n t . " << e n d l ; } Change the function definition to the one above and run again the program. Any observations? Chapter 17. Inheritance 184 17.4 Multiple Inheritance Multiple inheritance is allowed in C++. A child (derived) class can have more than one parent (base) class. Code 17.6: Multiple inheritance example 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 class Student { 6 public : 7 s t r i n g name ; 8 s t r i n g major ; 9 S t u d e n t ( ) { c o u t << " S t u d e n t c r e a t e d . " << e n d l ; } 10 ~ S t u d e n t ( ) { c o u t << " S t u d e n t d e l e t e d . " << e n d l ; } 11 v o i d s a y H e l l o ( ) { c o u t << " H e l l o I am a s t u d e n t . " << e n d l ; } 12 } ; 13 14 c l a s s T e a c h e r { 15 p u b l i c : 16 s t r i n g name1 ; 17 s t r i n g rank ; 18 T e a c h e r ( ) { c o u t << " T e a c h e r c r e a t e d . " << e n d l ; } 19 ~ T e a c h e r ( ) { c o u t << " T e a c h e r d e l e t e d . " << e n d l ; } 20 v o i d s a y H e l l o ( ) { c o u t << " H e l l o I am a t e a c h e r . " << e n d l ; } 21 } ; 22 23 c l a s s G r a d u a t e I n s t r u c t o r : p u b l i c S t u d e n t , p u b l i c T e a c h e r { 24 p u b l i c : 25 G r a d u a t e I n s t r u c t o r ( ) { c o u t << " I n s t r u c t o r c r e a t e d . " << e n d l ; } 26 ~ G r a d u a t e I n s t r u c t o r ( ) { c o u t << " I n s t r u c t o r d e l e t e d . " << e n d l ; } 27 } ; 28 29 i n t main ( ) { 30 G r a d u a t e I n s t r u c t o r gi1 ; 31 g i 1 . name= " Bob " ; 32 gi1 . rank=" I n s t r u c t o r " ; 33 c o u t << g i 1 . name << " i s an " << g i 1 . r a n k << e n d l ; 34 return 0; 35 } What are the benefits and risks of using multiple inheritance? 17.5 Multilevel Inheritance 17.5 185 Multilevel Inheritance Code 17.7: Multilevel inheritance example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 c l a s s Major { 5 public : 6 i n t id ; 7 Major ( ) { c o u t << "New m a j o r . " << e n d l ; } 8 ~ Major ( ) { c o u t << " Major d e l e t e d . " << e n d l ; } 9 }; 10 11 c l a s s E n g i n e e r i n g : p u b l i c Major { 12 p u b l i c : 13 E n g i n e e r i n g ( ) { c o u t << "New e n g i n e e r i n g m a j o r . " << e n d l ; } 14 ~ E n g i n e e r i n g ( ) { c o u t << " E n g i n e e r i n g m a j o r d e l e t e d . " << e n d l ; } 15 } ; 16 17 c l a s s C i v i l E n g i n e e r i n g : p u b l i c E n g i n e e r i n g { 18 p u b l i c : 19 C i v i l E n g i n e e r i n g ( ) { c o u t << "New c i v i l eng . m a j o r . " << e n d l ; } 20 ~ C i v i l E n g i n e e r i n g ( ) { c o u t << " C i v i l eng . d e l e t e d . " << e n d l ; } 21 } ; 22 23 i n t main ( ) { 24 C i v i l E n g i n e e r i n g major1 ; 25 major1 . id =10; 26 c o u t << " Major w i t h i d : " << m a j o r 1 . i d << e n d l ; 27 return 0; 28 } 18. Polymorphism 18.1 Polymorphism and Virtual Functions Polymorphism is an important mechanism in object oriented programming. The term itself means many forms. When two or more classes are related to each other via inheritance, we want to be able to determine which inherited member functions are executed during the life of a program. Polymorphism allows for this decision to be made during the execution of the program by adapting to the type of object is currently working with at the time the decision needs to be made. This is also called late binding. Virtual functions are used for this purpose. Before we look at the first example of virtual functions lets revisit functionality inheritance, function overloading and function redefinitions. 188 Chapter 18. Polymorphism Code 18.1: Overloading and redefining functions example 1 # include <iostream > 2 # include <string > 3 u s i n g namespace s t d ; 4 5 6 c l a s s Person { 7 public : 8 P e r s o n ( ) { c o u t << "New p e r s o n c r e a t e d . " << e n d l ; } 9 ~ P e r s o n ( ) { c o u t << " P e r s o n d e l e t e d . " << e n d l ; } 10 v o i d s a y H e l l o ( ) { c o u t << " H e l l o I am a p e r s o n . " << e n d l ; } 11 v o i d s a y H e l l o ( s t r i n g name ) { 12 c o u t << " I am " << name << " . I am a p e r s o n . " << e n d l ; } 13 } ; 14 15 c l a s s S t u d e n t : p u b l i c P e r s o n { 16 p u b l i c : 17 S t u d e n t ( ) { c o u t << "New s t u d e n t c r e a t e d . " << e n d l ; } 18 ~ S t u d e n t ( ) { c o u t << " S t u d e n t d e l e t e d . " << e n d l ; } 19 v o i d s a y H e l l o ( ) { c o u t << " H e l l o I am a s t u d e n t . " << e n d l ; } 20 v o i d s a y H e l l o ( s t r i n g name ) { 21 c o u t << " I am " << name << " . I am a s t u d e n t . " << e n d l ; } 22 } ; 23 24 i n t main ( ) { 25 Person pr1 ; 26 Student st1 ; 27 pr1 . sayHello ( ) ; 28 p r 1 . s a y H e l l o ( " Bob " ) ; 29 st1 . sayHello ( ) ; 30 s t 1 . s a y H e l l o ( " John " ) ; 31 return 0; 32 } In the example above we have both function overloading and function redefining. The decision on which function will be called during execution is made at compilation time. This is also referred to as static binding. In the next example we will use virtual functions and discuss the difference between static and late binding. 18.1 Polymorphism and Virtual Functions Code 18.2: Virtual function example 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 48 49 50 51 # include <iostream > u s i n g namespace s t d ; c l a s s Shape { public : int height ; Shape ( ) { h e i g h t = 1 ; } Shape ( i n t h ) { h e i g h t =h ; } v i r t u a l v o i d drawShape ( ) { c o u t << " Shape : h e i g h t : " << h e i g h t << e n d l ; } }; c l a s s S q u a r e : p u b l i c Shape { public : Square ( ) { h e i g h t =1;} S q u a r e ( i n t h ) { h e i g h t =h ; } v o i d drawShape ( ) { c o u t << " S q u a r e : h e i g h t : " << h e i g h t << e n d l ; f o r ( i n t i = 0 ; i < h e i g h t ; i ++){ f o r ( i n t j = 0 ; j < h e i g h t * 2 ; j ++) { c o u t << ’ * ’ ; } c o u t << e n d l ; } c o u t << e n d l << e n d l ; } }; c l a s s T r i a n g l e : p u b l i c Shape { public : T r i a n g l e ( ) { h e i g h t =1;} T r i a n g l e ( i n t h ) { h e i g h t =h ; } v o i d drawShape ( ) { c o u t << " T r i a n g l e : h e i g h t : " << h e i g h t << e n d l ; f o r ( i n t i = 1 ; i <=5; i ++) { f o r ( i n t j = 1 ; j <=5− i ; j ++) { c o u t << ’ ’ ; } f o r ( i n t k = 1 ; k <=2 * i − 1 ; k++ ) { c o u t << ’ * ’ ; } c o u t << ’ \ n ’ ; } c o u t << e n d l ; } }; i n t main ( ) { S q u a r e mySquare ( 4 ) ; Triangle myTriangle ( 5 ) ; Shape myShape ( 6 ) ; Shape * s h a p e p 1 = &mySquare ; Shape * s h a p e p 2 = &m y T r i a n g l e ; Shape * s h a p e p 3 = &myShape ; s h a p e p 1 −> drawShape ( ) ; s h a p e p 2 −> drawShape ( ) ; s h a p e p 3 −> drawShape ( ) ; return 0; } <— Get code here. 189 190 Chapter 18. Polymorphism Remove the keyword virtual and run the program. What do you observe? Use the dot (.) operator instead of pointers to call method drawShape(). Add the new function newDraw() and change main() as shown below. What do you notice? What does that tell you about the usefulness of virtual functions? Code 18.3: Try now additions/changes 1 v o i d newDraw ( Shape * s ) { 2 c o u t << " H e l l o I am t h e new f u n c t i o n ! ! ! " << e n d l ; 3 s −> drawShape ( ) ; 4 } 5 6 i n t main ( ) { 7 S q u a r e mySquare ( 4 ) ; 8 Triangle myTriangle ( 5 ) ; 9 Shape myShape ( 6 ) ; 10 newDraw(& mySquare ) ; 11 newDraw(& m y T r i a n g l e ) ; 12 newDraw(&myShape ) ; 13 return 0; 14 } What is the difference between redefining and overriding? 18.2 Abstract Classes 18.2 191 Abstract Classes A class with one or more pure virtual function is an abstract class. A pure virtual function is only declared but not defined within the same class. To declare a pure virtual function we use the following syntax. The pure virtual function format virtual return_type function_name (parameter list) = 0; Code 18.4: Virtual function example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 c l a s s Animal { 5 public : 6 Animal ( s t r i n g n ) : name ( n ) {} 7 v i r t u a l ~ Animal ( ) {} 8 v i r t u a l v o i d makeNoise ( ) = 0 ; 9 protected : 10 s t r i n g name ; 11 } ; 12 13 14 c l a s s Dog : p u b l i c Animal { 15 p u b l i c : 16 Dog ( s t r i n g n ) : Animal ( n ) {} 17 v o i d makeNoise ( ) o v e r r i d e { 18 c o u t << name << " s a y s woof ! " << e n d l ; 19 } 20 } ; 21 22 c l a s s C a t : p u b l i c Animal { 23 p u b l i c : 24 C a t ( s t r i n g n ) : Animal ( n ) {} 25 v o i d makeNoise ( ) o v e r r i d e { 26 c o u t << name << " s a y s meow ! " << e n d l ; 27 } 28 } ; 29 30 i n t main ( ) { 31 Dog myDog ( " L a s s i e " ) ; 32 myDog . makeNoise ( ) ; 33 C a t myCat ( " B e l l a " ) ; 34 myCat . makeNoise ( ) ; 35 return 0; 36 } Chapter 18. Polymorphism 192 Which of the three classes is abstract? Is override mandatory when defining inherited virtual functions? Can we create an object of type Animal using the above class definitions? Remove the makeNoise() function definition from the Dog class. Does the program work? In main() add an array of four animals, two dogs and two cats. Then use a for loop to call the makeNoise() function for each array element. 19. Templates 19.1 Background Before we introduce templates, we look back at a simple function which swaps the values of two variables. Code 19.1: Function swapValues() example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 v o i d s w a p V a l u e s ( i n t& one , i n t& two ) { 5 i n t temp = one ; 6 one = two ; 7 two = temp ; 8 } / / end swap 9 10 i n t main ( ) { 11 i n t f i r s t =3 , s e c o n d = 5 ; 12 c o u t << " B e f o r e swap . " << e n d l ; 13 c o u t << " f i r s t = " << f i r s t << e n d l ; 14 c o u t << " s e c o n d = " << s e c o n d << e n d l << e n d l ; 15 16 swapValues ( f i r s t , second ) ; 17 18 c o u t << " A f t e r swap . " << e n d l ; 19 c o u t << " f i r s t = " << f i r s t << e n d l ; 20 c o u t << " s e c o n d = " << s e c o n d << e n d l << e n d l ; 21 22 return 0; 23 } / / end main Chapter 19. Templates 194 Change the swapValues() definition to work with two double values. How about two char values? Add the following class definition to the program and make any necessary changes for the function to swap two Person objects. Code 19.2: Class Person definition 1 2 3 4 5 6 7 c l a s s Person { private : s t r i n g name ; public : P e r s o n ( s t r i n g n ) : name ( n ) {} s t r i n g getName ( ) { r e t u r n name ; } }; What could we do if we want all of the above examples to work in the same program? 19.2 Function Templates 19.2 195 Function Templates Function templates are used when we wish to declare and define a function which works for multiple value types. The following example illustrates a simple template for the swapValues() function. Code 19.3: First function template example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 t e m p l a t e < t y p e n a m e T> 5 v o i d s w a p V a l u e s ( T& one , T& two ) { 6 T temp = one ; 7 one = two ; 8 two = temp ; 9 } / / end s w a p V a l u e s 10 11 i n t main ( ) { 12 13 i n t f i r s t =3 , s e c o n d = 5 ; 14 c o u t << " B e f o r e swap . " << e n d l ; 15 c o u t << " f i r s t = " << f i r s t << e n d l ; 16 c o u t << " s e c o n d = " << s e c o n d << e n d l << e n d l ; 17 18 swapValues ( f i r s t , second ) ; 19 20 c o u t << " A f t e r swap . " << e n d l ; 21 c o u t << " f i r s t = " << f i r s t << e n d l ; 22 c o u t << " s e c o n d = " << s e c o n d << e n d l << e n d l ; 23 24 return 0; 25 } / / end main Change the keyword typename with the keyword class and run the program. Does it work? Do we need to use T for the typename? Change main() to test other types of values and run the program. Do not change the definition of swapValues(). Does it work? Can we separate the template function declaration from it definition? Chapter 19. Templates 196 Write a function template named largest(). The function takes three values of the same type as arguments and returns the largest of the three. The function should also work if the values are the same. Write a program to test the function for different values. A sample output is given below as a reference. Desired output format: Values are: 4 4 3 The largest value is: 4 Consider the Rectangle class definition below. Make all the necessary changes to make the largest() function template work with Rectangle types in a meaningful way. Code 19.4: Rectangle class definition 1 / * *********** D e c l a r a t i o n S e c t i o n ***************** * / 2 class Rectangle { 3 private : 4 i n t width , l e n g t h ; 5 public : 6 Rectangle ( ) ; 7 R e c t a n g l e ( i n t w, i n t l ) ; 8 R e c t a n g l e o p e r a t o r + ( R e c t a n g l e& r ) ; 9 }; 10 / * *********** I m p l e m e n t a t i o n S e c t i o n ***************** * / 11 R e c t a n g l e : : R e c t a n g l e ( ) { w i d t h = 1 , l e n g t h = 2 ; } 12 R e c t a n g l e : : R e c t a n g l e ( i n t w, i n t l ) { w i d t h = w, l e n g t h = l ; } 13 R e c t a n g l e R e c t a n g l e : : o p e r a t o r + ( R e c t a n g l e& r ) { 14 R e c t a n g l e temp ; 15 temp . w i d t h = t h i s −> w i d t h + r . w i d t h ; 16 temp . l e n g t h = t h i s −> l e n g t h + r . l e n g t h ; 17 r e t u r n temp ; 18 } 19.3 Class Templates 19.3 197 Class Templates Class templates are defined in a similar way as function templates. Below is a simple example adopted from the the book. Code 19.5: Class template example 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 # include <iostream > u s i n g namespace s t d ; t e m p l a t e < c l a s s T> class Pair { public : Pair ( ); P a i r (T f i r s t V a l u e , T secondValue ) ; void p r i n t P a i r ( ) const ; private : T first ; T second ; }; t e m p l a t e < c l a s s T> P a i r <T > : : P a i r ( T f i r s t V a l u e , T s e c o n d V a l u e ) { first = firstValue ; second = secondValue ; } t e m p l a t e < c l a s s T> v o i d P a i r <T > : : p r i n t P a i r ( ) c o n s t { c o u t << " ( " << f i r s t << " , " << s e c o n d << " ) " ; } i n t main ( ) { P a i r < i n t > p1 ( 3 , 5 ) ; P a i r < c h a r > p2 ( ’ a ’ , ’ b ’ ) ; c o u t << " F i r s t p a i r : " ; p1 . p r i n t P a i r ( ) ; c o u t << e n d l ; c o u t << " Second p a i r : " ; p2 . p r i n t P a i r ( ) ; return 0; } / / end main Give the definition for the default Pair constructor. Define a non-member template function T addValues(Pair<T> & myPair) which returns the sum of the two values in the pair. Add any necessary components to the class Pair. Test the function from main for different value types. 20. Linked Data Structures 20.1 Linked Lists Linked Lists allow us to create flexible and dynamic collections of data. Linked Lists do not have a fixed size and can expand or reduce in size as needed. Elements belonging to a linked list connect to one another via pointers. Before we introduce an example of a linked list we start with a small program using structs and pointers. Code 20.1: Starting example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 s t r u c t Node { 5 i n t value ; 6 Node * n e x t ; 7 }; 8 9 i n t main ( ) { 10 Node * one = new Node ; 11 one −> n e x t = NULL ; 12 one −> v a l u e = 1 ; 13 c o u t << one −> v a l u e << e n d l ; 14 } What is the default access mode for variables in a struct? Why sometimes is useful to set a pointer to NULL? 200 Chapter 20. Linked Data Structures Code 20.2: Linked list first example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 s t r u c t Node { 5 i n t value ; 6 Node * n e x t ; 7 }; 8 9 i n t main ( ) { 10 Node * one = new Node ; 11 one −> n e x t = NULL ; 12 one −> v a l u e = 1 ; 13 14 Node * two = new Node ; 15 two −> n e x t =NULL ; 16 two −> v a l u e = 5 ; 17 one −> n e x t = two ; 18 19 Node * t h r e e = new Node ; 20 t h r e e −> n e x t =NULL ; 21 t h r e e −> v a l u e = 6 ; 22 two −> n e x t = t h r e e ; 23 24 Node * v i s i t N o d e s = one ; 25 w h i l e ( v i s i t N o d e s ! = NULL) { 26 c o u t << v i s i t N o d e s −> v a l u e << " " ; 27 v i s i t N o d e s = v i s i t N o d e s −> n e x t ; 28 } / / end w h i l e 29 } 20.2 Linked Lists using Classes 20.2 201 Linked Lists using Classes Next we extend our discussion to include classes, and add some more components to each node. Each Node will now be an object of a class. Code 20.3: Linked list example using classes 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 c l a s s Node { 5 private : 6 i n t value ; 7 Node * n e x t ; 8 public : 9 Node ( ) {} 10 Node ( i n t v , Node * n ) : v a l u e ( v ) , n e x t ( n ) {} 11 i n t getValue ( ) const { r e t u r n value ;} 12 Node * g e t N e x t ( ) c o n s t { r e t u r n n e x t ; } 13 void setValue ( i n t v ) { value = v ;} 14 v o i d s e t N e x t ( Node * n ) { n e x t = n ; } 15 } ; 16 17 i n t main ( ) { 18 Node * one = new Node ( 1 , NULL ) ; 19 Node * two = new Node ( 5 , NULL ) ; 20 Node * t h r e e = new Node ( 6 , NULL ) ; 21 22 one −> s e t N e x t ( two ) ; 23 two −> s e t N e x t ( t h r e e ) ; 24 25 Node * v i s i t N o d e s = one ; 26 w h i l e ( v i s i t N o d e s ! = NULL) { 27 c o u t << v i s i t N o d e s −> g e t V a l u e ( ) << " " ; 28 v i s i t N o d e s = v i s i t N o d e s −> g e t N e x t ( ) ; 29 } / / end w h i l e 30 } Do we need the default constructor for class Node? Chapter 20. Linked Data Structures 202 20.3 Adding and Removing Nodes Code 20.4: Adding Nodes at the beginning of list 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 # include <iostream > u s i n g namespace s t d ; c l a s s Node { private : i n t value ; Node * n e x t ; public : Node ( i n t v , Node * n ) : v a l u e ( v ) , n e x t ( n ) {} i n t getValue ( ) const { r e t u r n value ;} Node * g e t N e x t ( ) c o n s t { r e t u r n n e x t ; } void setValue ( i n t v ) { value = v ;} v o i d s e t N e x t ( Node * n ) { n e x t = n ; } }; t y p e d e f Node * N o d e P o i n t e r ; v o i d p r i n t L i s t ( Node * h ) { c o u t << " L i s t c o n t e n t : " ; Node * v i s i t N o d e s = h ; w h i l e ( v i s i t N o d e s ! = NULL) { c o u t << v i s i t N o d e s −> g e t V a l u e ( ) << " " ; v i s i t N o d e s = v i s i t N o d e s −> g e t N e x t ( ) ; } / / end w h i l e c o u t << e n d l ; } / / end p r i n t L i s t ( ) v o i d i n s e r t H e a d ( N o d e P o i n t e r &h , i n t v ) { h = new Node ( v , h ) ; } i n t main ( ) { Node * h e a d = NULL ; p r i n t L i s t ( head ) ; i n s e r t H e a d ( head , 6 ) ; p r i n t L i s t ( head ) ; i n s e r t H e a d ( head , 5 ) ; p r i n t L i s t ( head ) ; i n s e r t H e a d ( head , 1 ) ; p r i n t L i s t ( head ) ; } 20.3 Adding and Removing Nodes 203 Add a function insert(NodePointer &after, int v) to the program above which adds a new Node with value = v after the given node. Test the function from main(); Add a function remove(NodePointer &after) to the program above which removes the given node. Test the function from main(); Add a function find(int key) to the program above which searches the linked list for a given key value. The function will return true if the key is found and false otherwise. 21. Exception Handling 21.1 Basic Exception Handling Exception handling is typically used to deal with unexpected errors that may occur during the execution of the program. This mechanism allows us to detect any errors and have an action plan to deal with them. Below we start with a very simple code. Code 21.1: A simple example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t friends = 0; 6 d o u b l e money = 0 . 0 ; 7 8 c o u t << "How many f r i e n d s do you h a v e ? " ; 9 c i n >> f r i e n d s ; 10 c o u t << "How much money do you h a v e ? " ; 11 c i n >> money ; 12 13 d o u b l e a v e r a g e = money / f r i e n d s ; 14 c o u t << " Each f r i e n d w i l l g e t $ " << a v e r a g e ; 15 return 0; 16 } Under which circumstances we will get an error and how we can deal with it? 206 Chapter 21. Exception Handling Code 21.2: Dealing with error example 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t f r i e n d s =0; 6 d o u b l e money = 0 . 0 , a v e r a g e = 0 . 0 ; 7 8 c o u t << "How many f r i e n d s do you h a v e ? " ; 9 c i n >> f r i e n d s ; 10 c o u t << "How much money do you h a v e ? " ; 11 c i n >> money ; 12 13 i f ( f r i e n d s <= 0 ) { 14 c o u t << " You n e e d t o f i n d a f r i e n d . " << e n d l ; 15 } 16 else { 17 a v e r a g e = money / f r i e n d s ; 18 c o u t << " Each f r i e n d w i l l g e t $ " << a v e r a g e ; 19 } 20 return 0; 21 } The potential error in the example above is easily predictable, so we can handle it in a simple way as we did. We will use the same scenario to illustrate the exception handling mechanism in C++. This use is not necessary in this example but is a good first example to explain how it works. 21.1 Basic Exception Handling 207 Code 21.3: Using try and catch blocks 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t f r i e n d s =0; 6 d o u b l e money = 0 . 0 , a v e r a g e = 0 . 0 ; 7 8 try { 9 c o u t << "How many f r i e n d s do you h a v e ? " ; 10 c i n >> f r i e n d s ; 11 c o u t << "How much money do you h a v e ? " ; 12 c i n >> money ; 13 14 i f ( f r i e n d s <= 0 ) 15 t h r o w money ; 16 17 a v e r a g e = money / f r i e n d s ; 18 c o u t << " Each f r i e n d w i l l g e t $ " << a v e r a g e ; 19 } 20 21 catch ( double e ){ 22 c o u t << " $ " << e ; 23 c o u t << " w i l l n o t make you happy i f you h a v e no f r i e n d s . " ; 24 } 25 return 0; 26 } Chapter 21. Exception Handling 208 21.2 Multiple Throws and Catches Code 21.4: From book. Using multiple try and catch blocks 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 c l a s s NegativeNumber { 5 public : 6 NegativeNumber ( ) { } ; 7 N e g a t i v e N u m b e r ( s t r i n g t h e M e s s a g e ) : m e s s a g e ( t h e M e s s a g e ) {} 8 s t r i n g getMessage ( ) c o n s t { r e t u r n message ; } 9 private : 10 s t r i n g message ; 11 } ; 12 c l a s s D i v i d e B y Z e r o { } ; 13 14 i n t main ( ) { 15 int pencils , erasers ; 16 d o u b l e ppe ; 17 try { 18 c o u t << "How many p e n c i l s do you h a v e ? \ n " ; 19 c i n >> p e n c i l s ; 20 i f ( p e n c i l s < 0) 21 throw NegativeNumber ( " p e n c i l s " ) ; 22 c o u t << "How many e r a s e r s do you h a v e ? \ n " ; 23 c i n >> e r a s e r s ; 24 i f ( e r a s e r s < 0) 25 throw NegativeNumber ( " e r a s e r s " ) ; 26 i f ( e r a s e r s !=0) 27 ppe = p e n c i l s / ( d o u b l e ) e r a s e r s ; 28 else 29 throw DivideByZero ( ) ; 30 c o u t << " Each e r a s e r must l a s t t h r o u g h " 31 << ppe << " p e n c i l s . \ n " ; 32 } 33 c a t c h ( NegativeNumber e ){ 34 c o u t << " C a n n o t h a v e a n e g a t i v e number o f " 35 << e . g e t M e s s a g e ( ) << e n d l ; 36 } 37 c a t c h ( DivideByZero ){ 38 c o u t << "Do n o t make any m i s t a k e s . \ n " ; 39 } 40 catch ( . . . ) { 41 c o u t << " S o m e t h i n g went wrong . " << e n d l ; 42 } 43 c o u t << " End o f p r o g r a m . \ n " ; 44 return 0; 45 } 21.3 Throwing an Exception in a Function 21.3 Throwing an Exception in a Function Code 21.5: From book. Throwing an exception in a function. 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 # include <iostream > # include < cstdlib > u s i n g namespace s t d ; c l a s s DivideByZero {}; double s a f e D i v i d e ( i n t top , i n t bottom ) throw ( DivideByZero ) ; i n t main ( ) { i n t numerator , denominator ; double q u o t i e n t ; c o u t << " E n t e r n u m e r a t o r : \ n " ; c i n >> n u m e r a t o r ; c o u t << " E n t e r d e n o m i n a t o r : \ n " ; c i n >> d e n o m i n a t o r ; try { q u o t i e n t = safeDivide ( numerator , denominator ) ; } c a t c h ( DivideByZero ){ c o u t << " E r r o r . D i v i s i o n by Z e r o . \ n " ; exit (0); } c o u t << " R e s u l t = " << q u o t i e n t << e n d l ; c o u t << " End o f p r o g r a m . \ n " ; return 0; } double s a f e D i v i d e ( i n t top , i n t bottom ) throw ( DivideByZero ){ i f ( b o t t o m == 0 ) throw DivideByZero ( ) ; r e t u r n top / ( double ) bottom ; } 209 22. Standard Template Library The Standard Template Library is a collection of C++ template classes that allows us to create commonly used data structures such as lists, vectors, stacks, queues, etc. Since these classes (ofter referred to as container classes) are often used, they are part of the C++ standard and can be used with any of the C++ installations. 22.1 Iterators A data structure is created to store and access information in an organized and efficient manner. One way of access and use this information is by using iterators. Iterators allows us to cycle through the data to obtain any necessary information stored in the data structure. Previously we discussed Linked Lists. We used pointers to visit each node (or a subset of nodes) as needed for various operations on a Linked List. The pointer in this case would be one example of an iterator. 212 22.2 Chapter 22. Standard Template Library Vectors Vectors are very similar to arrays. The main difference is the ability of vectors to change size during the execution of a program which is not true for arrays. Vectors are created by using a template from the STL. An iterator is available to allow access and manipulation of data in a given vector. The example below tests some of the basic functions of a vector data structure. Code 22.1: From book. Vector example 1 # include <iostream > 2 # include <vector > 3 u s i n g namespace s t d ; 4 5 i n t main ( ) { 6 vector <int > container ; 7 8 f o r ( i n t i = 1 ; i <= 4 ; i ++) 9 c o n t a i n e r . push_back ( i ) ; 10 11 c o u t << " Here i s what i s i n t h e c o n t a i n e r : \ n " ; 12 vector <int >:: i t e r a t o r p ; 13 f o r ( p = c o n t a i n e r . b e g i n ( ) ; p ! = c o n t a i n e r . end ( ) ; p ++) 14 c o u t << * p << " " ; 15 c o u t << e n d l ; 16 17 c o u t << " S e t t i n g e n t r i e s t o 0 : \ n " ; 18 19 f o r ( p = c o n t a i n e r . b e g i n ( ) ; p ! = c o n t a i n e r . end ( ) ; p ++) 20 *p = 0 ; 21 22 c o u t << " C o n t a i n e r now c o n t a i n s : \ n " ; 23 f o r ( p = c o n t a i n e r . b e g i n ( ) ; p ! = c o n t a i n e r . end ( ) ; p ++) 24 c o u t << * p << " " ; 25 c o u t << e n d l ; 26 27 return 0; 28 } 22.3 Queue Iterator Example 22.3 213 Queue Iterator Example The following example taken from your book shows an example of creating and using an iterator for a queue class. All separate content can be merged as is into one file or can be saved into separate files by adding the appropriate headers. The entire merged code can be obtained by following the link below: <— Get code here. Code 22.2: From book. Node class declaration with inline definitions 1 2 3 4 5 6 7 8 9 10 11 12 13 t e m p l a t e < c l a s s T> c l a s s Node { public : Node ( T t h e D a t a , Node<T> * t h e L i n k ) : d a t a ( t h e D a t a ) , l i n k ( t h e L i n k ) {} Node<T> * g e t L i n k ( ) c o n s t { r e t u r n l i n k ; } c o n s t T& g e t D a t a ( ) c o n s t { r e t u r n d a t a ; } v o i d s e t D a t a ( c o n s t T& t h e D a t a ) { d a t a = t h e D a t a ; } v o i d s e t L i n k ( Node<T> * p o i n t e r ) { l i n k = p o i n t e r ; } private : T data ; Node<T> * l i n k ; }; Code 22.3: From book. List Iterator class declaration with inline definitions 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 t e m p l a t e < c l a s s T> class ListIterator { public : L i s t I t e r a t o r ( ) : c u r r e n t (NULL) { } L i s t I t e r a t o r ( Node<T> * i n i t i a l ) : c u r r e n t ( i n i t i a l ) { } c o n s t T& o p e r a t o r * ( ) c o n s t { r e t u r n c u r r e n t −> g e t D a t a ( ) ; } L i s t I t e r a t o r& o p e r a t o r ++(){ c u r r e n t = c u r r e n t −> g e t L i n k ( ) ; return * this ; } L i s t I t e r a t o r & o p e r a t o r ++( i n t ) { ListIterator startVersion ( current ); c u r r e n t = c u r r e n t −> g e t L i n k ( ) ; return startVersion ; } b o o l o p e r a t o r ==( c o n s t L i s t I t e r a t o r r i g h t S i d e ) c o n s t { r e t u r n ( c u r r e n t == r i g h t S i d e . c u r r e n t ) ; } Chapter 22. Standard Template Library 214 22 23 24 25 26 27 28 29 bool o p e r a t o r !=( const L i s t I t e r a t o r r i g h t S i d e ) const { r e t u r n ( c u r r e n t != r i g h t S i d e . c u r r e n t ) ; } private : Node<T> * c u r r e n t ; }; Code 22.4: From book. Class Queue declaration with some inline definitions 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 t e m p l a t e < c l a s s T> c l a s s Queue { public : t y p e d e f L i s t I t e r a t o r <T> I t e r a t o r ; Queue ( ) ; Queue ( c o n s t Queue <T>& aQueue ) ; Queue <T>& o p e r a t o r = ( c o n s t Queue <T>& r i g h t S i d e ) ; v i r t u a l ~Queue ( ) ; v o i d add ( T i t e m ) ; T remove ( ) ; bool isEmpty ( ) c o n s t ; I t e r a t o r begin ( ) const { r e t u r n I t e r a t o r ( f r o n t ) ; } I t e r a t o r end ( ) c o n s t { r e t u r n I t e r a t o r ( ) ; } private : Node<T> * f r o n t ; Node<T> * b a c k ; }; Code 22.5: From book. Main function 1 2 3 4 5 6 7 8 9 10 11 12 13 14 i n t main ( ) { char next , ans ; do { Queue < c h a r > q ; c o u t << " E n t e r a l i n e o f t e x t : \ n " ; cin . get ( next ) ; while ( n e x t != ’ \ n ’ ){ q . add ( n e x t ) ; cin . get ( next ) ; } c o u t << " You e n t e r e d : \ n " ; Queue < c h a r > : : I t e r a t o r i ; 22.3 Queue Iterator Example 15 f o r ( i =q . b e g i n ( ) ; i ! = q . end ( ) ; i ++) 16 c o u t << * i ; 17 c o u t << e n d l ; 18 19 20 c o u t << " Again ? ( y / n ) : " ; 21 c i n >> a n s ; 22 cin . ignore (10000 , ’ \ n ’ ) ; 23 24 } w h i l e ( a n s ! = ’ n ’ && a n s ! = ’N ’ ) ; 25 26 return 0; 27 } Code 22.6: From book. Remaining function definitions from class Queue 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 t e m p l a t e < c l a s s T> Queue <T > : : Queue ( ) : f r o n t (NULL ) , b a c k (NULL) { } t e m p l a t e < c l a s s T> Queue <T > : : Queue ( c o n s t Queue <T>& aQueue ) { i f ( aQueue . i s E m p t y ( ) ) { f r o n t = b a c k = NULL ; } else { Node<T> * temp = aQueue . f r o n t ; b a c k = new Node<T> ( temp −> g e t D a t a ( ) , NULL ) ; f r o n t = back ; temp = temp −> g e t L i n k ( ) ; w h i l e ( temp ! =NULL) { back −> s e t L i n k ( new Node<T> ( temp −> g e t D a t a ( ) , NULL ) ) ; b a c k = back −> g e t L i n k ( ) ; temp = temp −> g e t L i n k ( ) ; } } } t e m p l a t e < c l a s s T> Queue <T>& Queue <T > : : o p e r a t o r = ( c o n s t Queue <T>& r i g h t S i d e ) { i f ( f r o n t == r i g h t S i d e . f r o n t ) return * this ; else { T next ; while ( ! isEmpty ( ) ) n e x t = remove ( ) ; } i f ( r i g h t S i d e . isEmpty ( ) ) { f r o n t = back = n u l l p t r ; 215 Chapter 22. Standard Template Library 216 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 return * this ; } else { Node<T> * temp = r i g h t S i d e . f r o n t ; b a c k = new Node<T> ( temp −> g e t D a t a ( ) , n u l l p t r ) ; f r o n t = back ; temp = temp −> g e t L i n k ( ) ; w h i l e ( temp ! = n u l l p t r ) { back −> s e t L i n k ( new Node<T> ( temp −> g e t D a t a ( ) , n u l l p t r ) ) ; b a c k = back −> g e t L i n k ( ) ; temp = temp −> g e t L i n k ( ) ; } return * this ; } } t e m p l a t e < c l a s s T> Queue <T > : : ~Queue ( ) { T next ; while ( ! isEmpty ( ) ) n e x t = remove ( ) ; } t e m p l a t e < c l a s s T> v o i d Queue <T > : : add ( T i t e m ) { i f ( isEmpty ( ) ) f r o n t = b a c k = new Node<T> ( i t e m , n u l l p t r ) ; else { back −> s e t L i n k ( new Node<T> ( i t e m , n u l l p t r ) ) ; b a c k = back −> g e t L i n k ( ) ; } } t e m p l a t e < c l a s s T> T Queue <T > : : remove ( ) { i f ( isEmpty ( ) ) { c o u t << " E r r o r : Removing an i t e m from an empty q u e u e . \ n " ; exit (1); } T r e s u l t = f r o n t −> g e t D a t a ( ) ; Node<T> * d i s c a r d ; discard = front ; f r o n t = f r o n t −> g e t L i n k ( ) ; i f ( f r o n t == n u l l p t r ) back = n u l l p t r ; 22.3 Queue Iterator Example 82 delete discard ; 83 return result ; 84 } 85 86 t e m p l a t e < c l a s s T> 87 b o o l Queue <T > : : i s E m p t y ( ) c o n s t { 88 r e t u r n ( b a c k == NULL ) ; 89 } 217 III Part Three - Other Topics 23 File Processing . . . . . . . . . . . . . . . . . . . . . 221 A Answers to Exercises . . . . . . . . . . . . . . . . 225 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 23. File Processing 23.1 Stream Objects The output generated by the C++ program will be lost unless is stored somewhere in permanent memory. In this section we will discuss how to store and retrieve data to and from a file. Code 23.1: Creating a new file in the current workspace. 1 # include <fstream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 ofstream myOutputFile ( " output . t x t " ) ; 6 7 m y O u t p u t F i l e << "MAC 101 " << e n d l ; 8 m y O u t p u t F i l e << " Computer S c i e n c e " << e n d l ; 9 myOutputFile . close ( ) ; 10 11 return 0; 12 } Note: File stream objects support the same function calls as the cin/cout objects. Change the output text and run the program again. What do you notice? Chapter 23. File Processing 222 Code 23.2: Creating a new file in a new, specific location. 1 # include <fstream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 ofstream myOutputFile ( " c : \ \ TestFolder \ \ output2 . t x t " ) ; 6 7 m y O u t p u t F i l e << "MAC 101 " << e n d l ; 8 m y O u t p u t F i l e << " Computer S c i e n c e " << e n d l ; 9 myOutputFile . close ( ) ; 10 11 return 0; 12 } Why do we need to use double slash (\\) in the file path? Example: We can use pre-defined functions to open a file, check the existence of a file and many other related operations. Code 23.3: Open a file example. 1 include <fstream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i f s t r e a m myOutputFile ; 6 m y O u t p u t F i l e . open ( " o u t p u t . t x t " ) ; 7 8 i f ( myOutputFile . f a i l ( ) ) { 9 c o u t << " C a n n o t open f i l e ! ! ! " ; 10 r e t u r n −1; 11 } 12 13 c o u t << " The f i l e i s open . " ; 14 myOutputFile . close ( ) ; 15 return 0; 16 } 23.1 Stream Objects 223 Example: Read content from a file one page at a time and display on the console window. Code 23.4: Read file example. 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 # include <iostream > # include <fstream > # include <string > u s i n g namespace s t d ; i n t main ( ) { s t r i n g fileName , l i n e O f T e x t ; c o u t << " E n t e r a f i l e name : " ; g e t l i n e ( cin , fileName ) ; i f s t r e a m myFile ( fileName ) ; i f ( ! myFile ) { c o u t << f i l e N a m e << " c o u l d n o t be o p e n e d . " ; r e t u r n −1; } while ( t r u e ) { char c = ’a ’ ; f o r ( i n t i = 1 ; i <= 24 && ! m y F i l e . e o f ( ) ; i ++) { g e t l i n e ( myFile , l i n e O f T e x t ) ; c o u t << l i n e O f T e x t << e n d l ; } i f ( myFile . eof ( ) ) break ; c o u t << " E n t e r ’Q ’ t o q u i t . " ; g e t l i n e ( cin , lineOfText ) ; c = lineOfText [ 0 ] ; i f ( c == ’Q ’ | | c == ’ q ’ ) break ; } return 0; } a) Create a folder PracticeFolder in the c: directory of your computer. b) Modify the C++ program from above to create a new file “numbers.txt”. c) Write in the file the first 100 positive integers, each value in a new line. d) Use the program to output the content of the “numbers.txt” file 10 numbers at a time. Chapter 23. File Processing 224 Example: Append text at the end of a file. Code 23.5: Append text example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 # include <iostream > # include <fstream > # include <string > u s i n g namespace s t d ; i n t main ( ) { s t r i n g someText ; o f s t r e a m m y F i l e ( " r e c o r d s . t x t " , i o s : : app ) ; i f ( ! myFile ) { c e r r << " F i l e c o u l d n o t be o p e n e d . " << e n d l ; exit (1); } c o u t << " E n t e r some t e x t o r t y p e ’ e x i t ’ t o s t o p : " << e n d l ; w h i l e ( g e t l i n e ( c i n , someText ) && someText ! = " e x i t " ) m y F i l e << someText << e n d l ; return 0; } Note: Besides ios::app, there several other available fstream modes. Write a C++ program that allows the user to search a file “MyText.txt” located in the current workspace for any word (String). The program should print the result of the search. In the event the word is found the program should indicate the line where it was found in the text file. Desired output format sample 1: Enter the word you are looking for: hello The word hello was not found. Desired output format sample 2: Enter the word you are looking for: hello The word hello was found in line 3 of the text. A. Answers to Exercises A.1 Chapter 1 → Answer to question 2 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) 5 { 6 c o u t << " T h i s i s t h e f i r s t l i n e . " << e n d l << e n d l ; 7 c o u t << " T h i s i s t h e s e c o n d l i n e . " << e n d l ; 8 9 return 0; 10 } → Answer to question 4 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 c o u t << " * \ n * * \ n * * * \ n **** " << e n d l ; 6 return 0; 7 } Chapter A. Answers to Exercises 226 → Answer to question 6 Write a C++ program that prompts the user to input their age, and then outputs a message stating their age. The program should use proper grammar and punctuation to form a complete sentence. For example, if the user enters "25", the program should output "You are 25 years old." Your program should display a prompt asking the user to enter their age, and then read in the age from the user using the appropriate input method. Finally, the program should output the user’s age in a message that includes the number of years and proper punctuation. 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t age ; 6 c o u t << " E n t e r y o u r a g e : " ; 7 c i n >> a g e ; 8 c o u t << " You a r e " << a g e << " y e a r s o l d . " << e n d l ; 9 return 0; 10 } → Item 2 A.2 Chapter 3 → Answer to question 1 1. variable: A variable is a named storage location in computer memory that holds a value of a particular data type. It is a symbolic representation of a memory location that can hold different values at different times during the execution of a program. 2. identifier: An identifier is a name given to a variable, function, class, or any other user-defined item in a program. An identifier must follow certain naming rules and conventions and should be unique within its scope. 3. keyword: A keyword is a reserved word that has a special meaning in the programming language and cannot be used as an identifier. Keywords are used to define the syntax and structure of the language, and they have predefined functions that cannot be changed by the programmer. 4. statement: A statement is a unit of code that performs a specific action in a program. It can be a declaration, an assignment, a function call, a control statement, or any other operation that can be performed in the language. 5. declaring a variable: Declaring a variable is the process of defining a named storage location in memory with a specific data type. It involves specifying the variable name, the data type, and optionally an initial value. 6. initializing a variable: Initializing a variable is the process of assigning an initial value to a declared variable. It can be done at the time of declaration or later in the program. 7. assignment statement: An assignment statement is a statement that assigns a value to a variable. It involves using the assignment operator ’=’ to assign a value to the variable on the left-hand side of the operator. A.2 Chapter 3 227 → Answer to question 2 1. All variables must be declared before being used. (True - False) True. This means that their type and name must be specified in a declaration statement before they can be used in any other statements. 2. C++ considers the variable number and NUMBER to be identical. (True - False) False. In C++, variable names are case sensitive, which means that "number" and "NUMBER" are two different identifiers and not identical. 3. The arithmetic operators *, /, +, and – have the same level of precedence. (True - False) False. The arithmetic operators in C++ have different levels of precedence, which determine the order in which they are evaluated. The * and / operators have a higher precedence than + and - operators. 4. The statement cout « “a = 5;” ; is a typical assignment statement. (True - False) False. The statement "cout « “a = 5;” ;" is an output statement that writes the value of the string "a = 5;" to the console. An assignment statement assigns a value to a variable, for example: "a = 5;". 5. The statements n +=2; and n = n+2; have the exact same outcome. (True - False) True. The statements "n += 2;" and "n = n + 2;" are equivalent and have the same outcome. The += operator is a compound assignment operator that adds the value on the right-hand side to the variable on the left-hand side and then assigns the result to the left-hand side variable. 6. The size of the int data type is guaranteed to be 4 bytes on all platforms. (True - False) False. The size of the int data type is not guaranteed to be 4 bytes on all platforms. The C++ standard only specifies that an int must be able to represent at least the range of values from -32767 to 32767, which requires 2 bytes. 7. The double data type can hold larger values than the float data type. (True - False) True. The double data type can hold larger values than the float data type because it uses 8 bytes to represent a floating-point number, while the float data type uses 4 bytes. 8. C++ has a built-in data type for representing Boolean values. (True - False) True. C++ has a built-in data type called bool that represents Boolean values, which can have the value true or false. 9. The "sizeof" operator in C++ returns the number of bytes occupied by a variable. (True - False) True. For example, the expression "sizeof(int)" returns the number of bytes occupied by an int variable on the current platform. → Answer to question 5 A variable that can have values only in the range 0 to 65535 is a two-byte unsigned integer. An unsigned integer is a non-negative integer that can have values from 0 to a certain maximum value determined by the number of bytes used to store the value. A two-byte unsigned integer can store values in the range of 0 to 216 − 1, which is equivalent to 0 to 65535. Therefore, option (d) "two-byte unsigned integer" is the correct answer. → Answer to question 7 The largest unsigned integer that can be represented with 32 bits is 232 − 1, which is equal to 4,294,967,295. The largest unsigned integer that can be represented with 64 bits is 264 − 1, which is equal to Chapter A. Answers to Exercises 228 18,446,744,073,709,551,615. → Answer to question 10 1 # include <iostream > 2 u s i n g namespace s t d ; 3 4 i n t main ( ) { 5 i n t x = 0; 6 7 / / U s i n g t h e + o p e r a t o r and t h e = o p e r a t o r 8 x = x + 1; 9 c o u t << " x = " << x << e n d l ; 10 11 / / U s i n g t h e += o p e r a t o r 12 x += 1 ; 13 c o u t << " x = " << x << e n d l ; 14 15 / / U s i n g t h e p o s t f i x ++ o p e r a t o r 16 x ++; 17 c o u t << " x = " << x << e n d l ; 18 19 / / U s i n g t h e p r e f i x ++ o p e r a t o r 20 ++x ; 21 c o u t << " x = " << x << e n d l ; 22 23 return 0; 24 } → Answer to question ?? A.3 Chapter 3 → Answer to question A.3 → Item 2 → Item 3 Index if and if-else Statements, 41 Abstract Classes, 181 Adding and Removing Nodes, 192 Addition and Subtraction of Numbers at Different Bases, 20 Arithmetic Operations, 29 Array Size, 101 Arrays and Pointer Arithmetic, 112 Arrays and Pointers, 150 Arrays of Structures, 118 Background, 183 Basic Exception Handling, 195 C++ Loops. The while and do. . . while Statement., 55 C++ Syntax Tokens, 25 C-style String Functions, 127 Characters, Strings and Arrays of Strings, 104 Class Composition, 147 Class Templates, 187 Classes, 122 Constant Objects, 145 Constructors, 140 Conversion Between Binary, Octal and Hexadecimal, 19 Converting Binary, Octal and Hexadecimal to Decimal, 15 Converting Decimal Numbers to Other Bases, 17 Default and Static Variables, 90 Default Function Arguments, 78 Destructors, 142 Function Overloading, 79 Function Templates, 185 Getting Started with C++, 11 How C++ Stores Text?, 125 Inheritance, 167 Inheritance and Constructors, 170 Inheriting Functionality, 172 Initializing Arrays, 98 Iterators, 201 Linked Lists, 189 Linked Lists using Classes, 191 Local and Global Variables, 89 Logical Operators, 46 Member Initializers, 146 More on Recursion, 159 Multi-Dimensional Arrays, 105 Multilevel Inheritance, 175 Multiple Inheritance, 174 Multiple Throws and Catches, 198 Objects, 121 Operator Overloading, 153 230 Passing a Parameter by Value or by Reference, 76 Passing Arrays to Functions, 102 Passing Structures to Functions, 119 Pointers and Some Special Operators, 150 Pointers Revisited, 149 Polymorphism and Virtual Functions, 177 Practice Questions 1, 13 Practice Questions 2, 22 Practice Questions 3, 32, 49 Practice Questions 5, 61 Practice Questions 6, 80 Practice Questions 7, 93, 162 Practice Questions 8, 106 Pre-defined Functions, 91 Primitive Data Types, 27 Queue Iterator Example, 203 Recursive Functions, 155 Relational and Comparison Operators, 41 Separating Content in Different Files, 143 Sorting Algorithms, 133 Storing Information in the Computer, 15 Stream Objects, 211 Structure Composition, 117 The <string> Class, 128 The break and continue Statements, 60 The for loop, 57 The switch Statement, 44 The First Example, 122 The Nested if-else Statements, 44 The this Keyword, 152 Throwing an Exception in a Function, 199 Vectors, 202 What are Arrays, 97 What are Functions?, 71 What are Pointers?, 111 What are Structures?, 115 What is Computer Science?, 9 What is Programming?, 10 INDEX