Computer Programming With C Kunal Pimparkhede
download
https://ebookbell.com/product/computer-programming-with-c-kunal-
pimparkhede-11371658
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Optimized Computer Programming With C10 And Net 6 Dive Into Advanced
Strategies For Crafting Lightningfast Resilient Applications With C
100 And Net 6 Anderson
https://ebookbell.com/product/optimized-computer-programming-
with-c10-and-net-6-dive-into-advanced-strategies-for-crafting-
lightningfast-resilient-applications-with-c-100-and-
net-6-anderson-89194732
Fundamentals Of Computer Programming With C Svetlin Nakov
https://ebookbell.com/product/fundamentals-of-computer-programming-
with-c-svetlin-nakov-38512526
Computer Graphics Programming In Opengl With C 2nd Edition V Scott
Gordon John Clevenger
https://ebookbell.com/product/computer-graphics-programming-in-opengl-
with-c-2nd-edition-v-scott-gordon-john-clevenger-30972724
Coding For Absolute Beginners Master The Basics Of Computer
Programming With Python Java Sql C C C Html And Css Andrew Warner
https://ebookbell.com/product/coding-for-absolute-beginners-master-
the-basics-of-computer-programming-with-python-java-sql-c-c-c-html-
and-css-andrew-warner-34095186
C And Computer Hacking Mobile Hacking 3 Bundle Manuscript Beginners
Guide To Learn C Programming With Computer Hacking And Mobile Hacking
Cody
https://ebookbell.com/product/c-and-computer-hacking-mobile-
hacking-3-bundle-manuscript-beginners-guide-to-learn-c-programming-
with-computer-hacking-and-mobile-hacking-cody-11124248
An Introduction To Objectoriented Programming In C With Applications
In Computer Graphics 2nd Edition Graham M Seed Beng
https://ebookbell.com/product/an-introduction-to-objectoriented-
programming-in-c-with-applications-in-computer-graphics-2nd-edition-
graham-m-seed-beng-4198618
Opencv 4 Computer Vision Application Programming Cookbook Build
Complex Computer Vision Applications With Opencv And C 4th Edition
David Milln Escriv Robert Laganiere
https://ebookbell.com/product/opencv-4-computer-vision-application-
programming-cookbook-build-complex-computer-vision-applications-with-
opencv-and-c-4th-edition-david-milln-escriv-robert-laganiere-11132666
Computer Programming With Matlab J Michael Fitzpatrick Kos Ldeczi
https://ebookbell.com/product/computer-programming-with-matlab-j-
michael-fitzpatrick-kos-ldeczi-5415618
Handbook Of Computer Programming With Python Dimitrios Xanthidis
https://ebookbell.com/product/handbook-of-computer-programming-with-
python-dimitrios-xanthidis-46634262
Computer Programming with C++
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.
Computer Programming with C++
Kunal Pimparkhede
University Printing House, Cambridge CB2 8BS, United Kingdom
One Liberty Plaza, 20th Floor, New York, NY 10006, USA
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.
Contents
Preface xi
Acknowledgements xiii
PART-I Structured Programming
1. Introduction 3
1.1 Overview 3
1.2 Computer System Architecture 8
1.3 C/C++ Development Environment 13
1.4 Evolution of Programming Languages 17
2. Fundamentals 23
2.1 Overview 23
2.2 The First C/C++ Program 23
2.3 Writing Comments 27
2.4 Constants or Literals 28
2.5 Variables and Data Types 31
2.6 printf() Statement (Supported by both C and C++) 38
2.7 C++ Style of Printing the Value on Computer Screen 49
2.8 endl Modifier (Supported by C++ not by C) 51
2.9 Accepting User Input Using scanf() Function (Supported by both
C and C++) 52
2.10 cin Object in C++ (Only in C++ not in C) 58
2.11 Manipulator setw 63
2.12 Defining Constants using #define—A Pre-processor Directive 65
2.13 Character Specific Input/Output 66
3. Operators and Type Casting 71
3.1 Overview 71
3.2 Arithmetic Operators 77
3.3 Relational Operators 82
vi ✦ Contents
3.4 Shorthand Operators 84
3.5 Bitwise Operators in C/C++ 85
3.6 Increment/Decrement Operators 89
3.7 Order of Operations Evaluated by the printf() Statement 94
3.8 Implicit Type Casting/System Casting 97
3.9 Explicit Type Casting 97
3.10 sizeof Operator in C/C++ 101
3.11 Scope Resolution Operator(::)| Only in C++ not in C 102
4. Decision Making Control Statements 110
4.1 Overview 110
4.2 if else Statement 110
4.3 Logical Operators 123
4.4 else if Ladder 125
4.5 switch Statement 132
4.6 Ternary Operator/Conditional Operator 135
4.7 goto Statement 139
5. Iterative Control Statements: Loops 146
5.1 Introduction 146
5.2 while Loop in C/C++ 149
5.3 for Loop in C/C++ 164
5.4 do..while Loop 180
5.5 break and continue Statements 183
5.6 Infinite Loops 190
5.7 Comma Operator with for Loop 192
5.8 Creating Variables Local to Loops (Possible in C++ but not in C) 192
5.9 Empty Loops 193
6. Arrays 216
6.1 Overview 216
6.2 Creating an Array 218
6.3 Array of Characters 238
6.4 2D Arrays 252
6.5 2D Array of Characters 261
6.6 String-Specific Input and Output Operations: gets()/puts() 264
7. Functions 299
7.1 Overview 299
7.2 Creating Functions 303
7.3 Local Variables of the Function 309
7.4 Functions with Arguments 313
7.5 Functions with Return Values 318
Contents ✦ vii
7.6	
Passing Array as an Argument to the Function 325
7.7 Recursion 329
7.8 Activation frames: How Function Calls and Returns are Internally
Handled in C/C++ 337
7.9 Storage Classes in C/C++ 342
7.10 Inline Functions in C/C++ 345
7.11 Function with Default Arguments (Only in C++ not in C) 347
7.12 Command Line Arguments 349
7.13 Some Built-in Functions 353
8. Pointers 371
8.1 Overview 371
8.2 Creating Pointers 377
8.3 Data Type of Pointers 380
8.4 Types of Function Calls 383
8.5 Arithmetic Operations with Pointers 393
8.6 Accessing Array Elements using a Pointer 400
8.7 Initialization of an Array: Revisited 407
8.8 Self-addressability of Character Variables 413
8.9 Array of Pointers 415
8.10 Pointer to a Pointer 418
8.11 Pointers and 2D Arrays 420
8.12 void Pointers 426
8.13 Pointer to a Function 427
8.14 Reference Variables (Only Available in C++ not in C) 429
8.15 Lvalue and Rvalue 433
9. Structures and Unions 445
9.1 Overview 445
9.2 Creating Structures 446
9.3 Array of Structure Objects 457
9.4 Nesting of Structures 469
9.5 Structures and Pointers 472
9.6 Accessing Array of Objects using a Pointer 476
9.7 Passing Object as an Argument to a Function 479
9.8 Difference between Structure and Union 481
10. Dynamic Memory Allocation in C++ 497
10.1 Overview 497
10.2 Dynamic Memory Management in C++ 499
10.3 Linked List 509
10.4 delete Keyword in C++ 527
viii ✦ Contents
PART-II Object Oriented Programming
11. Classes and Objects 533
11.1 Overview 533
11.2 Creating Classes 537
11.3 Creating Objects of a Class 538
11.4 Access Specifiers in C++ 542
11.5 Data Hiding and Encapsulation 545
11.6 Employee Management System: An Example 548
11.7 Account Management System: An Example 554
11.8 Calculating Slope of the Line: An Example 559
11.9 Addition of Complex Numbers: An Example 563
11.10 Addition of Points in Cartesian Coordinate System: An Example 567
11.11 Array of Objects 569
11.12 Employee Management System: Revisited 571
11.13 friend Functions 573
11.14 Addition of Point Objects using friend Function: An Example 574
11.15 Pointer to Objects 580
11.16 Binding of Pointers with Individual Members of the Class 584
11.17 this Pointer 589
11.18 Resolving Ambiguity using this Pointer 592
11.19 Cloning Objects using this Pointer: An Example 594
11.20 Dynamic Memory Allocation of Objects 596
11.21 Linked List to Maintain Data about Employees 600
11.22 Composition and Aggregation between Classes 609
11.23 Converting the Relationship to Aggregation 615
11.24 Defining the Member Functions Outside Class using Scope Resolution
Operator 620
11.25 Function Overloading and Compile Time Binding 622
11.26 Local Classes 625
11.27 Nested Classes 627
12. Constructors and Destructors 652
12.1 Overview 652
12.2 Creating Constructors 654
12.3 Constructor Overloading 659
12.4 Program to Perform Addition of Point Objects using Constructors: An
Example 665
12.5 Constructor with Default Arguments 668
12.6 Cloning Objects using Constructor/Copy Constructor 669
12.7 Allocating Dynamic Memory Inside Constructor 674
12.8 Destructors in C++ 680
12.9 Static Members and Static Member Functions 684
Contents ✦ ix
13. Operator Overloading 699
13.1 Overview 699
13.2 Overloading Operators 700
13.3	
Overloading One’s Complement ~ and Minus - Operators: An Example 703
13.4 Overloading Binary Operators Plus + and Minus - 707
13.5 Overloading Shorthand Operators: An Example 713
13.6 Overloading Relational Operators: An Example 716
13.7 Overloading Increment/Decrement Operators: An Example 720
13.8 Function Object: Overloading Function Call Operator () 726
13.9 Overloading Subscript Operator [] 728
13.10 Overloading Assignment Operator = 731
13.11 Overloading Type Cast Operator 735
13.12 Conversion of One User-defined Type to Another 738
13.13 Creating Global Operator Functions 741
13.14 Overloading Insertion and Extraction Operator for Student Objects:
An Example 745
13.15 Overloading Operators new and delete 749
13.16 Overloading operator - 754
14. Inheritance 770
14.1 Overview 770
14.2 Creating a Parent–Child Relationship between Classes 773
14.3 Access Specifiers in C++: Revisited 776
14.4 Types of Inheritance 788
14.5 IS-A and HAS-A Relationship: An Example 793
14.6 Multi-level Inheritance: Calculator 801
14.7 Resolving Ambiguity in Multiple Inheritance 808
14.8 Virtual Base Class 813
14.9 Function Overriding 821
14.10 Pointers and Inheritance 824
14.11 Overriding a Function with Different Return Type 831
14.12 Virtual Functions and Runtime Polymorphism 833
14.13 Virtual Tables 843
14.14 Pure Virtual Functions and Abstract Classes 851
14.15 static_cast and dynamic_cast 854
14.16 Constructors and Inheritance 858
14.17 Working of Constructors with Multiple Inheritance 863
14.18 Destructors and Inheritance 864
14.19 Virtual Destructors 867
15. Input and Output Streams in C++ 881
15.1 Overview 881
15.2 Types of I/O Streams 882
x ✦ Contents
15.3 Console Input and Output in C++ 883
15.4 Formatted v/s Unformatted I/O Operations 884
15.5 Formatting the Output using Member Functions of Class ios 885
15.6 Formatted I/O using ios Flags 889
15.7 Formatted I/O using Manipulators 893
15.8 Creating your Own Manipulator 894
15.9 Passing Arguments to the Custom Manipulator 895
15.10 Character by Character Unformatted I/O Operations 897
15.11 Line by Line Unformatted I/O Operations 900
15.12 File I/O Operations 902
15.13 Performing Operations on File 904
15.14 Closing the File 914
15.15 File Pointer Manipulation Functions 915
16. Templates in C++ 928
16.1 Overview 928
16.2 Function Templates 928
16.3 Class Templates 933
16.4	
Standard Template Library: One of the Applications of Class Templates 937
16.5 Implementation of Stack using Linked List: An Example 959
16.6 Queue using List 964
17. Exception Handling in C++ 969
17.1 Overview 969
17.2 Exception Handler in C++ 970
17.3 throw Keyword 971
17.4 Examples 971
17.5 Order of writing Catch Blocks 981
17.6 Catching and Throwing User-defined Objects 982
17.7 Program Specifying Throw List 986
17.8 C++ Built-in Exception Classes 988
ASCII Values 994
List of Keywords in C++ 998
Software Development Life Cycle 999
Bibliography 1002
Preface
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
9 Error Finding Exercise
9
9 Solved Problems
xii ✦ Preface
9
9 Objective Questions
9
9 Review Questions
Chapter Organization
This book comprises 17 chapters. Chapter 1 gives an overview of computer organization
and architecture. It also explains the C/C++ development environment. Chapters 2 to 5
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.

Does this book also explain the underlying systems which are involved in the execution of a
computer program ? ?
I have put my best efforts to make this book as illustrative and interactive as possible.
Any suggestions to further improve this book are always welcome. You can write to me at
kunalp84@rediffmail.com.
Acknowledgements
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.
PART-I
Structured Programming
Introduction
1.1 Overview
Aprogram 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
Chapter
4 ✦ Computer Programming with C++
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 2
Binary representation of 15
Byte 3
Binary representation of 25
10000011 00001111 00011001
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, 25
The 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
Introduction ✦ 5
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 + 25
Note 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.
15 + 25 ADD 15, 25
Input
Instruction written in
high level language
Compiler
Output
Instruction converted to
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 ATT 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’.
ADD 15, 25
Input
Instruction written in
assembly language
Assembler
Output
Instruction converted to
machine language
10000011 00001111 00011001
Figure 1.2: Assembler
6 ✦ Computer Programming with C++
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.
Introduction ✦ 7
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
.........
Machine language
C/C++
Program
Operating System
Figure 1.4: Layered architecture of application program, system programs, and computer
hardware
8 ✦ Computer Programming with C++
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:
Processing unit
Storage unit
Input Output
ALU
Control unit
Primary
memory
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
Introduction ✦ 9
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.
I1 d1;
I2 d2;
I3 d3;
I4 d4;
.
.
.
.
In dn;
Sequential execution
CPU executes the instructions in the file in a
sequence from top to bottom. This is
called as sequential execution.
Computer program
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
Asthehardwareofacomputersystemisultimatelybuiltupofelectronicandsemiconductor
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.
10 ✦ Computer Programming with C++
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.
Source Code
A program written in
a high level language
System programs
Machine Code
The high level language
is converted into a
language of 0’s and 1’s
Figure 1.7: Translation of high level language to low level language
Introduction ✦ 11
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
of the program.
1.2.4 Storage unit
The storage unit comprises of the memory devices, which are present in the computer
system where instructions and data are stored. The area of the memory where instructions
of the program are stored is called as a ‘code segment’ whereas the area of the memory
where the data required for the program is stored is called as a ‘data segment’. These
memory segments are managed by the memory management unit (MMU) of the operating
system in the primary memory of the computer system. In general, the memory units of a
computer system are categorized as follows:
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.
12 ✦ Computer Programming with C++
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
Processor
Operating
system
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
File File
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
Primary Memory
Secondary Memory
File in secondary memory
is stale
New version of the file
.
.
.
Processor
Operating
system
File** File
Write command
CPU performs
a “write” operation
on the file
Figure 1.10: Uncommitted writes done to the file
Introduction ✦ 13
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:
1. Editor
2. Pre-processor
3. Compiler
4. Linker
5. Loader
1.3.1 Editor
Editor provides an integrated development environment (IDE) to create and develop a C/
C++ program. An editor is a system program that provides the programmer with multiple
Primary Memory
Secondary Memory
New version of the file
.
.
.
Processor
Operating
system
File** File**
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
14 ✦ Computer Programming with C++
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 screen
1.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.
Introduction ✦ 15
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
Step 1
The preprocessor substitutes all the macro names
with the macro definition and create a new file on disk.
The file generated by the preprocessor will not have any
macros in it.
Step 2
The compiler converts the high level language into the
object code thereby generating a object file on the disk.
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
set as p1.obj
File without macros
Step 3
The linker converts the object code into the executable
code by resolving all the external symbol references
which are made by the programmer.
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
File
Pre-processor
Compiler
Linker
Loader
File
File
File
Primary Memory
.
.
.
File Processor
Disk
Figure 1.13: C/C++ development environment
16 ✦ Computer Programming with C++
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.
What is Lexical analysis? ?
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:
z = x+y;
This statement has 6 different tokens z , =, x, +, y and ;. Splitting of this statement into different tokens is
as shown below.
Individual tokens
in the C++ statement
z = x + y ;
Assignment
Result
The symbol “+” is used
to perform addition
First
operand
Second
operand
Every statement
in C++ ends with
a semicolon

