1. Trang chủ
  2. » Tất cả

LetMeRead.net__Cambridge.University.Press.Computer.Programming.with.Cplusplus.1316506800

1K 0 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.018
Dung lượng 48,43 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The language in which a computer program is written is called a computer programming language.. The instruction to perform addition of two numbers could be written in the machine languag

Trang 3

This textbook provides in-depth explanation of C and C++ programming languages along with the fundamentals of object oriented programming paradigm Essential concepts including functions, arrays, pointers and inheritance are explained in a coherent manner The book follows an example-driven approach, to facilitate easy comprehension of theoretical concepts Common concepts of C programming language are also elaborated wherever necessary The text provides detailed explanation on complex topics including Dynamic Memory Allocation, Object Slicing, VTABLEs, Up Casting and Down Casting The concepts are explained using line diagrams, notes, conversation themes and flow charts The book offers useful features including error finding exercises, quiz questions and points to remember Necessary comments to explain the logic used to implement particular functionality are provided for the ease of readers Plenty of computer programs, review questions and useful case studies are interspersed throughout the text.

The book is intended for undergraduate and graduate students of engineering and computer science

Kunal Pimparkhede is an adjunct faculty at the Vidyalankar Institute of Technology, Mumbai As a software professional, he has development experience in technologies such as Adobe Flex, Informatica; database systems like Oracle, Sybase; Java based frameworks like Spring, Struts, etc His areas of interest include Microprocessors, Automata Theory, Data Structures, Analysis of Algorithms, Artificial Intelligence and Computer Programming

Trang 5

Computer Programming with C++

Kunal Pimparkhede

Trang 6

477 Williamstown Road, Port Melbourne, vic 3207, Australia

4843/24, 2nd Floor, Ansari Road, Daryaganj, Delhi – 110002, India

79 Anson Road, #06–04/06, Singapore 079906

Cambridge University Press is part of the University of Cambridge.

It furthers the University’s mission by disseminating knowledge in the pursuit of education, learning and research at the highest international levels of excellence.

www.cambridge.org

Information on this title: www.cambridge.org/9781316506806

© Cambridge University Press 2017

This publication is in copyright Subject to statutory exception

and to the provisions of relevant collective licensing agreements,

no reproduction of any part may take place without the written

permission of Cambridge University Press.

First published 2017

Printed in India

A catalogue record for this publication is available from the British Library

Library of Congress Cataloging-in-Publication Data

Names: Pimparkhede, Kunal, author.

Title: Computer programming with C++ / Kunal Pimparkhede.

Description: New York : Cambridge University Press, 2016 | Includes index.

Identifiers: LCCN 2015051227 | ISBN 9781316506806 (paperback)

Subjects: LCSH: C++ (Computer program language) | C (Computer program

language) | Object-oriented programming (Computer science) | Computer

programming | BISAC: COMPUTERS / Programming Languages / General.

Classification: LCC QA76.73.C153 P469 2016 | DDC 005.13/3 dc23 LC record available at http://lccn.loc.gov/2015051227

ISBN 978-1-31-650680-6 Paperback

Additional resources for this publication at www.cambridge.org/9781316506806

Cambridge University Press has no responsibility for the persistence or accuracy

of URLs for external or third-party internet websites referred to in this publication, and does not guarantee that any content on such websites is, or will remain,

accurate or appropriate.

Trang 7

