Object Oriented Programming Using C++ - Student guide Part A
Object Oriented Programming Using C++ - Student guide Part A
Programming
Using C++
Student Guide
Table of Contents
Chapter 7 – Polymorphism
Chapter 8 – Inheritance
Glossary
Glossary-------------------------------------------------------------------------- G.
Chapter 1
Object-Oriented Programming (OOP) is one of the most popular methodologies in
software development. It offers a powerful model for creating computer programs. It
speeds up the program development process, improves maintenance, and enhances
reusability of programs.
Objectives
Programs
How does a computer know what are the steps to be followed to process reservation
requests? How does it manage to calculate your shopping bills at the local store? How
does it generate your report card at school? Is it an all-knowing machine? Do you have to
buy a different computer for each of these above-mentioned activities? The answer to the
last two questions is ‘No’. It is not an all-knowing machine and you do not require a
separate computer for each of these activities.
Then, how does a computer function? A computer is designed to accept input, process it,
and generate output. However, it has to be provided with a set of instructions that state:
The kind of input that will be provided. For example, in the case of reservation
requests, flight date, flight time, class, and destination will be some of the inputs.
The processing that needs to be done. For example, accepting the values, checking
for availability of seats, and validating accepted values.
The kind of output expected. For example, the seat availability status.
A set of instructions to perform a particular job is called a program. Therefore, for each
job that you want the computer to perform, you require a separate program. Instructions in
a program can be:
Sequential: Instructions that are executed one after the other.
Decision Making: Instructions that evaluate an expression (relation or condition)
first and then, depending upon whether the value of the expression is 'true' (non-zero)
or 'false' (zero), it transfers the control to a particular statement.
Iterative: Instructions that are executed repeatedly, depending on the value of an
expression (relation or condition).
Any real-life problem will consist of a number of small jobs. Therefore, to solve a
real-life problem, you have a number of programs that together form an application. For
example, a payroll application for processing employee compensation details and
generating paychecks and associated reports might have two programs:
Program to generate paychecks
Program to print reports
Programming Languages
A sequence of 0s and 1s can be used to describe any physical operation that the computer
performs. Therefore, a computer system uses a number system that consists of only two
digits, 0 and 1. This language that the computer understands is called the machine
language. For example, the machine language for a particular computer could have the
instruction set, as shown in the following table.
ADD 00000001
SUBTRACT 00000010
MULTIPLY 00000100
DIVIDE 00001000
Instruction Set
It is certainly difficult for anybody to remember instructions in the form of 0s and 1s.
Therefore, we use high-level programming languages to write programs. A high-level
programming language consists of a set of instructions, which are represented using
simple English words. So, when you want the computer to display the output on the
screen, you type the instruction ‘WRITE ON SCREEN’ and not ‘00100000’.
There are many high-level programming languages available, such as C, C++, and Java.
Each language has its own advantages. You need to evaluate the problem at hand before
deciding on the programming language to use.
All languages have a vocabulary, which is a list of words that have a specific meaning in
that language. Languages also have their own grammar rules, which state the rules for
combining words to form sentences. This is what ensures that whatever is spoken in a
particular language is interpreted similarly by all people who understand the language.
Similarly, programming languages also have a vocabulary, which is referred to as the set
of keywords of that language, and a grammar, which is referred to as the syntax.
For example, in the instruction Add A and B, Add is the opcode and A and B are
operands.
Before we actually start writing a program we need to derive a procedure for solving the
problem. An algorithm is a sequence of steps required to solve a problem.
Programming Approaches
There are a number of programming approaches that you can follow to create a program
or an application. Each approach has evolved as a result of certain limitations of its
previously prevalent approaches. The main reason for development of newer
programming approaches (techniques) over a period of time is to effectively handle the
increasing complexity of programs and to easily maintain code.
Sequential Approach
The sequential approach includes programs that are actually a list of instructions to the
system to perform a specific task. Each statement in a program is a command to be
processed by the system.
The limitation with this approach is that with an increase in the number of instructions,
the program becomes too lengthy and complicated to understand. As a result, the
maintenance overhead increases to a large extent. In addition, the programming effort
increases manifolds in a large program where each statement is an instruction to the
system.
Modular Approach
The modular approach was introduced to overcome the limitations of the sequential
approach. Since long programs are difficult to manage and maintain, the modular
approach divides the programs into entities known as functions. A function is a group of
statements that perform a specific task. Further, these functions are clubbed together in
logical groups with each group containing interrelated functions. Such logical groups are
known as modules.
In the modular approach, many modules/functions access the same set of data. Therefore,
a change in the type or location of data requires a change in all the functions that access
the data. This is quite tedious in programs with a large number of functions. Another
limitation of the modular approach is that it does not portray the real world and entities in
the programs. For example, in an inventory management application, more emphasis will
be on purchase-and-issue-related activities rather than on the inventory itself.
Object-Oriented Approach
Object-oriented approach is the latest of the programming approaches and portrays the
real world in the programs. The approach treats each entity as an object which has
well-defined state, behavior, and unique identity. The approach hides unnecessary details
from the users and allows creation of programs that are easy to manage and maintain.
Object-Oriented Programming
Object-Oriented Programming (OOP) is one of the most popular methodologies in
software development. It offers a powerful model for creating computer programs. It
speeds the program development process, improves maintenance, and enhances
reusability of programs.
People have often asked why software cannot be constructed the way an aircraft or a
high-rise building is constructed – by putting together several small constituent
components to build the whole. Software can be developed by first breaking the
application into its component objects, which interact with each other, and using these to
build the software. Thus, what is required is an object-oriented approach to the building of
software.
The basic concepts of object orientation are contained in the object model. The object
model furnishes the conceptual framework on which the object-oriented methods are
based. We will discuss the basic concepts specified in the object model in the following
pages.
Objects
An object is one of the first things that an infant learns to recognize just as it learns to
recognize its parents.
As the infant grows older, it learns to recognize an object, such as a clock, book, or a tape
recorder, as not only having a definite, distinct boundary, but also as one that has a unique
identity, quite apart from the other objects surrounding it.
The dictionary defines an object as a ‘material thing that is capable of being presented to
the senses’. For our purpose, a simple definition of an object would be a ‘tangible entity
that may exhibit some well-defined behavior’. Consider the following example of a tennis
ball:
A tennis ball is a tangible, visible entity, which has a visible boundary.
A tennis ball has a specific purpose.
You can direct a specific action towards a tennis ball (hit it with a racquet and send it
flying).
But let us not limit our definition of an object to merely ‘something that can be seen, held
and touched’, such as a tennis ball, an automobile, or an armchair. For the purpose of
software development, the idea of the object needs refinement. For example, consider the
Acme Nut and Bolt Company. An organization, you will argue, does not have a visible
boundary, unlike a tennis ball or a tape-recorder. True, but while it does not possess a
physical boundary, it does have a conceptual boundary. Like all organizations, it has a
specific purpose, and one can direct a specific action towards it (just ask the customers
and shareholders). Thus, by our definition, the Acme Nut and Bolt Company is an object.
For example, you can take a car as an object. It can have states such as moving and
stationary. It can accelerate, decelerate, turn right, or turn left, which is its behavior. The
car also has an identity, such as a unique registration number. The following figures
depict the characteristics of a car.
The state of an object is indicated by a set of attributes and the values of these attributes.
Thus, a chemical can be characterized by temperature, pressure, or density and the values
of each of these. The behavior refers to the change of these attributes over a period of
time.
Objects do not exist in isolation. They interact with other objects, and react to these
interactions. These interactions take place through messages. Grady Booch has defined
behavior as follows:
“Behavior is how an object acts and reacts, in terms of its state changes and message
passing.”
That explains the first part of the definition of an object “An object has state, exhibits
some well-defined behavior…”. Now, let us examine the next part of the
definition -“ … and has a unique identity.”
Each object has a unique identity, just as each person has a unique identity. The identity
of an object distinguishes it from all other objects. In the case of the pay-phone described
here, its identity will be its serial number assigned by the manufacturer. Two objects may
have the same behavior, may or may not have the same state, and will never have the
same identity. The identity of an object never changes in its lifetime. Thus, two tennis
balls may have the same color, be made of the same material, have the same weight and
the same circumference and display the same behavior, but will still have distinct
identities (say one ball has the factory seal number ‘A189735’ and the other ‘S660794’).
Classes
Look at the world around you. It is full of objects. Objects of different shapes, sizes and
colors; objects stationary and mobile; objects that exist in this world for different
purposes. If we were to deal with this vast number and variety of objects simultaneously,
we will be at a loss. We can only do what the zoologists do. The earth is inhabited by
millions of animals. A zoologist cannot do any meaningful study of these objects without
organizing this vast variety of animals found in the world in a logical manner. Thus,
zoologists have classified animals into their kingdom, genus, family, and species.
Similarly, the millions of objects that we see in this world can be classified on the basis of
common attributes that they possess. Let us take a simple example from the animal world.
The peacock, the sparrow, and the kingfisher are all called Birds. Why? All of them share
some common characteristics. All three have properties that are common to the family of
Birds. For example, all of them lay eggs and hatch their young; all of them are covered
with feathers, have hollow bone structures, and have the ability to fly. Thus, we can say
that the peacock, the sparrow and the kingfisher all share structural and behavioral
similarities and belong to the class called Birds, as shown in the following figure.
Birds
From the above example, we can define a class as ‘a set of objects that share structure and
a common behavior’.
We started off by saying that the world around us is full of objects. Making a conscious
attempt to identify the objects around you and classifying them into classes can be fun.
And (this is important from the point of view of software development), it can be equally
exciting to identify objects and classes in a given situation or situations. When we watch a
play in a theatre, we recognize the fact that there is a group of actors on the stage and each
actor is playing his/her own part. Similarly, in a given situation we can identify a group of
objects that play a part. The one difference here is that ‘objects’ include animate (living) as
well as inanimate objects. Thus, on the stage you can identify Professor Henry Higgins,
Col. Pickering and Eliza Doolittle, and the armchairs, the fireplace, or the portrait on the
wall.
Benefits of Object-Orientation
Why do we opt for the object-oriented approach? Some of the principal reasons are:
Realistic modeling, Reusability, and Resilience to change.
Realistic Modeling
Since we live in a world of objects, it logically follows that the object-oriented approach
models the real world more accurately.
Reusability
In the software industry, as in other industries, a large portion of time and energy is spent
in recreating the proverbial wheel. In the object-oriented approach, you build classes,
which can be used by several applications. Consider the following analogy.
Curlcare is a brand of shampoo sold in the European market. In spite of high investments
in advertising, the management at Curlcare felt that the shampoo did not really have an
identity of its own in a market that is infested with hundreds of brands of shampoo.
Therefore, the Marketing Division came up with a strategy to project a new image for
Curlcare. Curlcare was originally available in plastic bottles, just like all other brands of
shampoo. The idea conceived by the Marketing Division was to give the shampoo a new
look by packaging it in a soft-squeeze tube.
The Design Department of the Manufacturing Division designed the tube. This design
was created on a computer, and three-dimensional (3-D) views of the tube were made.
The Packaging Division used these images to check how the tubes would appear on
shelves in the shops, and how many would fit on a standard sized shelf. The Advertising
Division used these images to figure out the new advertising strategy, and how the tube
would look in the advertisement layout. The Finance Division needed to work out the cost
of manufacturing.
All these divisions can be viewed as several teams working on one project. All the teams
used the same information about the new tube to arrive at a complete solution for
Curlcare.
The scenario at Curlcare depicts the concept of reusability that is supported by the
object-oriented approach. In object-oriented terms, the tube is a class that can be used by
all the users who need it. In the object-oriented approach, classes are designed such that
they can be reused in several systems.
Now if we extend the above scenario to include a situation where Curlcare is diversifying
into new products, say toothpaste, the work done on the design of the tube of shampoo
can be used for the tube of toothpaste. Not only are the attributes of the tube, such as
length or radius being reused, but also the methods. For example, the method used by the
Finance Department to compute the manufacturing cost of the tube of shampoo can be
used for this new product.
The benefit of reusability translates to savings in time and effort, which in turn results in
cost benefits.
Resilience to Change
Through the object-oriented approach, systems can be allowed to evolve. When a change
is suggested, the old system need not be completely abandoned and re-built from scratch.
Consider the example of Joytoys, a company that manufactures toys for children in the
age group of 1-12. The payroll system of this company has been developed using
object-oriented techniques. The company has several employees, some of whom work in
the Design Department. These designers develop new toys every season. For the past
couple of years, the company has had no cause to complain about the payroll system.
However, new developments in the company have rendered the old payroll system
inadequate. In order to keep up with competition, the company realized the need to
employ more designers. Design work is done only in certain months of the year.
Therefore, the company has now employed freelance product designers who work in the
capacity of temporary employees.
The original payroll system was designed for employees of two kinds—confirmed
employees and trainees. Though there are many attributes that are common between
confirmed employees and trainees, like name and address, there are some attributes that
are different. For example, a confirmed employee receives basic pay while a trainee
receives a stipend.
The company now wants the system to be modified to accommodate freelancers as well.
In the object-oriented system, this change does not require the entire payroll system to be
revamped. A new class of freelancers needs to be introduced to take care of all activities
related to freelancers. The rest of the system remains unchanged.
Resilience to change results in the benefit of easier maintenance. For the same reason,
even during construction, parts of the system under development can be refined without
any major change in other parts.
Note
Information is passed as parameters in a function. You will learn more about functions
in subsequent chapters.
If a car collides against an object, the behavior of the car after the collision will depend on
the speed of the car and nature of the object that hit the car. For example, if the car collides
with another car at high speed, both the cars will be smashed and the drivers might
get injured. On the other hand, if a car collides with a street light at a slow speed, the
impact would be less. This ability to react differently based on the information associated
with the message is known as polymorphism.
C++: An Object-Oriented Language
In the early 1980s, Bjarne Stroustrup working for Bell Labs developed the C++ language.
In his own words, "C++ was designed primarily so that my friends and I would not have
to program in assembly, C, or various modern high-level languages. Its main purpose was
to make writing good programs easier and more pleasant for the individual programmer."
(Bjarne Stroustrup, The C++ Programming Language, Third Edition. Reading, MA:
Addition-Wesley Publishing Company, 1997).
C++ was originally known as 'C with classes' as two languages contributed to its
design – C, which provided low-level features, and Simula67, which provided the class
concept. C++ is an example of an object-oriented language. Other object-oriented
languages include Java and Smalltalk.
Classes in C++
After a class is created, you can use it without knowing the specifics of how it works or
even how a class is built.
The above class declaration provides the honk() method that will display the message
“BEEP BEEP!” on your screen.
Class names should follow certain naming conventions or guidelines. These are:
1. A class name should be meaningful [strongly recommended].
2. A class name should ideally be a noun.
3. The first letter of every word in a class name should be a capital if the class name
contains more than one word and does not use underscores. For example, for a class
related to employees, the class name can be Employee. A class name to describe
employee dependents can be EmployeeDependent.
Member Functions
As discussed earlier, objects interact with each other by passing messages and responding
to them. Objects use methods to pass messages. In C++, the task of passing messages can
be accomplished by using member functions.
The above code shows an example of a member function named, honk(), declared inside
the class. The declaration of a function is also called the prototype of the function.
The above code shows an example of a member function named, honk(), declared and
defined inside the class. Notice that the function definition contains the code, which is
enclosed in a block. The block is enclosed within braces '{}'.
Note
The cout operator is used to display output on the screen.
Note
The endl manipulator is a command that takes the cursor to the new line.
Activity: Creating Classes in C++
Problem Statement
As a member of a team that is developing the billing system software for Diaz
Telecommunications, Inc., you have been assigned the task of creating a software module
that accepts and displays customer details. Declare the Customer class and the member
functions. The member function that accepts customer details should display the message
“Accepting Customer Details”. Similarly, the member function to display customer details
on the screen should display the message “Displaying Customer Details”.
Solution
class Customer
{
void accept()
{
cout << “Accepting Customer Details” << endl;
}
void display()
{
cout << “Displaying Customer Details” << endl;
}
};
Practice Questions
CHAPTER 2
A class is a blueprint for an entity. To use this blueprint in a program, you need to
create an instance of the class. An instance of a class is known as an object. It
provides access to the member variables and member functions of a class.
This chapter discusses how to declare variables, and write and execute C++ programs. It
also discusses how to use arrays and structures in C++ programs.
Objectives
The following list provides the set of rules for naming variables in C++:
Variable names should not have any embedded spaces or symbols such as ? ! @ #
+ - % ^ & * ( ) [ ] { } . , ; : " ' / and \. However, underscores (‘_’) can
be used wherever a space is required, for example basic_salary.
Variable names must be unique. For example, to store four different numbers, four
unique variable names need to be used. Uppercase letters are considered distinct
from lowercase letters.
A variable name must begin with a letter or an underscore, which may be followed
by a sequence of letters, digits (0-9), or underscores. The first character in a variable
name cannot be a digit.
Keywords cannot be used as variable names. For example, you cannot declare a
variable named class, since it is a keyword in C++.
Note
A set of valid characters representing letters, digits, or any other symbols that are
recognized by C++ is known as its character set.
A variable must be declared by specifying its data type. A data type defines the type of
data that can be stored in a variable. For example, a variable called name will ideally store
characters; whereas, a variable called salary will store numbers.
Since the above data types are represented at the machine level, the storage requirement is
hardware dependant. The following table shows the storage requirements for the built-in
data types.
You can apply the preceding type modifiers to int data types. For example, you can
prefix an int declaration with the short modifier, as shown in the following statement:
short int num;
The size of a short int is two bytes. If you know that the size of the variables in your
program will be smaller than what an int can store, you can declare the variables as short.
This allows you to save system memory.
Similarly, you can apply long to int to increase the range of the int variable.
In addition to using short and long, you can modify the range of integers by qualifying
them as signed or unsigned. short, int, and long are signed by default. In other words,
they allow storing of negative values in their corresponding variables by default.
However, if you do not want to allow a variable to hold a negative value, you can declare
it as an unsigned variable.
Note
You can use only the short keyword instead of using short int as it is a short name
for the same.
Further, qualifying a data type as unsigned also modifies the range of the data type. For
example, if a signed integer has the range, -32768 to 32767 then an unsigned integer will
have the range, 0 to 65535. Declaring an integer as unsigned allows you to store higher
values in the variable than those that can be stored in a signed variable. You can use the
unsigned modifier when you know that there are no negative values to be stored. For
example, you can declare unsigned integers for storing population count, cricket scores, or
stock prices. You can use unsigned modifier as shown in the following statement:
unsigned int score;
The char variable is capable of storing various values, such as letters, digits, or symbols.
You can declare char data types as signed or unsigned. There is no default signed or
unsigned qualification for the char data types. The internal implementation depends on the
compiler and the type of hardware available.
A char data type allows you to store data from a range of 256 characters. As discussed
earlier, a signed data type allows you to store negative values. Similar to integers, the
char data types are also stored as integers in the memory. In other words, it is not the
actual character or symbol but its equivalent code that is stored in the memory.
Therefore, the range of a signed char data type is -128 to 127, whereas, the range of an
unsigned char data type is 0 to 255.
Member Variables
We have discussed earlier that objects have attributes or properties. For example, a car
has attributes, such as its color, model, and price. You can implement attributes in C++ by
using member variables. Member variables are declared inside the class body.
In the preceding syntax, name represents the name (identifier) of the variable that you
want to create and type represents the data type of the variable that you are creating.
The following code shows an example of a member variable declared inside the class:
class Car
{
float price;
};
In the above example, the variable price of type float is declared inside the class. You
can assign a value to a variable during compile time. Assigning a value to a variable is
referred to as initialization of the variable. Consider the following statements:
int price;
price = 150;
In the preceding statements, first a variable price is declared, and then is initialized with
the value 150. You can also declare and initialize a variable in the same statement.
There may be times when you have more than one variable of the same type that requires
initialization. In such a situation, you can declare and initialize multiple variables in the
same line, as shown in the following statement:
double loan = 1015.70 , interest = 0.5;
In addition to initializing variables during compile time, you can initialize the variables
during run time by accepting values from the users and assigning those values to the
corresponding variables.
public:
void acceptprice()
{
cout << “Enter Price :”;
cin >> price;
}
};
In C++, the cout object is used to display an output on the screen and the cin object is
used to accept and store input from the user. The cout object uses the <<output operator
to display the output on the screen. Similarly, the cin object uses the >> input operator to
accept input from the users. In the preceding code, the cout object is used to display the
text “Enter Price” on the screen and the cin object is used to accept the input provided by
the user and to store it in the price member variable.
The cout object is an instance of a predefined class named ostream, which is associated
with the standard output device. Similarly, the cin object is an instance of a predefined
class named istream, which is associated with the input device. In the case of the above
code, the message Enter Price is displayed. The cursor blinks on the screen and waits
for the user to enter data in the variable named price.
Similar to using multiple output operators, you can use multiple input operators (>>) in
the same statement. Consider that you have multiple variables that require input from the
user. One way to accept input for the variables is to use multiple cin statements, as shown
in the following code snippet:
int English_score, Math_score, Science_score;
cout << “ Enter English, Math, and Science Scores : ” ;
cin >> English_score;
cin >> Math_score;
cin >> Science_score;
The preceding statements are quite tedious to write and are more prone to
typographical/syntactical errors. However, you can reduce the number of statements by
performing multiple input operations in the same statement. You can achieve this by
using multiple input operators in the same statement, as shown in the following code
snippet:
int English_score, Math_score, Science_score;
cout << “ Enter English, Math, and Science Scores : ” ;
cin >> English_score >> Math_score >> Science_score;
Constants in C++
Literals are data items whose values do not change during the execution of a program.
Such data items are also called as constants. C++ includes the following constants
(literals):
Integer constants
Character constants
Floating constants
String literals
Integer Constants
Numbers that do not have any fractional part are known as integer constants. They are
whole numbers having at least one digit and no decimal point. Integer constants may be
signed or unsigned. Some valid examples of integer constants are:
5
+45
-100
Note
An integer constant does not include a comma. Therefore, the value 1,000 will not be
considered as an integer constant.
Characters enclosed within single quotes are known as character constants. Such
constants are of char type. Some valid examples of character constants are:
‘A’
‘s’
‘N’
‘5’
C++ also includes certain character constants that cannot be displayed directly on the
screen by using the keyboard. For example, you cannot display a carriage return,
backspace, or a backslash directly from the keyboard. To display such a constant, you
need to use an escape sequence, which is represented by a backslash (\) symbol followed
by the constant. Some of the commonly used escape sequences and their corresponding
character constants are provided in the following table.
\t Horizontal Tab
\b Backspace
\\ Backslash
\’ Single quote
\” Double quote
\n Newline
\a Audible bell
Floating Constants
Numbers that have a fractional part are known as floating constants. Floating constants
can be represented in either of the following forms:
Fractional form: This form represents real numbers having a decimal point between
digits. For example, 1.44, 3.14, or -92.7 are floating constants represented in the
fractional form.
String Literals
Multiple characters enclosed within double quotes are known as string literals. String
literals are character arrays, wherein, each character can be manipulated individually.
When a string literal is stored, an additional character, \0, is concatenated to the literal.
This special character is used to notify the compiler about the end of the literal.
Addition of the terminator character results in an increase in the size of the literal by 1.
For example, consider that you need to store the name “Jim”, which is of size 3. The
actual literal that will be stored in the memory will be “Jim\0”, whose size is now 4. This
means that the size of the stored literal includes the number of characters plus 1. Some
examples of valid string literals are:
“Jim\’s Songs”
“Black Sabbath”
“nirvana”
In the preceding statement, the variable Pi is initialized with the value of 3.14. However,
this time the value of Pi cannot be changed to any other value during program execution.
This is because the variable has been created as a constant variable making it a readable
variable only.
The software that handles the preprocessor directives is called a preprocessor. The
preprocessor directive shown above includes the code of the header file iostream.h into
the program. The header files contain definitions of functions, classes, and predefined
objects like cout and cin. The header files are in the include folder. Incidentally,
header file names have traditionally had the extension .h. However, this is not a
requirement for the C++ standards.
Note
The statement #include <iostream.h> does not terminate with a semicolon.
Example
#include<iostream>
int main()
{
//C++ code
return 0;
}
The operating system considers the number 0 that is returned to it to imply that the
program has completed execution without any errors. If any number other than 0 is
returned to the operating system, it implies that some error has occurred.
The main() function should create the objects of the appropriate classes and invoke
member functions.
void honk()
{
cout <<endl <<"BEEP BEEP!";
}
};
int main()
{
Car ford; //An object named ford of the type Car is created
ford.acceptprice(); //Invokes the member function acceptprice
ford.honk(); //Invokes the member function honk()
return 0;
}
In the above example, the code for object creation and invoking member functions is
written inside the main() function. You will learn more about access specifiers in
subsequent chapters.
You must ensure that the any output generated or displayed by your program is easily
readable and comprehendible by the users. This requires you to format the output that is
generated. C++ provides you with certain manipulators that can be used to format the
output to be displayed on the screen. One of the most commonly used manipulators
provided by C++ is the setw() manipulator.
The setw() manipulator is used to set the width of the field that is to be displayed on the
screen. The required width is provided as a parameter to the manipulator. Consider the
following statement:
cout << setw(10) <<”Bryan”;
In the preceding statement, the width of the text “Bryan” is 5. Since the setw()
manipulator is setting the width to 10, therefore, 5 additional characters will be prefixed
to the original 5 characters, and then the output will be displayed on the screen. The
characters that are prefixed to the original characters are whitespace characters.
The output generated by the preceding statement that includes the setw(10) manipulator
will be:
Bryan
In the preceding output, the “ _” characters prefixed before the text, Bryan, represent
whitespaces. Similarly, if you will display the text Ryan instead of Bryan and apply the
same width of 10 to the text, the output will be prefixed with 6 whitespaces in addition to
the 4 characters of “Ryan”.
Note
To use the setw() manipulator, you must include the iomanip.h header file in your
program.
Functions are the building blocks of C++ programs. When programs become large, a
single list of instructions becomes difficult to understand. For this reason, functions are
adopted. A function groups a number of program statements into a single unit. A function
has a clearly-defined purpose and a clearly-defined interface to other functions in the
program. A group of functions together form a larger entity called a module. Thus, this
approach to programming, where a program is broken down into smaller modules, is
known as modular programming.
Another reason for using functions is to reduce the program size. Any sequence of
instructions that is repeated in a program can be grouped together to form a function. The
function code is stored in only one place in the memory.
In the above program, the add() function is invoked from main(). The control passes to
the add() function, and the body of the function is executed. The control then returns to
main() and the remaining code is executed.
The sample output of the program that adds two numbers is as follows:
Calling function add()
Input two numbers
10
20
Function Prototyping
Just as any variable is declared in a program before it is used, it is necessary to declare or
prototype a function to inform the compiler that the function will be referenced at a later
point in the program.
Defining a Function
The function definition contains the code for the function. The function definition for
add() in the given program is:
A function declaration can be avoided if the function definition appears before the first
call to the function.
The given program for adding two numbers can be modified to avoid function declaration
as:
//This program uses a function to add two numbers
#include<iostream.h>
void add()
{
int iNum1,iNum2,iNum3;
cout<<”Input two numbers “;
cin>>iNum1;
cin>>iNum2;
iNum3=iNum1+iNum2;
cout<<”The sum of the two numbers is “<<iNum3;
}
Function Arguments
Argument(s) of a function is/are the data that the function receives when invoked from
another function. It is not always necessary for a function to have arguments. The add()
function did not contain any arguments.
If you are creating a function that accepts argument(s), you must specify the data type of
the arguments in the function declaration. For example, if you are creating a function
named add() that accepts two integer arguments, you can declare the function as:
void add(int, int);
You need to ensure that the function definition also includes the same argument types. For
example, the add() function can be defined as:
void add(int arg1, int arg2) //specifying the argument types as int
{
...
}
To invoke the add() function, you will pass two integer values to the function, as shown
in the following statement:
add(10, 15);
Note that the function call does not require you to provide the type specifiers for the
arguments being passed.
The add() function above that adds two numbers can be modified to accept two
arguments as, as shown in the following program:
#include<iostream.h>
void add(int iVar1,int iVar2) //function containing two arguments
{
int iVar3=iVar1+iVar2;
cout<<”The sum of the two numbers is “ <<iVar3<<endl;
}
void main()
{
When a function returns a value, the data type of the value must be specified before the
function name. In the preceding program, the type int is placed before the add()
function. Functions that return no value have the return type specified as void.
The statement:
A function that assigns default arguments is illustrated in the following code segment:
int add(int iNum1=10, int iNum2=20)
{
return iNum1+iNum2;
}
In the above code segment, if the add() function is invoked without any arguments, then
the default value of 10 and 20 is assigned to iNum1 and iNum2, respectively. If values are
passed to the function, then corresponding values are assigned to iNum1 and iNum2.
Constant Arguments
There may be situations where you do not want the function to modify the arguments that
you pass to it. In such a situation, you can ensure that the argument that is passed to the
function is a constant. To make an argument as constant, you need to use the const
keyword. For example, if you want that the integer arguments accepted by the add()
function should be constants, you can modify the declaration as:
int add(const int iVar1, const int iVar2);
Creating Objects
A class declaration does not reserve memory at the time of declaration. Memory is
allocated when an instance of the class is created. An instance of a class is called an
object. For example, in the following statement:
int iNum1, iNum2, iNum3;
Class
member variable1
member variable2
member function1
member function2
Object 1 Object 2
All the objects share the same copy of the member functions, but maintain a separate copy
of the member variables.
In the previous chapter, you learned to declare a class named Car. Now, to create an
object named ford of the type Car, you will use the following code:
Car ford;
The member functions of the class are accessed through an object of the class using the ‘.’
operator.
In the above example, the object name and the ‘.’ operator is used to access the member
function honk().
After compiling, the object code is linked with libraries. Libraries are a collection of
executable pieces of code that you can reuse in your program. A C++ library contains
object code snippets (called functions) for tasks like drawing a line on the screen and
displaying a character. These tasks are generally done by most programs; hence, they
have been put together in common library files, which every programmer can use.
Various software corporations have added libraries and are selling their implementations
of the C++ language. Hence, we have DJGPP, Borland C++, Symantec C++, Metrowerks
CodeWarrior, IBM VisualAge and KAI C++. These implementations provide Integrated
Development Environments (IDEs). An IDE is software that allows you to write a
program, check it for errors, and translate it into machine language. These tasks are
performed by using a built-in editor, debugger, and compiler, respectively. An IDE also
allows you to link and execute (run) the compiled program.
In this course, you will use Code Blocks for developing applications. You need to
perform the following steps to compile and execute a C++ program by using the Code
Blocks compiler:
1. Press the Windows logo key. The Start screen is displayed.
3. Click the Code Blocks icon on the Start screen. The Start here - Code::Blocks
17.12 window appears, as shown in the following figure.
Identifying Errors
Before starting the compilation process, you must ensure that the program is error-free.
An erroneous program will not compile. Some of the common types of errors are
categorized as:
Syntax errors
Semantics errors
Logical errors
Type errors
Run-time errors
Syntax Errors
Syntax refers to the rules that govern the structuring of statements in a language. You
need to ensure that the statements that you write in your program are syntactically correct.
Consider the following snippet:
void main()
{
cout << “ Hello World”.
}
The preceding snippet when executed in the compiler will result in an error. This is
because, each statement in C++ must terminate with a semicolon (;), which has not been
done in the preceding code snippet. If in a program, you terminate a statement with a
symbol other than the semicolon (;), the program will cause a syntax error.
Semantic Errors
Semantic errors are those that are caused because of statements that are not meaningful.
Semantic refers to the meaning of a statement. The statement that you write may be
syntactically correct, but if the meaning of the statement is not correct, a semantic error
will be raised by the compiler. For example, you always place the expression to be
evaluated on the right-hand side of the assignment operator and the variable to which the
result is assigned is placed on the left-hand side of the assignment operator.
The preceding statement will result in a semantic error and the compiler will not execute
the program, even when the syntax of using variables, adding, assigning, and terminating
is correct.
Logical Errors
Logical errors are caused by statements that generate undesirable or unpredicted outputs.
For example, if you have to calculate the average score of 4 subjects but divide the sum of
4 subjects by 3, then this will constitute as a logical error as it will generate an undesirable
result.
Type Errors
Type errors are caused when you pass a type of value that is different than the one that is
expected by the program. For example, if you try to store an integer value in a string
variable, a type error will be raised.
Run-Time Errors
Run-time errors occur while the program is executing. Such errors are a result of certain
illegal operations. For example, during the program, if an expression causes a value to be
divided by zero, a run-time error will occur. Further, if during the execution of a program
there is insufficient memory, a run-time error is raised. Similarly, a run-time error will be
raised if the program tries to open a file that is nonexistent.
To understand the need for an array, let us consider a situation where the information
regarding fifty models of cars needs to be stored. Since a variable is capable of storing
only one value at a time and defining and keeping track of 50 variables in a program is
not easy, the solution is to declare one variable with 50 elements to store the information
about the various car models.
Before an array variable can be initialized, its data type and size (number of elements in
the array) must be defined. The definition and the initialization of an array variable can
occur within the same statement.
Each element of the array can be accessed by its subscript number. The subscript number
specifies the position of an element within the array (also called the index of the element).
The first element of an array has an index 0, and the last element has an index one less
than the dimension size of the array.
All the elements of an array must be of the same data type. Thus, there cannot be an array
with five elements of which three are char elements and two are float elements.
Example
The size of the array is 5. When the array definition is executed, memory is allocated for
the user-defined variable arr. The array elements will be positioned one after the other in
the memory. Following is a schematic representation of the placement of array elements
in the memory.
In the above diagram, arr is the name of the array variable. The elements of the array are
arr[0], arr[1], arr[2], arr[3], and arr[4]. Here, 0, 1, 2, 3, and 4 are the
subscripts (or indices) of the elements. Note that the index starts from 0.
In order to initialize this array, you need to initialize the individual elements, as shown in
the following statements:
arr[0] = 14;
arr[1] = 15;
arr[2] = 17;
arr[3] = 45;
arr[4] = 81;
The elements can be initialized in any order. Following is a schematic diagram of the
same array after initialization.
14 15 17 45 81
or
arr[4] = arr[0] + arr[2];
If you initialize an array at the time of its declaration, then it is not necessary to specify
the dimension of the array, as shown in the following statement:
int arr[] = {14, 15, 17, 45, 81};
Since an array subscript starts from zero, arr[2] refers to the third element in the array.
Therefore, writing cout << arr[2]; will display 17.
Note
You must specify the size of an array at the time of its declaration, unless you are
initializing it in the same statement. Therefore, the following code snippet is incorrect:
If you specify the size of an array as 3, and try to initialize more than three elements in
it, the compiler will show a warning and will ignore the last value:
An array cannot be initialized with another array. The only way to copy an array into
another is to copy its individual elements. The following statements show the correct and
incorrect ways to copy elements of an array to another array:
int abc[3] = {100,200,300}, xyz[3]; // Valid declaration
xyz = abc; // ERROR!! an array cannot be initialized with
// another array.
xyz[2] = abc[1]; // Correct
xyz[0] = abc[2]; // Correct
xyz[1] = abc[0]; // Correct
Consider a situation where you need to store details such as the price and mileage of two
popular models of cars.
#include <iostream>
class Car
{
float price;
int mileage;
void accept()
{
cout<< “\n Enter Price of a model\t”;
cin>>price;
cout<< “\n Enter Company Quoted Mileage\t”;
cin>>mileage;
}
};
int main()
{
Car car_det[2]; // Declares an array of user-defined data
// type populates the array with values
car_det[0].accept();
car_det[1].accept();
In the above program, an array of two elements is declared by using the statement:
Car car_det[2];
Note
The NULL character has the American Standard Code for Information Interchange
(ASCII) code 0 but is not the same as the digit ‘0’, which has the ASCII code 48.
The following code is a modified version of the program that stores details of cars. This
version of the program displays the model of the car along with the price and mileage:
#include <iostream.h>
#include <stdio.h> // for implementing getchar()
#include <conio.h> // for implementing clrscr()
class Car
{
float price;
int mileage;
char model[30];
public:
void display()
{
cout<< “\n The Model of Car is \t”<<model;
cout << “\nThe Price is \t”<<price;
cout << “\n The Average Mileage is \t”<<mileage;
}
void accept()
{
cout<< “\n Enter the Model of the Car\t”;
cin>>model;
cout<< “\n Enter Price of a model\t”;
cin>>price;
cout<< “\n Enter Company Quoted Mileage\t”;
cin>>mileage;
}
};
Even though you can use the cin object to accept input and the cout object to display
output for character arrays, these objects are not exclusively meant for string
manipulations. C++ provides you with string functions for manipulating strings. The
functions, gets() and puts() allow you to accept input for and display the value stored
in string arrays, respectively. You can also use the puts() function to display string
literals on the screen.
The preceding statements declare a character array, designation. The puts() function
displays the text “Enter Designation” on the screen. The gets() function allows you to
store the input provided by the user in the character array, designation. Next, the puts()
function displays the value stored in the string array. Each puts() statement displays the
output in a new line.
Note
The cin object does not accept whitespaces, whereas, the gets() function allows you
to enter strings that include white spaces.
Problem Statement
As a member of a team that is developing the billing system software for Diaz
Telecommunications, Inc., you have been assigned the task of creating a software module
that accepts the following customer details and displays it:
Mobile number, containing a maximum of 12 characters
Name, containing a maximum of 25 characters
Date of birth, containing a maximum of 10 characters
Billing address, containing a maximum of 50 characters
City, containing a maximum of 25 characters
Residence phone number, containing a maximum of 13 characters.
Amount outstanding, containing decimal values
Solution
#include <iostream>
class Customer
{
private:
char mobileNo[13];
char name[26];
char dateOfBirth[11];
char billingAdd[51];
char city[26];
char phoneNo[14];
float amountOutstanding;
public:
void print()
{
cout << endl << "Mobile phone number: ";
cout << mobileNo << endl;
cout << "Name: ";
cout << name << endl;
cout << "Date of Birth: ";
cout << dateOfBirth << endl;
cout << "Billing Address: ";
cout << billingAdd << endl;
cout << "City: ";
cout << city << endl;
cout << "Residence phone number: ";
cout << phoneNo << endl;
cout << "Amount due: ";
cout << amountOutstanding << endl;
}
After saving and compiling the program, execute the program to enter the following
highlighted information:
Mobile phone number: 678-295-9518
Name: Michael
Date of Birth: 10/8/1971
Billing Address: 14, George Street, New York
City: California
Residence phone number: 534-177-3312
Amount due: 0
Almost all applications need to store data for future use. Most of the times, this data is a
logical group of related information, such as employee details, product details, or student
details. The storage and retrieval of such data will be easier if it is stored in the form of
records. C++ provides structures that allow you to store information as a record. You can
use structures to group various types of data under one name.
Defining Structures
Structures are defined by using the struct keyword. Consider the following record
definition:
struct salesdata{
char transno [4];
int salesno;
int prodno;
int unit_sold;
float value_of_sale;
};
In the preceding definition, salesdata is the identifier of the structure that will store sales
records with details such as transaction number, salesman number, and product number.
Here, the struct keyword declares that the variables are to be treated as one unit called
salesdata. As in the case of other declarations, the struct declaration also ends with a
semi-colon.
The preceding snippet just defines the form of the structure and does not allocate memory
for the structure. To allocate memory to the structure, you need to declare a structure
variable.
In the preceding snippet, a structure variable, salesrec, has been declared. The structure
variable can be used to access the member variables of the structure.
You can also declare a structure variable by using the following syntax:
struct struct_name{
...
...
...
...
};
struct_name struct_variable;
The preceding method of declaring a structure variable does not require you to declare the
variable along with the definition. Therefore, you can declare a structure variable
anywhere in your program.
Thus, the structure variable for the salesdata structure can be declared as:
struct salesdata
{
char transno [4];
int salesno;
int prodno;
int unit_sold;
float value_of_sale;
};
salesdata salesrec;
The advantage of this method of declaration is evident when the structure salesrec has
to be passed to a function. Instead of declaring the entire structure type in the called
function, the parameter of the function can be declared to be of the structure type
salesdata in the same way that salesrec has been declared.
After you have created a structure variable, you can access the member variables of the
structure by using the dot operator. For example salesrec.salesno refers to the
variable salesno. Similarly, salesrec.transno[1] refers to the second element of the
array transno.
As in the case of other data types, it is possible to define an array of structures. You can
create an array of a structure to store multiple records. Consider that you have a structure
that includes three variables for storing student name, roll number, and score. A single
structure variable will allow you to store only one student record. However, if you create
an array of the structure, you can store multiple records of students, depending on the size
of the array.
If there are 20 students in a class, an array of the structure to hold 20 records has to be
created in the system memory. The array members can be initialized while declaring the
array of a structure.
Note that each set of values for the array has been enclosed in braces ({…}). This is not
essential but improves clarity of the code. You can refer to any member of the structure
by using an index along with the name of the array.
The following code snippet depicts how to create and use an array of a structure:
#include<iostream.h>
#include<conio.h>
#include <stdio.h>
struct Student_details
{
char Student_Name[30];
int Roll_No;
int score;
void main()
{
clrscr();
Student_details stud_records[] = {
{"Sach",1,0},
{"Jim",2,0,},
{"Bryan",3,0,},
{"Steven",4,0}
};
cout<<stud_records[0].Student_Name<<endl;
cout<<stud_records[0].Roll_No<<endl;
cout<<stud_records[1].Student_Name<<endl;
cout<<stud_records[1].Roll_No<<endl;
getch();
}
#include <iostream.h>
void main()
{
char ch=’A’;
char ch1=66;
int i=60.00;
cout<<ch<<endl<<ch1<<endl<<i;
}
#include <iostream.h>
class Customer
{
public:
int age;
};
void main()
{
Customer obj1, obj2;
cout<<”Enter the first customer’s age:”;
cin>>obj1.age;
obj2=obj1;
cout<<obj1.age<<” is the age of customer1”<<endl;
cout<<obj2.age<<” is the age of customer2”<<endl;
}
Exercise 1
You have defined an Employee class as part of developing a software application for Diaz
Telecommunications, Inc. The class, which you have defined, is as follows:
class Employee
{
char firstName;
char lastName;
char dateOfBirth;
char dateOfJoining;
char city;
char phoneNo;
public:
void accept()
{
//Code to accept employee details
}
void display()
{
//Code to display employee details
}
}
The Employee class definition shown above contains errors and is incomplete. Identify
and fix the errors. Complete the code in the Employee class definition and write the
main() function. Compile and execute the code.
Exercise 2
Jim works for an airline company. Customers fill the Booking Request Form with the
details of the flight like the flight number, destination, and date and hand it over to Jim.
He then books tickets for the customers based on the availability of seats.
Identify the classes and objects involved in the above scenario and their attributes. Write
methods in the class to accept and display the values of the different attributes.
Exercise 4
You need to write a program that accepts and displays the details of a specified number of
candidates who want to register in the gym, SuperGym. The details should include:
candidate_id, containing integer type of data.
candidate_name, containing a character array of length 30 characters.
candidate_age, containing float type of data.
Now, you need to write a program that uses a function student to calculate:
The number of students passed with distinction.
Number of students failed.
For distinction, a student needs to score at least 70% and minimum passing marks is 35%.
In object-oriented programming, data and the methods that can operate on the data are
clubbed as a single unit. This concept is known as encapsulation. Similarly, in object-
oriented programming, only the relevant data is exposed, hiding the rest of the data. This
concept is known as abstraction.
This chapter introduces the concept of encapsulation and abstraction. It discusses the
implementation of encapsulation by using access specifiers. In addition, it explains the
concept of static variables, functions, and friend functions.
Objectives
The above story, however doubtful of its authenticity, underlines an important reality – in
a complex world, neither does every individual concentrate nor does one need to
concentrate on every aspect of a given entity.
Similarly, a housewife would typically pay attention to the size, ease of handling, and
durability of a vacuum cleaner (she would not be interested in the gadgetry inside it, that
is in the purview of the maintenance man); sales personnel may concentrate on entirely
different factors. There is a term given to the above process: abstraction.
The Object Oriented approach also works on the same concept. It hides the unnecessary
details of a program and shows only the essential characteristics of the program to the
user. This process is known as abstraction.
- Grady Booch
Unable to deal with the complexity of an object, humans choose to ignore its non-essential
details and concentrate on the details that are essential to our understanding. Put very
simply and in context of the object model, abstraction means ‘looking for what you want’
in an object or a class.
“Encapsulation is the process of hiding all of the details of an object that do not
contribute to its essential characteristics.”
- Grady Booch
Therefore, when a housewife plugs in the cord of the vacuum cleaner and clicks on the
switch, the vacuum cleaner starts smoothly. She cannot, and does not, get to see the
complex processes needed to actually convert the electricity into suction power. In other
words, the exact working of the cleaner has been encapsulated. Encapsulation is also
called information hiding or data hiding, since it involves hiding many of the important
details of an object from the user.
Abstraction and encapsulation are different but related features. Abstraction enables you to
make the relevant information visible. Encapsulation enables you to package information
to implement the desired level of abstraction. Therefore, encapsulation assists abstraction
by providing a means of suppressing the nonessential details.
An access specifier is used to determine whether any other class or function can access
the member variables and functions of a particular class. C++ supports the following three
access specifiers:
public
private
protected
Access specifiers define the boundary between the accessible and inaccessible parts of a
class. It is the privilege of the designer of the class to demarcate which parts of a class
need to be obscured from the users view and which should be offered to them as an
interface to the class. Thus, you can use the access specifiers to implement encapsulation
and abstraction in C++.
In the above example, the variable color can be accessed from any function. Consider the
following code snippet that includes a public function:
#include<iostream>
class Car
{
public:
char color[15];
void honk()
{
cout << "PARRP PARRP!" << endl;
}
};
int main()
{
Car ford;
ford.honk(); //Displays PARRP PARRP!
return 0;
}
In the above example, the honk()function will be accessible from anywhere in the
program to any function.
In the above example, the setModel() and displayModel() functions can be called from
the ford object defined in the main() function. However, the model variable cannot be
accessed through the ford object since it is a private member variable. Similarly, the
honk() function cannot be accessed through the ford object, since it is a private member
function.
The default access specifier for a class member is private. In the following example, the
model member variable is private even though it has not been specified explicitly:
class Car
{
char model[21];
public:
...
};
In the above example, the setModel() and displayModel() functions can be called from
the ford object defined in the main() function. However, the model variable cannot be
accessed through the ford object since it is a protected member variable. Similarly, the
honk() function cannot be accessed through the ford object since it is a protected
member function.
Private Yes No
protected Yes No
Static Variables
You already know that each object has its own set of member variables. However, in
some situations, it is preferable to have one or more variables that are common for all
objects. C++ provides static variables for this purpose.
As its name suggests, static variables retain their value even after the function to which
it belongs has been executed. This means that a static variable retains its value throughout
the program.
Note
The static variables have to be initialized explicitly either inside the class declaration
or outside the class.
Static variables are initialized outside the member function or class definition. The
following example illustrates the declaration and initialization of a static variable:
class staticExample
{
int data;
static int staticVar; // Static variable declared
public:
//Definition of member function
};
int staticExample :: staticVar=0; //Static variable initialized to 0
In the above example, a static variable is initialized outside the class definition. Creating
more than one object will not reinitialize the static variable. Unlike member variables, only
one copy of static variable exists in the memory for all objects of that class. Thus, all
objects share one copy of the static variable in memory. Consider a situation where you are
required to keep track of the number of objects created for a given class. If you declare a
non-static member variable called counter, every instance of that class will create a
separate variable, and there will be no single variable having a count of the total number
of objects created. To avoid this, you can use static member variables because it is this
single static variable that gets incremented by all objects.
You can also initialize the static variable inside the class definition, as shown in the
following example:
#include <iostream>
class myclass
{
void increment()
{
static int i=5;
cout<<i<<endl;
i++;
}
public:
void display()
{
cout<<"calling increment for first time"<<endl;
increment();
cout<<"calling increment for second time"<<endl;
increment();
}
};
int main()
{
myclass m1;
m1.display();
return 0;
}
Static Functions
Like static variables, you can also declare a function to be static. Static functions can only
access static variables and not non-static variables. You use the class name to access the
static functions, as shown below:
ClassName::StaticFunctionName ;
In a situation where you want to check whether any object of a class has been created, you
make use of static functions because they come into existence even before the object is
created.
Friend Functions
Any non-member function may be declared a friend by a class, in which case the
function may directly access the private member attributes and methods of the class
objects. Consider the following code snippet:
class Z
{
friend void fn();
private:
int a;
};
void fn()
{
Z one;
one.a=5; // Okay, as fn() is a friend
}
void fn1()
{
Z one;
one.a=5; // Wrong as fn1 is not a friend of 'Z'
}
Note that 'fn()' is a global (non-member) function that has been declared a friend.
Member functions of other classes may also be declared as friends by declaring the class
as a friend class.
friend functions are used when the design of a class requires that another class or
non-member function should access the private elements of the class. In such a case,
friend function declarations may be used to enable the class to access those variables
directly.
Just as a function can be made a friend of a class, a class can also be made a friend of
another class:
class distance
{
...
friend class length;
...
};
In this example, the length class is the friend of the distance class. All the members
of the distance class can now be accessed from the length class. The program below
illustrates an entire class declared as a friend of another class:
#include<iostream>
class class1
{
private:
int i;
public:
friend class class2;
};
class class2
{
public:
void func()
{
class1 A1;
cout<<"The value of i in class class1 is "<<A1.i<<endl;
//The function can access the private data of class1
}
};
int main()
{
class2 B1;
B1.func();
return 0;
}
In the preceding program, the class2 class is a friend of the class1 class. Now, all the
member functions of class2 class can access the non-public data of class1.
#include <iostream.h>
class Counter
{
private :
unsigned int count;
public:
Counter ( ) {count = 0;}
void inc_Count ( ) { count ++;}
int get_Count( ) {return count;}
};
void main( )
{
Counter C1, C2;
cout<<”\n C1=”<<C1.get_Count( );
cout<<”\n C2=”<<C2.get_Count( );
C1.inc_Count( );
C2.inc_Count( );
C2.inc_Count( );
cout<<”\n C1=”<<C1.get_Count( );
cout<<”\n C2=”<<C2.get_Count( );
}
Exercise 1
You have defined a Dealer class as part of developing the billing system software for
Diaz Telecommunications, Inc. The class, which you have defined, is as follows:
class Dealer
{
private:
char mobileNo[11];
char dealerName[25];
char dealerAddress[51];
char dealerCity[25];
char phoneNo[11];
public:
static int CompanyID
static void showID()
{
cout<<"The dealer name is"<<dealerName;
cout<<"The company ID is"<<CompanyID;
}
void get()
{
//Code to accept the dealer details
}
void print()
{
//Code to print the dealer details
}
};
int CompanyID=6519;
The Dealer class definition shown above is incorrect. Identify the errors in the Dealer
class and write a correct definition for it.
CH AP T E R 4
While programming, you may come across various situations where you need to perform
computations on data. Similarly, you may come across situations that involve
decision-making and iterative tasks. Such situations can be handled by using the various
types of operators, decision-making constructs, and looping constructs provided in C++.
This chapter discusses the various types of operators, provided in C++, with their
precedence. It also discusses the various conditional and looping constructs provided in
C++. In addition, it discusses the scope of variables.
Objectives
Arithmetic Operators
Arithmetic Operators
Example
int x = 7 + 3 * 6;
cout << x << endl; // Output would be 25
int y = 100 / 4 * 5;
cout << y << endl; // Output would be 125
To understand the above outputs, consider the following precedence and associativity
table for arithmetic operators.
Thus, '*' has a higher precedence than '+', and '/' has the same precedence as '*'. In the
expression, int x = 7 + 3 * 6;, the part 3 * 6 is evaluated first and the result 18 is
added to 7. And in the expression int y = 100 / 4 * 5;, the part 100/4 is evaluated first,
since the operator '/' is to the left of the operator '*'.
You can change the precedence and associativity of the arithmetic operators by using the
operator '()' since the '()' operator has the highest precedence among the three types
being discussed. The '()' operator has left to right associativity for evaluating the data
within it.
Example
int x = (7 + 3) * 6;
cout << x << endl; // Output is 60
int y = 100 / (4 * 5);
cout << y << endl; // Output is 5
int z = 7 + ( 5 * (8 / 2) + (4 + 6));
cout << z << endl; // Output is 37
Note
The modulus operator works only with int operands.
You use the assignment operator '=' to assign the value of the right operand to the left. For
example, the statement x=y assigns the value of y to x. You can also assign values to more
than one variable at the same time. Here, the values will be assigned from the right to the
left.
Example
x = y = 0;
In the example given above, y will be initialized before x.
The statement count=count+2 increments the value of the variable count by 2. This
statement can be modified by using the arithmetic assignment operator (+=), as shown in
the following example:
count+=2; //Is the same as count=count+2
count-=2; //Is the same as count=count-2
+= Adds the operands and assigns x += y Adds the value of y to x and stores
the result to the left operand the result in x
The expression can also be written as
x = x + y
-= Subtracts the right operand from x -= y Subtracts y from x and stores the
the left operand and stores the result in x
result in the left operand
Equivalent to x = x - y
*= Multiplies the left operand by the x *= y Multiplies the values of x and y and
right operand and stores the stores the result in x
result in the left operand
Equivalent to x = x * y
/= Divides the left operand by the x /= y Divides x by y and stores the result in
right operand and stores the x
result in the left operand
Equivalent to x = x / y
The unary operators operate on one operand. The following table explains the two unary
operators, increment and decrement.
Unary Operators
The decrement operator can also be used in both the prefix and postfix forms.
If the operator is to the left of the expression, the value of the expression is modified
before the assignment. Conversely, when the operator is to the right of the expression,
increment or decrement occurs only after the assignment. Therefore, in the statement
var2 = var1++; the original value of var1 is assigned to var2. In the statement
var2 = ++var1;, the incremented value of var1 is assigned to var2.
Comparison Operators
Comparison operators, which are also called relational operators, are used to compare
two values. Comparison operators evaluate to true or false.
== Evaluates whether or not the x == y Returns true if the values are equal
operands are equal. and false otherwise
!= Evaluates whether or not the x != y Returns true if the values are not
operands are not equal equal and false otherwise
> Evaluates whether or not the x > y Returns true if x is greater than y and
left operand is greater than false otherwise
the right operand
< Evaluates whether or not the x < y Returns true if x is less than y and
left operand is less than the false otherwise
right operand
>= Evaluates whether or not the x >= y Returns true if x is greater than or
left operand is greater than or equal to y and false otherwise
equal to the right operand
<= Evaluates whether or not the x <= y Returns true if x is less than or equal
left operand is less than or to y and false otherwise
equal to the right operand
Comparison Operators
Logical Operators
Logical operators are used to combine two or more expressions. C++ provides the
AND(&&), the OR(||), and the NOT(!) logical operators. The following table shows
various logical operators.
Logical Operators
The operators, && and ||, are called short circuit operators. Short circuit operators do
not evaluate the second expression if the result can be obtained by evaluating the first
expression alone.
The second condition (y > 10) is skipped if the first condition is false, since the entire
expression will anyway be false. Similarly with the || operator, if the first condition
evaluates to true, the second condition is skipped as the result will anyway be true.
* Multiply
/ Divide
+ Addition
- Subtraction
== Equal to
!= Not equal to
6 = Simple assignment
Operator Precedence
Expressions in C++
Arithmetic Expressions
Arithmetic expressions include two types of expressions, integer expressions and real
expressions. The type of arithmetic expression that is created depends on the type of
operators and operands that you combine.
Integer Expressions
The result of an integer expression will always be an integer. Consider that you have a, b,
and c as integer variables and d as integer constant.
Real Expressions
Logical Expressions
An expression that evaluates to either true or false is known as a logical expression. You
can form a logical expression by combining constants or variables by using relational or
logical operators. The following statements are examples of logical expressions:
1. a > b
2. (a – b) < d && (c + a) < b
3. (a > b) || (b > c)
4. (a<= b) && (d<=c)
Note
An expression that is formed by combining integer variables/constants with real
variables/constants by using arithmetic operators is known as compound or
mixed-mode expression.
There may be situations where you need to use constants or variables of one type with
those of some other types in an expression. In such a scenario, the result of the expression
is converted into the type of variable to which the result is being stored.
This process of conversion of one type into a different type is referred to as type
conversion. C++ provides the following two methods of type conversions:
Implicit type conversion: This form of conversion does not require any intervention
by the programmer. It is performed implicitly by the compiler. Relying on implicit
type conversion may result in loss of data in case a higher data type is converted into
a lower data type.
Explicit type conversion: This form of conversion forces the compiler to convert
one data type into a specified data type. In C++, you can explicitly convert an
expression into a specific type by using type casting, which has the following syntax:
result = (type) expression;
In the above syntax, type represents the data type in which you want the result of the
expression to be converted to. This result will then be stored in the result on the left
side of the assignment operator (=).
Consider the following statement:
int x = 5.5/2;
In the above statement, the expression on the right evaluates to a decimal value and
the expression on the left is an integer and hence, cannot hold a fraction. An analogy
would be excessive amount of tea poured into a tea cup. Data can be lost when the
expression is converted from a higher data type to a lower data type.
You can also explicitly typecast the preceding assignment, as shown in the following
statement:
int x = (int)5.5 / 2;
Here, the generated output will be 90, which is the ASCII value of Z.
Consider the following statement that shows implicit type conversion:
int var1;
var1=19.99 + 11.99; //Value stored in var1 is 31
Note
The operator ==, which is used for comparing two data items, is different from the
assignment operator =.
In the above example, if the input character is 'A', the message, The character is A, is
displayed or else the message, The character is not A, is displayed. In addition, note
that the condition has to be specified within parenthesis.
If however, the = operator is used instead of the == operator, the statement is executed as
an assignment. For example, if the statement if(chr == 'A') is written as if(chr =
'A') then, chr would be assigned the value 'A' and the condition will be evaluated as
true. Thus, the message The character is A will be displayed, regardless of the input.
Conditional Operator
Consider the following if...else statements:
if ( iNum1 > iNum2 )
{
iMax = iNum1;
}
else
{
iMax = iNum2;
}
In the above program code, iMax is assigned the value iNum1 if the test expression is true,
and is assigned the value iNum2 if the test expression is false.
The ?: operator is called the conditional (or the ternary) operator and takes the form:
Exp1 ? Exp2: Exp3;
where, Exp1, Exp2, and Exp3 are expressions. Exp1 is evaluated. If it is true, Exp2
becomes the value of the expression, and if false, Exp3 becomes the value of the
expression. For example, in the following statement:
iVar1=10;
iVar2 = (iVar1 > 9) ? 30 : 40;
iVar2 will be assigned the value 30. If iVar1 is less than or equal to 9, then iVar2 will
receive the value 40.
You can also use a nested if...else construct in your program. In a nested if...else
construct, you can have an if...else construct inside another if...else construct. The
following program uses a nested if...else construct to check if the input character is
uppercase or lowercase:
#include <iostream>
class constructs
{
char inp;
public:
void acceptCharacter( )
{
cout << "Enter a character: ";
cin >> inp;
if(inp >= 'A')
if(inp <= 'Z')
cout << endl << "Uppercase";
else if (inp >= 'a')
if(inp <= 'z')
cout << endl << "Lowercase";
else
cout << endl << "Input character > z";
else
cout << endl << "Input character > Z but less than a";
else
cout << endl << "Input character less than A";
}
};
int main()
{
constructs c1;
c1.acceptCharacter();
return 0;
}
The following program shows how the clarity of steps can be increased by using braces
({ and }) for enclosing parts of the code that follow an if or an else statement:
#include <iostream>
class constructs
{
char inp;
public:
void acceptCharacter( )
{
cout << "Enter a character: ";
cin >> inp;
if(inp >= 'A')
{
if(inp <= 'Z')
{
cout << endl << "Uppercase";
}
else if (inp >= 'a')
{
if(inp <= 'z')
{
cout << endl << "Lowercase";
}
}
}
}
};
int main()
{
constructs c1;
c1.acceptCharacter();
return 0;
}
The following program uses a cascading if...else construct to determine if the input
character is a vowel, else it prints an appropriate message:
#include <iostream>
class constructs
{
char in_chr;
public:
The output of this program for two different character inputs is shown below:
Enter a character in lowercase
e
Vowel e
Another conditional construct available in C++ is, switch...case. It is used when there
are multiple values for a variable. When the switch statement is executed, its
condition-variable is evaluated and compared with each case constant. If one of the case
constants is equal to the value of the condition-variable, control is passed to the statement
following the matched case label. If no case constant matches the condition-variable, and
there is a default label, control passes to the statement with the label default. If no
case matches and if there is no default label, then none of the statements in the switch
is executed. A break statement is used to exit the switch statement.
The data type of the case constant should match with that of the switch variable. Before
entering the switch construct, a value should be assigned to the switch variable.
Note
Both, case and default, statements may occur in any order. The case expressions
can be either an int or a char expression only.
Here, the variable y is assigned a value depending on the value of the variable x. In case x
has the value 1, the first case statement block is executed and y is assigned the value 1.
The break statement passes the program control out of the switch construct.
Note
The case constants in the switch construct cannot have the same value.
Similar to the nested if…else construct, you can also nest switch..case statements in
your code. In other words, you can place another switch..case construct within an outer
switch..case construct. Consider the following code snippet:
switch(x)
{
case 1: switch (z)
{
case 2 : mul = x * z;
break;
case 3 : mul = x * x;
}
break;
case 2:
mul = 10;
break;
default:
mul = 0;
}
In the preceding code snippet, a switch ..case construct is nested within the case 1
statement. If the value of x matches 1, another switch..case construct nested within the
outer construct is executed and the statements within the nested construct are tested for
the value of z.
The while loop is a looping construct available in C++. The while loop continues until
the evaluating condition/expression becomes false. The evaluating condition has to be a
logical expression and must return either a true or a false value. The variable that is
checked in the Boolean expression is called the loop control variable.
Consider a Fibonacci series. In a Fibonacci series, each number is the sum of its two
preceding numbers. The series starts with 1. The following program generates a Fibonacci
series between 1 and 200:
#include <iostream>
class loops
{
int num1;
int num2;
public:
void fibonacci()
{
num1=num2=1;
cout << num1 << endl;
while (num2 < 200)
{
cout << num2 << endl;
num2 += num1;
num1 = num2 – num1;
}
}
};
Output
1
1
2
3
5
8
13
21
34
55
89
144
Note that in the preceding output, each number in the series is the sum of the two
preceding numbers.
The control exits the loop when the condition num2 == 89, becomes true.
The do...while loop construct is similar to the while loop construct, as both iterate until
the specified loop condition becomes false. It differs from the while loop because the
body of the do…while loop is executed at least once, and the condition is evaluated for
subsequent executions.
do while
Execute body
of loop
Evaluate
condition
FALSE
TRUE
Evaluate
condition FALSE Execute body
of loop
while
TRUE
In the preceding example, the condition while (num < 10) is evaluated only after the
body of the loop has been executed once. Therefore, the value of num is increased by 1. If
the same code is written in a while loop, the loop will not be executed.
The for loop construct provides a compact way of specifying the statements that control
the repetition of the steps within the loop. In the for construct, the loop control statements
are not written within the body of the loop; instead they are written at the top. This makes
the program more readable and easily understandable. The for statement consists of the
keyword for followed by parentheses containing three expressions, each separated by a
semicolon. These are the initialization expression, the test expression, and the
increment/decrement expression.
The body of the for loop is enclosed within braces. In the following statement:
for( ivar = 0; ivar <= 10; ivar++)
ivar = 0 is the initialization expression, ivar <= 10 is the test expression, and ivar++ is
the increment expression. Here, ivar is the loop variable.
Initialization Expression
The initialization expression is executed only once, when the control is passed to the loop
for the first time. It gives the loop variable an initial value.
A common mistake that programmers might make is to terminate the for loop with a
semicolon. For example, check the following statements:
for( var = 0; var <= 10; var++);
{
cout << var * var;
}
Since the for statement is terminated with a semicolon, it becomes a self-executing for
loop that moves to the next statement only when the condition in the for loop becomes
false. The for loop is exited when the value of var is 11, and hence the output is 121
(11*11).
Nested Loops
Similar to the nested if…else or nested switch…case constructs, you can nest loops
within another loop. In a nested loop, the inner loop terminates before the termination of
the outer loop.
void main()
{
In the preceding code snippet, the nested for loop is executed for each value of j. The
nested for loop is executed until i is less than or equal to the value of j. When the value
of j is 1, i is initialized with 1 and its value is displayed on the screen. The nested loop
executes only once because i is already equal to the value of j before the first iteration.
Next, when j=2, the nested loop will execute twice, that is, till the value of i becomes 2.
Similarly, the inner loop executes thrice for j=3 and four times for j=4.
Problem Statement 1
Write a program that will reverse an accepted string and copy it into another string.
Solution
#include <iostream>
class strings
{
char source[101], dest[101];
int pos ,j;
public:
void reverseString()
{
pos=j=0;
cout << "Enter string to be reversed"
<< " (please enter a maximum of 100 characters): " << endl;
cin >> source;
while(source[pos]!= '\0')
{
pos = pos + 1;
}
for(--pos; pos >= 0 ;dest[j++] = source[pos--]);
dest[j] = ‘\0’;
cout << endl << "The reversed string is: " << endl << dest << endl;
}
};
int main()
{
strings S1;
S1.reverseString();
return 0;
}
position the variable pos at the location of the NULL character in the array named source.
This statement can also be written as:
pos = -1;
while(source[++pos]);
The statement, dest[j] = ‘\0’;, is required because the array must terminate with a
NULL character.
Problem Statement 2
Write a program to accept and display the amount outstanding for 10 customers. The
amount outstanding should be displayed in an ascending order.
Solution
In this program, to sort the float array in ascending order, you need to perform the
following steps:
1. Traverse the array.
2. Compare the value of the current element with the value of the next element for each
element in the array.
float amounts[10];
public:
void sortData()
{
int ctr;
for ( ctr = 0; ctr < 10; ctr ++ )
{
cout << “Enter the amount : ";
cin >> amounts[ctr];
}
int counter=0;
/* Traverse the array */
while(counter < 9)
{
float temp;
/* Compare the value of current element with the next */
if(amounts[counter] > amounts[counter + 1])
{
/* Swap the values */
temp = amounts[counter];
amounts[counter] = amounts[counter + 1];
amounts[counter + 1] = temp;
counter = 0;
continue;
}
counter++;
}
}
void display()
{
/* Display all the array elements */
for(int counter = 0;counter < 10; ++counter)
{
cout << "Element " << counter << ": " <<
amounts[counter] << endl;
}
}
};
Problem Statement 3
Write a program to convert upper-case characters in a sentence into lower-case characters.
Solution
// Program to convert case,
/*function to convert a string to lower-case*/
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char in_str[101];
int i=0;
printf("Enter a string (upto 100 characters)\n");
gets(in_str);
while(in_str[i]!='\0')
{
if(in_str[i]>='A' && in_str[i]<'Z') /*check for upper-
case letters*/
in_str[i]=in_str[i]+32;
i=i+1;
}
cout<<"The converted string is"<< in_str;
getch();
}
File Scope
File scope is considered to be the outermost scope. It is defined as "the space outside all
functions". Variables that have file scope are accessible throughout the program file and
are called global variables.
Global variables can also be referred as extern. Consider the following code snippet
given in the file J1.cpp:
#include <iostream>
#include “C:\myprograms\j2.cpp”
int i=10;
void main()
{
void disp();
i=i+9;
cout<<"J1.cpp ->"<<i;
disp();
}
To access the variable i from another file J1.cpp, it should be referred to as extern in file
j2.cpp. The following example shows the contents of j2.cpp file:
#include <iostream>
extern int i;
void disp()
{
i=i-3;
cout<<" j2.cpp->"<<i;
}
On compilation and execution of j1.cpp file, the global variable i defined in the J1.cpp
file is accessible to file J2.cpp.
Note
You can include code of one file in another file by using the following syntax in the file
where the inclusion needs to be done:
#include “filepath/filename”
However, you need to ensure that the program that finally gets executed contains only
one main() function. The program should not have another main() as a result of
multiple inclusions.
Local Scope
Local scope is defined as being limited to the braces of a function or a control structure
like for, while, and if. The variables that have local scope are not accessible outside the
function or the control structure. Such variables are called local variables. The following
program shows an example of local and global variables:
#include <iostream>
int globalVar;
class scope
{
int x;
public:
void func1()
{
int localVar=10; //localVar can be accessed only in
//func1()
cout<<globalVar<<endl; // globalVar can be accessed
//here
}
void func2()
{
cout<<localVar<<endl; //Error! LocalVar is no longer
//accessible
//localVar is out of scope.
}
};
Class Scope
When a class declaration is employed, all the members are accessible only within the
class. In other words, the member variables and functions within the class declaration will
no longer be visible to the functions outside it. The member variables and the functions in
this case are said to have class scope since their accessibility is restricted to the class.
C++ offers you the flexibility of deciding which member variables or functions should be
accessible outside the class. Declaring a member of a class as a public member enables
this. Shown below is the class declaration point, which illustrates the class scope of
member variables and functions:
class point
{
private:
int x_co_ord;
int y_co_ord;
public: // Private section ends here and public
// starts here.
// All preceding entries are not
// accessible by a variable
// of the type point. They can be
// manipulated only through
// functions defined in the public section
void set_point();
};
Practice Questions
1. Write a program to accept the salaries of 10 employees from the user and display
them in descending order for all the employees. If the user enters zero, the program
should display the message “The amount should be greater than zero” and accept the
value again.
Summary
In this chapter, you learned that:
Operators are used to compute and compare values and test multiple conditions.
You use arithmetic operators to perform arithmetic operations, such as addition,
subtraction, multiplication, and division.
You can also use arithmetic assignment operators to perform arithmetic operations.
The unary operators, such as the increment and decrement operators operate on one
operand.
Comparison operators, which are also called relational operators, are used to
compare two values.
Logical operators are used to combine two or more expressions.
Conditional constructs are used to allow the selective execution of statements. The
conditional constructs in C++ are:
if...else
switch...case
Looping constructs are used when you want a section of a program to be repeated a
certain number of times. C++ offers the following looping constructs:
while
do...while
for
The break and continue statements are used to control the program flow within a
loop.
The scope of a variable specifies its accessibility.
C++ features three types of scopes: file, class, and local scope.
Exercise 1
Create a menu-driven application that accepts the salaries of ten employees and displays
the following information:
The maximum salary
The minimum salary
The average salary
The number of employees whose salary is greater than 1000
The salaries in ascending and descending orders
Exercise 2
The following code to display the number of days in a month is very complex and
therefore you need to simplify the code and execute:
#include<iostream>
int main()
{
int month;
cout<< "Tell me a month number.";
cout<< "I will tell you the number of days in that month.";
cin>>month;
if((month==1)||(month==3)||(month==5)||(month==7)||(month==8)||(month
==10)||(month==12))
{
cout<<"Month has 31 days";
}
else
{
if((month==4)||(month==6)||(month==9)||(month==11))
{
cout<<"Month has 30 days";
}
else
{
if (month==2)
{
Exercise 3
The following code prints a number less than the total number of objects created:
#include<iostream>
class CountsItself
{
static int objectCount;
int localCount;
public:
void setCount()
{
localCount=objectCount++;
}
void displayCount()
{
cout<<"Total number of objects :"<<localCount; }
};
int CountsItself::objectCount;
int main()
{
CountsItself count1, count2, count3;
count1.setCount();
count2.setCount();
count3.setCount();
count3.displayCount();
}
However, the preceding code does not execute correctly. Write and execute the correct
code.
Exercise 1
Exercise 2
class sample
{
public:
void display()
{
cout<<"var1="<<var1;
cout<<"var2="<<var2;
}
};
int main()
{
sample S1;
S1.display();
}
Fix the error in the preceding code and verify the same by executing the code.
4.42 Operators and Decision-Making Constructs
Exercise 3
Consider the following program that assigns values to three different variables var1,
var2, and var3 through a member function assign():
#include<iostream>
class values
{
int var1;
int var2;
int var3;
public:
void assign()
{
var1=5;
var2=10;
var3=15;
}
void display()
{
cout<<"The value of variable1 is:"<<var1<<endl;
cout<<"The value of variable2 is:"<<var2<<endl;
cout<<"The value of variable3 is:"<<var3<<endl;
}
};
void main()
{
values V1;
V1.assign();
V1.var2=20;
V1.display();
}
The object of the class in the preceding program should change the value of variable var2
in the main() function. Make the necessary changes in the code to accomplish the same.
Exercise 4
Write a program to find the total runs scored by a player in three cricket matches. Also,
find the average of the runs scored.
Exercise 5
Write a program to find the maximum and minimum values from a set of values provided
by the user.
Exercise 7
A programmer may also come across a situation where he/she may want the users to
provide input values at the time of executing a program. This can be achieved by
implementing command line parameters in the program.
This chapter discusses how to use built-in functions in a C++ program. In addition, it
discusses how to handle command line parameters in a C++ program.
Objectives
Character Functions
You need to include the ctype.h library in the program in order to use the standard
character functions.
void main()
{
clrscr();
char ch=’%’;
if(isalnum(ch))
cout<< "is alphanumeric";
else
cout<< "is not alphanumeric";
getch();
}
You need to include the string.h library in the program in order to use the standard
string-handling functions.
strlen Returns the length for the int strlen (const If the array cStr1 contains
string. The length does char * str1 ); the string “Normal is boring”,
not include the NULL Where: then the following statement:
character.
iNum=strlen(cStr1);
str1 refers to string whose
length needs to be will cause iNum to have the
determined. value 16.
strstr Scans string1 for the first char * strstr (char * char str1[]=”Hello
occurrence of string2. string1, const char * World”;
This function returns the string2 );
char str2[]=”or”;
offset of one string within Where:
another. char
string2 refers to string *sFound=strstr(str1,st
that needs to be searched r2);
for in string1. cout<<sFound-str1+1;
will display 8.
strchr Searches for a character char * strchr (const ptr = strchr( s, '\0'
in a string. char * string, int );
c);
The '\0' symbol that terminates
Where: the string is also considered
part of the string; thus it is
string refers to string that
possible to find the end of the
needs to be searched for string with the preceding
character c. example
Numeric Functions
You need to include the math.h library in the program in order to use the standard
numeric functions. Whereas, in case of the abs and atoi function you include the
stdlib.h library file.
sqrt Returns the square root of double sqrt ( double param = 1024.0;
parameter. x );
result = sqrt
where x refers to the (param);
non-negative floating point will store 32 in the
value. result variable
atoi Returns the integer value int atoi (const char Char
stored as a string. * string); str[]=”345A”;
main()
{
double a=3.9;
double b=2.3;
int x;
x=floor(a);
cout<<endl<<"The floor value of a is: "<<x;
x=floor(b);
cout<<endl<<"The floor value of b is: "<< x;
x=ceil(a);
cout<<endl<<"The ceil value of a is: "<< x;
x=ceil(b);
cout<<endl<<"The ceil value of b is: "<< x;
}