Introduction ✦ 17
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.
18 ✦ Computer Programming with C++
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.Astructured
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.
call
call
call
call
return
return
return
B
D
C
E
A
Figure 1.14: Structured programming
Introduction ✦ 19
2. Function calls are always handled sequentially. This means that, if function Acalls 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 → E
The 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 mainte­
nance and support of the code becomes difficult as the size of the code increases. Hence,
in many cases, ‘object-oriented programming’ is preferred over structured programming
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
20 ✦ Computer Programming with C++
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.
Student
roll_no;
name;
marks;
give_exam();
print_result();
save_student();
name;
specialization;
salary;
save_professor();
teach();
evaluate_student();
Professor
name;
budget;
assets;
save_data();
calculate_annual_budget();
Department
title;
duration;
fees;
save_data();
print_data();
Course
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
Introduction ✦ 21
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
1. Which of the following is done before compilation?
(a) Translation of source code to object
code
(b) Linking
(c) Loading
(d) Macro substitution
(e) None of the mentioned options.
2. Which of the following statements are true?
(a) Compiler generates output of the program as the result of the compilation process
(b) Linker transfers the machine code from secondary memory to primary memory
(c) Loader transfers the machine code from primary memory to secondary memory
(d) Pre-processing happens after the code is compiled
(e) None of the above statements are true
3. Assembler generates _____ language as its output.
(a) Language of mnemonics
(b) High-level language
(c) Machine language
(d) Middle-level language
4. Which of the following is not the function of compiler?
(a) Syntax analysis
(b) Lexical analysis
(c) Semantic analysis
(d) Code generation
(e) Resolving external symbol references
22 ✦ Computer Programming with C++
5. Structured programming is a way to organize program as collection of ________.
(a) Classes
(b) Objects
(c) Functions
(d) Structures
6. Wrapping of data and related functions together is called as
(a) Data hiding
(b) Encapsulation
(c) Inheritance
(d) None of the mentioned options.
7. Inheritance facilitates
(a) Data hiding
(b) Security to the code
(c) Reusability of the code
(d) Modular programming
8. Which of the following statements is true
(a) C/C++ programs are hardware dependent
(b) C/C++ programs are operating system independent
(c) C/C++ programs are operating system dependent and hence they cannot execute
cross platforms
(d) C/C++ programs are hardware and processor independent
9. Object-oriented features are supported by:
(a) Both C and C++
(b) Only by C
(c) Only by C++
(d) Neither by C nor by C++
10. Opcode represents
(a) Operations performed by the instruction
(b) Data used by instruction
(c) Both A and B
(d) None of the above
11. Which of the following statements is true
(a) Calling function may complete before called function
(b) Called function may complete before calling function
(c) Called function always completes before calling function
(d) Called function and calling function completes at the same time
(e) Function calls are resolved sequentially
12. Program written in which language is easy to maintain?
(a) Machine language (b) Assembly language (c) High level language
Review Questions
1. What is the difference between the structured programming and the object-oriented
programming?
2. Write a short note on the functions performed by the compiler.
3. Explain the C/C++ development environment in detail. Give the functions of each of the
system programs involved in the translation of C/C++ into a machine code.
4. Explain the difference between system programs and application programs with
appropriate examples of each type.
5. Write a short note on object-oriented programming paradigm. List different properties of
object-oriented programming in C++.
6. Explain the difference between compile time and run time of the program?
Fundamentals
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
Chapter
24 ✦ Computer Programming with C++
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 a
function named as main()
Set of instructions
in the program
Start of main()
function
End of main()
function
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.
#includestdio.h
void main()
{
printf(I like Computer Programming);
}
Every statement in C/C++
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,
#includestdio.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.
Fundamentals ✦ 25
As stated before, execution of any program always starts from main() function. Given
that this program has only one statement in the main() function (which is the printf()
statement), the output of the program is shown below.
I like Computer Programming
Note: Following is applicable to C++ and not to C
The program shown in Figure 2.2 executes in C as well as C++. This is because the
printf() function is supported by both the languages. Along with support to
printf() statement, C++ supports another way to print a message on the computer
screen. cout is a built-in object available in C++ but not in C, which is used to stream
messages on an output device. The program written in Figure 2.3 shows the usage of
cout object to print the message on the computer screen.
#includeiostream.h
void main()
{
coutI like Computer Programming;
}
Every statement in C++
ends with semicolon
cout 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 iostream.h into the C++ program
Figure 2.3: Source code to print a message on the computer screen
The statement
coutI like Computer Programming;
isusedtoprintamessageI like Computer Programmingonthecomputerscreen.Note
that every statement ends with a semicolon. The operator  is called as an insertion operator,
which actually inserts a text message on the computer screen. We have also explained in
Chapter 4 of this text book that the operator  is also used as ‘left shift operator’, which
can be used to shift the bits of a binary number in the left direction. However, in this case,
we have used the operator , which acts as an insertion operator and prints a message on
the screen because it is internally overloaded by C++ in one of the built-in classes which is
named as ostream. The class ostream is fully defined inside the header file iostream.h.
Also, cout is an object of class ostream, which is created inside the file iostream.h.
Therefore, we have written the first statement of the C++ program as,
#includeiostream.h
26 ✦ Computer Programming with C++
Notes
The program given in Figure 2.2 uses printf() statement to print a message on the computer screen.The printf()
function is declared in header file stdio.h which is included in the program.The program using printf() works with
C as well as C++ because the header file stdio.h and printf() function are supported by both the languages.
However, the program using cout shown in Figure 2.3 works with C++ but not with C.This is because the object cout
and header file iostream.h are only supported by C++ and not by C.This clearly means that C++ supports streaming
output operations whereas C does not.We will learn more about streams supported by C++ in Chapter 15.
The statement includes the contents of the header file iostream.h into the program,
so as to facilitate the programmer to use the built-in object of class ostream, which is
named as cout directly in the code. Remember, #include is a pre-processor directive,
which is used to include the contents of a particular header file into the C++ program
before the compilation of the code starts. This ensures that the complete definition of
the class ostream and the insertion operator  is included in the program before the
compilation. Details about classes and objects are discussed in Chapter 11 of this text
book. The only point we must understand at this stage is that the statement
coutI like Computer Programming;
is used to print a message as I like Computer Programming on the computer screen
as shown in Figure 2.4. And we must include the contents of header file iostream.h before
making use of cout in our program.
cout

The object cout invokes an
insertion operator function 
Object of class ostream
I like Computer Programming
I like Computer Programming
Message to be printed
The message to be printed is passed as an
argument to the insertion operator function
The insertion operator function is present in class ostream.
The complete definiton of the class ostream is present in the
header file iostream.h
Output on the screen
The insertion operator inserts a
message on the computer screen
Figure 2.4: Usage of cout
C++ supports streaming outputs, which are not supported by C. In general, the word
stream refers to the flow of data in the computer system. The ‘output stream’ of C++ allows the
programmer to perform a ‘write’ operation on the output devices such as ‘screen’, ‘file’, and
‘disk’.Theheaderfileiostream.hdefinesthenecessaryclassesandfunctionstosupportthe
streaming input and output. We will discuss the input streams of C++ in the later sections of
this chapter.As we have written the cout instruction inside the main function, the processor
will now execute the instruction after translating the instruction into a machine code, thereby
printing a message specified on the computer screen as seen in the output of the program.
Fundamentals ✦ 27
Can I write C/C++ programs in upper case? ?
The answer is NO; because C/C++ is a case sensitive language. This means that, upper case
and lower case characters have different meaning for the language. For example, printf() and
PRINTF() will be considered as two different identifiers by the compiler. stdio.h declares the function
printf() in lower case and hence compiler will not be able to recognize a symbol PRINTF(). Therefore,
we cannot just write the complete C/C++ program in the upper case, rather we have to preserve the syntax
of the language along with the case. Syntax of C/C++ is such that most of the built-in keywords and reserved
words are in lower case. There are still some built-in macros which are to be written in upper case.