2.9 Accepting User Input Using scanf() Function (Supported by both

2.12 Defining Constants using #define—A Pre-processor Directive 65

Trang 8

3.4 Shorthand Operators 84

5.8 Creating Variables Local to Loops (Possible in C++ but not in C) 192

Trang 9

7.6 Passing Array as an Argument to the Function 325

Trang 10

PART-II Object Oriented Programming

11.10 Addition of Points in Cartesian Coordinate System: An Example 567

11.24 Defining the Member Functions Outside Class using Scope Resolution

Trang 11

13 Operator Overloading 699

13.3 Overloading One’s Complement ~ and Minus - Operators: An Example 703

13.14 Overloading Insertion and Extraction Operator for Student Objects:

Trang 12

15.3 Console Input and Output in C++ 883

15.5 Formatting the Output using Member Functions of Class ios 885

16.4 Standard Template Library: One of the Applications of Class Templates 937

Trang 13

A computer program is a set of instructions which is followed by a machine to generate the required output The language in which a computer program is written is called a computer programming language Several computer programming languages are in use

in the IT industry today, for developing diverse software applications

The study of C and C++ is considered an important step towards mastering computer programming fundamentals Hence, C and C++ are included in the syllabus of any computer science course

This textbook provides in-depth explanations of C and C++ programming languages along with the fundamentals of the object oriented programming paradigm

About the Book

This book will be of use to anyone who is a beginner and aspires to learn the fundamentals

of computer programming using C and C++ It has been primarily written for students of academic courses which include the study of C, C++ and object oriented programming paradigm Simple and lucid language has been used to facilitate easy comprehension of complex topics

Salient Features

• Example-driven approach illustrates application of theoretical concepts

• Theme of a conversation interspersed in the text, elucidate essential themes of the subject

• Each program includes necessary comments to explain the logic used to implement a particular functionality

• Several line diagrams and flow charts facilitate easy comprehension of theoretical concepts

• Student-friendly pedagogical features include:

9 Error Finding Exercise

9 Solved Problems

Trang 14

discuss the basic features of C/C++ including data types, variables and different control

statements which are supported by the language Chapter 6 describes the creation

of multivalued data types (also referred to as collection types) using arrays in C/C++

Chapter 7 explains modular programming using functions Chapter 8 elucidates the fundamentals of memory management using pointers in C/C++ Chapter 9 discusses

the creation of composite data types using structures and unions in C/C++ Chapter 10 explains the principles of memory management and Dynamic memory allocations in C++

style Chapters 11 to 17 provide in-depth coverage of object oriented features supported

by C++

Notes

Chapters 1 to 9 cover features which are common to C as well as C++ Hence programs written in these chapters will work with C as well as C++ compilers unless specified otherwise Whereas Chapters 11 to 17 cover object oriented features which are supported only by C++ and not by C Chapter 10 explains dynamic memory allocation in C++ style Hence programs written from Chapter 10 to 17 will work with C++ compilers only.

Chapter 1 gives an understanding of computer organization, operating system and other system programs which make up the underlying platform required to execute any C/C++ program Chapter 1 also gives an overview of many areas which are relevant for understanding computer programming fundamentals using C/C++ The specific features of individual topics have been explained

in detail in the later chapters of this book.

Trang 15

Contribution and support of many people in my life has made this book possible I am indebted to Vishwas Deshpande, Chairman, Vidyalankar Institute of Technology for giving me a wonderful platform to showcase my learnings I am grateful to Professor N H Dubey for his constructive feedback, which added significant value to this project I owe special thanks to my dear dearer dearest daughter Swara for allowing me to work long hours while I was writing this book

I am thankful to Professors V S Padmakumar, Sanjeev Dwivedi, Sachin Bhojewar, Pankaj Vanwari from Vidyalankar Institute of Technology; Professors Kalpana Sagvekar, Sunil Surve and Brijmohan Daga from Fr Conceacao Rodrigues College of Engineering, Mumbai; Professor Asawari Dudwadkar, Vivekanand Institute of Technology, Mumbai; Professors Prasad Kulkarni, Vinayak Shinde, Leena Thakur, Surbhi Crasto and Ajit Parab from Babasaheb Gawde Institute of Technology, Mumbai; Professor Yogesh Prabhu,

Dr A. K Pathak, Professor Sameer Velankar and Professor Yogesh Rajadhyaksha for their excellent support at different stages which helped me to present my learnings so well in the form of this book

I am thankful to Ruhi Bajaj, Thadomal Shahani Engineering College, Mumbai and Shweta Loonkar, D J Sanghavi College of Engineering, Mumbai for their valuable suggestions which helped mould this script to meet the needs of a wide range of audience

I sincerely acknowledge the contribution of all my teachers, who have played a vital role in developing my understanding of the subject and broadening my perspectives They have strongly influenced me in building a positive attitude towards creative learning

I would also like to thank every member of the team at Cambridge University Press, including Rachna Sehgal, who supported me throughout the publishing process to actuate timely release of this book

I express heartfelt gratitude to my family for their moral support and patience I am thankful to Pradeep Pimparkhede, Shalaka Pimparkhede, Dipti Pimparkhede, Swara Pimparkhede, Prabhavati Pimparkhede, Nivedita Bakre, Rajgopal Pai and Jayanti Pai for their patience while I was writing this script

Trang 17

PART-I

Structured Programming

Trang 19

1.1 Overview

A program is a set of instructions, which are followed by the machine so as to generate a desired

output This means that writing a computer program is giving instructions to a processor, so

as to delegate a particular job to the hardware of the computer system Every instruction is

a command given to the computer hardware to perform a specific job Computer hardware

is a digital system (collection of functional switches) and hence every instruction must be converted into the form of 0’s and 1’s (where a symbol 0 represents open switch and a symbol 1 represents closed switch) As an example, let us assume that we want the computer system to perform the addition of two numbers say 15 and 25 The instruction to perform addition of two numbers could be written in the machine language as shown below:

10000011 00001111 00011001

In this case, the first eight bits represent the code informing the hardware that the

addition of the two numbers is to be performed This is called as an opcode (operational

code) of the instruction Different instructions would have different opcodes and their purpose is to convey the meaning of the instruction to the internal hardware circuitry

In this case, we have assumed an arbitrary opcode of ADD instruction as 10000011 Different processors have different decoders and internal designs, hence the length and format of the opcode will certainly differ from processor to processor Some processors have eight bit opcodes (e.g., intel 8085), some have 16 bit opcodes (e.g., intel 8086) Today’s generation processors have 32 bit/64 bit opcodes or even 128 bit opcodes We need not look into the hardware configurations and designs at this stage, but the key point to understand is that every instruction has an opcode and in this case, we just assume an arbitrary opcode of 8 bits as 10000011, which represents ADD operation

A different combination of 8 bits, say 11001010, may represent subtraction and so on

In theory, the variety of instructions any processor can offer is indirectly dependent on the length of its opcode A processor with an opcode length of 8 bits can just offer 28 =

256 distinct instructions whereas a processor with an opcode length of 16 bits can offer

216 = 65536 distinct instructions We cannot just increase the length of opcode arbitrarily, the internal hardware and the instruction decoders must support it too A processor that has a rich-instruction set certainly has highly effective internal circuitry and decoders to support it In today’s generation, we are working with processors having 32 bit opcodes

1

Trang 20

or 64 bit opcodes giving us rich- and high-performing instruction set, and this facilitates the execution of even complex programs in an optimized way The next bits are the binary translations of the data values 15 and 25 over which addition is to be performed The sample format of the ADD instruction is shown in Figure 1.1 We need not go too much

in detail about computer hardware, however, the rationale of this discussion was just to make us clear that every processor has a digital circuitry, which only understands the

language of 0’s and 1’s This language is called as machine language.

Sample format of ADD instruction

Byte 1

Opcode of ADD instruction Byte 2Binary representation of 15 Byte 3Binary representation of 25

Figure 1.1: Representation of instruction in a machine language

Writing every instruction using machine language could be very complex when there are

a large number of operations to be performed in the program as it requires us not only to work with 0’s and 1’s but also to understand hardware specifications of the processor In today’s generation, computer programs are written to design many complex applications having business challenges in itself, hence, it is practically impossible for a human being to write such programs in machine language

To make the programmers life easy, an assembly language is designed, which codes

every instruction using a mnemonic For example, an instruction to perform the addition of

15 and 25 could be written in the assembly language as

ADD 15, 25The symbol ADD is called as a mnemonic, which represents addition, whereas the constants

15 and 25 represent the data (also called as operands) over which the ‘add’ operation

is to be performed It is important to note that mnemonics are English symbols and hence they cannot be directly understood by the machine Therefore, there is a need for

a translator, which can translate the assembly language into a language of 0’s and 1’s This will ensure that the hardware of the computer system can understand the meaning

of the instruction, which is actually written in the assembly language by the programmer The unit that performs the translation of assembly language into the machine language is

called as an assembler Therefore, the instruction ADD 15, 25 will be first translated by the

assembler into the machine language as shown in Figure 1.2 After the translation process

is completed, the hardware of the computer system can execute the instruction, which will actually perform the addition of constants 15 and 25

The assembly language program can still be tedious to create if the program has a large number of operations to be performed So as to make the programmer’s life simple,

the high-level programming languages are designed A high-level programming language

is an ‘English-like’ programming language wherein the programmer can make use of user

Trang 21

friendly words and symbols to code an instruction For example, we can write the following high-level instruction so as to perform the addition of two numbers:

Z = 15 + 25Note that we have directly used a user friendly symbol + instead of coding the instruction

in a machine language or an assembly language Hence, the value of Z will be evaluated

as 40, which is the addition of 15 and 25 High-level language is a set of ‘English-like’ symbols and hence these symbols cannot be directly decoded by the hardware of the system Therefore, the high-level language is first converted into an assembly language

by a unit called as ‘compiler’ The assembly code can then be further converted into the machine code using the ‘assembler as shown in Figure 1.3 It is important to reinforce on a point that the processor can execute a particular instruction only after it is translated into the machine language

Assembler 10000011 00001111 00011001

Assembly language

Compiler generates an assembly language as its output.

This language is given as an input to the assembler which generates machine code.

Figure 1.3: Translation of high level language to machine code

As the instructions in high-level programming languages are very user friendly and easy to code, they facilitate the creation of complex programs in a much more readable and maintainable then assembly or machine level languages Hence, the programs written in high-level languages are easy to create, edit, debug and maintain There are several high-level programming languages, which are currently being used in the software industries for creating different applications Some of the high-level programming languages include

C, C++, Java, Visual basic, FORTRAN, COBOL, etc In this text book, we discuss computer

programming using ‘C and C++’.

C programming language is designed by Dennis Ritche in 1973 and C++ is designed by Bjarne Stroustrup in 1980 as an extension of C Both C and C++ are designed in AT&T Bell

Laboratories C++ is an extension of the ‘C’ language, which means that all the features supported by ‘C’ are also supported by C++ Furthermore, C++ adds many useful features such as object orientation and template management, which are not supported by ‘C’

10000011 00001111 00011001

Figure 1.2: Assembler

Trang 22

Processor (CPU) is an integrated circuit that responds to a specific set of instructions Instruction set for any processor is packaged along with its release and can be understood referring to hardware manuals of the processor The instruction set of any processor is very much coupled and dependent on its internal circuitry Every CPU has an instruction decoder which decodes the input instruction and passes it to the relevant architectural blocks for activating necessary hardware components to generate required results Since an instruction needs to be ultimately decoded and

executed by hardware, it must have a representation in binary form (in the form of zeroes and one’s) This language of zeroes and one’s which is directly executed by the processor is called as machine language or Binary language.

It is technically impossible for Human beings to communicate with processor directly using machine language Hence any release of processor is also packaged with the mnemonics to each of the instructions

it supports These mnemonics are readable by human beings and is called as the assembly language of

a particular processor Remember, since the mnemonics are English like symbols, they cannot be passed directly to the hardware It is the responsibility of system programmers to design an assembler which can convert assembly language into machine language Assembler is a software utility and it is packaged along the system programs required to compile and execute any High Level language.

In practice, both Assembly and machine languages are categorized as Low Level Languages from

Application programmers perspective.

What is the difference between Assembly Language and Machine Language? ?

Notes

We have been saying that assembly and machine languages are very complex and it is practically impossible for a

programmer to use these languages for application programming Whilst this statement is very true, the portability of

programs is another big problem in these languages This is because assembly and machine languages are specific

to a particular processor For example, the assembly/machine language of an intel processor is very different from that of an AMD processor Hence, even if we manage to write a program in assembly/machine language, our program may only be specific to our own platform and it cannot work if the hardware of the system is changed It is absolutely not a good practice to design programs, which are very much dependent on hardware, because computer hardware

ROADMAP OF THE BOOK

This text book is divided into two parts

Part 1: Chapters 1 to 9 are the topics, which are common with C and C++ The programs given in these chapters will work with both C as well as C++ compilers unless specified otherwise Chapter 10 gives an explanation on dynamic memory allocation in C++ style This feature is also supported by C but this book explains C++ notations Part 2: Chapters 11 to 17 explain additional features, which are only supported by C++ and not by C These are object-oriented features, which are not supported by C, hence the programs given in Chapters 11 to 17 will only work with C++ compiler.

It is impossible for a reader to understand the features of object orientation without having a thorough knowledge

of structured programming, hence we should be extra careful when reading Chapters 1 to 10 as they become the prerequisite for Chapters 11 to 17.

Trang 23

often gets upgraded with technology improvements It should not happen that the program runs well on current system and fails after processor or hardware/operating system is upgraded or changed C/C++ programs do not have a direct dependency on platform (hardware/operating system), once designed they could run on different platforms without major changes We have used the phrase ‘without major changes’ because C/C++ is not fully platform independent, there are changes that programmer has to make the program while migrating the program

from one platform to another Note that C/C++ programs are just platform dependent and not hardware dependent;

intermediate system programs such as operating system, compilers, loaders, and linkers make a cohesive architecture

so that C/C++ programs can run on any hardware with almost no change in the code as shown in Figure 1.4 Because

of the additional layer introduced by operating system, loaders, compilers, linkers (in general called as a layer of

system programs), we can be sure of the fact that the C/C++ programs we create can run without any changes

when just hardware of the system is changed or upgraded This layered architecture gives hardware independence to

application programs Now the next question is, What if there are any changes in the system program? For example,

what if we decide to change our operating system from windows to Linux? This is called as a change in platform and

in this case, we are not sure that a C/C++ program which runs on a windows platform will also run on Linux This is because the C/C++ compiler for windows is different than that of Linux So, in practice, we will also have to change the compiler if we change the platform Clearly, C/C++ languages have removed the hardware dependency on the programs but not the platform dependency and this is because compiler is different for different platforms Whilst platform dependency remains one of the challenges with C/C++ programs, it is also a settled situation in software industries that platforms are not changed very often Hence, C/C++ languages are still used at an extensive scale in the world of application development In this discussion, we have mentioned names of some system programs such

as loaders and linkers and we will debrief about them in section 1.3, for now just understand that these are some of the system programs which help to keep our code independent of the underlying hardware.

Application Programs

These are the programs written using high

level languages to deliver a specific business

requirement High level programming languages

like C and C++ are extensively used to design

application programs.

These applications designed by programmers are used

by business users who may not have any technical expertise

Few examples of Application programs are program for online

shopping used to design an online shopping website,

a banking program used to perform banking transactions online,

online railway reservation system used over the web, web site

for booking movie tickets etc Application programs need not be

always web based, they can also be Desktop applications

like Microsoft paint, Microsoft office, desktop games etc All these

applications are designed in some high level programming languages

like C/C++ A web based program is a program which can be

accessed over intemet without a need of any prior installation

whereas a desktop application is always accessed locally and

needs to be installed on the machine before it can be used All

applications designed in this book are desktop based applications.

System Programs

These are utility programs which are necessary to develop and execute application programs For example, operating system, compiler, assembler, loader, linker, etc.

Some of programs are tightly coupled with the hardware of the system and hence you must have knowledge about system hardware and configuration before you could design such programs

The scope of this text book is to learn application programming using C/C++ Design of system programs is out of scope of this text book, we may mention about them as and when needed to understand certain application programming concepts though

Compiler Assembler Linker Loader

Trang 24

1.2 Computer System Architecture

Before deep diving into the intricacies of C/C++ programming, we need to first understand the general flow of data and instruction in a computer system Figure 1.5 shows the basic building blocks of a system, which consist of the following units:

Secondary memory

Figure 1.5: Block diagram of a computer system

1 Input unit

2 Processing unit

3 Output unit

4 Storage unit

1.2.1 Input to the system

‘Data’ and ‘instructions’ are given as input to the system so as to perform a particular operation Here, the term ‘instruction’ represents the operation to be performed, whereas the term ‘data’ represents the information over which an operation is to be performed For

example, if we want the system to perform the addition of two numbers say x and y then

we could write a statement as shown below:

x + y

The symbol + in this case, will be translated into an instruction ADD which will inform the

underlying hardware to actually perform the addition of two numbers The numbers x and y represent the ‘data’ over which the instruction ADD operates to generate the required

output We can give multiple instructions as input to the system, so as to get a consolidated

Trang 25

result Let us consider that we want the computer system to give us a result of sequence

of instructions say I1,I2,…, In which operate on a series of data values d1,d2,…,dn, respectively as shown in Figure 1.6 These instructions can be stored in the file and can further be processed by the CPU thereby giving the required result as an output

I1,I2,…, In are instructions

stored in the file The instructions

I1 to In operate over the

data items d1 to dn, respectively.

Figure 1.6: Computer program

The sequence of instructions that the system can process so as to generate the required

output is called as program and the language in which a program can be written is called as

a computer programming language Although, we can write multiple instructions in a single

file, the CPU can only process one instruction at a time Hence, in reality, the processor runs just one instruction at a time in a sequence from first to last until all the instructions present

in the file are fully executed

This process of executing instructions in a file one by one is called as sequential execution.

1.2.2 Translation

As the hardware of a computer system is ultimately built up of electronic and semiconductor devices, it can only understand a binary language of 0’s and 1’s However, it is impossible for us to write programs in machine language as this will involve a detailed study on the circuitry over which the system is built upon In addition, as the fabrication of the machine changes, every machine will have a different machine language This is because every machine is built up using different hardware technologies and circuitry In summary,

we do not understand machine language and machine does not understand the language

we speak This means that there is a need of a translator that can translate the ‘human language’ into the ‘machine language’ The language that we can understand is called as high-level language whereas the language that only machines understand is called as a low-level language

The set of programs that perform a translation of high-level language into a low-level

language are called as system programs The system programs take the high-level code

(also called as source code) as input and generate an equivalent machine code at the output, as shown in Figure 1.7 The language compilers, assemblers, loader, linkers, etc are examples of system programs, which are involved in translation of source code to machine code

Trang 26

So as to ensure that the system programs correctly perform a translation from a source code to a machine code, we must follow certain rules while creating a program in the

high-level language These rules are also called as ‘syntax’ of that language Hence, every programming language has a syntax, which describes the set of rules and we must follow while writing a program Furthermore, every programming language will have a dedicated

‘compiler’, which converts the high-level language into a low-level language1 The compiler also checks if the programmer has preserved the syntax of the language while creating a program before it starts the translation process The compiler will throw an ‘error’ message

to the programmer if any of the syntax rules are violated, and the translation process is immediately terminated if at least one error is located in the input program Hence, it becomes easy for the programmer to apply necessary corrections to the code and restart the compilation process after necessary fixes have been applied

1.2.3 Processing unit

After the high-level language is translated into a language of 0’s and 1’s, the machine starts running each instruction one by one, so as to generate required output The processing stage

is called as ‘execution stage’ of the program Of course, the output of the code will be generated

at the time when the code is under execution and not at the time when the code is getting translated or compiled The process of translation or compilation just converts the program from one language to another while the process of execution actually runs the program thereby generating the results on output device It is ultimately the hardware that performs the execution of the program The hardware that executes the instructions written in the

program one by one is called as ‘processing unit’ of the computer system The processing unit

consists of two major blocks in it:

1 Arithmetic and logical unit (ALU)

2 Control unit

The ALU performs all the arithmetic and logical operations on the input data whereas the control unit is a circuitry that manages and controls the overall flow of data and instructions within the computer system The control unit also consists of a set of decoders that can

1 The output of compilation process is called as a target code The target code differs from language

to language as every language has its own compiler The output of C/C++ compiler is called as object code which is a low level language.

Figure 1.7: Translation of high level language to low level language

Trang 27

understand the input instruction; it also passes the data to the ALU if the execution of the instruction requires any arithmetic or logical operation to be performed The unit is responsible for reading the data and instructions from the ‘input’ devices, processing the instructions and sending the final results to the ‘output’ device so as to generate the output

1 Primary memory (e.g RAM)

2 Secondary memory (e.g hard disk)

Hard disk or a secondary memory is generally a magnetic memory that stores the information persistently The primary memory or RAM is a semiconductor memory that can store the information only for the time when the computer is powered ON This means that RAM cannot store any information when the system is switched off and hence RAM

is a ‘volatile memory whereas a hard disk can store the information persistently even if the power is lost, therefore, hard disk as a ‘non-volatile’ memory

Processor can directly access the data and information only if it is available in RAM, this is because CPU is also a semiconductor device, which is a very large-scale integrated circuitry (often abbreviated as VLSI) Hence, it is the duty of the MMU (unit part of operating system) to get the necessary data and information from hard disk to RAM when needed for CPU to access it, as shown in Figure 1.8 The transfer of information content from secondary memory to primary memory is also controlled by the MMU The key point

to note is that any program can be executed by the CPU if only the code and data referred

by the program are brought into RAM

When we ‘open’ any file for read or write operation, the file is actually copied from the hard disk to RAM by the operating system This facilitates the CPU to directly access the data and instructions stored in the file Once the MMU brings the file into the primary memory, CPU can then perform read /write operations on the file as shown in Figure 1.9 Therefore, once the file is opened, there are two copies of the file maintained in the system The first copy of the file is in RAM whereas the second copy of the file is the original file present in the hard disk as shown in Figure 1.9

When CPU writes any information only the file in RAM will be modified whereas the copy of the file in the hard disk will still represent an older version as shown in Figure 1.10 Hence, this is a state where the data in RAM is modified; however, the file in hard disk

is stale Such a write operation to a file is called as ‘uncommitted’ (or ‘unsaved’) write operation, which is performed by the CPU as shown in Figure 1.10

Trang 28

Primary memory

(e.g., RAM) is a

semiconductor memory which is organized as set

of locations The primary

memory can be directly accessed by the CPU

Primary Memory

.

Secondary Memory

Data files

Secondary memory (e.g., Hard Disk) is

a magnetic memory which is organized

as set of platters Hard disk stores the

data in the form of files

Figure 1.8: CPU accessing RAM

Primary Memory

Secondary Memory

File to be opened

Processor

Operating system

Step 2:

CPU access the copy

of the file from RAM

Step 1:

Operating system copies the file from secondary memory to primary memory

Figure 1.9: CPU accessing the file

Operating system

Trang 29

When we save the file using ‘save’ command (a command of operating system) operating system copies the file from RAM back to the hard disk This ensures that the file in hard disk gets modified with the recent data as shown in Figure 1.11 Therefore, when we open the file next time, new changes will be reflected in the file However, if we do not ‘save’ the file, which was modified by the CPU in the RAM space then any changes made to the file in RAM will not be copied to the hard disk and hence the file in the hard disk will not be modified Therefore, when we ‘open’ the file next time, we will see the older version of the file This means that all the uncommitted writes to the file will be lost as the file in the hard disk was never modified with the updates made by the CPU in RAM In summary, every program that is ‘opened’ for execution at a particular instant of time must be brought into the RAM space; whereas, every program that is ‘inactive’ or ‘closed’ can be presented in the secondary memory or hard disk Therefore, a hard disk memory is typically very large in size when compared to the RAM space of the computer system (the size of the hard disk is specified in Giga bytes whereas the size of RAM is specified in megabytes as a part of computer system configuration).

1.3 C/C++ Development Environment

So as to fully translate the high-level language into the machine language every C/C++ program has to go through the set of system programs before the machine can execute the code to generate the required output The list of system programs involved in the process

of translating the high-level language into a low-level language is as given below:

Operating system

Write command

CPU performs a “write”

operation on the file

Save command

Operating system copies the modified file from the primary memory to the secondary memory

Figure 1.11: Saving the file

Trang 30

menu options so as to facilitate creation and maintenance of a software project Some of the key facilities provided by editor include:

1 Creation of a new program

2 Editing an existing program

3 Debugging of a program

4 Initiate compilation and execution of the program

In summary, an editor is a system software using which we can create and save a C/C++ file

on the disk A C++ file which contains the source code is generally saved with an extension as

‘.cpp’ on the hard disk (C program file has an extension c.) Figure 1.12 shows a screen shot of

a Turbo C/C++ editor, which is available in the DOS mode The detailed description of all the menu options provided by the editor is out of the scope of this text book

Figure 1.12: Turbo C/C++ editor screen1.3.2 Pre-processor

We can give an abbreviation for group of instructions to be executed in a C/C++ program

Such an abbreviation is called as a macro The macro facility enables us to attach a name

with the sequence of instructions, which are to be executed repeatedly in the program The advantage of such naming is that we can now use a name of a macro each time we need to execute the sequence of instructions instead of actually typing the same instructions again and again in the program

A macro pre-processor is a system program that resolves the macro references by

substituting a ‘macro name’ with its ‘definition’ All the macro references made by the programmer in the source code will actually be substituted by the sequence of instructions and the data which are defined by the macro The pre-processor runs just before the compilation of the program starts Hence, the compiler will not see any abbreviations or macros because they would already be expanded by pre-processor before the compilation

of the code kicks off The pre-processor creates a file without macros on the disk which is used by the compiler for the translation of the code as shown in Figure 1.13

The instructions within the program that are understood by the pre-processor are called

as pre-processor directives The pre-processor directives are generally prefixed by a symbol #

in C/C++ Some of the pre-processor directives are:

1 #include – The directive is used to include a header file in the C/C++ program

2 #define – The pre-processor directive is used to define macros in the C/C++ program

We will discuss the details of these directives in Chapter 2 of this text book

Trang 31

1.3.3 Compiler

The compiler is a system program that converts the source code into the machine language The machine language is also called as an object code, which is generated as an output

of  the compilation process The compiler generates an ‘.obj’ file on the disk after the

successful compilation of the source code as shown in Figure 1.13 There are three major tasks, which are performed on the source code as a part of compilation process These are the key phases of the compilation process and they are as explained below:

1 Syntax analysis: Program can be translated into the machine code only if the source code written by the programmer does not violate any of the syntactical rules defined by the language The syntax phase is used to check if the syntax of the source code is correct

Source Code

File containing the C/C++ source

code The extension of C file must be ".c"

whereas the extension of C++ file must be

set as ".cpp" Let us assume that the

name of the file is "p1.cpp"

This is the object file created by the

compiler This file will have a extension

as ".obj" Hence, if the name of the

file containing the source code is p1.cpp

then the name of the object file will be

Step 4

Loader loads the executable code in RAM

so that CPU can execute the program

Step 5

CPU runs the program Executable file

This is the executable file created by

the linker This file will have a

extension as ".exe" Hence, if the

name of the file containing source code

is p1.cpp then the name of the

executable file will be set as p1.exe

Disk Disk

Disk

Figure 1.13: C/C++ development environment

Trang 32

The component inside compiler that validates the syntax of the program is called as a

parser The parser will throw an ‘error’ message to the programmer if any of the syntax rules are violated The translation process is immediately terminated if at least one error

is located in the input program Every programming language has a grammar, which defines the syntactical rules of that language A parser is a program that checks if the input sentence preservers the syntactical rules, which are defined by the grammar of the language, thereby detecting syntax errors (if any) in the source code So as to examine the sentence for syntax errors, the compiler partitions the sentence into discrete tokens

The process of partitioning a single sentence into separate tokens is called as ‘lexical analysis ’, which happens before the ‘syntax analysis’ phase of the compilation process.

2 Semantic analysis: The phase is used to check the input program for the semantic errors The semantic rules define the ‘data types’ over which a specific operation can

be performed The semantic phase will throw an error and stop the translation process

if there is a ‘data type’ mismatch while performing an operation We discuss the details

of ‘data types’ and operations in Chapters 2 and 3 of this text book

3 Code generation: Once the syntax and semantic analyses are completed successfully, the code generation phase generates the optimized object code (which is the machine

language) on the disk The object code for the program is created and stored as an ‘.obj’

file on the disk

The total time required for the compilation of the source code so as to generate the object

file is often referred to as ‘compile time’ of the program.

Before initiating translation, compiler needs to ensure that the programmer has not violated any of the syntactical rules which are defined by the language To check the syntax of each of the statements written by the programmer, compiler needs to split each statement into different tokens A token

is a smallest indivisible part of each statement For example, if value of z is to be calculated as addition of x and y the statement must be written as:

a semicolon

Trang 33

1.3.4 Linker

It is possible that the C/C++ program contains references to functions or data, which are actually defined in the external libraries These libraries can provide the definitions of the common functions or the data required throughout the development of the project and hence the program may be required to refer to functions and data present in multiple such libraries Creation and usage of libraries facilitate reusability of the code in the project The object file generated by the compiler will contain certain ‘gaps’ due to such external

references present in the source code The ‘linker’ is a system program, which links the

object code produced by the compiler with the object code for the external libraries by resolving all the external symbol references thereby filling the gaps present in the object

file Once all the external references are resolved, the linker generates an executable code

(which is named as an ‘.exe’ file) on the disk as shown in the Figure 1.13

1.3.5 Loader

The linker generates the executable code (.exe file) on the disk Recall from the section 1.2.4 that CPU cannot make a direct access to the code present in the hard disk Therefore, the executable code must be first placed in RAM A loader is the system program that loads the executable code in the main memory of the computer system (in RAM) so that the code can be executed by the CPU

After the code is loaded into RAM, the processor can start executing the program, thereby generating the output The time required to execute the ‘executable code’ of the

program is often referred as ‘run time’ of the program.

1.4 Evolution of Programming Languages

Along with the growth in hardware systems, the features provided by the programming languages are also being enhanced with time In general, the computer programming paradigms can be categorized as ‘structured programming’ and ‘object-oriented programming’ The type of the programming style to be used is dependent on the type

of the application to be developed In this section, we understand the difference between

a ‘structured programming’ paradigm and an ‘object-oriented programming’ paradigm

This process of splitting a instruction into set of tokens is called as Lexical analysis The syntax analysis phase now determines if all the tokens are organized correctly in the statement The syntax analysis will throw an error if there is any incorrect formation of tokens detected in particular statement For example, the following statement would result into an compilation error.

z = x y+ ; This is because, it organizes the tokens incorrectly according to the syntax defined by the language The syntax of C/C++ is such that the operator + must be written exactly in between the two operands x and y which are to be added Compiler does not allow writing the symbol + at the right side (or left side) of both the operands whose values are to be added.

Trang 34

1.4.1 Structured programming (supported by both C and C++)

Structured programming is also referred to as modular programming or procedural programming where the program to be developed is organized into different procedures

Each of the modules defined in the program is called as a function or a procedure A structured

programming paradigm solves a large problem by dividing the problem into small pieces known as functions Each of the small pieces are considered as different problems and solved independently by writing different functions The results produced by each of the small functions are consolidated at the end, so as to derive the solution for the large problem For example, let us consider that we need to create a program to sort 100 numbers stored in a file in an ascending order The structured programming may divide the large problem statement into the following functions:

1 Function to read the 100 numbers from the file

2 Function to arrange the numbers in the ascending order

3 Function to write the result back to the file

Hence, we have now divided a large problem to sort the data in the file into three different problems as listed above

In general, the structured programming paradigm divides the large program into different modules based on the ‘algorithm’ or the ‘function’ that the module performs

A function A can call another function B if A needs service which is offered by B For example, if the job of function A is to calculate factorial of a number and job of function B is

to perform multiplication, function A would need to call function B multiple times because factorial requires performing multiplication multiple times with different data values Figure 1.14 shows a typical structured programming behaviour with five functions A, B, C,

D and E Execution flow with functions are explained in detail in Chapter 7, at this stage,

we just define structured programming as a collection of different building blocks called as functions such that each function is dedicated to perform a specific operation We will just note a few points about function calls at this stage:

1 After the ‘called function’ completes its execution, the control is ‘returned’ to the calling function For example, function A calls function B and after function B completes the control is returned to function A Similarly, D calls E and hence after E completes, the control is returned to D

Figure 1.14: Structured programming

Trang 35

2 Function calls are always handled sequentially This means that, if function A calls two functions B and C, they will be executed one by one depending on which is called first

If B is called before C, B will be executed before C

3 All called functions complete before the execution of calling function can complete In this example, function B calls D and D further calls E, this means that D will complete only after E completes and B will complete only after D completes

4 The structure given below has two branches of function execution:

A → B → D → E

A → C → D → EThe function A completes its execution only when execution of both the mentioned branches completes Here, we assume A calls B before calling C and hence the branch A →

B → D → E is executed before A → C → D → E

Calling function can pass values to the called function These values passed from

‘calling’ function to the ‘called’ function are called as ‘parameters’ or ‘arguments’ On the

other hand, the ‘called’ function can also return the result of operation to the ‘calling’ function This value which is returned from the ‘called’ function to the ‘calling’ function

is called as return value Parameter-passing and return values are very useful when the

results produced by one function are required by some other function so as to perform the required set of operations to solve a given problem

One of the major drawbacks of a structured programming paradigm is that the nance and support of the code becomes difficult as the size of the code increases Hence,

mainte-in many cases, ‘object-oriented programmmainte-ing’ is preferred over structured programmmainte-ing because the object orientation facilitates much better organization of the code thereby making the program easy to maintain and support The ‘C’ programming language is an example of a structured programming paradigm whereas C++ supports many additional object-oriented features along with supporting structured programming features

1.4.2 Object-oriented programming (only in C++)

Many applications and software systems to be developed require to operate with complex data elements such that each of the data elements in the program simulates one object in the real world Object-oriented programming paradigm is an approach of programming that can correctly simulate a real world, such that one ‘object’ created in the program represents the data about one entity in the real world C++ supports object orientation by allowing the creation of ‘classes’ in the C++ program Unlike the concept of structured programming, the object orientation gives an emphasis on the ‘data’ on which the functions operate on rather than the ‘algorithm’ of the functions Object-oriented program is organized as a set of ‘classes’, such that each class combines related ‘data’ elements and the ‘functions’ that operate on these data elements In summary, a class is a combination of ‘data’ and related ‘functions’ into a single unit

As an example, if we consider the development of a website for a particular educational institute, we will be required to maintain data about the following real world objects:

1 Students studying in the institute

2 Professors in the institute

Trang 36

3 Courses offered by the institute

4 Departments of the institute, etc

So as to store the data about these real world entities, we can create different classes in the C++ program such that each of the class combines the ‘data’ and ‘functions’ required to manage the information about one entity in the real world as shown in Figure 1.15 Hence,

we can create classes named as Student, Professor, Course and Department so as

to store representing each of the respective real world entities

Figure 1.15: Example of classes in C++

Note that, each class combines related ‘data’ and ‘functions’ together For example, the class Student contains the data elements named as roll_no, name and marks which indicates that for every student in the institute we will be storing the roll number, name and marks of the student object in computer memory Further, the functions defined in class Student represent the operations that a student object can perform in the real world The function save_student() indicates that the student object can save his/her details online

by registering on the website of the institute The presence of the function give_exam()

in the class Student indicates that the student in the real world can appear for an online exam which is deployed on the web site of the educational institute and the function print_result() indicates that student can take a printout of his/her result, which prints the marks obtained by the student in the online examination Similarly, we can imagine the meaning of data and functions which we have shown in other classes as shown in Figure 1.15

The object-oriented program organizes the code based on the ‘data’ and hence it makes the large programs easy to maintain and support The details of object-oriented programming paradigm along with its features are discussed in Chapters 11 to 14 of this text book The key features of the object-oriented programming paradigm are as listed below We have just given one liners for each of these features, however, understanding

Trang 37

these features is understanding object-oriented programming They are quite vast to explain in the first chapter, we will find each of these features explained in detail along with the real world examples throughout from Chapters 11 to 17 At this point, we would not worry about them much other than just the core definitions.

1 Abstraction: It is an ability of the program to hide the logical complexities and only reveals the necessary details to the programmer to progress with the software development This feature is discussed in detail in Chapter 11

2 Message passing: It is an ability of the object-oriented program to facilitate communication between different objects by passing data values (also called as messages) to each other This feature is discussed in detail in Chapter 11

3 Polymorphism: It is an ability of an operator or a variable to take multiple forms This feature is discussed in detail in Chapters 11, 12, 13 and 14

4 Data hiding: It is to ensure that critical data items in the program are secured from accidental updates Such critical data variables belonging to a business object can be made private to a class and they are hidden from outside world to avoid any updates

to these items This feature is discussed in detail in Chapter 11

5 Encapsulation: The process of wrapping variables and related functions is called as encapsulation to access these variables in a single logical unit called as a class This feature is discussed in detail in Chapter 11

6 Inheritance: A parent–child relationship between classes such that selective features of parent class are made available to child class to facilitate the reusability of the code is called

as inheritance Child class can define additional features of its own and by default inherit all the features from its parent classes This feature is discussed in detail in Chapter 14

Quiz

code

Trang 38

5 Structured programming is a way to organize program as collection of .

cross platforms

Review Questions

programming?

system programs involved in the translation of C/C++ into a machine code

appropriate examples of each type

object-oriented programming in C++

Trang 39

2.1 Overview

C++ is an extension of C This means that all the features of C are also available in C++ Furthermore, C++ has certain additional features of object-oriented programming, which makes it superior to the conventional C language The details of object orientation and other features of C++ are covered in the later chapters of this text book

In this chapter, we will study some fundamentals, which build the foundation to understand the advanced features of C and various object-oriented features supported

by C++

2.2 The First C/C++ Program

Recall from Chapter 1 that every C/C++ program has to be compiled and linked so as to convert the high-level language into the machine code All the instructions written in the program are executed one-by-one by the processor in a sequence as they appear in the program file Therefore, it is the job of the programmer to inform the processor about the exact starting point from which the execution of the program should begin The main() function in C/C++ is used to represent the start and end points of the program execution Hence, every program must have exactly one main() function, which is shown in Figure 2.1

CPU will execute all the instructions where we write inside the body of the main()function in a sequence as they appear The presence of empty round parenthesis after a special word main() informs the compiler that the function main() does not take any arguments By default, every function in C/C++ is expected to return a value to the one who invokes the function We can use a keyword void if we do not want to return any value to the calling function The complete details of functions with arguments and return values are discussed in Chapter 7 of this text book and hence the details about ‘function arguments’ and ‘return types’ can be ignored at this point of time

At this stage, we need to understand that a main() function is to be created using a template shown in Figure 2.1 The function main() defines the ‘start point’ and the ‘end point’ of the program, as the execution of any program starts from a point where the main() function begins and the execution of the program terminates at a point where the

2

Trang 40

main() function ends The opening and closing of the curly brackets are used to represent the start and end of the main() function as shown in Figure 2.1.

void main() {

/*program statements*/

}

Keyword void indicates that the

main() function does not return any value Every program must contain afunction named as main()

Figure 2.1: Template for creating the main() function

As an example, let us create a first program that prints a text message on the computer screen Figure 2.2 gives the full source code to print a text message I like Computer Programming on the computer screen

ends with semicolon

printf() statement is used to print a message on the computer screen

#include is a pre-processor directive which includes

the contents of the header file stdio.h into the program

Figure 2.2: Source code to print a message on the computer screen

The statement

printf("I like Computer Programming");

is used to print a message I like Computer Programming on the computer screen printf() is a built-in function available in C as well as C++ and this function is declared in the header file stdio.h Therefore, we have written the first statement of the program as,

#include<stdio.h>

The statement includes the contents of the header file stdio.h into the program, so as to facilitate the programmer to call (or use) the built-in function printf() directly within the program Recall from Chapter 1, #include is a pre-processor directive, which is used

to include the contents of a particular header file into the program before the compilation

of the code starts This ensures that the complete declaration of printf() is included in the program before the compiler starts compiling the code

Ngày đăng: 11/08/2020, 14:54