PROGRAMMING 621 Study Guide PDF
Document Details

Uploaded by GloriousZombie
Richfield Graduate Institute of Technology
Tags
Summary
This study guide, published by Richfield Graduate Institute of Technology, is for the PROGRAMMING 621 module. It covers C++ basics, object-oriented programming, and file I/O. Focus is also given to control structures.
Full Transcript
STUDENT GUIDE FACULTY OF INFORMATION TECHNOLOGY PROGRAMMING 621 i Registered with the Department of Higher Education as a Private Higher Education Institution under the Higher Education Act, 1997.Registration Certificate No. 2000/HE07/008...
STUDENT GUIDE FACULTY OF INFORMATION TECHNOLOGY PROGRAMMING 621 i Registered with the Department of Higher Education as a Private Higher Education Institution under the Higher Education Act, 1997.Registration Certificate No. 2000/HE07/008 FACULTY OF INFORMATION TECHNOLOGY LEARNER GUIDE MODULE: PROGRAMMING 621 PREPARED ON BEHALF OF RICHFIELD GRADUATE INSTITUTE OF TECHNOLOGY (PTY) LTD RICHFIELD GRADUATE INSTITUTE OF TECHNOLOGY (PTY) LTD Registration Number: 2000/000757/07 All rights reserved; no part of this publication may be reproduced in any form or by any means, including photocopying machines, without the written permission of the Institution. ii Malik, D.S 2018. C++ Programming: Program Design including Data Structures. Eighth Edition. United Kingdom: Cengage Learning Williams, A. 2019 C++ Concurrency in Action PUBLISHER Simon and Schuster, 2019 ISBN 1638356351 3|Page Contents CHAPTER 1 PROGRAMMING LANGUAGES PARADIGM...............................................................9 1.1 INTRODUCTION TO PROGRAMMING LANGUAGE PARADIGMS........................9 1.1.1 Difference Between Imperative and Declarative Programming.................................9 1.2 STRUCTURED PROGRAMMING................................................................................10 1.3 OBJECTED ORIENTED PROGRAMMING.................................................................10 1.4 PROBLEM ANALYSIS-CODING-EXECUTION CYCLE...........................................12 1.5 PROCESSING A C++ PROGRAM.................................................................................17 Review Questions..................................................................................................................20 Chapter 2: INTRODUCTION TO C++............................................................................................21 2.1. INTRODUCTION..........................................................................................................21 2.1.1 BASICS OF A C++ PROGRAM..............................................................................22 2.1.3 Special Symbols & Identifiers..................................................................................25 int, float, double, char, const, void, return.........................................................................27 2.2 DATA TYPES..................................................................................................................28 2.2.1 C++ Data Types........................................................................................................29 2.3 VARIABLE DECLARATION.........................................................................................36 2.3.2. Declaring and Initializing Variables.............................................................................39 Quick Review....................................................................................................................49 Review Question....................................................................................................................50 CHAPTER 3 CONTROL STRUCTURES...............................................................................52 3.1 INTRODUCTION...........................................................................................................52 3.2 SELECTION: if AND if….else.......................................................................................53 3.2.1 Two-Way Selection...................................................................................................54 3.3 Switch Structures.............................................................................................................59 3.4 REPETITION...........................................................................................................64 4|Page 3.4.1 while Looping Structure...........................................................................................65 3.4.2 Counter Controlled while Loops...............................................................................67 3.4.3Sentinel Controlled while Loops...............................................................................71 3. 5 Break and Continue Statements......................................................................................79 3. 6 Nested Control Structures..............................................................................................81 Review Questions..................................................................................................................84 Chapter 4: FUNCTIONS..............................................................................................................87 4.1 INTRODUCTION...........................................................................................................87 4.2 Predefined Functions.......................................................................................................87 4.3 User- Defined Functions..................................................................................................91 4.4 Value-Returning Functions..............................................................................................92 4.5 Function Prototype...........................................................................................................97 4.6 Void Functions.................................................................................................................99 4.6.1 Parameter Types......................................................................................................100 Review Questions................................................................................................................ 112 CHAPTER 5 COMPOUND DATA TYPES...................................................................................... 113 5.1 INTRODUCTION......................................................................................................... 113 5.2 ARRAYS........................................................................................................................124 5.3 Multidimensional ARRAYS..........................................................................................141 5.4 POINTERS....................................................................................................................155 Review Questions................................................................................................................170 TOPIC 6 CLASSES (PART ONE)...................................................................................................172 6.1 INTRODUCTION.........................................................................................................172 6.2 INHERITANCE.............................................................................................................201 6.2 Classes and Pointers.......................................................................................................218 6.2.1 Destructor................................................................................................................219 5|Page Review Questions................................................................................................................229 Chapter 7 :CLASSES (PART TWO)..............................................................................................230 7.1 TEMPLATES.................................................................................................................230 7.1.1 Class Templates......................................................................................................231 7.2 Function Templates........................................................................................................236 7.3 Virtual Functions............................................................................................................238 7.4 Abstract Classes and Pure Virtual Functions.................................................................241 7.5OVERLOADING...........................................................................................................251 7. 5.1 OPERATOR OVERLOADING.............................................................................252 7.5.2 Overloading the Stream Extractoin Operator(>>)..................................................257 Review Questions................................................................................................................264 Chapter 8: ADVANCED CONCEPTS.................................................................................266 8.1 FILE INPUT/OUTPUT.................................................................................................266 8.2 EXCEPTION HANDLING....................................................................................272 8.3 Quick Review................................................................................................................282 6|Page The Information Technology (IT) qualification at Richfield College is a dynamic and future- focused program designed to equip students with advanced technical, analytical, and problem-solving skills. At the core of the qualification is a commitment to academic excellence, industry alignment, and innovation, fostering graduates who are proficient in addressing modern technological challenges. This qualification strategically integrates theoretical knowledge with practical applications, preparing students for various roles in the IT sector. The IT program is structured to address the growing complexity of the evolving technological landscape. The Higher certificate in Information Technology (HCIT) program is a foundational stepping-stone for students who wish to pursue further studies or enter the workforce. Graduates of this program are well-prepared to articulate to the Diploma in IT (DIT) or the Bachelor of Science in IT (BSc IT) qualifications, providing a seamless transition for those seeking to deepen their knowledge and skills in specialized IT areas. Additionally, the program equips students with the essential competencies for entry-level IT roles such as IT Support Technicians, Junior Web/ System Developers, IT Administrators, etc. The Diploma in Information Technology (DIT) is a comprehensive and practical program designed to build a strong foundation in IT principles while equipping students with the hands-on skills required to meet industry demands. Focused on both theoretical knowledge and applied learning, this qualification prepares students for intermediate-level roles in IT and serves as a stepping-stone for further academic progression or specialization. Graduates of this program are well-prepared to articulate to the Bachelor of Science in IT (BSc IT) qualification. The curriculum covers programming, networking, database management, system analysis etc., ensuring graduates possess the competencies to solve real-world IT challenges effectively. The Bachelor of Science in IT (BSc IT) program is structured to address the growing complexity of the evolving technological landscape. Through carefully curated modules, students gain a deep understanding of software development, database management, 7|Page cloud computing, cybersecurity, IT management, artificial intelligence, machine learning, networking etc. Graduates of this program are well-prepared to articulate to the Bachelor of Science Honours in IT qualification. The curriculum is designed to bridge the gap between academic learning and real-world applications, thus fostering innovation and an entrepreneurial mindset. Students are encouraged to participate in research and practical learning. The programming focus within the IT qualification exemplifies academic innovation and professional alignment. By integrating a diverse range of programming languages with practical application, the curriculum prepares students to excel in the rapidly evolving tech industry. The program aligns with industry courses from globally recognized leading tech giants, such as Oracle, AWS, IBM, etc ensures that graduates possess the credentials to validate their expertise in software development and cloud-based technologies. This blend of foundational knowledge, practical experience, and industry-standard courses prepares students for immediate employment and establishes a strong basis for long-term career advancement in software development. Programming 621 introduces students to the foundational concepts of C++ programming, equipping them with the skills to design and implement efficient and structured code. This module covers key topics such as variables, operators, control structures, and functions, providing students with a strong understanding of procedural programming. Additionally, the module delves into arrays, pointers, and the basics of object-oriented programming (OOP), including classes and objects, enabling students to design modular and reusable code. The module concludes with file handling, teaching students how to read from and write to files, an essential skill for managing data in software applications. Through hands- on exercises and practical projects, students gain a comprehensive understanding of C++ as a versatile programming language. 8|Page CHAPTER 1 PROGRAMMING LANGUAGES PARADIGM LEARNING OUTCOMES: After studying this topic, you should be able to: Understand the importance of programming language paradigms Become aware of structured-design and object-oriented design programming methodologies Learn what an algorithm is and explore problem-solving techniques Discover what a compiler is and what it does Examine a C++ program Explore how a C++ program is processed 1.1 INTRODUCTION TO PROGRAMMING LANGUAGE PARADIGMS Paradigm can be termed as method to solve some problem or do a specified task. Programming paradigm is an approach to solve problem using some programming language or also it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots of programming language that are known but all of them need to follow some strategy when they are implemented, and this methodology/strategy is paradigms. Two popular approaches to programming design are the structured approach and the object-oriented approach, which are outlined below. 1.1.1 Difference Between Imperative and Declarative Programming Imperative Programming as the name suggests is a type of programming that describes how the program executes. It comprises with how to get an answer step by step. Comprises the sequence of command imperatives. In this, the order of execution is very important and uses both mutable and immutable data. 9|Page Fortran, C, C++ programming languages are examples Declarative Programming is a type of programming paradigm that describes what programs to be executed. It declares what kind of results we want and leave programming language aside focusing on simply figuring out how to produce them. Mainly focuses on the end result. It expresses the logic of computation. Miranda, Erlang, Prolog are examples. 1.2 STRUCTURED PROGRAMMING Dividing a problem into smaller sub problems is called structured design. Each sub problem is then analysed, and a solution is obtained to solve the sub problem. The solutions to all of the sub problems are then combined to solve the overall problem. This process of implementing a structured design is called structured programming. The structured-design approach is also known as top-down design, bottom-up design, stepwise refinement, and modular programming. 1.3 OBJECTED ORIENTED PROGRAMMING Object-oriented design (OOD) is a widely used programming methodology. In OOD, the first step in the problem-solving process is to identify the components called objects, which form the basis of the solution, and to determine how these objects interact with one another. For example, suppose you want to write a program that automates the DVD rental process for a local DVD store. The two main objects in this problem are the DVD and the customer. After identifying the objects, the next step is to specify for each object the relevant data and possible operations to be performed on that data. For example, for a DVD object, the data might include: o movie name o year released 10 | P a g e o producer o production company o number of copies in stock Some of the operations on a DVD object might include: o checking the name of the movie o reducing the number of copies in stock by one after a copy is rented o incrementing the number of copies in stock by one after a customer returns a particular DVD of length. This illustrates that each object consists of data and operations on that data. An object combines data and operations on the data into a single unit. In OOD, the final program is a collection of interacting objects. A programming language that implements OOD is called an object-oriented programming (OOP) language. To work with objects, you need to know how to combine data and operations on the data into a single unit. In C11, the mechanism that allows you to combine data and operations on the data into a single unit is called a class. Finally, or some problems, the structured approach to program design will be very effective. Other problems will be better addressed by OOD. For example, if a problem requires manipulating sets of numbers with mathematical functions, you might use the structured- design approach and outline the steps required to obtain the solution. The C11 library supplies a wealth of functions that you can use effectively to manipulate numbers. On the other hand, if you want to write a program that would make a juice machine operational, the OOD approach is more effective. C11 was designed specially to implement OOD. Furthermore, OOD works well with structured design. Both the structured-design and OOD approaches require that you master the basic components of a programming language to be an effective programmer. 11 | P a g e 1.4 PROBLEM ANALYSIS-CODING-EXECUTION CYCLE Programming is a process of problem solving. Different people use different techniques to solve problems. Some techniques are nicely outlined and easy to follow. They not only solve the problem, but also give insight into how the solution is reached. These problem-solving techniques can be easily modified if the domain of the problem changes. To be a good problem solver and a good programmer, you must follow good problem solving techniques. One common problem-solving technique includes analysing a problem, outlining the problem requirements, and designing steps, called an algorithm, to solve the problem. Algorithm: A step-by-step problem-solving process in which a solution is arrived at in a finite amount of time. In a programming environment, the problem-solving process requires the following three steps: 1. Analyse and outline the problem and its solution requirements, and design an algorithm to solve the problem. 2. Implement the algorithm in a programming language, such as C11, and verify that the algorithm works. 3. Maintain the program by using and modifying it if the problem domain changes. Figure 1-1 summarizes the first two steps of this programming process. 12 | P a g e FIGURE 1-1 Problem analysis-coding-execution cycle To develop a program to solve a problem, you start by analyzing the problem. You then design the algorithm; write the program instructions in a high-level language, or code the program; and enter the program into a computer system. Analyzing the problem is the first and most important step. This step requires you to do the following: 1. Thoroughly understand the problem. Understand the problem requirements. Requirements can include whether the program requires interaction with the user, whether it manipulates data, whether it produces output, and what the output looks like. If the program manipulates data, the programmer must know what the data is and how it is represented. That is, you need to 13 | P a g e look at sample data. If the program produces output, you should know how the results should be generated and formatted. 2. If the problem is complex, divide the problem into subproblems and repeat Steps 1 and 2. That is, for complex problems, you need to analyze each subproblem and understand each sub problem’s requirements. After you carefully analyze the problem, the next step is to design an algorithm to solve the problem. If you break the problem into subproblems, you need to design an algorithm for each subproblem. Once you design an algorithm, you need to check it for correctness. You can sometimes test an algorithm’s correctness by using sample data. At other times, you might need to perform some mathematical analysis to test the algorithm’s correctness. Once you have designed the algorithm and verified its correctness, the next step is to convert it into an equivalent programming code. You then use a text editor to enter the programming code or the program into a computer. Next, you must make sure that the program follows the language’s syntax. To verify the correctness of the syntax, you run the code through a compiler. If the compiler generates error messages, you must identify the errors in the code, remove them, and then run the code through the compiler again. When all the syntax errors are removed, the compiler generates the equivalent machine code, the linker links the machine code with the system’s resources, and the loader places the program into main memory so that it can be executed. The final step is to execute the program. The compiler guarantees only that the program follows the language’s syntax. It does not guarantee that the program will run correctly. During execution, the program might terminate abnormally due to logical errors, such as division by zero. 14 | P a g e Even if the program terminates normally, it may still generate erroneous results. Under these circumstances, you may have to re-examine the code, the algorithm, or even the problem analysis Example 1.1 In this example, we design an algorithm to find the perimeter and area of a rectangle. To find the perimeter and area of a rectangle, you need to know the rectangle’s length and width. The perimeter and area of the rectangle are then given by the following formulas: perimeter = 2 · (length + width) area = length · width The algorithm to find the perimeter and area of the rectangle is as follows: 1. Get the length of the rectangle. 2. Get the width of the rectangle. 3. Find the perimeter using the following equation: perimeter = 2 · (length + width) 4. Find the area using the following equation: area = length · width Example 1.2 In this example, we design an algorithm that calculates the sales tax and the price of an item sold in a particular state. The sales tax is calculated as follows: The state’s portion of the sales tax is 4%, and the city’s portion of the sales tax is 1.5%. If the item is a luxury item, such as a car more than $50,000, then there is a 10% luxury tax. To calculate the price of the item, we need to calculate the state’s portion of the sales tax, the city’s portion of the sales tax, and, if it is a luxury item, the luxury tax. Suppose salePrice denotes the selling price of the item, stateSalesTax denotes the state’s sales tax, citySalesTax denotes the city’s sales tax, luxuryTax denotes the luxury tax, salesTax denotes the total sales tax, and amountDue denotes the final price of the item. To calculate the sales tax, we must know the selling price of the item and whether the item is a luxury item. 15 | P a g e The stateSalesTax and citySalesTax can be calculated using the following formulas: stateSalesTax = salePrice · 0.04 citySalesTax = salePrice · 0.015 Next, you can determine luxuryTax as follows: if (item is a luxury item) luxuryTax = salePrice · 0.1 otherwise luxuryTax =0 Next, you can determine salesTax as follows: salesTax = stateSalesTax + citySalesTax + luxuryTax The algorithm to determine salesTax and amountDue is, therefore: 1. Get the selling price of the item. 2. Determine whether the item is a luxury item. 3. Find the state’s portion of the sales tax using the formula: stateSalesTax = salePrice · 0.04 4. Find the city’s portion of the sales tax using the formula: citySalesTax = salePrice · 0.015 5. Find the luxury tax using the following formula: if (item is a luxury item) luxuryTax = salePrice · 0.1 otherwise luxuryTax = 0 6. Find salesTax using the formula: salesTax = stateSalesTax + citySalesTax + luxuryTax 7. Find amountDue using the formula: amountDue = salePrice + salesTax 16 | P a g e 1.5 PROCESSING A C++ PROGRAM To execute on a computer, these C++ instructions first need to be translated into machine language. A program called a compiler translates instructions written in highlevel languages into machine code. Compiler: A program that translates instructions written in a high-level language into the equivalent machine language. Consider the following C++ program: #include using namespace std; int main() { cout