2.3 Writing Comments
Comment is a part of the code, which is ignored by the compiler. However, programmers
may still write comments in the program to give documentation for the complex logic
implemented using a particular piece of code. Although, comments do not contribute
in generating the output of the program (comments are not even compiled), it is always
recommended to comment the source code wherever possible. This makes the code easy
to read and understand if any part of the code is to be referred in future for editing or
debugging purpose. There are two different types of commenting styles that can be applied
to the program:
1. Single line comments (only supported by C++ and not by C)
2. Multi-line comments (supported by both C and C++)
A single line comment starts with two slash symbols written back to back without any
space in between two slash symbols as shown below:
// This is a single line comment
The compiler will ignore any text that is written within the line after two slash (//)
symbols. Note that, a single line comment can be stretched until the end of current line
only. This means that, if we wish to write a comment across multiple lines then we must
begin each of the lines by the two slash symbols as shown below:
// This is the first line of the comment
// This is the second line of the comment
// This is the third line of the comment
Along with a support to // symbol for single line comments, compiler also ignores any
text which is written in between /* and */ so as to support creation of multiline comments
in the program. Hence, we can write a multiline comment in the code, such that, it begins
with a token /* and ends with a token */ as shown below:
/*This is the first line of the comment
This is the second line of the comment
This is the third line of the comment*/
28 ✦ Computer Programming with C++
REMEMBER
Single line commenting style is only supported by C++ but not by C
//This commenting style is only supported in C++
Multi-line commenting style is supported by both C as well as C++
/*This commenting style is supported by C as well as C++*/
Given below is an example that includes comments in the program that we have created
to print a text message on the computer screen.
/*This is a program to print a message
I like Computer Programming
on the computer screen*/
#includestdio.h
void main()
{
/*The below statement prints the text message on the screen*/
printf(I like Computer Programming);
}
Output:
I like Computer Programming
2.4 Constants or Literals
A constant or a literal is a part of the program that cannot change its value. The constants
in C/C++ are classified as:
1. Integer constants
2. Real number constants
3. Character constants
4. String constants
We can directly create/use any of the above constants in the program, so as to perform
operations with the constant values. Given below is the description for each of the above
categories of constants giving the examples of each type of constant values which are
supported by both C and C++.
2.4.1 Integer constants
These are numbers without a decimal point which can be written directly in the program.
The integer constants can be positive or negative, without any fractional component
present as a part of the constant value.
Fundamentals ✦ 29
Given below are some valid and invalid examples of integer constants
10 /*This is a VALID integer constant*/
-95 /*This is a VALID integer constant which represents
a negative value*/
45.9 /*This is an INVALID integer constant as there is a decimal
point in the number*/
25,000 /*This is an INVALID integer constant as there is a comma
used in between the digits of the number*/
Note that the integer constants must be written as a combination of digits 0 to 9 in the code
without any special characters like comma, space in between the digits.
2.4.2 Real constants
These are numbers with decimal point which can be written directly in the program. A real
constant can be positive or negative and can also include a fractional component present
as a part of the constant value. Real constants are also called as float constants or double
constants in C/C++.
Given below are some valid and invalid examples of real constants.
10.5 /*This is a VALID floating point constant*/
-90.832 /*This is a VALID floating point constant*/
25,000.976 /*This is an INVALID floating point constant as there
is a comma used in between the digits of the number*/
Note that just like integer constants, real constants must be written as a combination of
digits 0 to 9 in the code without any special characters like comma, space in between the
digits. The real constants may contain exactly one decimal point in between the digits so as
to represent a floating point value.
2.4.3 Character constants
A character constant is a single symbol enclosed in the single quotes. Given below are
some valid and invalid examples of character constants in C/C++.
‘e’ 
/*This is a VALID character constant which represents a letter e*/
‘1’ 
/*This is a VALID character constant which represents a symbol 1*/
‘$’ 
/*This is a VALID character constant which represents a symbol
dollar*/
‘ ’ 
/*This is a VALID character constant which represents a blank
space*/
‘10’ 
/*This is an INVALID character constant as it encloses two
different symbols (1 and 0) within the single quotes*/
‘ad’ 
/*This is an INVALID character constant as it encloses two
different symbols(letters ‘a’ and ‘d’) within the single quotes*/
30 ✦ Computer Programming with C++
Note that ‘1’ is not same as a number 1. In a sense, a ‘1’ represents a character constant
whereas a number 1 represents an integer constant. Generally, we use only numbers and
not characters in any of the arithmetic operations. For example, the below operation
1 + 5
will perform the addition of two integer constants 1 and 5, thereby giving a result of the
arithmetic operation as 6. However, we would get indifferent results in the program if
we perform the arithmetic operations with characters instead of integers. This is because
C/C++ maps every character constant with an integer code so as to store the character
constant in the computer memory. A unique integer code which is associated with every
character constant is called as an ASCII code of that character. ASCII stands for American
standard code of information and interchange. Although we attempt to store a character
constant in the memory, C/C++ internally stores the ASCII code corresponding to that
character in the memory. Whenever, we attempt to output the character on the screen,
the internally stored integer value is converted back to the original character and hence
we always get the result in terms of character symbols on the computer screen. Appendix
I gives the complete list of ASCII codes for each of the characters relevant to C/C++. As
seen from appendix I, the ASCII values of upper case characters from ‘A’ to ‘Z’ are 65 to 90,
whereas the ASCII values of the lower case characters from ‘a’ to ‘z’ are 97 to 122 and the
ASCII values for digits from ‘0’ to ‘9’ are 48 to 57, respectively. In all, the ASCII values range
from 000 to 127 wherein the remaining ASCII values are assigned for the special characters.
As an example, if we attempt to store an character constant ‘b’ in the computer memory,
internally a value 98 will be stored which is the ASCII value of character ‘b’ as shown in
Figure 2.5. Furthermore, if we attempt to print the character value, the code 98 will be
converted back into a character constant and then printed on the computer screen. Due
to this translation, we always get the output in a character format as shown in Figure 2.5.
b
98
Step 2
Step 3
Memory
.
.
ASCII value of the
character ‘b’ is stored in
the computer memory
C/C++ converts the ASCII value back to the character
constant at the time of generating the output. Hence,
the character ‘b’ gets printed on the computer screen
Step 1
User inputs the character ‘b’
from the keyboard
Figure 2.5: Storing characters in memory
Fundamentals ✦ 31
2.4.4 String constants
Collection of characters is called as a string. A string constant is formed by enclosing
multiple characters in double quotes.
Given below are some valid and invalid examples of string constants in C/C++
Computer 
/*This is a VALID string constant which is a collection
of eight characters*/
C 
/*This is a VALID string constant which contains just a single
character*/
'com' 
/*This is an INVALID string constant. This is because a
string cannot be enclosed in single quotes*/
45+6 
/*This is a VALID string constant which is a collection of
4 characters*/
Every string in C/C++ terminates with a special character called as a NULL character,
which is represented by ‘0’. For example, the string “Computer” will be internally stored
in the memory as shown in Figure 2.6.
C
A string always ends with a NULL character 0
o m p u t e r 0
Figure 2.6: Memory representation of a string
Note that, the last character of the string is automatically added as ‘0’, which is the
end of the string marker and is called as a NULL character. The details of string constants
and their processing are discussed in Chapter 6 of this text book.
Why do we store the ASCII values for character constants in the memory? ?
Recall from the Chapter 1 that, every symbol written in the high level language must be converted
into the machine language before it can be processed by the CPU. Integer or real constants can
be directly converted into the machine language by representing them into a binary number system. So
as to facilitate the storage of the character constants in the computer memory, every character constant is
internally assigned an integer code which is called as the ASCII value of that character. Hence, we can now
store a character constant in the computer memory by simply representing the ASCII code of that character
in binary number system.

2.5 Variables and Data Types
A variable is a place holder for a particular value to be stored in the memory. This means
that variable is a reserved area in the computer memory wherein we can store a value.
The process of creating a variable is called a ‘declaration’ of a variable whereas the process
of storing a particular value inside a variable is called as ‘initialization’ of the variable.
32 ✦ Computer Programming with C++
Every variable is associated with a particular data type.Adata type of a variable determines
the type of value that can be stored inside the variable. The list of basic data types which
are supported by C/C++ is given below:
Data
type Description
Size in
bytes
Range of
values
int A variable of type int can store any integer type of constant
which falls under the range of -32,768 to +32,767
2 bytes1
-32,768 to
+32,767
float A variable of type float can store any number with a
decimal point which falls under the range of -3.4e-38 to
+3.4e+38
4 bytes -3.4e-38 to
+3.4e+38
char The data type char is used to store character constant
which is single symbol enclosed in the single quotes
1 byte -128 to
+127
double A variable of type double can store any number with
a decimal point which falls under the range of -1.7e-
308 to +1.7e+308. This data type has higher precision
when compared to float. Hence a double type variable
requires 8 bytes in the memory whereas the float type
of variable just requires 4 bytes in the computer memory
8 bytes -1.7e-308
to
+1.7e+308
short
int
A variable of type short int can store any integer type of
constant which falls under the range of -128 to +127. The
keywords short int define a smaller version of the int
type in C++. Hence, the short int type of variables just
requires 1 byte in the computer memory, whereas the int
variable actually requires 2 bytes in the computer memory
1 byte -128 to
+127
long A variable of type long can store any integer type of
constant which falls under the range of -2147483648 to
+2147483647. The keyword long represents the larger
version of the int type in C++. Hence, the long type of
variables requires 4 bytes in the computer memory whereas
the int variable just requires 2 bytes in the computer
memory
4 bytes -2147483648
to
+2147483647
1

We assume 16 bit compiler throughout this text book where size of an integer is 2 bytes (16 bits). If you get the
size of integer as 4 bytes it means you are working on a 32 bit compiler.
2.5.1 Evaluating the range of data types
The range of values which can be stored inside a variable of a particular type is dependent
on the size of that ‘data type’ in the computer memory. The range of a particular data type
can be decided by considering the total number of permutations that can be represented
by the bit values assigned to the variable. As an example, let us consider an integer type
variable which requires 2 bytes in the computer memory. As each byte is formed using
eight bits, we can say that an integer variable requires 16 bits in the computer memory.
Therefore, the total number of permutations (X) that can be represented using 16 bits can
be calculated as shown below:
Number of permutations (X) = 216
= 65,536
Fundamentals ✦ 33
Out of the total number of states that can be represented using 16 bits, half of the
permutations must represent negative numbers in the high-level language and remaining
half of the permutations must represent positive numbers in the high-level language. Also,
one of the permutations of 16 bits must represent a value zero in the high-level language.
Therefore, we divide the total number of permutations by two as shown below:
X/2 = 65,536/2 = 32,768
As one of the permutations of 16 bits is used to represent zero (this is when all the bit
positions become 0), the range of integer constants in C/C++ is –32,768 to +32,767 as
shown in Figure 2.7. This theory is used to convert a number in the high-level language
into the machine language thereby storing the machine language in the computer memory
as seen in Figure 2.7. The most significant bit (which is the left most bit) represents the sign
bit which is 1 when a negative number is translated into the machine language and 0 when
a positive number is translated into the machine language.
Figure 2.7: Translation of integers into machine language
1
Each integer requires 16 bits in memory
Least significant bit
Most significant bit
This bit is also called
as a sign bit. The bit
is 1 for negative
numbers and 0 for
positive numbers
0 0 0 0 0 0 0 0 0 0 0
0
0
0
0
0
0 0 0 0
This permutation of bits represents
a negative value -32768
This permutation of bits represents
a negative value -32767
This permutation of bits represents
a negative value -32766
This permutation of bits
represents a value zero
This permutation of bits
represents a positive value +1
This permutation of bits
represents a positive value +2
This permutation of bits represents
a positive value +32767
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
1 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
1
0 1 1 1 1 1 1 1 1 1 1 1 1 1 1
The range for other data types such as short, long, and char can be calculated using a
similar approach. Evaluating the range of floating point types such as double and floats is
out of scope of this text book, as it requires a detailed study on IEEE formats in which the
mantissa and exponent are internally stored in the computer memory.
What will happen if we give a value to a variable which is out of the range specified by its data type? ?
This situation is called as overflow/underflow of values. We will not get any compilation error in
this case; however program will produce unpredictable results. For example, if we assign a value
say 66990 to a 2 byte integer; results produced by the program would be erroneous and unpredictable.

34 ✦ Computer Programming with C++
2.5.2 Declaration of variables
As we have mentioned above, a variable creates a place in memory where we can store
a value of a particular type. The process of creating a variable in memory is called as
‘declaration’ of the variable. Every variable must be declared before it is used in the program.
Given below is the syntax to declare a variable in C/C++:
DataType variableName;
For example, the statement
int marks;
creates an integer type variable named as marks in the computer memory. The compiler
allocates the memory for the variable when it is declared in the program. Hence, the above
statement allocates a memory of 2 bytes for the variable which is named as marks as shown in
Figure 2.8. Note that the initial value of any variable is undefined in C/C++ and hence we say
that the variable marks initially contains an unknown value or a junk value as shown in Figure 2.8.
The initial value of the
variable is junk
Every integer type
variable requires 2 bytes
in computer memory
marks 2 bytes
Name of the
variable
Figure 2.8: Declaration of the variable named as marks
Notes
Variable name is also called as an identifier. For example, in this case marks is an identifier which identifies the
exact memory location where the integer value is stored.
Figure 2.9 gives examples of declaring three variables named as a, b, and c of type
integer, float, and character, respectively. As shown in Figure 2.9, the compiler allocates
2 bytes in memory for variable a because it is declared as integer. Whereas, the compiler
allocates 4 bytes in memory for variable b because it is declared as float and 1 byte for the
variable c because it is declared as character as shown in Figure 2.9. Note that, each of the
variables initially contain junk values as shown in Figure 2.9.
If all the variables to be declared are of the same type, then we can also use a comma
operator as a separator between the variable names so as to create multiple variables using a
single C/C++ statement. For example, the below statement creates three different variables
named as marks, salary, and score of type float:
float marks,salary,score;
Other documents randomly have
different content
Star, that was John's brother! exclaimed Edith, after he had
disappeared over the hill, and that little girl was his sister.
Resuming her composure over the excitement the incident caused,
she sat down in one of the lounging chairs, with Star by her looking
serious enough herself.
I believe so, Edith; but why didn't we stop long enough to talk with
them? said Star, apparently disappointed.
Oh, I wanted to stop to speak—but that would not do, dear Star—
would not do at all; but I will have a talk with them when he comes
here next week, never mind, cried Edith, with much joyousness in
the ring of her voice. Isn't she such a pretty creature—just like one
of those little fairy mountain girls you see sometimes in romantic
plays in the theaters, and I know she is more romantic.
What do you think of him, Edith—the man—her brother—if that is
whom he is? asked Star, blushing for the first time Edith ever saw
that intelligible sign in her face.
If he is not Mr. Winthrope's brother, he is his living stature in
bronze, replied Edith; and now, Star, tell me your opinion?
I can't say that I have an opinion, Edith; I am really dumb with
amazement. He is such a big fellow—more like a mill-worker, or such
—oh, my, Edith; don't ask me for—
Well, now, I like that way of speaking about Mr. Winthrope's
brother. Maybe it was not him at all, and we have had our little scare
for nothing. Oh, goodness! here comes Mr. Cobb again! dear me!
and Edith subsided.
Pursuing the tenor of his prevailing thoughts, Jasper Cobb sought
Edith and found her on the eastern end of the veranda. After
saluting the two young ladies again quite prodigiously, he asked
Edith for a private interview at once. Star, hearing the request, rose
and left them, as if she had an errand in her room, before Edith had
time to ask her to remain. Star, however, was waiting for such an
opportunity to absent herself, knowing what young Cobb's mission
was. Having been informed by Edith what her answer would be, she
went away satisfied that she would return to find that young man
laboring under a severe jolt to his mercenary soul.
Now, when alone, Mr. Cobb drew up a seat and sat near Edith.
Miss Jarney, we have always been friends—our families?
Yes.
And we have been friends for years, you and I?
Yes.
Would you consider a proposition from me to make that friendship
permanent and lasting?
Yes.
His heart bounded—a little.
Well, Miss Jarney—may I call you Edith?—I came here to ask you to
marry me?
You? she said, turning on him.
Yes; me, he answered, dejectedly, for he caught the tone of her
voice in no uncertain meaning.
No, said Edith, firmly, looking at him, with a sort of a
commiserated smile for his imbecility. If you want to be my friend,
Mr. Cobb, all right, you may consider me as such; but, as to
marrying you, never can I make up my mind to that end.
Dear Miss Jarney, you don't know the blow that you have struck me
—it almost topples me over, he insisted, and Edith came near
laughing in his face, so ludicrous was the expression that he had
now assumed. I have always thought you had encouraged me—
Oh, never was I guilty of such an offense, Mr. Cobb—never. You are
laboring under a misconception, or a delusion, or something else.
Encourage you, Mr. Cobb? How ridiculous!
Then, you refuse? he asked, coldly and fiercely.
I most certainly have my senses with me, she retorted, with a
laugh.
Ah, then, I'll go my old way. I thought I might settle down some
day and be a man, he whispered.
Be a man first, Mr. Cobb, and settle down afterwards, is my advice
to you, she responded.
You are cruel, Miss Jarney—cruel—as cruel as all the other women
of the rich, who make monkeys of we men folk, he said,
despairingly.
You must understand, Mr. Cobb, that I am not one 'of all the other
women' of the rich, of whom you speak so slightingly, she replied,
still keeping a good temper.
Well, I guess not, Miss Jarney, he said, with a sneer, looking away
from her. I see, Miss Jarney—I am not blind—that you have set
your cap for that young man in your father's office.
You are disrespectful, Mr. Cobb; leave me at once, she replied,
with some scorn for the first time exhibiting itself in her bearing. She
arose and left him sitting there alone, with his pipe as his only
comforting companion. After recovering from this jolt, as Star
predicted, he gathered up his belongings, together with his valet,
and vanished.
Imagine such a union of hearts! There are plenty of them founded
upon the rock of riches. Yes; imagine it! See this young man Cobb,
and know his worth! His face was like that of a well bred bull terrier,
with a pipe between its lips, and a red cap upon its head. He had a
pair of dull-gray pants on his hind legs, and they were turned up,
with a pair of yellow shoes sticking out below the turn-ups. Around
the middle of his body was a yellow belt fastened by a silver buckle,
and above the belt was a silken white shirt, with turn-down collar,
and around the collar was a red necktie, in which stuck a scarabee
pin. And he called himself a man worthy of Edith.
He had been to Harvard, she to Vassar. She had learned to write a
grammatical sentence and spell in the good old Websterian way. She
could sing and play on the piano; and converse on the economic
questions of the day with the perspicacity of a Stowe. She read the
poets down through the catalogue of famous men and women, and
the novelists of the class of Dickens and Hawthorne. She knew of
the painters, the musicians, the theologians, and could talk
intelligently on them all.
Him? He had learned a lot of things. He could flip the Harvard stroke
with the ease of a Cook. He could make a touchdown without
breaking sixteen ribs of an adversary. He could twirl the pigskin like
an artist of the green cloth. He could take the long jump, or the long
hike, with the grace of a giraffe. He could dance like a terpsichorian
dame. He could drink whiskey, champagne and beer, smoke
cigaretts, play cards. He could talk with the profundity of an ass and
write with the imbecility of an ox. Yes, indeed, he had all the
refinements of a college education—the kind confined to the male
gender. The only virtue he had was his prospective inheritance from
his father—money.
And he wanted Edith to marry him! Pooh!
CHAPTER XXX.
FOR JOHN IS COMING HOME.
There is a little frame house sitting, in the shade of maples and
oaks, by the roadside to the south aways from Chalk Hill. It is a
leaning building, to some extent, in many ways, by reason of its age.
A crooked little chimney heaves up on the exterior of one end, by
reason of its insecure foundation. Shingles curl, up, as if in dotage,
by reason of the sun. Weather boarding warp and twist and turn,
grayed by the wash of years, by reason of their antiquity. Windows
peep out, with little panes, and rattle in the wind, by reason of their
frailty. Wasps and bees, in season, build their mud nests beneath
curling shingle and behind twisting board; bats fly out, at eventide,
from unseen holes in the gables; and swallows chatter and circle
round the chimney top in the twilight of the summer days. An
ancient porch, with oaken floor, hangs against the front wall, and the
woodbine and morning glory creep and twine and bloom around its
slanting columns. A gate swings out at the end of the path leading
from the door to the highway. Flowers—the rose, the marigold, the
bouncingbetty, the wild pink, the primrose, all as old-fashioned as
the people who dwell here—border the pathway. A paled patch of
ground stands to one side, as sacred as the Garden of Gethsemane.
In the rear a gnarled and aged orchard has but recently shed its
snowy burden of bloom, with lingering scents still in the air; and
beyond and around, fence-enclosed fields are greening with growing
crops, and still beyond are dark forests and open fields and noisy
ravines.
Evening is coming on. The sun has gone down over the mountain
top. Shadows have disappeared into the gray of fading light. Odors
of night are ascending from the cooling earth. The robins are
rendering the last stanza of their solemn doxology to the dying day.
The whippoorwills send forth their melancholy praises to the
approaching darkness through the wooded chancel of their shadowy
choir loft. And frogs swell their throats in grave bass tones to the
melody of country life at this time of departing day.
A gray-haired farmer, in rough garb, sits on the porch, smoking his
pipe, and by his side sits his patient, loving wife. On the top step of
the porch sits their young daughter, reading her fate, perhaps, in the
evening stars, the while glancing up the road, and listening for the
click of horses' feet on the stones. But no sound is heard before
night comes on. The mother rises, goes in, and lights the oil lamp,
and sets it by a window for the expected visitor to see. For John is
coming home.
They are late in getting here, says the mother, as she descends
from the porch, and goes down the path to the gate. She looks up
the road through the shadows; then returns, and sits down by her
daughter on the steps.
The father relights his pipe, clanks down to the gate, in his heavy
boots, looks up the road through its shadows; then returns. They
are late, he says, and resumes his seat.
I wonder what is keeping them, says the daughter, with an
expectant hush in her sweet voice, as she rises, and goes down to
the gate. She looks up the road through its shadows; then returns,
and sits down.
Listen!
John is coming home.
They hear the clank of horses' hoofs, the rattling wheels, the rhythm
of a lively trot; then indistinct voices far in the distance.
John is coming home. The son who went away the year before—the
brother—is coming home. The father's boots clank on the porch as
he impatiently walks back and forth. The mother rises, and shades
her eyes, and peers up the roadway through the shadows. The sister
rises, with a dancing heart, and flutters down to the gate, like an
angel in the darkness.
For John is coming home. Home! His only place of sweet
rememberance.
It is an age, it seems, before the team draws up and John leaps out
to catch his sister in his arms.
Come into the light, Anne, that I may see your face, for I know you
are growing so handsome, said John, putting his arm around his
sister, and went laughing with her toward the house. Could he have
seen those blushes, in the darkness, because of his brotherly
praising of her!
How is mother? was his greeting to his mother, as he kissed her at
the foot of the steps. And, with her clinging to him on one side and
Anne on the other, he ascended the steps to the porch.
Where is father? asked John, not seeing him in the darkness,
standing just ahead of them. Oh, here he is! John exclaimed, as he
released himself from his mother and sister, and grasped his father's
rough hand. Come into the light and let me see you all, said John,
after the formalities of greeting had been performed, to the
satisfaction of all around.
The light brought forth a revelation for them all, as light does for
everything. The family now saw in John a new being in outward
appearance, but still the same loving son and brother. John now saw
his father and mother a little older, it appeared, perhaps, from
anxiety over his absence, or it may have been their strenuous toil
was showing plainer on them. He also saw in his sister, a simple
country maiden in the rusticity of young beauty.
Anne, will you let me kiss you again? asked John, as he stood in
admiration over her by the lamp, holding her hand, after his mother
and father had gone to complete the supper that had been almost
ready for hours waiting for him.
Anne tip-toed up to her brother, at his request, and put up her sweet
lips to his.
And how has my little sister been all these months? he asked,
patting her on the cheek.
Very well, John; I hope you have been a good boy, she answered.
Sister wouldn't expect anything else of me, would she? he asked,
kissing her again.
Oh, no, indeed, John, she replied, with wide eyes.
And have you been good? he asked.
Very, John, she responded.
No beaus yet, I hope? he asked, in his teasing way he always had
with her.
Why, no, John! and she blushed, not that she had a beau, but
through maiden coyness. You are the only one I've got, John.
Supper was then announced. James, who brought John from town,
came in after putting away the horses. And they all sat down in
happy reunion once more. For John was home.
What was the cause of your delay, John? asked Michael Winthrope,
the father.
Oh, by the way, father, I must tell you about it, answered John,
laughing heartily, and looking slyly at James, who was now dressed
in his best clothes, and presented as good an appearance as John
himself. I have two lady friends, who—
Why, John! exclaimed the mother, looking over her glasses.
Wait, mother; will you hear my story? said John, turning a happy
smile upon his mother. As I was going to say, I have two lady
friends stopping at the Summit House. One is the daughter of my
employer; the other her cousin. They saw us, as we were coming by,
and, of course, we saw them. Knowing them as I do, I could not
come on without the formality of greeting them. I introduced James
to them, mother; and what do you think?—
Now, John, you mustn't be too severe on me, said James,
modestly, for I don't pretend to your polish since you went away.
Never mind, James; you are a capital fellow, after all—but, mother,
James and sister here—turning to Anne—saw them the other day,
and they are—they think he and sister cannot be beaten as—roving
mountaineers—no, they didn't say that sister—turning to his sister
again—They did say they would come out to see us, if you will drive
in for them.
Law, me, John; we have no place here to entertain such grand
people. What do you mean? asked the mother, holding up her
spoon, and shaking it with a remonstrative motion as emphasis to
her thoughts.
Wait, mother; wait, and hear me out, before remonstrating any
further, said John, cheerfully. They wouldn't accept my invitation;
but they want sister to drive our old rig in for them, and extend the
invitation to spend the day with us. They thought it would be so
romantic to go on a lark with little sister—turning to her again with
such a fond look that Anne beamed under his countenance. Will
you go, sister? he asked.
Shall I, mother? asked Anne.
If John says so. What do you say, James? asked the mother.
That is up to John, responded James.
And father? asked the mother.
Whatever John says about it, replied the father.
Now, everything is up to you, sister, said John. Are you going?
Why, of course, brother, she answered. When?
Tomorrow, replied John.
So it was settled. That night, as John lay down to sleep in his old
bed, so pure and white, in a little room up stairs, he heard again,
above the screeching insects, the booming frogs, the wailing owls,
that old sweet song that carried him into the slumberous land of
nowhere—Good bye! Good bye!—as on so many nights before.
In the night, when the house was still, a gray-haired man, in night
clothes and carrying a lighted lamp, softly stole into John's room.
John lay with his face upturned, his eyes closed, and his lips parted
in a sleeping smile. The father stood over him a moment, bent down
and touched his lips to his son's brow. He is a good boy yet, he
said to himself, and softly stole away.
Anne was singing, as she went about her work, when John awoke in
the morning; and life was astir on every hand. The pigs were
squealing in their sty; the calves were bawling in their pens; ducks
were squawking in their pond; chickens were cackling in the barn
yard, and the sun was shining everywhere. John dressed himself and
descended the narrow stairway, with tousled head and open shirt
front. The mother was milking the cows, James was in the field, and
the father was in the barn. Anne was preparing breakfast.
Now, I may see you in the sunlight, sister, said John, as he
sauntered into the old-fashioned kitchen, and stood before her, with
folded arms, and half yawning yet from sleep, as she was spreading
the cloth upon the table. I didn't know I had such a dear little
sister, he said, as he put his arm about her and kissed her on the
lips.
You are such a fine brother, John, that I am almost in love with
you, she returned, as she lovingly left an imprint of a kiss on his
cheek; then leaving him to pursue her work.
Whose love would I want more than yours, Anne? he asked, in his
laughing manner.
Oh, I don't know, John; maybe you have a girl better than me to
love you, she replied.
I shall never place any one above my dear little sister, he said
thoughtfully; but—for no one can be your equal—except—one.
Is it one of those, John, whom I am going after this morning?
asked Anne, rattling the skillet on the stove. One of those whom
brother James and I met on the road a short time ago?
One of those, Anne—the rich man's only child—but I am too poor
for her, he answered, regretfully.
Is she as good as you, brother—and me? asked Anne, distributing
the plates around the table. She was innocent yet of the ways of the
world; but was feeling the first calling of young maidenhood.
She is very good, Anne; very good; but no better than you, he
returned, with the same uncertain cloud of perplexity that overcast
him so often before, still pervading him like a wave of blinding light
that comes to obscure the vision, at times, by reason of its intensity
of purpose.
She is very fine looking, John—both of them, John. Which one is it
you mean?
The smaller of the two.
Oh, the one with the bluest eyes, who took fright at us and ran.
That is just like Edith, to run.
I know I could love her, John.
You are anticipating, sister.
Why, who couldn't love you, John? asked Anne, looking up at him,
with some doubts as to what he meant.
That is a sister's opinion, child, said John.
A sister's opinion of her brother is better than any one else's. Maybe
she does love you, John. Did you ever ask her?
Maybe she does, said John, going toward the door and looking out
over the garden fence and into the fields, and dreamily into the
distance; but she is too rich to accept me, sister, he said, turning
about. How soon will breakfast be ready?
As soon as you wash your face, she answered.
John, heeding this hint, went to a basin on a bench in the yard,
which forcibly recalled the old days. How refreshing it was to him to
soap and souse his face into the cold water! And how inconveniently
unpleasant it was, after such soaping and sousing, to rush with
blinded eyes, and water trickling down the neck beneath the shirt
collar, to the kitchen and fumble, like a blind man, for the towel. But
it was home to John.
The rattling wheels and squeaking springs of the old rig could be
heard far up the road after Anne, dressed in a clean white frock and
wearing a pink sun-bonnet, had left the front gate on her mission,
guiding the old farm horses on their sure and steady gait.
Oh, John, John! If there is anything worth while, it is Edith's love,
the love that never dies. Blind man, as you are, and too considerate
of high state, and too proud of your own, you are the only one to
make her sweet soul happy. Bestir yourself, John, and come out of
the fog of self-consciousness that has kept you in obscurity so long
as to your final intentions. High state and low state are all the same
to the Cupid that has engaged you so relentlessly. High caste and
low caste do not count for him. Come and see the right, and see the
light. She is only mortal, you are only mortal. Money is nothing to
her; money is nothing to you. Love is all to her; love is all to you. It
is the man and woman, after all, that makes happiness supreme.
Come!
John has donned the garb of a mountaineer, which gives him a wild
romantic bearing. It is the garb of his former self. This is the one in
which Edith, secretly, wished to see him in, sometimes; and she shall
have her wish fulfilled. He wears a gray slouch hat; a check shirt,
opened in the front and turned up at the sleeves; a pair of blue
overalls, with bed-ticken suspenders, and high boots. Typical! He is
in his elements now, for his vacation period. He wishes Edith, when
she comes, to see him as he once was. It is not vanity; it is pride of
home. He wishes her to see life as it really is in a well directed loving
home, where toil is the simple reward of living. He wishes her to see
what life is to these people of the hills, how they thrive, and how
they bear their burdens. He wishes her to see all this in contrast to
her own life, and how love and duty can go on perpetually in a
humble home, as well as in a mansion.
Work must not cease on the farm, at this season, except in case of
sickness or death; visitors must make themselves at home during
the work hours, and be entertained only at meal time, or go their
way. The wheels of industry must go on there as noisily, ever
grinding, as the wheels of industry, ever grinding, in the city. But
there are rare occasions, even in both instances, when surcease is
had for a spell to meet the call of recreation. And this was one of
those rare occasions on the farm. For Edith and Star were coming,
and a half holiday was cut out for their especial pleasure. James
would cease his ploughing the corn at noon. The father would knock
off duty at eleven to help mother get up the feast, and then smoke
his pipe thereafter, perhaps, as his company. Thus it was planned.
After Anne had gone, John roamed about the place, speculating on
the tender association everything had for him. He went through the
house from garret to cellar, and beheld, with warming heart, how
dear the old things were, and how different they were to the things
in the mansion on the hill. Here was everything still that he knew in
his boyhood days, and he saw with a thrill of regret, but not
remorse, for it was still his home any time he wished to abide
therein. And no one could gainsay him that privilege.
But how would Edith look upon all this, and not be struck by the
simple evidence of his lowly origin? Ah, the comparison is too great,
he thought, as he went into the garden, where he first learned the
secrets of plant life; and then into the orchard, where he first saw
the wonderfulness of the fruiting time; and then into the old barn,
where was taught him the nature of domesticated animals; and then
into the fields, where he had ploughed and sowed and reaped. How
different from his life for the past year! How different!
Edith could see nothing of interest in such bucolic surroundings, he
thought. She would come, and see, and go, and want to forget him.
It is well, he thought, that she sees it now, and of her own coming.
CHAPTER XXXI.
IN CONCLUSION.
The rattling wheels and squeaking springs could be heard far up the
road. Anne was returning with her precious load. The horses trotted
down the hill, and came up with a rattle and a bang, and a sudden
stop, at the gate, with Edith at the lines, and Anne by her side, and
Star in the rear seat alone holding on tightly lest she should be
bumped out.
Wasn't that great! exclaimed Edith. I told you I could drive. This is
your home? to Anne.
This is our home, replied Anne, as she began to climb over the
wheel in getting out.
Isn't it a beautiful place, Star! said Edith. Just look at the roses
blooming! and all those flowers around the porch! Anne you have
such a romantic little home! Well, if here isn't our mountaineer, for a
surety! she exclaimed seeing John coming down the walk. How do
you do, Mr. Winthrope? I see you at last in your true character! How
will I ever get over this wheel?
If you will be real good, I will help you out—with your permission,
said John, as he approached, and offered up both hands for her to
fall into, as she liked. Sister, I will put away the horses, he said to
Anne, as he saw she was holding the head of one of the horses to
await the unloading. Remember, this is not an auto, he reminded
Edith, as she was cautiously putting out one little foot on the rim of
the wheel before her.
I would not have had so much fun if it had been an auto, returned
Edith, looking down into his upturned face, and laughing; and you
have such a fine sister, as she turned her head toward Anne.
Now, jump, said John, as he caught her beneath the arms, she
resting her hands on his shoulders in the momentary act before the
plunge. Down you come—there!—not so difficult after all, he said,
as she bounced on her feet on the ground. Now, Miss Barton, we
will see with what grace you can perform the feat.
You will have to be careful; I am so awkward, said Star, preparing
to go through the same acrobatic act.
Jump, Star! said Edith, seeing her hesitate.
Here I go, then! she said, laughing, as she took the downward
dive.
Oh, my! Miss Barton! exclaimed John, as she tumbled into his
arms, as a big rag doll might. Are you hurt? he asked, as he
released her from the necessary embracing he had to perform to
prevent her from falling to the ground.
Not hurt, but a little frightened, she answered, flushed from the
incident, and brushing out her skirts. I am all right.
Now, you ladies go into the house with my sister while I put the
horses away. Here, Anne, you take the ladies, and I will take the
horses, he said, leaving his guests, and taking up Anne's position in
charge of the team.
May I call you Anne? asked Edith, as Anne came up to her.
Yes, Miss Jarney, if you wish; we all use our first names up here,
responded Anne, opening the gate.
You may call me Edith, if you like, and this other lady will be our
guiding Star, said Edith, walking with her arm around Anne's
shoulders up the walk, her face aflush, her eyes beaming, and
seeing everything about, talking continually.
Star was not as talkative; but she was just as seeing as Edith was.
She, too, saw something in that home, more than its simplicity, to
attract her admiration. Was it the fragrant flowers and hopping birds
and cool freshness that she saw? or was it the peace of
contentment, indefinably overloading everything? or was it the
radical difference in the two homes, ideal though in both, and
irresistable in their contradictory elements, that caused her spirits to
rise above the normal point of enthusiasm? Or was it something
else? Star did not know.
Arriving at the door, arm in arm now, Anne passed straight through
the opening, holding on to Edith, and Star followed with
considerable wonderment at what she might encounter.
Take off your hats, ladies, said Anne, withdrawing her arm from
Edith's and standing off, with folded hands, looking at her, with
gladness all over her face.
No, you must say Edith and Star, said Edith, seeing how humbly
courteous Anne tried to be.
If you will have it that way; Edith and Star, take off your hats and
gloves. Now, I've said it, and I didn't mean to be so rude, said
Anne, abashed.
Anne, I will not love you if you do not call me Edith, said Edith,
scolding pleasantly, pulling off her gloves. I do not like too much
formality. I have had so much of that that it does my heart good to
get out where I can be free; and you will let me be free here, Anne,
won't you?
Oh, yes, Edith, answered Anne; and Star, too; you may be as free
as you please, Edith, for we are such common folk, so long as you
don't carry off my brother, John. She said this without the least
knowledge of its true meaning; not mentioning her brother James,
because she did not think of such things in his connection.
Edith blushed a deep crimson, as well as Star, at this extraordinary
remark on this the most extraordinary day that ever came into their
virtuous lives. Anne had a faint inkling of what these blushes meant,
for she continued: Now, Miss Edith, since you want to be free with
me, I will be just as free with you, and tell you that my brother l—l—
likes you.
Edith was not prepared for all this, and she had to turn her head in
the most confused state of feelings she ever fell into, all for wanting
to be tender and kind and loving toward this mountain girl, who was
not yet clearly or fully instructed in the propriety of fine speech.
Edith made no reply. She stood a moment, after facing Anne,
cogitating on what an appropriate reply should be.
Anne, she said directly, with a bright smile, will you let me kiss
you?
Edith held out her hands for Anne to come to her. Anne responded
to the ineffable sweetness of Edith to make amends for her offense,
which she realized she had committed against the fine lady opening
her heart to her.
I love you, Anne, said Edith, holding the dear little girl to her
breast; I love you; will you be my friend?
Why, of course, Edith, replied Anne; then she broke away, and was
gone, leaving Edith and Star alone.
They removed their hats and placed them on a table in a corner;
and then sat down on a lounge that graced the wall under a window
looking out on the porch, both in bewildered confusion and
agitation.
What do you think of his sister, Star? asked Edith.
She is a fine young child; no more than sixteen, perhaps,
responded Star, and so lively that I wish I could be here with her all
the time.
I wonder if they will let us take her with us to the city, Star, to be
our companion? said Edith. We would educate her, and teach her
music and everything.
The kitchen door opened, and Anne came in with her mother, who
wore a gingham apron as the badge of her position in the
household. Anne advanced with her mother and presented her, with
much dignity, as she conceived it, to Edith and Star.
This is my mother, Edith and Star, said Anne, as the two young
ladies arose and advanced to the middle of the room.
Edith presented her small white hand and took the coarse hand of
Mrs. Winthrope. I am so glad to know you, Mrs. Winthrope, said
Edith, as she kissed the aging woman, whose age was more from
toil than years. Star having performed the same act of greeting,
including the osculatory part thereof, Mrs. Winthrope held up her
hands in an astonished attitude, and said: Well, well; I declare; and
you two are John's friends, are you? I hope you are well.
We are well; thank you, they both repeated.
Just make yourselves at home, ladies, with what we have here to
entertain you, while I finish the dinner. Be seated by the window
where it is cool, for I know you must be warm after the long drive in
the sun.
Thank you, Mrs. Winthrope, they answered; and were seated.
Then the mother and daughter disappeared again; and Anne
returned, after a little, with her father, who was in the clothes of a
ploughman. Mr. Winthrope was a tall man, a little stooped, with chin
whiskers, and gray blue eyes; and, while rough looking, was not
boorish. Anne escorted him to the young ladies, who arose at his
approach. He greeted them so warmly and effusively that, for some
time thereafter, they felt the grip of his vise-like hand on theirs.
Just make yourselves at home, as you like, he said. We are
farmers, you know, and if you find any pleasure here it is yours. We
will be through our work by noon, then mother and me will find time
to talk, if you care to be bothered with us at all. Then he left them.
Are they not very good people, said Edith to Star, after the father
had gone out with Anne.
I like them very much, opined Star; they are so pleasant.
John came in shortly, and sat down on a split-bottom chair in the
middle of the room.
I hope you ladies are enjoying yourselves, he said, toying with his
hat he held in his hands.
I could not enjoy myself any more if it were my own home,
answered Edith. Why, you have such a delightful home, Mr.
Winthrope, and such nice parents, and such a sweet little sister, with
whom I have already fallen in love. I am regretting that I have not
known them longer.
That's a beautiful encomium, Miss Jarney, on my native heath; but
you know that you and your father and mother have been saying so
many nice things about me that I am uncertain whether you mean it
or not. John said this while glancing at the floor, picturing intangible
things in the woof and warp of the old rag carpet.
I mean every word of it. Mr. Winthrope, replied Edith, also
picturing similar intangible things in the old rag carpet as easily as if
she had pictured them out of the delicate flowers in the velvet rug in
her boudoir.
Star sat gazing out the window, looking at some intangible shapes
that made up the green hills beyond. Their conversation thereafter
was not of the progressive kind, nor was it brilliant. Both became
secretively reserved, and time was hanging monstrously on their
hands. John was dreaming. Edith was dreaming. Both were
uncertain as to what to say or how to act, so discomposed were
they. But James came in soon to break the spell. He was such a
strapping fine fellow, fine in texture, and as good as he was fine.
I knew very well who you were the day we met you on the road,
said Edith, shaking his hand.
Had I known all this then. I should have bundled you into my
wagon and brought you right home, he replied, with considerable
liveliness in his speech. But not knowing you, of course, I could do
nothing else but drive on. However, the pleasure of meeting you
now, here, is certainly beyond my mean ability to express.
We might have come, said Edith, with a ringing laugh. Would it
not have been odd, and so romantic, just to have come right along
with you?
I am sure I would have enjoyed it, he said; and by this time I
would have had you converted into farm hands.
And wearing calico dresses, said Edith.
And brogan shoes, said Star, remembering how she used to wear
such articles of clothing.
Yes; it is certain one can't work here and wear silks, responded
James. Then looking down at himself, he was reminded that he was
still in his rough garb. If you ladies will excuse me, I will make
myself more presentable for appearance at dinner.
He then left them; and when he returned, wearing his best Sunday
suit, all brushed and fitting him very well, he was equally as stylish
looking as his brother John in his best.
When dinner was announced (dinner is at the noon hour with the
mountain people), John lead Edith and James lead Star to the
bounteously laden dining table set in the kitchen. It might have been
noticed by Edith, had she not been otherwise engaged, that Star
was more aflush than ever before, just at this period of her proud
behavior. James talked to her very entertainingly during the progress
of the long meal, and she was very cordial toward him. She laughed
and talked with great glee, being amused at his ready wit and simple
manner. But John and Edith were distressingly quiet, for some
reason, listening mostly to the conversation of the others. Little
Anne, at times, cast side glances at Edith and John, that might have
been suggestive of their meaning.
Would you ladies like to try your hand at fishing? asked James,
who was warming up for any kind of sport that might be introduced
for the entertainment of their guests.
Oh, delighted! cried Edith. I never fished in my life.
Nor I, said Star; will you teach me how, Mr. Winthrope?
(meaning James.)
I thought we old people were to entertain you this afternoon, said
the father.
We will return in time for that, father, James said, rising. John, I'll
get the bait; you get the tackle, and we will teach these young ladies
how to fish.
Be careful, admonished the mother; don't fall into the stream.
Anne, are you not going? asked Edith, as she rose with the others.
I must remain here and help mother; and will await your return,
said Anne, as she came around to Edith and put her arm around her.
You are a dutiful child, Anne, said Edith, kissing Anne thereat.
Edith and Star were both dressed in gray serge skirts, white silk
waists and sailor hats. While John and James got ready the ladies
prepared themselves for the event of their lives. They were in
waiting on the porch when John and James came up, with plenty of
bait and tackle in their hands. So off they went immediately: John
and Edith together, and James and Star, the father and mother and
Anne standing on the porch watching their going.
They struck the mountain stream a mile below the house, and the
two ladies fell to the sport with the spirited joy of youth. The pair
became separated after awhile, as all such sportsmen and women
often do. One pair went up the stream, and one went down, after
the elusive fish.
John and Edith came to a pool, after wandering through the bypaths
of the forest, far below the other two. Around the pool the trees
hung low, and the shades were heavy, and the water was dark and
deep. By the pool they sat down on a log, and cast their lines to
await the fisherman's luck.
Isn't this delightful, said Edith, holding her pole with inexperienced
hands over the water.
Fish won't bite, if we talk too loud, said John, critically, but
pleasantly, as he sat below her on the log, slanting into the stream.
She became quiet; he became quiet. The water trickled over the
miniature falls at the head of the pool in such an isolated tone of
ripling that it made wild sweet music for Edith. The trees above
them sighed in a low crescendo, and the birds were singing
everywhere. The sun rays glinted through the boughs of the trees,
and danced upon the water, making a fretted work of moving lights
and shadows. Water riders ran back and forth, as if playing with the
sunlight let into their darksome place of habitation, and fish jumped
up now and then, as if to taunt the patient anglers. And Edith and
John sat quietly—waiting, waiting.
Then a fish came along, and caught the bait of Edith's hook; and
went tearing away in its struggle for liberty. So sudden was the
unlooked for happening that Edith lost her balance, by reason of the
gyrations of the fish, which she pluckily attempted to land, and
plunged into the water. It came so sudden that John, who was at
that moment meditating on the catch he would make, and on how
he would boast over the rest of them when he got home, did not
notice Edith's danger till it was too late. Without a moment's
reflection, however, he dropped his pole and leaped into the pool
after her. Edith came up with a scared look, beating the water with
her hands, as he went down by her side. He seized her around the
waist, and swam for the shore, and when they reached the shore,
she laughed, being reminded of another watery occasion; but still
permitting him to hold her in his arms.
I am a pretty sight now, she said, still remaining in his arms on the
sloping bank, up which he was assisting her.
It seems we have an affinity for water, Edith, he said, reaching the
top of the slope, still holding her in his arms. May I call you Edith,
now? he said, clasping her wet form to his.
She laid her dripping head upon his breast, one arm stole around his
neck, and she looked up into his face. Yes, she answered. And he
kissed her for the first time on those sweet lips that had so often
uttered his name before; but now they said, John. And still he held
her in his arms.
Edith, will you be my wife, some day? he asked, looking with the
fervor of an impassioned youth into her dear blue eyes, and pushing
back the wet hair from her white temples.
Why, yes; dear John, I love you, as I always have since the first
time I met you, she answered, with such an appealing tone for that
old responsive note in him that he pressed her closer to his bosom.
And the longing in her soul was recompensed in that moment of her
eternal bliss.
You know me, Edith; you know my people now; you know what I
am. Are you satisfied? he asked, still harboring that same old
uncertain doubt that always perplexed him so; and still holding her
in his arms.
I know you to be a noble young man, dear John. I know your
people now, and I love them. I am satisfied, she whispered. You
are all that I care for, John—all. I love you, I love you, and she
kissed him.
I am satisfied, dear Edith. It was not an hallucination, after all, was
it dear? he answered.
Thus, plighting their troth, they went hand in hand up the shady
wood path as happy as two young children over their mishap.
Life is beautiful, and life is sweet; but what would life be to those
young people without the love between them?
Coming to the path where they left James and Star, on parting, they
found them sitting there, waiting. When Star saw them coming, she
instinctively comprehended, and knew that the crisis was over
between Edith and John. Star was happy herself over a secret of her
own. And together they returned home.
John proudly, on arriving in the old-fashioned sitting room,
announced to his parents and sister his intended bride, and told
them they could take her now, in her bedraggled condition, for their
daughter and sister.
Now, will you go with me, Anne, to the city? asked Edith, after she
had been costumed in some of Anne's clothing that fit her narrowly.
I will educate you, and have you for my own dear sister, hugging
Anne to her breast.
Some day, Edith; some day, answered Anne, uncertain in her mind.
When will you come after me?
When I am your real sister, Anne, replied Edith, stroking Anne's
golden hair, and then she looked up at Anne's mother, who could not
fully realize what it meant for her future life. You will let her go,
Mrs. Winthrope?
I may some day, answered the good old mother.
I wouldn't want to leave papa and mamma yet, Edith, said Anne,
with a happy smile.
You shall return to see them often; so shall I, said Edith.
I will go some time, Edith, after you are my sister, answered the
coy Anne.
That will be soon, dear sister, said Edith, folding Anne in her arms
and crying with excessive happiness. You may have two sisters
soon, Anne—Star, I am sure, will be your other sister. Star blushed,
and therefore told her tale.
The family stood on the porch that evening, and listened to the
receding sound of the rattling wheels and squeaking springs of the
rig, as John drove away with his precious load. God bless them,
said the good old father; and Anne cried when the last hoof beat
came down the shadowy roadway. In silence they sat in darkness till
they heard the clanking hoofs returning. The mother went in and
lighted the lamp; the father went in, the sister went in, the two
brothers went in; and they all knelt down in family worship.
As the curtain of the passing night drew thickly over the mountains,
and the lights in the corridor of the Summit House became dim, and
their room dark, Edith knelt down by her bed and offered up her
prayers to the Good Lord, who had brought her safely through her
troubles; and Star, kneeling by her side, said, Amen.
A few days thereafter, after Edith had written her parents of the
happy culmination of her fishing trip, the following message was
received by her from them: Congratulations.
So endeth the story of Edith and John.
*** END OF THE PROJECT GUTENBERG EBOOK EDITH AND JOHN:
A STORY OF PITTSBURGH ***
Updated editions will replace the previous one—the old editions will
be renamed.
Creating the works from print editions not protected by U.S.
copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.
START: FULL LICENSE
THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
To protect the Project Gutenberg™ mission of promoting the free
distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.
Section 1. General Terms of Use and
Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.
1.B. “Project Gutenberg” is a registered trademark. It may only be
used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

Computer Programming With C Kunal Pimparkhede

  • 1.
    Computer Programming WithC Kunal Pimparkhede download https://ebookbell.com/product/computer-programming-with-c-kunal- pimparkhede-11371658 Explore and download more ebooks at ebookbell.com
  • 2.
    Here are somerecommended products that we believe you will be interested in. You can click the link to download. Optimized Computer Programming With C10 And Net 6 Dive Into Advanced Strategies For Crafting Lightningfast Resilient Applications With C 100 And Net 6 Anderson https://ebookbell.com/product/optimized-computer-programming- with-c10-and-net-6-dive-into-advanced-strategies-for-crafting- lightningfast-resilient-applications-with-c-100-and- net-6-anderson-89194732 Fundamentals Of Computer Programming With C Svetlin Nakov https://ebookbell.com/product/fundamentals-of-computer-programming- with-c-svetlin-nakov-38512526 Computer Graphics Programming In Opengl With C 2nd Edition V Scott Gordon John Clevenger https://ebookbell.com/product/computer-graphics-programming-in-opengl- with-c-2nd-edition-v-scott-gordon-john-clevenger-30972724 Coding For Absolute Beginners Master The Basics Of Computer Programming With Python Java Sql C C C Html And Css Andrew Warner https://ebookbell.com/product/coding-for-absolute-beginners-master- the-basics-of-computer-programming-with-python-java-sql-c-c-c-html- and-css-andrew-warner-34095186
  • 3.
    C And ComputerHacking Mobile Hacking 3 Bundle Manuscript Beginners Guide To Learn C Programming With Computer Hacking And Mobile Hacking Cody https://ebookbell.com/product/c-and-computer-hacking-mobile- hacking-3-bundle-manuscript-beginners-guide-to-learn-c-programming- with-computer-hacking-and-mobile-hacking-cody-11124248 An Introduction To Objectoriented Programming In C With Applications In Computer Graphics 2nd Edition Graham M Seed Beng https://ebookbell.com/product/an-introduction-to-objectoriented- programming-in-c-with-applications-in-computer-graphics-2nd-edition- graham-m-seed-beng-4198618 Opencv 4 Computer Vision Application Programming Cookbook Build Complex Computer Vision Applications With Opencv And C 4th Edition David Milln Escriv Robert Laganiere https://ebookbell.com/product/opencv-4-computer-vision-application- programming-cookbook-build-complex-computer-vision-applications-with- opencv-and-c-4th-edition-david-milln-escriv-robert-laganiere-11132666 Computer Programming With Matlab J Michael Fitzpatrick Kos Ldeczi https://ebookbell.com/product/computer-programming-with-matlab-j- michael-fitzpatrick-kos-ldeczi-5415618 Handbook Of Computer Programming With Python Dimitrios Xanthidis https://ebookbell.com/product/handbook-of-computer-programming-with- python-dimitrios-xanthidis-46634262
  • 7.
    Computer Programming withC++ 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.
  • 9.
    Computer Programming withC++ Kunal Pimparkhede
  • 10.
    University Printing House,Cambridge CB2 8BS, United Kingdom One Liberty Plaza, 20th Floor, New York, NY 10006, USA 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.
  • 11.
    Contents Preface xi Acknowledgements xiii PART-IStructured Programming 1. Introduction 3 1.1 Overview 3 1.2 Computer System Architecture 8 1.3 C/C++ Development Environment 13 1.4 Evolution of Programming Languages 17 2. Fundamentals 23 2.1 Overview 23 2.2 The First C/C++ Program 23 2.3 Writing Comments 27 2.4 Constants or Literals 28 2.5 Variables and Data Types 31 2.6 printf() Statement (Supported by both C and C++) 38 2.7 C++ Style of Printing the Value on Computer Screen 49 2.8 endl Modifier (Supported by C++ not by C) 51 2.9 Accepting User Input Using scanf() Function (Supported by both C and C++) 52 2.10 cin Object in C++ (Only in C++ not in C) 58 2.11 Manipulator setw 63 2.12 Defining Constants using #define—A Pre-processor Directive 65 2.13 Character Specific Input/Output 66 3. Operators and Type Casting 71 3.1 Overview 71 3.2 Arithmetic Operators 77 3.3 Relational Operators 82
  • 12.
    vi ✦ Contents 3.4Shorthand Operators 84 3.5 Bitwise Operators in C/C++ 85 3.6 Increment/Decrement Operators 89 3.7 Order of Operations Evaluated by the printf() Statement 94 3.8 Implicit Type Casting/System Casting 97 3.9 Explicit Type Casting 97 3.10 sizeof Operator in C/C++ 101 3.11 Scope Resolution Operator(::)| Only in C++ not in C 102 4. Decision Making Control Statements 110 4.1 Overview 110 4.2 if else Statement 110 4.3 Logical Operators 123 4.4 else if Ladder 125 4.5 switch Statement 132 4.6 Ternary Operator/Conditional Operator 135 4.7 goto Statement 139 5. Iterative Control Statements: Loops 146 5.1 Introduction 146 5.2 while Loop in C/C++ 149 5.3 for Loop in C/C++ 164 5.4 do..while Loop 180 5.5 break and continue Statements 183 5.6 Infinite Loops 190 5.7 Comma Operator with for Loop 192 5.8 Creating Variables Local to Loops (Possible in C++ but not in C) 192 5.9 Empty Loops 193 6. Arrays 216 6.1 Overview 216 6.2 Creating an Array 218 6.3 Array of Characters 238 6.4 2D Arrays 252 6.5 2D Array of Characters 261 6.6 String-Specific Input and Output Operations: gets()/puts() 264 7. Functions 299 7.1 Overview 299 7.2 Creating Functions 303 7.3 Local Variables of the Function 309 7.4 Functions with Arguments 313 7.5 Functions with Return Values 318
  • 13.
    Contents ✦ vii 7.6 PassingArray as an Argument to the Function 325 7.7 Recursion 329 7.8 Activation frames: How Function Calls and Returns are Internally Handled in C/C++ 337 7.9 Storage Classes in C/C++ 342 7.10 Inline Functions in C/C++ 345 7.11 Function with Default Arguments (Only in C++ not in C) 347 7.12 Command Line Arguments 349 7.13 Some Built-in Functions 353 8. Pointers 371 8.1 Overview 371 8.2 Creating Pointers 377 8.3 Data Type of Pointers 380 8.4 Types of Function Calls 383 8.5 Arithmetic Operations with Pointers 393 8.6 Accessing Array Elements using a Pointer 400 8.7 Initialization of an Array: Revisited 407 8.8 Self-addressability of Character Variables 413 8.9 Array of Pointers 415 8.10 Pointer to a Pointer 418 8.11 Pointers and 2D Arrays 420 8.12 void Pointers 426 8.13 Pointer to a Function 427 8.14 Reference Variables (Only Available in C++ not in C) 429 8.15 Lvalue and Rvalue 433 9. Structures and Unions 445 9.1 Overview 445 9.2 Creating Structures 446 9.3 Array of Structure Objects 457 9.4 Nesting of Structures 469 9.5 Structures and Pointers 472 9.6 Accessing Array of Objects using a Pointer 476 9.7 Passing Object as an Argument to a Function 479 9.8 Difference between Structure and Union 481 10. Dynamic Memory Allocation in C++ 497 10.1 Overview 497 10.2 Dynamic Memory Management in C++ 499 10.3 Linked List 509 10.4 delete Keyword in C++ 527
  • 14.
    viii ✦ Contents PART-IIObject Oriented Programming 11. Classes and Objects 533 11.1 Overview 533 11.2 Creating Classes 537 11.3 Creating Objects of a Class 538 11.4 Access Specifiers in C++ 542 11.5 Data Hiding and Encapsulation 545 11.6 Employee Management System: An Example 548 11.7 Account Management System: An Example 554 11.8 Calculating Slope of the Line: An Example 559 11.9 Addition of Complex Numbers: An Example 563 11.10 Addition of Points in Cartesian Coordinate System: An Example 567 11.11 Array of Objects 569 11.12 Employee Management System: Revisited 571 11.13 friend Functions 573 11.14 Addition of Point Objects using friend Function: An Example 574 11.15 Pointer to Objects 580 11.16 Binding of Pointers with Individual Members of the Class 584 11.17 this Pointer 589 11.18 Resolving Ambiguity using this Pointer 592 11.19 Cloning Objects using this Pointer: An Example 594 11.20 Dynamic Memory Allocation of Objects 596 11.21 Linked List to Maintain Data about Employees 600 11.22 Composition and Aggregation between Classes 609 11.23 Converting the Relationship to Aggregation 615 11.24 Defining the Member Functions Outside Class using Scope Resolution Operator 620 11.25 Function Overloading and Compile Time Binding 622 11.26 Local Classes 625 11.27 Nested Classes 627 12. Constructors and Destructors 652 12.1 Overview 652 12.2 Creating Constructors 654 12.3 Constructor Overloading 659 12.4 Program to Perform Addition of Point Objects using Constructors: An Example 665 12.5 Constructor with Default Arguments 668 12.6 Cloning Objects using Constructor/Copy Constructor 669 12.7 Allocating Dynamic Memory Inside Constructor 674 12.8 Destructors in C++ 680 12.9 Static Members and Static Member Functions 684
  • 15.
    Contents ✦ ix 13.Operator Overloading 699 13.1 Overview 699 13.2 Overloading Operators 700 13.3 Overloading One’s Complement ~ and Minus - Operators: An Example 703 13.4 Overloading Binary Operators Plus + and Minus - 707 13.5 Overloading Shorthand Operators: An Example 713 13.6 Overloading Relational Operators: An Example 716 13.7 Overloading Increment/Decrement Operators: An Example 720 13.8 Function Object: Overloading Function Call Operator () 726 13.9 Overloading Subscript Operator [] 728 13.10 Overloading Assignment Operator = 731 13.11 Overloading Type Cast Operator 735 13.12 Conversion of One User-defined Type to Another 738 13.13 Creating Global Operator Functions 741 13.14 Overloading Insertion and Extraction Operator for Student Objects: An Example 745 13.15 Overloading Operators new and delete 749 13.16 Overloading operator - 754 14. Inheritance 770 14.1 Overview 770 14.2 Creating a Parent–Child Relationship between Classes 773 14.3 Access Specifiers in C++: Revisited 776 14.4 Types of Inheritance 788 14.5 IS-A and HAS-A Relationship: An Example 793 14.6 Multi-level Inheritance: Calculator 801 14.7 Resolving Ambiguity in Multiple Inheritance 808 14.8 Virtual Base Class 813 14.9 Function Overriding 821 14.10 Pointers and Inheritance 824 14.11 Overriding a Function with Different Return Type 831 14.12 Virtual Functions and Runtime Polymorphism 833 14.13 Virtual Tables 843 14.14 Pure Virtual Functions and Abstract Classes 851 14.15 static_cast and dynamic_cast 854 14.16 Constructors and Inheritance 858 14.17 Working of Constructors with Multiple Inheritance 863 14.18 Destructors and Inheritance 864 14.19 Virtual Destructors 867 15. Input and Output Streams in C++ 881 15.1 Overview 881 15.2 Types of I/O Streams 882
  • 16.
    x ✦ Contents 15.3Console Input and Output in C++ 883 15.4 Formatted v/s Unformatted I/O Operations 884 15.5 Formatting the Output using Member Functions of Class ios 885 15.6 Formatted I/O using ios Flags 889 15.7 Formatted I/O using Manipulators 893 15.8 Creating your Own Manipulator 894 15.9 Passing Arguments to the Custom Manipulator 895 15.10 Character by Character Unformatted I/O Operations 897 15.11 Line by Line Unformatted I/O Operations 900 15.12 File I/O Operations 902 15.13 Performing Operations on File 904 15.14 Closing the File 914 15.15 File Pointer Manipulation Functions 915 16. Templates in C++ 928 16.1 Overview 928 16.2 Function Templates 928 16.3 Class Templates 933 16.4 Standard Template Library: One of the Applications of Class Templates 937 16.5 Implementation of Stack using Linked List: An Example 959 16.6 Queue using List 964 17. Exception Handling in C++ 969 17.1 Overview 969 17.2 Exception Handler in C++ 970 17.3 throw Keyword 971 17.4 Examples 971 17.5 Order of writing Catch Blocks 981 17.6 Catching and Throwing User-defined Objects 982 17.7 Program Specifying Throw List 986 17.8 C++ Built-in Exception Classes 988 ASCII Values 994 List of Keywords in C++ 998 Software Development Life Cycle 999 Bibliography 1002
  • 17.
    Preface A computer programis 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 9 Error Finding Exercise 9 9 Solved Problems
  • 18.
    xii ✦ Preface 9 9Objective Questions 9 9 Review Questions Chapter Organization This book comprises 17 chapters. Chapter 1 gives an overview of computer organization and architecture. It also explains the C/C++ development environment. Chapters 2 to 5 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.  Does this book also explain the underlying systems which are involved in the execution of a computer program ? ? I have put my best efforts to make this book as illustrative and interactive as possible. Any suggestions to further improve this book are always welcome. You can write to me at kunalp84@rediffmail.com.
  • 19.
    Acknowledgements Contribution and supportof 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.
  • 21.
  • 23.
    Introduction 1.1 Overview Aprogram isa 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 Chapter
  • 24.
    4 ✦ ComputerProgramming with C++ 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 2 Binary representation of 15 Byte 3 Binary representation of 25 10000011 00001111 00011001 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, 25 The 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
  • 25.
    Introduction ✦ 5 friendlywords 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 + 25 Note 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. 15 + 25 ADD 15, 25 Input Instruction written in high level language Compiler Output Instruction converted to 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 ATT 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’. ADD 15, 25 Input Instruction written in assembly language Assembler Output Instruction converted to machine language 10000011 00001111 00011001 Figure 1.2: Assembler
  • 26.
    6 ✦ ComputerProgramming with C++ 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.
  • 27.
    Introduction ✦ 7 oftengets 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 ......... Machine language C/C++ Program Operating System Figure 1.4: Layered architecture of application program, system programs, and computer hardware
  • 28.
    8 ✦ ComputerProgramming with C++ 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: Processing unit Storage unit Input Output ALU Control unit Primary memory 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
  • 29.
    Introduction ✦ 9 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. I1 d1; I2 d2; I3 d3; I4 d4; . . . . In dn; Sequential execution CPU executes the instructions in the file in a sequence from top to bottom. This is called as sequential execution. Computer program 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 Asthehardwareofacomputersystemisultimatelybuiltupofelectronicandsemiconductor 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.
  • 30.
    10 ✦ ComputerProgramming with C++ 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. Source Code A program written in a high level language System programs Machine Code The high level language is converted into a language of 0’s and 1’s Figure 1.7: Translation of high level language to low level language
  • 31.
    Introduction ✦ 11 understandthe 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 of the program. 1.2.4 Storage unit The storage unit comprises of the memory devices, which are present in the computer system where instructions and data are stored. The area of the memory where instructions of the program are stored is called as a ‘code segment’ whereas the area of the memory where the data required for the program is stored is called as a ‘data segment’. These memory segments are managed by the memory management unit (MMU) of the operating system in the primary memory of the computer system. In general, the memory units of a computer system are categorized as follows: 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.
  • 32.
    12 ✦ ComputerProgramming with C++ 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 Processor Operating system 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 File File 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 Primary Memory Secondary Memory File in secondary memory is stale New version of the file . . . Processor Operating system File** File Write command CPU performs a “write” operation on the file Figure 1.10: Uncommitted writes done to the file
  • 33.
    Introduction ✦ 13 Whenwe 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: 1. Editor 2. Pre-processor 3. Compiler 4. Linker 5. Loader 1.3.1 Editor Editor provides an integrated development environment (IDE) to create and develop a C/ C++ program. An editor is a system program that provides the programmer with multiple Primary Memory Secondary Memory New version of the file . . . Processor Operating system File** File** 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
  • 34.
    14 ✦ ComputerProgramming with C++ 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 screen 1.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.
  • 35.
    Introduction ✦ 15 1.3.3Compiler 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 Step 1 The preprocessor substitutes all the macro names with the macro definition and create a new file on disk. The file generated by the preprocessor will not have any macros in it. Step 2 The compiler converts the high level language into the object code thereby generating a object file on the disk. 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 set as p1.obj File without macros Step 3 The linker converts the object code into the executable code by resolving all the external symbol references which are made by the programmer. 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 File Pre-processor Compiler Linker Loader File File File Primary Memory . . . File Processor Disk Figure 1.13: C/C++ development environment
  • 36.
    16 ✦ ComputerProgramming with C++ 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. What is Lexical analysis? ? 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: z = x+y; This statement has 6 different tokens z , =, x, +, y and ;. Splitting of this statement into different tokens is as shown below. Individual tokens in the C++ statement z = x + y ; Assignment Result The symbol “+” is used to perform addition First operand Second operand Every statement in C++ ends with a semicolon 
  • 37.
    Introduction ✦ 17 1.3.4Linker 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.
  • 38.
    18 ✦ ComputerProgramming with C++ 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.Astructured 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. call call call call return return return B D C E A Figure 1.14: Structured programming
  • 39.
    Introduction ✦ 19 2.Function calls are always handled sequentially. This means that, if function Acalls 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 → E The 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 mainte­ nance and support of the code becomes difficult as the size of the code increases. Hence, in many cases, ‘object-oriented programming’ is preferred over structured programming 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
  • 40.
    20 ✦ ComputerProgramming with C++ 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. Student roll_no; name; marks; give_exam(); print_result(); save_student(); name; specialization; salary; save_professor(); teach(); evaluate_student(); Professor name; budget; assets; save_data(); calculate_annual_budget(); Department title; duration; fees; save_data(); print_data(); Course 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
  • 41.
    Introduction ✦ 21 thesefeatures 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 1. Which of the following is done before compilation? (a) Translation of source code to object code (b) Linking (c) Loading (d) Macro substitution (e) None of the mentioned options. 2. Which of the following statements are true? (a) Compiler generates output of the program as the result of the compilation process (b) Linker transfers the machine code from secondary memory to primary memory (c) Loader transfers the machine code from primary memory to secondary memory (d) Pre-processing happens after the code is compiled (e) None of the above statements are true 3. Assembler generates _____ language as its output. (a) Language of mnemonics (b) High-level language (c) Machine language (d) Middle-level language 4. Which of the following is not the function of compiler? (a) Syntax analysis (b) Lexical analysis (c) Semantic analysis (d) Code generation (e) Resolving external symbol references
  • 42.
    22 ✦ ComputerProgramming with C++ 5. Structured programming is a way to organize program as collection of ________. (a) Classes (b) Objects (c) Functions (d) Structures 6. Wrapping of data and related functions together is called as (a) Data hiding (b) Encapsulation (c) Inheritance (d) None of the mentioned options. 7. Inheritance facilitates (a) Data hiding (b) Security to the code (c) Reusability of the code (d) Modular programming 8. Which of the following statements is true (a) C/C++ programs are hardware dependent (b) C/C++ programs are operating system independent (c) C/C++ programs are operating system dependent and hence they cannot execute cross platforms (d) C/C++ programs are hardware and processor independent 9. Object-oriented features are supported by: (a) Both C and C++ (b) Only by C (c) Only by C++ (d) Neither by C nor by C++ 10. Opcode represents (a) Operations performed by the instruction (b) Data used by instruction (c) Both A and B (d) None of the above 11. Which of the following statements is true (a) Calling function may complete before called function (b) Called function may complete before calling function (c) Called function always completes before calling function (d) Called function and calling function completes at the same time (e) Function calls are resolved sequentially 12. Program written in which language is easy to maintain? (a) Machine language (b) Assembly language (c) High level language Review Questions 1. What is the difference between the structured programming and the object-oriented programming? 2. Write a short note on the functions performed by the compiler. 3. Explain the C/C++ development environment in detail. Give the functions of each of the system programs involved in the translation of C/C++ into a machine code. 4. Explain the difference between system programs and application programs with appropriate examples of each type. 5. Write a short note on object-oriented programming paradigm. List different properties of object-oriented programming in C++. 6. Explain the difference between compile time and run time of the program?
  • 43.
    Fundamentals 2.1 Overview C++ isan 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 Chapter
  • 44.
    24 ✦ ComputerProgramming with C++ 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 a function named as main() Set of instructions in the program Start of main() function End of main() function 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. #includestdio.h void main() { printf(I like Computer Programming); } Every statement in C/C++ 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, #includestdio.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.
  • 45.
    Fundamentals ✦ 25 Asstated before, execution of any program always starts from main() function. Given that this program has only one statement in the main() function (which is the printf() statement), the output of the program is shown below. I like Computer Programming Note: Following is applicable to C++ and not to C The program shown in Figure 2.2 executes in C as well as C++. This is because the printf() function is supported by both the languages. Along with support to printf() statement, C++ supports another way to print a message on the computer screen. cout is a built-in object available in C++ but not in C, which is used to stream messages on an output device. The program written in Figure 2.3 shows the usage of cout object to print the message on the computer screen. #includeiostream.h void main() { coutI like Computer Programming; } Every statement in C++ ends with semicolon cout 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 iostream.h into the C++ program Figure 2.3: Source code to print a message on the computer screen The statement coutI like Computer Programming; isusedtoprintamessageI like Computer Programmingonthecomputerscreen.Note that every statement ends with a semicolon. The operator is called as an insertion operator, which actually inserts a text message on the computer screen. We have also explained in Chapter 4 of this text book that the operator is also used as ‘left shift operator’, which can be used to shift the bits of a binary number in the left direction. However, in this case, we have used the operator , which acts as an insertion operator and prints a message on the screen because it is internally overloaded by C++ in one of the built-in classes which is named as ostream. The class ostream is fully defined inside the header file iostream.h. Also, cout is an object of class ostream, which is created inside the file iostream.h. Therefore, we have written the first statement of the C++ program as, #includeiostream.h
  • 46.
    26 ✦ ComputerProgramming with C++ Notes The program given in Figure 2.2 uses printf() statement to print a message on the computer screen.The printf() function is declared in header file stdio.h which is included in the program.The program using printf() works with C as well as C++ because the header file stdio.h and printf() function are supported by both the languages. However, the program using cout shown in Figure 2.3 works with C++ but not with C.This is because the object cout and header file iostream.h are only supported by C++ and not by C.This clearly means that C++ supports streaming output operations whereas C does not.We will learn more about streams supported by C++ in Chapter 15. The statement includes the contents of the header file iostream.h into the program, so as to facilitate the programmer to use the built-in object of class ostream, which is named as cout directly in the code. Remember, #include is a pre-processor directive, which is used to include the contents of a particular header file into the C++ program before the compilation of the code starts. This ensures that the complete definition of the class ostream and the insertion operator is included in the program before the compilation. Details about classes and objects are discussed in Chapter 11 of this text book. The only point we must understand at this stage is that the statement coutI like Computer Programming; is used to print a message as I like Computer Programming on the computer screen as shown in Figure 2.4. And we must include the contents of header file iostream.h before making use of cout in our program. cout The object cout invokes an insertion operator function Object of class ostream I like Computer Programming I like Computer Programming Message to be printed The message to be printed is passed as an argument to the insertion operator function The insertion operator function is present in class ostream. The complete definiton of the class ostream is present in the header file iostream.h Output on the screen The insertion operator inserts a message on the computer screen Figure 2.4: Usage of cout C++ supports streaming outputs, which are not supported by C. In general, the word stream refers to the flow of data in the computer system. The ‘output stream’ of C++ allows the programmer to perform a ‘write’ operation on the output devices such as ‘screen’, ‘file’, and ‘disk’.Theheaderfileiostream.hdefinesthenecessaryclassesandfunctionstosupportthe streaming input and output. We will discuss the input streams of C++ in the later sections of this chapter.As we have written the cout instruction inside the main function, the processor will now execute the instruction after translating the instruction into a machine code, thereby printing a message specified on the computer screen as seen in the output of the program.
  • 47.
    Fundamentals ✦ 27 CanI write C/C++ programs in upper case? ? The answer is NO; because C/C++ is a case sensitive language. This means that, upper case and lower case characters have different meaning for the language. For example, printf() and PRINTF() will be considered as two different identifiers by the compiler. stdio.h declares the function printf() in lower case and hence compiler will not be able to recognize a symbol PRINTF(). Therefore, we cannot just write the complete C/C++ program in the upper case, rather we have to preserve the syntax of the language along with the case. Syntax of C/C++ is such that most of the built-in keywords and reserved words are in lower case. There are still some built-in macros which are to be written in upper case.  2.3 Writing Comments Comment is a part of the code, which is ignored by the compiler. However, programmers may still write comments in the program to give documentation for the complex logic implemented using a particular piece of code. Although, comments do not contribute in generating the output of the program (comments are not even compiled), it is always recommended to comment the source code wherever possible. This makes the code easy to read and understand if any part of the code is to be referred in future for editing or debugging purpose. There are two different types of commenting styles that can be applied to the program: 1. Single line comments (only supported by C++ and not by C) 2. Multi-line comments (supported by both C and C++) A single line comment starts with two slash symbols written back to back without any space in between two slash symbols as shown below: // This is a single line comment The compiler will ignore any text that is written within the line after two slash (//) symbols. Note that, a single line comment can be stretched until the end of current line only. This means that, if we wish to write a comment across multiple lines then we must begin each of the lines by the two slash symbols as shown below: // This is the first line of the comment // This is the second line of the comment // This is the third line of the comment Along with a support to // symbol for single line comments, compiler also ignores any text which is written in between /* and */ so as to support creation of multiline comments in the program. Hence, we can write a multiline comment in the code, such that, it begins with a token /* and ends with a token */ as shown below: /*This is the first line of the comment This is the second line of the comment This is the third line of the comment*/
  • 48.
    28 ✦ ComputerProgramming with C++ REMEMBER Single line commenting style is only supported by C++ but not by C //This commenting style is only supported in C++ Multi-line commenting style is supported by both C as well as C++ /*This commenting style is supported by C as well as C++*/ Given below is an example that includes comments in the program that we have created to print a text message on the computer screen. /*This is a program to print a message I like Computer Programming on the computer screen*/ #includestdio.h void main() { /*The below statement prints the text message on the screen*/ printf(I like Computer Programming); } Output: I like Computer Programming 2.4 Constants or Literals A constant or a literal is a part of the program that cannot change its value. The constants in C/C++ are classified as: 1. Integer constants 2. Real number constants 3. Character constants 4. String constants We can directly create/use any of the above constants in the program, so as to perform operations with the constant values. Given below is the description for each of the above categories of constants giving the examples of each type of constant values which are supported by both C and C++. 2.4.1 Integer constants These are numbers without a decimal point which can be written directly in the program. The integer constants can be positive or negative, without any fractional component present as a part of the constant value.
  • 49.
    Fundamentals ✦ 29 Givenbelow are some valid and invalid examples of integer constants 10 /*This is a VALID integer constant*/ -95 /*This is a VALID integer constant which represents a negative value*/ 45.9 /*This is an INVALID integer constant as there is a decimal point in the number*/ 25,000 /*This is an INVALID integer constant as there is a comma used in between the digits of the number*/ Note that the integer constants must be written as a combination of digits 0 to 9 in the code without any special characters like comma, space in between the digits. 2.4.2 Real constants These are numbers with decimal point which can be written directly in the program. A real constant can be positive or negative and can also include a fractional component present as a part of the constant value. Real constants are also called as float constants or double constants in C/C++. Given below are some valid and invalid examples of real constants. 10.5 /*This is a VALID floating point constant*/ -90.832 /*This is a VALID floating point constant*/ 25,000.976 /*This is an INVALID floating point constant as there is a comma used in between the digits of the number*/ Note that just like integer constants, real constants must be written as a combination of digits 0 to 9 in the code without any special characters like comma, space in between the digits. The real constants may contain exactly one decimal point in between the digits so as to represent a floating point value. 2.4.3 Character constants A character constant is a single symbol enclosed in the single quotes. Given below are some valid and invalid examples of character constants in C/C++. ‘e’ /*This is a VALID character constant which represents a letter e*/ ‘1’ /*This is a VALID character constant which represents a symbol 1*/ ‘$’ /*This is a VALID character constant which represents a symbol dollar*/ ‘ ’ /*This is a VALID character constant which represents a blank space*/ ‘10’ /*This is an INVALID character constant as it encloses two different symbols (1 and 0) within the single quotes*/ ‘ad’ /*This is an INVALID character constant as it encloses two different symbols(letters ‘a’ and ‘d’) within the single quotes*/
  • 50.
    30 ✦ ComputerProgramming with C++ Note that ‘1’ is not same as a number 1. In a sense, a ‘1’ represents a character constant whereas a number 1 represents an integer constant. Generally, we use only numbers and not characters in any of the arithmetic operations. For example, the below operation 1 + 5 will perform the addition of two integer constants 1 and 5, thereby giving a result of the arithmetic operation as 6. However, we would get indifferent results in the program if we perform the arithmetic operations with characters instead of integers. This is because C/C++ maps every character constant with an integer code so as to store the character constant in the computer memory. A unique integer code which is associated with every character constant is called as an ASCII code of that character. ASCII stands for American standard code of information and interchange. Although we attempt to store a character constant in the memory, C/C++ internally stores the ASCII code corresponding to that character in the memory. Whenever, we attempt to output the character on the screen, the internally stored integer value is converted back to the original character and hence we always get the result in terms of character symbols on the computer screen. Appendix I gives the complete list of ASCII codes for each of the characters relevant to C/C++. As seen from appendix I, the ASCII values of upper case characters from ‘A’ to ‘Z’ are 65 to 90, whereas the ASCII values of the lower case characters from ‘a’ to ‘z’ are 97 to 122 and the ASCII values for digits from ‘0’ to ‘9’ are 48 to 57, respectively. In all, the ASCII values range from 000 to 127 wherein the remaining ASCII values are assigned for the special characters. As an example, if we attempt to store an character constant ‘b’ in the computer memory, internally a value 98 will be stored which is the ASCII value of character ‘b’ as shown in Figure 2.5. Furthermore, if we attempt to print the character value, the code 98 will be converted back into a character constant and then printed on the computer screen. Due to this translation, we always get the output in a character format as shown in Figure 2.5. b 98 Step 2 Step 3 Memory . . ASCII value of the character ‘b’ is stored in the computer memory C/C++ converts the ASCII value back to the character constant at the time of generating the output. Hence, the character ‘b’ gets printed on the computer screen Step 1 User inputs the character ‘b’ from the keyboard Figure 2.5: Storing characters in memory
  • 51.
    Fundamentals ✦ 31 2.4.4String constants Collection of characters is called as a string. A string constant is formed by enclosing multiple characters in double quotes. Given below are some valid and invalid examples of string constants in C/C++ Computer /*This is a VALID string constant which is a collection of eight characters*/ C /*This is a VALID string constant which contains just a single character*/ 'com' /*This is an INVALID string constant. This is because a string cannot be enclosed in single quotes*/ 45+6 /*This is a VALID string constant which is a collection of 4 characters*/ Every string in C/C++ terminates with a special character called as a NULL character, which is represented by ‘0’. For example, the string “Computer” will be internally stored in the memory as shown in Figure 2.6. C A string always ends with a NULL character 0 o m p u t e r 0 Figure 2.6: Memory representation of a string Note that, the last character of the string is automatically added as ‘0’, which is the end of the string marker and is called as a NULL character. The details of string constants and their processing are discussed in Chapter 6 of this text book. Why do we store the ASCII values for character constants in the memory? ? Recall from the Chapter 1 that, every symbol written in the high level language must be converted into the machine language before it can be processed by the CPU. Integer or real constants can be directly converted into the machine language by representing them into a binary number system. So as to facilitate the storage of the character constants in the computer memory, every character constant is internally assigned an integer code which is called as the ASCII value of that character. Hence, we can now store a character constant in the computer memory by simply representing the ASCII code of that character in binary number system.  2.5 Variables and Data Types A variable is a place holder for a particular value to be stored in the memory. This means that variable is a reserved area in the computer memory wherein we can store a value. The process of creating a variable is called a ‘declaration’ of a variable whereas the process of storing a particular value inside a variable is called as ‘initialization’ of the variable.
  • 52.
    32 ✦ ComputerProgramming with C++ Every variable is associated with a particular data type.Adata type of a variable determines the type of value that can be stored inside the variable. The list of basic data types which are supported by C/C++ is given below: Data type Description Size in bytes Range of values int A variable of type int can store any integer type of constant which falls under the range of -32,768 to +32,767 2 bytes1 -32,768 to +32,767 float A variable of type float can store any number with a decimal point which falls under the range of -3.4e-38 to +3.4e+38 4 bytes -3.4e-38 to +3.4e+38 char The data type char is used to store character constant which is single symbol enclosed in the single quotes 1 byte -128 to +127 double A variable of type double can store any number with a decimal point which falls under the range of -1.7e- 308 to +1.7e+308. This data type has higher precision when compared to float. Hence a double type variable requires 8 bytes in the memory whereas the float type of variable just requires 4 bytes in the computer memory 8 bytes -1.7e-308 to +1.7e+308 short int A variable of type short int can store any integer type of constant which falls under the range of -128 to +127. The keywords short int define a smaller version of the int type in C++. Hence, the short int type of variables just requires 1 byte in the computer memory, whereas the int variable actually requires 2 bytes in the computer memory 1 byte -128 to +127 long A variable of type long can store any integer type of constant which falls under the range of -2147483648 to +2147483647. The keyword long represents the larger version of the int type in C++. Hence, the long type of variables requires 4 bytes in the computer memory whereas the int variable just requires 2 bytes in the computer memory 4 bytes -2147483648 to +2147483647 1 We assume 16 bit compiler throughout this text book where size of an integer is 2 bytes (16 bits). If you get the size of integer as 4 bytes it means you are working on a 32 bit compiler. 2.5.1 Evaluating the range of data types The range of values which can be stored inside a variable of a particular type is dependent on the size of that ‘data type’ in the computer memory. The range of a particular data type can be decided by considering the total number of permutations that can be represented by the bit values assigned to the variable. As an example, let us consider an integer type variable which requires 2 bytes in the computer memory. As each byte is formed using eight bits, we can say that an integer variable requires 16 bits in the computer memory. Therefore, the total number of permutations (X) that can be represented using 16 bits can be calculated as shown below: Number of permutations (X) = 216 = 65,536
  • 53.
    Fundamentals ✦ 33 Outof the total number of states that can be represented using 16 bits, half of the permutations must represent negative numbers in the high-level language and remaining half of the permutations must represent positive numbers in the high-level language. Also, one of the permutations of 16 bits must represent a value zero in the high-level language. Therefore, we divide the total number of permutations by two as shown below: X/2 = 65,536/2 = 32,768 As one of the permutations of 16 bits is used to represent zero (this is when all the bit positions become 0), the range of integer constants in C/C++ is –32,768 to +32,767 as shown in Figure 2.7. This theory is used to convert a number in the high-level language into the machine language thereby storing the machine language in the computer memory as seen in Figure 2.7. The most significant bit (which is the left most bit) represents the sign bit which is 1 when a negative number is translated into the machine language and 0 when a positive number is translated into the machine language. Figure 2.7: Translation of integers into machine language 1 Each integer requires 16 bits in memory Least significant bit Most significant bit This bit is also called as a sign bit. The bit is 1 for negative numbers and 0 for positive numbers 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 This permutation of bits represents a negative value -32768 This permutation of bits represents a negative value -32767 This permutation of bits represents a negative value -32766 This permutation of bits represents a value zero This permutation of bits represents a positive value +1 This permutation of bits represents a positive value +2 This permutation of bits represents a positive value +32767 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 The range for other data types such as short, long, and char can be calculated using a similar approach. Evaluating the range of floating point types such as double and floats is out of scope of this text book, as it requires a detailed study on IEEE formats in which the mantissa and exponent are internally stored in the computer memory. What will happen if we give a value to a variable which is out of the range specified by its data type? ? This situation is called as overflow/underflow of values. We will not get any compilation error in this case; however program will produce unpredictable results. For example, if we assign a value say 66990 to a 2 byte integer; results produced by the program would be erroneous and unpredictable. 
  • 54.
    34 ✦ ComputerProgramming with C++ 2.5.2 Declaration of variables As we have mentioned above, a variable creates a place in memory where we can store a value of a particular type. The process of creating a variable in memory is called as ‘declaration’ of the variable. Every variable must be declared before it is used in the program. Given below is the syntax to declare a variable in C/C++: DataType variableName; For example, the statement int marks; creates an integer type variable named as marks in the computer memory. The compiler allocates the memory for the variable when it is declared in the program. Hence, the above statement allocates a memory of 2 bytes for the variable which is named as marks as shown in Figure 2.8. Note that the initial value of any variable is undefined in C/C++ and hence we say that the variable marks initially contains an unknown value or a junk value as shown in Figure 2.8. The initial value of the variable is junk Every integer type variable requires 2 bytes in computer memory marks 2 bytes Name of the variable Figure 2.8: Declaration of the variable named as marks Notes Variable name is also called as an identifier. For example, in this case marks is an identifier which identifies the exact memory location where the integer value is stored. Figure 2.9 gives examples of declaring three variables named as a, b, and c of type integer, float, and character, respectively. As shown in Figure 2.9, the compiler allocates 2 bytes in memory for variable a because it is declared as integer. Whereas, the compiler allocates 4 bytes in memory for variable b because it is declared as float and 1 byte for the variable c because it is declared as character as shown in Figure 2.9. Note that, each of the variables initially contain junk values as shown in Figure 2.9. If all the variables to be declared are of the same type, then we can also use a comma operator as a separator between the variable names so as to create multiple variables using a single C/C++ statement. For example, the below statement creates three different variables named as marks, salary, and score of type float: float marks,salary,score;
  • 55.
    Other documents randomlyhave different content
  • 56.
    Star, that wasJohn's brother! exclaimed Edith, after he had disappeared over the hill, and that little girl was his sister. Resuming her composure over the excitement the incident caused, she sat down in one of the lounging chairs, with Star by her looking serious enough herself. I believe so, Edith; but why didn't we stop long enough to talk with them? said Star, apparently disappointed. Oh, I wanted to stop to speak—but that would not do, dear Star— would not do at all; but I will have a talk with them when he comes here next week, never mind, cried Edith, with much joyousness in the ring of her voice. Isn't she such a pretty creature—just like one of those little fairy mountain girls you see sometimes in romantic plays in the theaters, and I know she is more romantic. What do you think of him, Edith—the man—her brother—if that is whom he is? asked Star, blushing for the first time Edith ever saw that intelligible sign in her face. If he is not Mr. Winthrope's brother, he is his living stature in bronze, replied Edith; and now, Star, tell me your opinion? I can't say that I have an opinion, Edith; I am really dumb with amazement. He is such a big fellow—more like a mill-worker, or such —oh, my, Edith; don't ask me for— Well, now, I like that way of speaking about Mr. Winthrope's brother. Maybe it was not him at all, and we have had our little scare for nothing. Oh, goodness! here comes Mr. Cobb again! dear me! and Edith subsided. Pursuing the tenor of his prevailing thoughts, Jasper Cobb sought Edith and found her on the eastern end of the veranda. After saluting the two young ladies again quite prodigiously, he asked Edith for a private interview at once. Star, hearing the request, rose and left them, as if she had an errand in her room, before Edith had time to ask her to remain. Star, however, was waiting for such an
  • 57.
    opportunity to absentherself, knowing what young Cobb's mission was. Having been informed by Edith what her answer would be, she went away satisfied that she would return to find that young man laboring under a severe jolt to his mercenary soul. Now, when alone, Mr. Cobb drew up a seat and sat near Edith. Miss Jarney, we have always been friends—our families? Yes. And we have been friends for years, you and I? Yes. Would you consider a proposition from me to make that friendship permanent and lasting? Yes. His heart bounded—a little. Well, Miss Jarney—may I call you Edith?—I came here to ask you to marry me? You? she said, turning on him. Yes; me, he answered, dejectedly, for he caught the tone of her voice in no uncertain meaning. No, said Edith, firmly, looking at him, with a sort of a commiserated smile for his imbecility. If you want to be my friend, Mr. Cobb, all right, you may consider me as such; but, as to marrying you, never can I make up my mind to that end. Dear Miss Jarney, you don't know the blow that you have struck me —it almost topples me over, he insisted, and Edith came near laughing in his face, so ludicrous was the expression that he had now assumed. I have always thought you had encouraged me—
  • 58.
    Oh, never wasI guilty of such an offense, Mr. Cobb—never. You are laboring under a misconception, or a delusion, or something else. Encourage you, Mr. Cobb? How ridiculous! Then, you refuse? he asked, coldly and fiercely. I most certainly have my senses with me, she retorted, with a laugh. Ah, then, I'll go my old way. I thought I might settle down some day and be a man, he whispered. Be a man first, Mr. Cobb, and settle down afterwards, is my advice to you, she responded. You are cruel, Miss Jarney—cruel—as cruel as all the other women of the rich, who make monkeys of we men folk, he said, despairingly. You must understand, Mr. Cobb, that I am not one 'of all the other women' of the rich, of whom you speak so slightingly, she replied, still keeping a good temper. Well, I guess not, Miss Jarney, he said, with a sneer, looking away from her. I see, Miss Jarney—I am not blind—that you have set your cap for that young man in your father's office. You are disrespectful, Mr. Cobb; leave me at once, she replied, with some scorn for the first time exhibiting itself in her bearing. She arose and left him sitting there alone, with his pipe as his only comforting companion. After recovering from this jolt, as Star predicted, he gathered up his belongings, together with his valet, and vanished. Imagine such a union of hearts! There are plenty of them founded upon the rock of riches. Yes; imagine it! See this young man Cobb, and know his worth! His face was like that of a well bred bull terrier, with a pipe between its lips, and a red cap upon its head. He had a pair of dull-gray pants on his hind legs, and they were turned up,
  • 59.
    with a pairof yellow shoes sticking out below the turn-ups. Around the middle of his body was a yellow belt fastened by a silver buckle, and above the belt was a silken white shirt, with turn-down collar, and around the collar was a red necktie, in which stuck a scarabee pin. And he called himself a man worthy of Edith. He had been to Harvard, she to Vassar. She had learned to write a grammatical sentence and spell in the good old Websterian way. She could sing and play on the piano; and converse on the economic questions of the day with the perspicacity of a Stowe. She read the poets down through the catalogue of famous men and women, and the novelists of the class of Dickens and Hawthorne. She knew of the painters, the musicians, the theologians, and could talk intelligently on them all. Him? He had learned a lot of things. He could flip the Harvard stroke with the ease of a Cook. He could make a touchdown without breaking sixteen ribs of an adversary. He could twirl the pigskin like an artist of the green cloth. He could take the long jump, or the long hike, with the grace of a giraffe. He could dance like a terpsichorian dame. He could drink whiskey, champagne and beer, smoke cigaretts, play cards. He could talk with the profundity of an ass and write with the imbecility of an ox. Yes, indeed, he had all the refinements of a college education—the kind confined to the male gender. The only virtue he had was his prospective inheritance from his father—money. And he wanted Edith to marry him! Pooh!
  • 60.
    CHAPTER XXX. FOR JOHNIS COMING HOME. There is a little frame house sitting, in the shade of maples and oaks, by the roadside to the south aways from Chalk Hill. It is a leaning building, to some extent, in many ways, by reason of its age. A crooked little chimney heaves up on the exterior of one end, by reason of its insecure foundation. Shingles curl, up, as if in dotage, by reason of the sun. Weather boarding warp and twist and turn, grayed by the wash of years, by reason of their antiquity. Windows peep out, with little panes, and rattle in the wind, by reason of their frailty. Wasps and bees, in season, build their mud nests beneath curling shingle and behind twisting board; bats fly out, at eventide, from unseen holes in the gables; and swallows chatter and circle round the chimney top in the twilight of the summer days. An ancient porch, with oaken floor, hangs against the front wall, and the woodbine and morning glory creep and twine and bloom around its slanting columns. A gate swings out at the end of the path leading from the door to the highway. Flowers—the rose, the marigold, the bouncingbetty, the wild pink, the primrose, all as old-fashioned as the people who dwell here—border the pathway. A paled patch of ground stands to one side, as sacred as the Garden of Gethsemane. In the rear a gnarled and aged orchard has but recently shed its snowy burden of bloom, with lingering scents still in the air; and beyond and around, fence-enclosed fields are greening with growing crops, and still beyond are dark forests and open fields and noisy ravines. Evening is coming on. The sun has gone down over the mountain top. Shadows have disappeared into the gray of fading light. Odors of night are ascending from the cooling earth. The robins are
  • 61.
    rendering the laststanza of their solemn doxology to the dying day. The whippoorwills send forth their melancholy praises to the approaching darkness through the wooded chancel of their shadowy choir loft. And frogs swell their throats in grave bass tones to the melody of country life at this time of departing day. A gray-haired farmer, in rough garb, sits on the porch, smoking his pipe, and by his side sits his patient, loving wife. On the top step of the porch sits their young daughter, reading her fate, perhaps, in the evening stars, the while glancing up the road, and listening for the click of horses' feet on the stones. But no sound is heard before night comes on. The mother rises, goes in, and lights the oil lamp, and sets it by a window for the expected visitor to see. For John is coming home. They are late in getting here, says the mother, as she descends from the porch, and goes down the path to the gate. She looks up the road through the shadows; then returns, and sits down by her daughter on the steps. The father relights his pipe, clanks down to the gate, in his heavy boots, looks up the road through its shadows; then returns. They are late, he says, and resumes his seat. I wonder what is keeping them, says the daughter, with an expectant hush in her sweet voice, as she rises, and goes down to the gate. She looks up the road through its shadows; then returns, and sits down. Listen! John is coming home. They hear the clank of horses' hoofs, the rattling wheels, the rhythm of a lively trot; then indistinct voices far in the distance. John is coming home. The son who went away the year before—the brother—is coming home. The father's boots clank on the porch as he impatiently walks back and forth. The mother rises, and shades
  • 62.
    her eyes, andpeers up the roadway through the shadows. The sister rises, with a dancing heart, and flutters down to the gate, like an angel in the darkness. For John is coming home. Home! His only place of sweet rememberance. It is an age, it seems, before the team draws up and John leaps out to catch his sister in his arms. Come into the light, Anne, that I may see your face, for I know you are growing so handsome, said John, putting his arm around his sister, and went laughing with her toward the house. Could he have seen those blushes, in the darkness, because of his brotherly praising of her! How is mother? was his greeting to his mother, as he kissed her at the foot of the steps. And, with her clinging to him on one side and Anne on the other, he ascended the steps to the porch. Where is father? asked John, not seeing him in the darkness, standing just ahead of them. Oh, here he is! John exclaimed, as he released himself from his mother and sister, and grasped his father's rough hand. Come into the light and let me see you all, said John, after the formalities of greeting had been performed, to the satisfaction of all around. The light brought forth a revelation for them all, as light does for everything. The family now saw in John a new being in outward appearance, but still the same loving son and brother. John now saw his father and mother a little older, it appeared, perhaps, from anxiety over his absence, or it may have been their strenuous toil was showing plainer on them. He also saw in his sister, a simple country maiden in the rusticity of young beauty. Anne, will you let me kiss you again? asked John, as he stood in admiration over her by the lamp, holding her hand, after his mother
  • 63.
    and father hadgone to complete the supper that had been almost ready for hours waiting for him. Anne tip-toed up to her brother, at his request, and put up her sweet lips to his. And how has my little sister been all these months? he asked, patting her on the cheek. Very well, John; I hope you have been a good boy, she answered. Sister wouldn't expect anything else of me, would she? he asked, kissing her again. Oh, no, indeed, John, she replied, with wide eyes. And have you been good? he asked. Very, John, she responded. No beaus yet, I hope? he asked, in his teasing way he always had with her. Why, no, John! and she blushed, not that she had a beau, but through maiden coyness. You are the only one I've got, John. Supper was then announced. James, who brought John from town, came in after putting away the horses. And they all sat down in happy reunion once more. For John was home. What was the cause of your delay, John? asked Michael Winthrope, the father. Oh, by the way, father, I must tell you about it, answered John, laughing heartily, and looking slyly at James, who was now dressed in his best clothes, and presented as good an appearance as John himself. I have two lady friends, who— Why, John! exclaimed the mother, looking over her glasses.
  • 64.
    Wait, mother; willyou hear my story? said John, turning a happy smile upon his mother. As I was going to say, I have two lady friends stopping at the Summit House. One is the daughter of my employer; the other her cousin. They saw us, as we were coming by, and, of course, we saw them. Knowing them as I do, I could not come on without the formality of greeting them. I introduced James to them, mother; and what do you think?— Now, John, you mustn't be too severe on me, said James, modestly, for I don't pretend to your polish since you went away. Never mind, James; you are a capital fellow, after all—but, mother, James and sister here—turning to Anne—saw them the other day, and they are—they think he and sister cannot be beaten as—roving mountaineers—no, they didn't say that sister—turning to his sister again—They did say they would come out to see us, if you will drive in for them. Law, me, John; we have no place here to entertain such grand people. What do you mean? asked the mother, holding up her spoon, and shaking it with a remonstrative motion as emphasis to her thoughts. Wait, mother; wait, and hear me out, before remonstrating any further, said John, cheerfully. They wouldn't accept my invitation; but they want sister to drive our old rig in for them, and extend the invitation to spend the day with us. They thought it would be so romantic to go on a lark with little sister—turning to her again with such a fond look that Anne beamed under his countenance. Will you go, sister? he asked. Shall I, mother? asked Anne. If John says so. What do you say, James? asked the mother. That is up to John, responded James. And father? asked the mother.
  • 65.
    Whatever John saysabout it, replied the father. Now, everything is up to you, sister, said John. Are you going? Why, of course, brother, she answered. When? Tomorrow, replied John. So it was settled. That night, as John lay down to sleep in his old bed, so pure and white, in a little room up stairs, he heard again, above the screeching insects, the booming frogs, the wailing owls, that old sweet song that carried him into the slumberous land of nowhere—Good bye! Good bye!—as on so many nights before. In the night, when the house was still, a gray-haired man, in night clothes and carrying a lighted lamp, softly stole into John's room. John lay with his face upturned, his eyes closed, and his lips parted in a sleeping smile. The father stood over him a moment, bent down and touched his lips to his son's brow. He is a good boy yet, he said to himself, and softly stole away. Anne was singing, as she went about her work, when John awoke in the morning; and life was astir on every hand. The pigs were squealing in their sty; the calves were bawling in their pens; ducks were squawking in their pond; chickens were cackling in the barn yard, and the sun was shining everywhere. John dressed himself and descended the narrow stairway, with tousled head and open shirt front. The mother was milking the cows, James was in the field, and the father was in the barn. Anne was preparing breakfast. Now, I may see you in the sunlight, sister, said John, as he sauntered into the old-fashioned kitchen, and stood before her, with folded arms, and half yawning yet from sleep, as she was spreading the cloth upon the table. I didn't know I had such a dear little sister, he said, as he put his arm about her and kissed her on the lips. You are such a fine brother, John, that I am almost in love with you, she returned, as she lovingly left an imprint of a kiss on his
  • 66.
    cheek; then leavinghim to pursue her work. Whose love would I want more than yours, Anne? he asked, in his laughing manner. Oh, I don't know, John; maybe you have a girl better than me to love you, she replied. I shall never place any one above my dear little sister, he said thoughtfully; but—for no one can be your equal—except—one. Is it one of those, John, whom I am going after this morning? asked Anne, rattling the skillet on the stove. One of those whom brother James and I met on the road a short time ago? One of those, Anne—the rich man's only child—but I am too poor for her, he answered, regretfully. Is she as good as you, brother—and me? asked Anne, distributing the plates around the table. She was innocent yet of the ways of the world; but was feeling the first calling of young maidenhood. She is very good, Anne; very good; but no better than you, he returned, with the same uncertain cloud of perplexity that overcast him so often before, still pervading him like a wave of blinding light that comes to obscure the vision, at times, by reason of its intensity of purpose. She is very fine looking, John—both of them, John. Which one is it you mean? The smaller of the two. Oh, the one with the bluest eyes, who took fright at us and ran. That is just like Edith, to run. I know I could love her, John. You are anticipating, sister.
  • 67.
    Why, who couldn'tlove you, John? asked Anne, looking up at him, with some doubts as to what he meant. That is a sister's opinion, child, said John. A sister's opinion of her brother is better than any one else's. Maybe she does love you, John. Did you ever ask her? Maybe she does, said John, going toward the door and looking out over the garden fence and into the fields, and dreamily into the distance; but she is too rich to accept me, sister, he said, turning about. How soon will breakfast be ready? As soon as you wash your face, she answered. John, heeding this hint, went to a basin on a bench in the yard, which forcibly recalled the old days. How refreshing it was to him to soap and souse his face into the cold water! And how inconveniently unpleasant it was, after such soaping and sousing, to rush with blinded eyes, and water trickling down the neck beneath the shirt collar, to the kitchen and fumble, like a blind man, for the towel. But it was home to John. The rattling wheels and squeaking springs of the old rig could be heard far up the road after Anne, dressed in a clean white frock and wearing a pink sun-bonnet, had left the front gate on her mission, guiding the old farm horses on their sure and steady gait. Oh, John, John! If there is anything worth while, it is Edith's love, the love that never dies. Blind man, as you are, and too considerate of high state, and too proud of your own, you are the only one to make her sweet soul happy. Bestir yourself, John, and come out of the fog of self-consciousness that has kept you in obscurity so long as to your final intentions. High state and low state are all the same to the Cupid that has engaged you so relentlessly. High caste and low caste do not count for him. Come and see the right, and see the light. She is only mortal, you are only mortal. Money is nothing to her; money is nothing to you. Love is all to her; love is all to you. It
  • 68.
    is the manand woman, after all, that makes happiness supreme. Come! John has donned the garb of a mountaineer, which gives him a wild romantic bearing. It is the garb of his former self. This is the one in which Edith, secretly, wished to see him in, sometimes; and she shall have her wish fulfilled. He wears a gray slouch hat; a check shirt, opened in the front and turned up at the sleeves; a pair of blue overalls, with bed-ticken suspenders, and high boots. Typical! He is in his elements now, for his vacation period. He wishes Edith, when she comes, to see him as he once was. It is not vanity; it is pride of home. He wishes her to see life as it really is in a well directed loving home, where toil is the simple reward of living. He wishes her to see what life is to these people of the hills, how they thrive, and how they bear their burdens. He wishes her to see all this in contrast to her own life, and how love and duty can go on perpetually in a humble home, as well as in a mansion. Work must not cease on the farm, at this season, except in case of sickness or death; visitors must make themselves at home during the work hours, and be entertained only at meal time, or go their way. The wheels of industry must go on there as noisily, ever grinding, as the wheels of industry, ever grinding, in the city. But there are rare occasions, even in both instances, when surcease is had for a spell to meet the call of recreation. And this was one of those rare occasions on the farm. For Edith and Star were coming, and a half holiday was cut out for their especial pleasure. James would cease his ploughing the corn at noon. The father would knock off duty at eleven to help mother get up the feast, and then smoke his pipe thereafter, perhaps, as his company. Thus it was planned. After Anne had gone, John roamed about the place, speculating on the tender association everything had for him. He went through the house from garret to cellar, and beheld, with warming heart, how dear the old things were, and how different they were to the things in the mansion on the hill. Here was everything still that he knew in his boyhood days, and he saw with a thrill of regret, but not
  • 69.
    remorse, for itwas still his home any time he wished to abide therein. And no one could gainsay him that privilege. But how would Edith look upon all this, and not be struck by the simple evidence of his lowly origin? Ah, the comparison is too great, he thought, as he went into the garden, where he first learned the secrets of plant life; and then into the orchard, where he first saw the wonderfulness of the fruiting time; and then into the old barn, where was taught him the nature of domesticated animals; and then into the fields, where he had ploughed and sowed and reaped. How different from his life for the past year! How different! Edith could see nothing of interest in such bucolic surroundings, he thought. She would come, and see, and go, and want to forget him. It is well, he thought, that she sees it now, and of her own coming.
  • 70.
    CHAPTER XXXI. IN CONCLUSION. Therattling wheels and squeaking springs could be heard far up the road. Anne was returning with her precious load. The horses trotted down the hill, and came up with a rattle and a bang, and a sudden stop, at the gate, with Edith at the lines, and Anne by her side, and Star in the rear seat alone holding on tightly lest she should be bumped out. Wasn't that great! exclaimed Edith. I told you I could drive. This is your home? to Anne. This is our home, replied Anne, as she began to climb over the wheel in getting out. Isn't it a beautiful place, Star! said Edith. Just look at the roses blooming! and all those flowers around the porch! Anne you have such a romantic little home! Well, if here isn't our mountaineer, for a surety! she exclaimed seeing John coming down the walk. How do you do, Mr. Winthrope? I see you at last in your true character! How will I ever get over this wheel? If you will be real good, I will help you out—with your permission, said John, as he approached, and offered up both hands for her to fall into, as she liked. Sister, I will put away the horses, he said to Anne, as he saw she was holding the head of one of the horses to await the unloading. Remember, this is not an auto, he reminded Edith, as she was cautiously putting out one little foot on the rim of the wheel before her. I would not have had so much fun if it had been an auto, returned Edith, looking down into his upturned face, and laughing; and you
  • 71.
    have such afine sister, as she turned her head toward Anne. Now, jump, said John, as he caught her beneath the arms, she resting her hands on his shoulders in the momentary act before the plunge. Down you come—there!—not so difficult after all, he said, as she bounced on her feet on the ground. Now, Miss Barton, we will see with what grace you can perform the feat. You will have to be careful; I am so awkward, said Star, preparing to go through the same acrobatic act. Jump, Star! said Edith, seeing her hesitate. Here I go, then! she said, laughing, as she took the downward dive. Oh, my! Miss Barton! exclaimed John, as she tumbled into his arms, as a big rag doll might. Are you hurt? he asked, as he released her from the necessary embracing he had to perform to prevent her from falling to the ground. Not hurt, but a little frightened, she answered, flushed from the incident, and brushing out her skirts. I am all right. Now, you ladies go into the house with my sister while I put the horses away. Here, Anne, you take the ladies, and I will take the horses, he said, leaving his guests, and taking up Anne's position in charge of the team. May I call you Anne? asked Edith, as Anne came up to her. Yes, Miss Jarney, if you wish; we all use our first names up here, responded Anne, opening the gate. You may call me Edith, if you like, and this other lady will be our guiding Star, said Edith, walking with her arm around Anne's shoulders up the walk, her face aflush, her eyes beaming, and seeing everything about, talking continually.
  • 72.
    Star was notas talkative; but she was just as seeing as Edith was. She, too, saw something in that home, more than its simplicity, to attract her admiration. Was it the fragrant flowers and hopping birds and cool freshness that she saw? or was it the peace of contentment, indefinably overloading everything? or was it the radical difference in the two homes, ideal though in both, and irresistable in their contradictory elements, that caused her spirits to rise above the normal point of enthusiasm? Or was it something else? Star did not know. Arriving at the door, arm in arm now, Anne passed straight through the opening, holding on to Edith, and Star followed with considerable wonderment at what she might encounter. Take off your hats, ladies, said Anne, withdrawing her arm from Edith's and standing off, with folded hands, looking at her, with gladness all over her face. No, you must say Edith and Star, said Edith, seeing how humbly courteous Anne tried to be. If you will have it that way; Edith and Star, take off your hats and gloves. Now, I've said it, and I didn't mean to be so rude, said Anne, abashed. Anne, I will not love you if you do not call me Edith, said Edith, scolding pleasantly, pulling off her gloves. I do not like too much formality. I have had so much of that that it does my heart good to get out where I can be free; and you will let me be free here, Anne, won't you? Oh, yes, Edith, answered Anne; and Star, too; you may be as free as you please, Edith, for we are such common folk, so long as you don't carry off my brother, John. She said this without the least knowledge of its true meaning; not mentioning her brother James, because she did not think of such things in his connection.
  • 73.
    Edith blushed adeep crimson, as well as Star, at this extraordinary remark on this the most extraordinary day that ever came into their virtuous lives. Anne had a faint inkling of what these blushes meant, for she continued: Now, Miss Edith, since you want to be free with me, I will be just as free with you, and tell you that my brother l—l— likes you. Edith was not prepared for all this, and she had to turn her head in the most confused state of feelings she ever fell into, all for wanting to be tender and kind and loving toward this mountain girl, who was not yet clearly or fully instructed in the propriety of fine speech. Edith made no reply. She stood a moment, after facing Anne, cogitating on what an appropriate reply should be. Anne, she said directly, with a bright smile, will you let me kiss you? Edith held out her hands for Anne to come to her. Anne responded to the ineffable sweetness of Edith to make amends for her offense, which she realized she had committed against the fine lady opening her heart to her. I love you, Anne, said Edith, holding the dear little girl to her breast; I love you; will you be my friend? Why, of course, Edith, replied Anne; then she broke away, and was gone, leaving Edith and Star alone. They removed their hats and placed them on a table in a corner; and then sat down on a lounge that graced the wall under a window looking out on the porch, both in bewildered confusion and agitation. What do you think of his sister, Star? asked Edith. She is a fine young child; no more than sixteen, perhaps, responded Star, and so lively that I wish I could be here with her all the time.
  • 74.
    I wonder ifthey will let us take her with us to the city, Star, to be our companion? said Edith. We would educate her, and teach her music and everything. The kitchen door opened, and Anne came in with her mother, who wore a gingham apron as the badge of her position in the household. Anne advanced with her mother and presented her, with much dignity, as she conceived it, to Edith and Star. This is my mother, Edith and Star, said Anne, as the two young ladies arose and advanced to the middle of the room. Edith presented her small white hand and took the coarse hand of Mrs. Winthrope. I am so glad to know you, Mrs. Winthrope, said Edith, as she kissed the aging woman, whose age was more from toil than years. Star having performed the same act of greeting, including the osculatory part thereof, Mrs. Winthrope held up her hands in an astonished attitude, and said: Well, well; I declare; and you two are John's friends, are you? I hope you are well. We are well; thank you, they both repeated. Just make yourselves at home, ladies, with what we have here to entertain you, while I finish the dinner. Be seated by the window where it is cool, for I know you must be warm after the long drive in the sun. Thank you, Mrs. Winthrope, they answered; and were seated. Then the mother and daughter disappeared again; and Anne returned, after a little, with her father, who was in the clothes of a ploughman. Mr. Winthrope was a tall man, a little stooped, with chin whiskers, and gray blue eyes; and, while rough looking, was not boorish. Anne escorted him to the young ladies, who arose at his approach. He greeted them so warmly and effusively that, for some time thereafter, they felt the grip of his vise-like hand on theirs. Just make yourselves at home, as you like, he said. We are farmers, you know, and if you find any pleasure here it is yours. We
  • 75.
    will be throughour work by noon, then mother and me will find time to talk, if you care to be bothered with us at all. Then he left them. Are they not very good people, said Edith to Star, after the father had gone out with Anne. I like them very much, opined Star; they are so pleasant. John came in shortly, and sat down on a split-bottom chair in the middle of the room. I hope you ladies are enjoying yourselves, he said, toying with his hat he held in his hands. I could not enjoy myself any more if it were my own home, answered Edith. Why, you have such a delightful home, Mr. Winthrope, and such nice parents, and such a sweet little sister, with whom I have already fallen in love. I am regretting that I have not known them longer. That's a beautiful encomium, Miss Jarney, on my native heath; but you know that you and your father and mother have been saying so many nice things about me that I am uncertain whether you mean it or not. John said this while glancing at the floor, picturing intangible things in the woof and warp of the old rag carpet. I mean every word of it. Mr. Winthrope, replied Edith, also picturing similar intangible things in the old rag carpet as easily as if she had pictured them out of the delicate flowers in the velvet rug in her boudoir. Star sat gazing out the window, looking at some intangible shapes that made up the green hills beyond. Their conversation thereafter was not of the progressive kind, nor was it brilliant. Both became secretively reserved, and time was hanging monstrously on their hands. John was dreaming. Edith was dreaming. Both were uncertain as to what to say or how to act, so discomposed were they. But James came in soon to break the spell. He was such a strapping fine fellow, fine in texture, and as good as he was fine.
  • 76.
    I knew verywell who you were the day we met you on the road, said Edith, shaking his hand. Had I known all this then. I should have bundled you into my wagon and brought you right home, he replied, with considerable liveliness in his speech. But not knowing you, of course, I could do nothing else but drive on. However, the pleasure of meeting you now, here, is certainly beyond my mean ability to express. We might have come, said Edith, with a ringing laugh. Would it not have been odd, and so romantic, just to have come right along with you? I am sure I would have enjoyed it, he said; and by this time I would have had you converted into farm hands. And wearing calico dresses, said Edith. And brogan shoes, said Star, remembering how she used to wear such articles of clothing. Yes; it is certain one can't work here and wear silks, responded James. Then looking down at himself, he was reminded that he was still in his rough garb. If you ladies will excuse me, I will make myself more presentable for appearance at dinner. He then left them; and when he returned, wearing his best Sunday suit, all brushed and fitting him very well, he was equally as stylish looking as his brother John in his best. When dinner was announced (dinner is at the noon hour with the mountain people), John lead Edith and James lead Star to the bounteously laden dining table set in the kitchen. It might have been noticed by Edith, had she not been otherwise engaged, that Star was more aflush than ever before, just at this period of her proud behavior. James talked to her very entertainingly during the progress of the long meal, and she was very cordial toward him. She laughed and talked with great glee, being amused at his ready wit and simple manner. But John and Edith were distressingly quiet, for some
  • 77.
    reason, listening mostlyto the conversation of the others. Little Anne, at times, cast side glances at Edith and John, that might have been suggestive of their meaning. Would you ladies like to try your hand at fishing? asked James, who was warming up for any kind of sport that might be introduced for the entertainment of their guests. Oh, delighted! cried Edith. I never fished in my life. Nor I, said Star; will you teach me how, Mr. Winthrope? (meaning James.) I thought we old people were to entertain you this afternoon, said the father. We will return in time for that, father, James said, rising. John, I'll get the bait; you get the tackle, and we will teach these young ladies how to fish. Be careful, admonished the mother; don't fall into the stream. Anne, are you not going? asked Edith, as she rose with the others. I must remain here and help mother; and will await your return, said Anne, as she came around to Edith and put her arm around her. You are a dutiful child, Anne, said Edith, kissing Anne thereat. Edith and Star were both dressed in gray serge skirts, white silk waists and sailor hats. While John and James got ready the ladies prepared themselves for the event of their lives. They were in waiting on the porch when John and James came up, with plenty of bait and tackle in their hands. So off they went immediately: John and Edith together, and James and Star, the father and mother and Anne standing on the porch watching their going. They struck the mountain stream a mile below the house, and the two ladies fell to the sport with the spirited joy of youth. The pair became separated after awhile, as all such sportsmen and women
  • 78.
    often do. Onepair went up the stream, and one went down, after the elusive fish. John and Edith came to a pool, after wandering through the bypaths of the forest, far below the other two. Around the pool the trees hung low, and the shades were heavy, and the water was dark and deep. By the pool they sat down on a log, and cast their lines to await the fisherman's luck. Isn't this delightful, said Edith, holding her pole with inexperienced hands over the water. Fish won't bite, if we talk too loud, said John, critically, but pleasantly, as he sat below her on the log, slanting into the stream. She became quiet; he became quiet. The water trickled over the miniature falls at the head of the pool in such an isolated tone of ripling that it made wild sweet music for Edith. The trees above them sighed in a low crescendo, and the birds were singing everywhere. The sun rays glinted through the boughs of the trees, and danced upon the water, making a fretted work of moving lights and shadows. Water riders ran back and forth, as if playing with the sunlight let into their darksome place of habitation, and fish jumped up now and then, as if to taunt the patient anglers. And Edith and John sat quietly—waiting, waiting. Then a fish came along, and caught the bait of Edith's hook; and went tearing away in its struggle for liberty. So sudden was the unlooked for happening that Edith lost her balance, by reason of the gyrations of the fish, which she pluckily attempted to land, and plunged into the water. It came so sudden that John, who was at that moment meditating on the catch he would make, and on how he would boast over the rest of them when he got home, did not notice Edith's danger till it was too late. Without a moment's reflection, however, he dropped his pole and leaped into the pool after her. Edith came up with a scared look, beating the water with her hands, as he went down by her side. He seized her around the
  • 79.
    waist, and swamfor the shore, and when they reached the shore, she laughed, being reminded of another watery occasion; but still permitting him to hold her in his arms. I am a pretty sight now, she said, still remaining in his arms on the sloping bank, up which he was assisting her. It seems we have an affinity for water, Edith, he said, reaching the top of the slope, still holding her in his arms. May I call you Edith, now? he said, clasping her wet form to his. She laid her dripping head upon his breast, one arm stole around his neck, and she looked up into his face. Yes, she answered. And he kissed her for the first time on those sweet lips that had so often uttered his name before; but now they said, John. And still he held her in his arms. Edith, will you be my wife, some day? he asked, looking with the fervor of an impassioned youth into her dear blue eyes, and pushing back the wet hair from her white temples. Why, yes; dear John, I love you, as I always have since the first time I met you, she answered, with such an appealing tone for that old responsive note in him that he pressed her closer to his bosom. And the longing in her soul was recompensed in that moment of her eternal bliss. You know me, Edith; you know my people now; you know what I am. Are you satisfied? he asked, still harboring that same old uncertain doubt that always perplexed him so; and still holding her in his arms. I know you to be a noble young man, dear John. I know your people now, and I love them. I am satisfied, she whispered. You are all that I care for, John—all. I love you, I love you, and she kissed him. I am satisfied, dear Edith. It was not an hallucination, after all, was it dear? he answered.
  • 80.
    Thus, plighting theirtroth, they went hand in hand up the shady wood path as happy as two young children over their mishap. Life is beautiful, and life is sweet; but what would life be to those young people without the love between them? Coming to the path where they left James and Star, on parting, they found them sitting there, waiting. When Star saw them coming, she instinctively comprehended, and knew that the crisis was over between Edith and John. Star was happy herself over a secret of her own. And together they returned home. John proudly, on arriving in the old-fashioned sitting room, announced to his parents and sister his intended bride, and told them they could take her now, in her bedraggled condition, for their daughter and sister. Now, will you go with me, Anne, to the city? asked Edith, after she had been costumed in some of Anne's clothing that fit her narrowly. I will educate you, and have you for my own dear sister, hugging Anne to her breast. Some day, Edith; some day, answered Anne, uncertain in her mind. When will you come after me? When I am your real sister, Anne, replied Edith, stroking Anne's golden hair, and then she looked up at Anne's mother, who could not fully realize what it meant for her future life. You will let her go, Mrs. Winthrope? I may some day, answered the good old mother. I wouldn't want to leave papa and mamma yet, Edith, said Anne, with a happy smile. You shall return to see them often; so shall I, said Edith. I will go some time, Edith, after you are my sister, answered the coy Anne.
  • 81.
    That will besoon, dear sister, said Edith, folding Anne in her arms and crying with excessive happiness. You may have two sisters soon, Anne—Star, I am sure, will be your other sister. Star blushed, and therefore told her tale. The family stood on the porch that evening, and listened to the receding sound of the rattling wheels and squeaking springs of the rig, as John drove away with his precious load. God bless them, said the good old father; and Anne cried when the last hoof beat came down the shadowy roadway. In silence they sat in darkness till they heard the clanking hoofs returning. The mother went in and lighted the lamp; the father went in, the sister went in, the two brothers went in; and they all knelt down in family worship. As the curtain of the passing night drew thickly over the mountains, and the lights in the corridor of the Summit House became dim, and their room dark, Edith knelt down by her bed and offered up her prayers to the Good Lord, who had brought her safely through her troubles; and Star, kneeling by her side, said, Amen. A few days thereafter, after Edith had written her parents of the happy culmination of her fishing trip, the following message was received by her from them: Congratulations. So endeth the story of Edith and John.
  • 82.
    *** END OFTHE PROJECT GUTENBERG EBOOK EDITH AND JOHN: A STORY OF PITTSBURGH *** Updated editions will replace the previous one—the old editions will be renamed. Creating the works from print editions not protected by U.S. copyright law means that no one owns a United States copyright in these works, so the Foundation (and you!) can copy and distribute it in the United States without permission and without paying copyright royalties. Special rules, set forth in the General Terms of Use part of this license, apply to copying and distributing Project Gutenberg™ electronic works to protect the PROJECT GUTENBERG™ concept and trademark. Project Gutenberg is a registered trademark, and may not be used if you charge for an eBook, except by following the terms of the trademark license, including paying royalties for use of the Project Gutenberg trademark. If you do not charge anything for copies of this eBook, complying with the trademark license is very easy. You may use this eBook for nearly any purpose such as creation of derivative works, reports, performances and research. Project Gutenberg eBooks may be modified and printed and given away—you may do practically ANYTHING in the United States with eBooks not protected by U.S. copyright law. Redistribution is subject to the trademark license, especially commercial redistribution. START: FULL LICENSE
  • 83.
    THE FULL PROJECTGUTENBERG LICENSE
  • 84.
    PLEASE READ THISBEFORE YOU DISTRIBUTE OR USE THIS WORK To protect the Project Gutenberg™ mission of promoting the free distribution of electronic works, by using or distributing this work (or any other work associated in any way with the phrase “Project Gutenberg”), you agree to comply with all the terms of the Full Project Gutenberg™ License available with this file or online at www.gutenberg.org/license. Section 1. General Terms of Use and Redistributing Project Gutenberg™ electronic works 1.A. By reading or using any part of this Project Gutenberg™ electronic work, you indicate that you have read, understand, agree to and accept all the terms of this license and intellectual property (trademark/copyright) agreement. If you do not agree to abide by all the terms of this agreement, you must cease using and return or destroy all copies of Project Gutenberg™ electronic works in your possession. If you paid a fee for obtaining a copy of or access to a Project Gutenberg™ electronic work and you do not agree to be bound by the terms of this agreement, you may obtain a refund from the person or entity to whom you paid the fee as set forth in paragraph 1.E.8. 1.B. “Project Gutenberg” is a registered trademark. It may only be used on or associated in any way with an electronic work by people who agree to be bound by the terms of this agreement. There are a few things that you can do with most Project Gutenberg™ electronic works even without complying with the full terms of this agreement. See paragraph 1.C below. There are a lot of things you can do with Project Gutenberg™ electronic works if you follow the terms of this agreement and help preserve free future access to Project Gutenberg™ electronic works. See paragraph 1.E below.
  • 85.
    Welcome to ourwebsite – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com