Upload
gourav-bhatt
View
228
Download
0
Embed Size (px)
Citation preview
8/4/2019 C lecturenotes
1/344
Lecture No. 1
Introduction to OOPS
Why Do We Need OOP?
OOP was developed because limitations werediscovered in earlier approaches toprogramming. To appreciate what OOP does,you need to understand what theselimitations are and how they arose fromtraditional programming languages.
Procedural Languages
Pascal, C, BASIC, Fortran, and similartraditional programming languages are
procedural languages. That is, eachstatement in the language tells the computerto do something: Get some input, add thesenumbers, divide by 6, display that output. Aprogram in a procedural language is a list ofinstructions.For very small programs, no otherorganizing principle (often called aparadigm)is needed. The programmer creates the list of
8/4/2019 C lecturenotes
2/344
instructions and the computer carries themout.
Division into Functions
When programs become larger, a single list ofinstructions becomes unwieldy. Fewprogrammers can comprehend a program ofmore than a few hundred statements unless itis broken down into smaller units. For thisreason, the function was adopted as a way tomake programs more comprehensible to theirhuman creators. (The term function is used inC++ and C. In other languages, the sameconcept may be called a subroutine, asubprogram, or a procedure.) A program isdivided into functions andideally, at leasteach function has a clearly defined purposeand a clearly defined interface to the otherfunctions in the program. The idea ofbreaking a program into functions can beextended by grouping a number of functions
8/4/2019 C lecturenotes
3/344
together into a larger entity called a module,but the principle is similar: a grouping ofinstructions that carry out specific tasks.Dividing a program into functions andmodules is one of the cornerstones ofstructured programming, the somewhatloosely defined discipline that has influencedprogramming design for several decades.
Problems with Structured Programming
As programs grow ever larger and morecomplex, even the structured programmingapproach begins to show signs of strain. Youmay have heard about, or been involved in,horror stories of program development. Theproject is too complex, the schedule slips,more programmers are added, complexityincreases, costs skyrocket, the schedule slipsfurther, and disaster ensues. Analyzing thereasons for these failures reveals weaknessesin the procedural paradigm itself. No matterhow well the structured programmingapproach is implemented, large programsbecome excessively complex. What are thereasons for this failure of procedural
8/4/2019 C lecturenotes
4/344
languages? One of the most crucial is the roleplayed by data. In a procedural language, theemphasis is on doing thingsread thekeyboard, invert the vector, check for errors,and so on. The subdivision of a program intofunctions continues this emphasis. Functionsdo things, just as single program statementsdo. What they do may be more complex orabstract, but the emphasis is still on theaction. What happens to the data in thisparadigm? Data is, after all, the reason for aprograms existence. The important part of aninventory program isnt a function thatdisplays the data or a function that checks forcorrect input; its the inventory data itself. Yetdata is given second-class status in theorganization of procedural languages. Forexample, in an inventory program, the datathat makes up the inventory is probably readfrom a disk file into memory, where it istreated as a global variable. Global, meansthat the variables that constitute the data aredeclared outside of any function so they areaccessible to all functions. These functionsperform various operations on the data. Theyread it, analyze it, update it, rearrange it,
8/4/2019 C lecturenotes
5/344
display it, write it back to the disk, and so on.I should note that most languages, such asPascal and C, also support local variables,which are hidden within a single function. Butlocal variables are not useful for importantdata that must be accessed by many differentfunctions. Figure 1-1 shows the relationshipbetween global and local variables.
Figure 1-1 Global and local variables
Suppose a new programmer is hired to write afunction to analyze this inventory data in a
certain way. Unfamiliar with the subtleties ofthe program, the programmer creates afunction that accidentally corrupts the data.
This is easy to do, because every function hascomplete access to the data. Its like leavingyour personal papers in the lobby of your
8/4/2019 C lecturenotes
6/344
apartment building: Anyone can change ordestroy them. In the same way, global datacan be corrupted by functions that have nobusiness changing it. Another problem is that,because many functions access the samedata, the way the data is stored becomescritical. The arrangement of the data cant bechanged without modifying all the functionsthat access it. If you add new data items, forexample, youll need to modify all thefunctions that access the data so that theycan also access these new items. It will behard to find all such functions and evenharder to modify all of them correctly. Itssimilar to what happens when your localsupermarket moves the bread from aisle 4 toaisle 12. Everyone who patronizes thesupermarket must figure out where the breadhas gone and adjust their shopping habitsaccordingly. The relationship of functions anddata in procedural programs is shown inFigure 1-2.
8/4/2019 C lecturenotes
7/344
Figure 1-2The procedural paradigm
What is needed is a way to restrict access tothe data, to hide it from all but a few criticalfunctions. This will protect the data, simplifymaintenance, and offer other benefits.
Relationship to the Real World
Procedural programs are often difficult todesign. The problem is that their chief
componentsfunctions and data structuresdont model the real world very well. Forexample, suppose you are writing code tocreate the elements of a graphics userinterface: menus, windows, and so on. Whatfunctions will you need? What data
8/4/2019 C lecturenotes
8/344
structures? The answers are not obvious, tosay the least. It would be better if windowsand menus corresponded more closely toactual program elements.
New Data Types
There are other problems with traditionalanguages. One is the difficulty of creatingnew data types. Computer languagestypically have several built-in data types:integers, floating-point numbers, characters,and so on. What if you want to invent yourown data type? Perhaps you want to workwith complex numbers, or two-dimensionalcoordinates, or datesquantities the built-indata types dont handle easily. Being able tocreate your own types is called extensibilitybecause you can extend the capabilities ofthe language. Traditional languages are notusually extensible. Without unnaturalconvolutions, you cant bundle both x and ycoordinates into a single variable called Pointand then add and subtract values of this type.
8/4/2019 C lecturenotes
9/344
Traditional programs are more complex towrite and maintain.
The Object-Oriented Approach
The fundamental idea behind object-orientedlanguages is to combine into a single programentity both data and the functions thatoperate on that data. Such an entity is calledan object.
An objects functions, called memberfunctions in C++ (because they belong to aparticular class of objects), typically providethe only way to access its data. If you want toread a data item in an object, you call amember function in the object. It will read theitem and return the value to you. You cantaccess the data directly. The data is hidden,so it is safe from accidental alteration. Dataand its functions are said to be encapsulatedinto a single entity. Encapsulation and datahiding are key terms in the description ofobject-oriented languages. If you want tomodify the data in an object, you know
8/4/2019 C lecturenotes
10/344
exactly what functions interact with it: themember functions in the object. No otherfunctions can access the data. This simplifieswriting, debugging, and maintaining theprogram. A C++ program typically consists ofa number of objects that communicate witheach other by calling one anothers memberfunctions.
Figure 1-3 shows the organization of a C++program.
Figure 1-3The object-oriented paradigm
8/4/2019 C lecturenotes
11/344
What are called member functions in C++ arecalled methods in some other object-oriented(OO) languages such as Smalltalk, one of thefirst OO languages. Also, data items may becalled instance variables. Calling an objectsmember function is often referred to assending a message to the object.
The Corporate Analogy
You might want to think of objects asdepartmentssuch as sales, accounting,personnel, and so onin a company.Departments provide an important approachto corporate organization. In most companies(except very small ones), people dont workon personnel problems one day, payroll thenext, and then go out in the field as
8/4/2019 C lecturenotes
12/344
salespeople the following week. Eachdepartment has its own personnel, withclearly assigned duties. It also has its owndata: payroll, sales figures, personnel records,inventory, or whatever, depending on thedepartment. The people in each departmentcontrol and operate on that departmentsdata. Dividing the company into departmentsmakes it easier to comprehend and controlthe companys activities and helps maintainthe integrity of the information used by thecompany. The payroll department, forinstance, is responsible for payroll data. If youwork in the sales department and you need toknow the total of all the salaries paid in thesouthern region in July, you dont just walkinto the payroll department and startrummaging through file cabinets. You send amemo to the appropriate person in thedepartment and then wait for that person toaccess the data and send you a reply with theinformation you want. This ensures that thedata is accessed accurately and it is notcorrupted by inept outsiders.
8/4/2019 C lecturenotes
13/344
This view of corporate organization is shownin Figure 1-4. In the same way, objectsprovide an approach to program organizationwhile helping to maintain the integrity of theprograms data.
Figure 1-4The
corporateparad
Concepts of OOPS
Features of Object-Oriented Languages
8/4/2019 C lecturenotes
14/344
Real-World Objects
When you approach a programming problemin an object-oriented language, you no longerask how the problem will be divided intofunctions, but how it will be divided intoobjects. Thinking in terms of objects ratherthan functions has a surprisingly helpful effecton how easily you can design programs. Thisresults from the close match between objectsin the programming sense and objects in thereal world. What kinds of things becomeobjects in object-oriented programs? Theanswer is limited only by your imagination,buthere are some typical categories to start youthinking:
Physical objectsElevators in an elevator control programAutomobiles in a traffic flow simulationCountries in an economics modelAircraft in an air traffic control system
8/4/2019 C lecturenotes
15/344
Elements of the computer user environmentWindowsMenusGraphics objects (lines, rectangles, circles)
The mouse, keyboard, disk drives, printer Data-storage constructsCustomized arraysStacksLinked listsBinary trees Human entitiesEmployeesStudentsCustomersSalespeople Collections of dataAn inventoryA personnel fileA dictionaryA table of the latitudes and longitudes ofworld cities User-defined data types
TimeAnglesComplex numbersPoints on the plane
8/4/2019 C lecturenotes
16/344
States and AbilitiesThe match between programming objects andreal-world objects is the happy result ofcombining data and member functions. This isan important concept, so lets look at itanother way. Many real-world objects, at leastthe interesting ones, have both a state(characteristics that can change) and abilities(things they can do). For example, anelevator could be in the following state: Itson the 3rd floor, it contains four passengers,and the passengers have pushed buttons forthe 7th, 11th, and 15th floors. The elevatormight also have the following abilities: It cango down, it can go up, it can open and closeits doors, it can query other elevators to seewhere they are, and it can calculate where itshould go next.
In C++, an objects data records its state andits member functions correspond to its
8/4/2019 C lecturenotes
17/344
abilities. For an elevator object, the datamight be Current_floor_number Number_of_passengers_aboard List_of_buttons_pushed
The member functions might be GoDown() GoUp() OpenDoors() CloseDoors() GetInfo() CalculateWhereToGo()
The underscore character (_) is often used toseparate words in C++ names, as is the technique of
running words together but capitalizing the first letters.
Parentheses (( )) after a name indicate a function.
Incidentally, most C++ compilers allow names (variable
names, function names, and so on) to be as long as you
want, but only the first 32 characters are meaningful to
the compiler. Upper- and lowercase letters, the
underscore, and the digits from 0 to 9 are permissible
characters, but a name cannot start with a digit.
Object-oriented programming combines the programming
equivalent of states and abilitieswhich are represented
8/4/2019 C lecturenotes
18/344
in a program by data and functionsinto a single entity
called an object. The result is a programming entity thatcorresponds neatly with many real-world objects.Making
objects the central feature of program design constitutes a
revolution in programming. No such close match between
programming constructs and the items being modeled
exists in procedural languages.
Classes
In OOP, objects are instances of classes. What does this
mean? Lets look at an analogy. Almost all computer
languages have built-in data types. For instance, a data
type int, meaning integer, is predefined in C++. You can
declare as many variables of type int as you need in your
program:
int day; int count; int divisor; int answer;
In a similar way, you can define many objects of the sameclass, as shown in Figure 2-1. A class serves as a plan, or
a template. It specifies what data and what functions will
be included in objects of that class. Defining the classdoesnt create any objects, just as the mere existence of a
type int doesnt create any variables of type int.
8/4/2019 C lecturenotes
19/344
Figure 2-1 A class and its objects
A class is thus a description of a number of similarobjects. This fits your non-technical understanding of the
word class. Sting, Madonna, and the artist formerlyknown as Prince, are members of the class of rock
musicians. There is no one person called rock musician,
but specific people with specific names are members of
this class if they possess certain characteristics.
An object can be called an instance or an instantiation ofa class because the object is a real example or an
instance of the specifications provided by the class. This
leads to a name commonly used for an objects data:
8/4/2019 C lecturenotes
20/344
instance data. It is called this because there is separate
data for each object; that is, for each instance of the class.
What is Abstraction?
The concept of abstraction relates to the idea of hiding
data that are not needed for presentation. The main idea
behind data abstraction is to give a clear separation
between properties of data type and the associated
implementation details. This separation is achieved in
order that the properties of the abstract data type are
visible to the user interface and the implementation
details are hidden. Thus, abstraction forms the basic
platform for the creation of user-defined data types called
objects. Data abstraction is the process of refining data to
its essential form. An Abstract Data Type is defined as a
data type that is defined in terms of the operations that it
supports and not in terms of its structure or
implementation.
In object-oriented programming language C++, it is
possible to create and provide an interface that accesses
only certain elements of data types. The programmer can
decide which user to give or grant access to and hide the
other details. This concept is called data hiding which is
similar in concept to data abstraction.
8/4/2019 C lecturenotes
21/344
How Types of Abstraction Differs:
There are two broad types of abstraction; functional
abstraction and data abstraction. The main difference
between functional abstraction and data abstraction is that
functional abstraction refers to a function that can be used
without taking into account how the function is
implemented. Data abstraction refers to the data that can
be used without taking into account how the data are
stored. There is also a difference in the way the access
takes place in functional abstraction and data abstraction.
In functional abstraction, access to the function is
provided through a specific interface defined to invoke
the function. In contrast, in data abstraction, access to the
data is provided through a specific set of operations
defined to examine and manipulate the data. For instance,
when a programmer is using C++ standard data types, this
means that users are using the concept of data abstraction.
When using data types, the users are not concerned with
how the data is stored but they are concerned with what
operations are provided and what properties are
supported.
8/4/2019 C lecturenotes
22/344
Reasons for the need of Abstraction
Flexibility in approach:
By hiding data or abstracting details that are not needed
for presentation, the programmer achieves greater
flexibility in approach.
Enhanced Security:
Abstraction gives access to data or details that are needed
by users and hide the implementation details, giving
enhanced security to application.
Easier Replacement:
With the concept of abstraction in object-oriented
programming language, it is possible to replace code
without recompilation. This makes the process easier and
saves time for users.
Modular Approach:
In object-oriented programming language C++, the
abstraction concept helps users to divide the project
8/4/2019 C lecturenotes
23/344
application into modules and test each of them separately.
Then all modules are integrated and ultimately tested
together. This approach makes the application
development easier.
There are various ways of achieving abstraction in object-
oriented programming language C++. One approach is to
take modular based code that is broken apart into smaller
segments, known as functions. This functional or modular
approach helps the code to be reused again and again
when needed. For example, a programmer might write afunction for computing an average and another
programmer might write a function for computing salary.
These functions can be reused when needed, by anyone.
The modular based approach helps to centralize all data
of a similar type, under the control of a type module.
Defining module types allow the module to be an abstractdata type. In many other programming languages, there is
a small drawback associated with the approach to
accessing module type.
Data abstraction
It is the result of defining classes with emphasis on the
similarities of its objects and ignoring their differences. A
good abstraction is one that emphasizes details that are
8/4/2019 C lecturenotes
24/344
significant to us and suppresses details that are not
important. A class is an abstraction. Thus, an abstraction
focuses on the outside view of the object and clearly
separates its essential behavior from the internal
implementation details.
1. Emphasizes similarity of objects and ignore their
differences
2. Good abstraction emphasizes significant details and
ignores unimportant details
3. Class is abstraction4. Focuses on outside view of object only
Encapsulation
The concept of abstraction brings forth another related
term known as encapsulation. Encapsulation is the
process of combining or packaging data with functions
and thereby allowing users to create a new data type. This
new data type is termed abstract data type. Though the
new data type is similar to that of built-in data type, it is
termed abstract data type because it enables users to
abstract a concept from the problem space into the
solution space. Apart from the above, all the features that
hold for built-in types also hold for abstract data types.
8/4/2019 C lecturenotes
25/344
Type checking process that are performed for built-in
types are also achieved in the same way and level for
abstract data types.
Encapsulation is the process of combining data and
functions into a single unit called class. Using the method
of encapsulation, the programmer cannot directly access
the data. Data is only accessible through the functions
present inside the class. Data encapsulation led to the
important concept of data hiding. Data hiding is the
implementation details of a class that are hidden from the
user. The concept of restricted access led programmers to
write specialized functions or methods for performing the
operations on hidden members of the class. Attention
must be paid to ensure that the class is designed properly.
8/4/2019 C lecturenotes
26/344
Lecture No. 3
Concepts of OOPS
Inheritance
The idea of classes leads to the idea ofinheritance. In our daily lives, we use theconcept of classes being divided intosubclasses. You know that the class ofanimals is divided into mammals, amphibians,insects, birds, and so on. The class of vehiclesis divided into cars, trucks, buses, andmotorcycles.The principle in this sort ofdivision is that each subclass shares commoncharacteristics with the class from which itsderived. Cars, trucks, buses, and motorcyclesall have wheels and a motor and are used totransport people or goods; these are thedefining characteristics of vehicles. Inaddition to the characteristics shared withother members of the class, each subclassalso has its own particular characteristics:
8/4/2019 C lecturenotes
27/344
Buses, for instance, have seats for manypeople, whereas trucks have space forhauling heavy loads. This idea is shown inFigure 3-1. Notice in the figure that features Aand B, which are part of the base class, arecommon to all the derived classes, but thateach derived class also has features of itsown.
Figure 3-1 Inheritance
In a similar way, an OOP class can be used as the basisfor one or more different subclasses. In C++, the original
class is called the base class; other classes can be defined
that share its characteristics, but add their own as well.
These are called derived classes.
8/4/2019 C lecturenotes
28/344
Inheritance is somewhat analogous to using functions to
simplify a traditional procedural program. If you find that
three different sections of a procedural program do almost
exactly the same thing, you can recognize an opportunity
to extract the common elements of these three sections
and put them into a single function. The three sections of
the program can call the function to execute the common
actions and they can perform their own individual
processing as well. Similarly, a base class contain
elements common to a group of derived classes. Asfunctions do in a procedural program, inheritance
shortens an object-oriented program and clarifies the
relationship among program elements.
Reusability
Once a class has been written, created, anddebugged, it can be distributed to otherprogrammers for use in their own programs.
This is called reusability. It is similar to theway a library of functions in a procedurallanguage can be incorporated into differentprograms. However, in OOP, the concept ofinheritance provides an important extensionto the idea of reusability. A programmer can
8/4/2019 C lecturenotes
29/344
take an existing class and, without modifyingit, add features and capabilities to it. This isdone by deriving a new class from theexisting one. The new class will inherit all thecapabilities of the old one, but may alsoinclude new features of its own. For example,you might have written (or purchased fromsomeone else) a class that creates a menusystem, such as that used in the Turbo C++Integrated Development System (IDE). Thisclass works fine and you dont want to changeit, but you want to add the capability to makesome menu entries flash on and off. To dothis, simply create a new class that inherits allthe capabilities of the existing one but addsflashing menu entries. The ease with whichexisting software can be reused is a majorbenefitpossibly the major benefitof OOP.Many companies find that reusing classes ona second project provides a major return ontheir original investment.
Creating New Data Types
8/4/2019 C lecturenotes
30/344
One of the benefits of objects is that they givethe programmer a convenient way toconstruct new data types. Suppose you workwith two-dimensional positions (such as x andy coordinates or latitude and longitude) inyour program. You would like to expressoperations on these positional values withnormal arithmetic operations, such asposition1 = position2 + origin; wherethe variables position1, position2, andorigin each represent apairof independentnumerical quantities. By creating a class thatincorporates these two values and declaringposition1, position2, and origin to be
objects of this class, you can, in effect, createa new data type. Many features of C++ areintended to facilitate the creation of new datatypes in this manner.
Polymorphism and Overloading
The = (equal) and + (plus) operators, used inthe position arithmetic shown above, dontact the same way they do in operations onbuilt-in types such as int. The objectsposition1 and so on are not predefined in
8/4/2019 C lecturenotes
31/344
C++, but are programmer-defined objects ofclass Position. How do the = and +operators know how to operate on objects?We must define new operations for theseoperators. These operators will be memberfunctions of the Position class. Usingoperators or functions in different ways,depending on what they are operating on, iscalled polymorphism (one thing with severaldistinct forms). When an existing operator,such as + or =, is given the capability tooperate on additional data types, it is said tobe overloaded. Functions are overloadedwhen multiple functions have the same name
but different arguments. Overloading canmake programs easier to write and tounderstand. Its a kind of polymorphism; it isalso an important feature of OOP.
C++ and C
8/4/2019 C lecturenotes
32/344
C++ is derived from the C language. Strictlyspeaking, it is a superset of C: Almost everycorrect statement in C is also a correctstatement in C++, although the reverse is nottrue. The most important elements added toC to create C++ are concerned with classes,objects, and object-oriented programming.(C++ was originally called C with classes.)However, C++ has many other features aswell, including an improved approach to I/Oand a new way to write comments. Figure 3-2shows the relationship between C and C++.
Figure 3-2 The relationship between C andC++
Message
8/4/2019 C lecturenotes
33/344
A running program is a pool of objects where objects are
created, destroyed and interacting. This interacting isbased on messages which are sent from one object to
another asking the recipient to apply a method on itself.
To give you an understanding of this communication, let's
come back to the class Integer. In our pseudoprogramming language we could create new objects and
invoke methods on them. For example, we could use
Integer i; /* Define a new integer object */
i.setValue(1); /* Set its value to 1 */to express the fact, that the integer object i should set itsvalue to 1. This is the message ``Apply method setValue
with argument 1 on yourself.'' sent to object i. We notatethe sending of a message with ``.''. This notation is also
used in C++; other object-oriented languages might use
other notations, for example ``- ''.
Sending a message asking an object to apply a method is
similar to a procedure call in ``traditional'' programming
languages. However, in object-orientation there is a view
of autonomous objects which communicate with each
other by exchanging messages. Objects react when they
receive messages by applying methods on themselves.
They also may deny the execution of a method, for
example if the calling object is not allowed to execute the
requested method.
8/4/2019 C lecturenotes
34/344
In our example, the message and the method which
should be applied once the message is received have the
same name: We send ``setValue with argument 1'' to
object i which applies ``setValue(1)''.
Definition (Message) A message is a request to an objectto invoke one of its methods. A message therefore
contains
the name of the method and
the arguments of the method.
Consequently, invocation of a method is just a reaction
caused by receipt of a message. This is only possible, if
the method is actually known to the object.
Definition (Method) A methodis associated with a class.
An object invokes a method as a reaction to receipt of amessage.
Dynamic Binding
Early bindingrefers to events that occur at compile time.
In essence, early bindingoccurs when all information needed to call a function is
known at compile time. (Put
differently, early binding means that an object and a
function call are bound during
8/4/2019 C lecturenotes
35/344
compilation.) Examples of early binding include normal
function calls (including
standard library functions), overloaded function calls, and
overloaded operators. The
main advantage to early binding is efficiency. Because all
information necessary to call
a function is determined at compile time, these types of
function calls are very fast.
The opposite of early binding is late binding. As it relatesto C++, late binding refers
to function calls that are not resolved until run time.
Virtual functions are used to
achieve late binding. As you know, when access is via a
base pointer or reference, the
virtual function actually called is determined by the typeof object pointed to by the
pointer. Because in most cases this cannot be determined
at compile time, the object
and the function are not linked until run time. The main
advantage to late binding is
flexibility. Unlike early binding, late binding allows youto create programs that can
respond to events occurring while the program executes
without having to create a
large amount of "contingency code." Keep in mind that
because a function call is not
8/4/2019 C lecturenotes
36/344
resolved until run time, late binding can make for
somewhat slower execution times.
8/4/2019 C lecturenotes
37/344
Lecture No. 4
C++ syntax, exceptions and statements and
namespaces
Program Organization
Heres how your source file is usuallyarranged. Preprocessor directives such as#include come first, followed by classspecifications, followed by main(). Themain() function contains statements thatdefine objects and send messages to them.Figure 4-1 shows what this looks like.
Figure 4-1 Source file organization
In larger programs, things may be a bit morecomplicated. There will probably be manyfiles. Some will contain class specifications,
8/4/2019 C lecturenotes
38/344
whereas others will hold the code that usesthese classes. Nevertheless, the simplearrangement used here reveals theessentials of OOP.
Syntax of the Class Specification
The class specification consists of thekeyword class, the name of the class (hereits HotDogStand), an opening brace, a closingbrace, and a semicolon:class HotDogStand
8/4/2019 C lecturenotes
39/344
situations as well. Notice how the openingbrace is aligned vertically over the closingbrace. This makes it easier to tell which bracegoes where when you read a listing. Thesemicolon ends the entire specification.Semicolons are used to end programstatements, data declarations, and classspecifications (but not functions). In the caseof classes, both a closing brace and asemicolon are necessary. Remember that theclass specification does not create any hotdog stand objects; it merely specifies howthey will look when (and if) they are created.
Variable Declarations
Two variables, HotDogsOnHand andBunsOnHand, are declared and specified to beintegers (type int). This is one of severalbasic data types available in C++.int HotDogsOnHand;
int BunsOnHand;
These declarations dont give values (such as47) to these variables, they merely give themnames and specify that they will require acertain space in memory (although memory
8/4/2019 C lecturenotes
40/344
space is not actually set aside until an objectis created).
Functions
There are three functions in the classspecification: initData(), SoldOneDog(),and displayData(). Tell the C++ compilerthat these names apply to functions (and notvariables or something else) by appendingparentheses to the name:void initData()
8/4/2019 C lecturenotes
41/344
the parentheses. Arguments convey values tothe function, like this:void anotherFunc(float temperature,
float humidity){
}
As with the class specification itself, the bodyof the function is delimited with braces:void initData()
8/4/2019 C lecturenotes
42/344
Figure 4-2 Public and private access
The public and private keywords, followedby colons, are used to designate these parts.
Here all the data is private and all themember functions are public. This is the usualsituation: You want to hide the data from theoutside world so it is protected fromaccidental alteration. However, you want themember functions to be public so other parts
of the program can call them to tell the objectto do something. To work with the data, dontaccess it directly; instead, ask a memberfunction to access it for you.
8/4/2019 C lecturenotes
43/344
Exceptions
Exceptions provide a systematic, object-oriented approach to handling runtime errorsgenerated by C++ classes. To qualify as anexception, such errors must occur as a resultof some action taken within a program andthey must be ones the program itself candiscover. For example, a constructor in auser-written string class might generate anexception if the application tries to initializean object with a string thats too long.Similarly, a program can check if a file wasopened or written too successfully andgenerate an exception if it was not. Not allruntime errors can be handled by theexception mechanism. For instance, someerror situations are not detected by theprogram but by the operating system, whichmay then terminate the application. Examplesare stack overflow, the user pressing the keycombination, or a hardware divide-by-zeroerror.
Namespaces
8/4/2019 C lecturenotes
44/344
The larger a program is, the greater thedanger of name clashes, that is, a singlename being usedinadvertentlyto refer toseveral different things. This is a particularproblem in multifile programs, where filesmay have been created by differentprogrammers or different companies. Forexample, suppose a class alpha is defined ina file A:// file A
class alpha
{ };
In another file, which will eventually be linkedwith file A, there is also a specification for aclass that unbeknownst to the creators offile Ahas been given the same name:// file B
class alpha
{ };
The resulting name clash will cause linker
errors. Programmers might then try to fix theproblem by renaming one of the alpha
classes. However, theres an easier way. Arecent revision to the draft ANSI C++
standard introduces a new solution to this
8/4/2019 C lecturenotes
45/344
problem: namespaces. A namespace is asection of a program specified by the keywordnamespace and enclosed in brackets. A name
used within a namespace does not haveglobal visibility; instead, its scope is limited to
the namespace.
8/4/2019 C lecturenotes
46/344
Lecture No. 5
Basic program construction: data types, variables,
functions and statements
Basic C++ Data Types
Objects are composed of two major elements:instance data and member functions.
You can use C++ to define any data type youwant, but the built-in types save you fromgoing to this trouble in most commonsituations. There are seven basic types builtinto C++. Of these basic types, onerepresents characters, three represent wholenumbers (integers), and three represent real(floating-point) numbers. Table 1-1summarizes the C++ data types.Table 5-1 C++ data types
Type Name - Used to Store - Examplesof Values Storedchar - Characters - a, B,$, 3, ?
8/4/2019 C lecturenotes
47/344
short - Small whole numbers - 7,30,000, -222int - Normal-sized whole numbers(same as short or same as long) -long - Large whole numbers -
1,000,000,000, -123,456,789float - Small real numbers - 3.7, 199.99,-16.2, 0.000125
double - Large real numbers -7,553.393.95,47, -0.048512934long double - Extra-large real numbers -9,123,456,789,012,345.666
CharactersCharacters are stored in variables of typechar. The statementchar ch3;
creates space in memory for a character andnames it ch3. To store a particular character
in this variable, use a statement likech3 = a;Character constants, such as a, B, & or4, are surrounded by single quotes.
8/4/2019 C lecturenotes
48/344
Assignment Operator
The equal sign (=) causes the value on itsright to be assigned to (placed in) the variableon its left; that is, following this statement,the variable ch3 will have the value a. Theequal sign is called the assignment operatorbecause it assigns the value on the right tothe variable on the left.All characters are actually stored as numbers(which, as you know, is all a computerunderstands). The ASCII code is used totranslate characters into numbers. Thus Ais 65, B is 66, and so on. The ASCII code is
shown in Appendix E.
Escape Sequences
Various special characters are represented by
letters preceded by a backslash. This is calledan escape sequence because the backslashcauses the interpretation of the nextcharacter to escape from the normal ASCIIcode and indicate something different. Table
8/4/2019 C lecturenotes
49/344
1-2 shows the most common escapesequences.
Table 5-2 Common escape sequence
Escape Sequence - Character Represented\n - New line. Causes the cursor to moveto the start of the next line. (Same as acarriage return plus a line feed.)\t - Tab character.\b - Backspace.\r - Carriage return. Causes the cursor tomove to the start of this line. Also generatedby the key.
Variables of type char are occasionally usedto store whole numbers rather thancharacters. You can saych3 = 44;However, the range of numericalvalues that can be stored in type char isfrom -128 to 127, so this works only for very
small numbers. Whole numbers are usuallystored in variables of type int, which is fasterfor the computer to process than type char.Avariable of type char occupies 1 byte, or 8bits, of memory.
8/4/2019 C lecturenotes
50/344
Integers
Integers represent whole numbers, that is,values that can be counted, such as thenumber of people living in Thomasville(12,348) or lines of text on a page (33).Integers cannot represent numbers withdecimal points or fractional parts, such as 2.3or 4/7. Integers can be negative: -7, -413.
There are three integer types in C++: short,int, and long. They are similar but occupydifferent amounts of memory and can handlenumbers in different numerical ranges, as
Table 1-3 shows. I also include type char inthis table, even though it is mostly used forcharacters, because it can be used to storesmall whole numbers as well.Table 5-3 Integer types in C++
Type - Name - Size - Rangechar - 1 byte (8 bits) - -128 to 127short - 2 bytes (16 bits) - -32,768 to 32,767int - Same as short on 16-bit systems,same as long on 32-bit systems
8/4/2019 C lecturenotes
51/344
long - 4 bytes (32 bits) - -2,147,483,648 to2,147,483,647
Type short always occupies 2 bytes. It canstore numbers in the range of -32,768 to32,767. Type long always occupies 4 bytesand can store numbers in the range of-2,147,483,648 to 2,147,483,647.In 16-bit systems, type int occupies 2 bytes,
the same asshort
. In 32-bit systems, itoccupies 4 bytes, the same as long, and cantherefore handle a larger range of values.Older operating systems, such as DOS andWindows 3.1, are 16-bit systems. Newersystems, such as Windows 95, OS/2, and
Windows NT, are 32-bit systems. Unix hasalways been a 32-bit system. The int type isthe most commonly used integer type andoperates the most efficiently whateversystem you use. However, if you want toguarantee a 2-byte variable even in a 32-bit
system (to save space), you must use short;if you want to guarantee a 4-byte variable ona 16-bit system (to hold large values), youmust use long. Heres an example of definingsome integer variables and giving themvalues:
8/4/2019 C lecturenotes
52/344
int MilesDriven;
8/4/2019 C lecturenotes
53/344
unsigned long - 4 bytes (32 bits) - 0 to4,294,967,295Ordinary integers, without the unsigneddesignation, are signed by default. You canuse the keyword signed, but its notnecessary.
Floating Point
Floating-point numbers are used to representvalues that can be measured, such as thelength of a room (which might be 5.32
meters) or the weight of a rock (124.65pounds). Floating-point values are normallyexpressed with a whole number to the left ofa decimal point and a fraction to the right.Instead of a decimal point, you can useexponential notation for floating-point
numbers. Thus, 124.65 in normalnotation is 1.2465e2 in exponential notation,where the number following the e indicatesthe number of digits the decimal point mustbe moved to the right to restore the numberto normal notation. Exponential notation is
8/4/2019 C lecturenotes
54/344
commonly used to display numbers that areinconveniently long in decimal notation. Thus,9,876,000,000,000,000,000 in normalnotation is 9.876e18 in exponential notation.
There are three kinds of floating-poinnumbers in popular operating systems, asshown in Table 1-5. (Some systems donthave long double.)Table 5-5 Floating-point numbers
Type Name - Size - Range - Precisionfloat - 4 bytes (32 bits) - 10e-38 to 10e38 5digitsdouble - 8 bytes (64 bits) - 10e-308 to10e308 15 digitslong double
- 10 bytes (80 bits) - 10e-4932to 10e4932 19 digits The most common floating-point type isprobably type double, which is used for mostC++ mathematical library functions. Typefloat requires less memory than double
and may speed up your calculations. Typelong double is used in the floating-pointprocessor in Intel microprocessors and isuseful for very large numbers Heres anexample of defining and using variables ofthe various floating-point types:
8/4/2019 C lecturenotes
55/344
float pi_float;
double pi_double;
long double pi_long_double;
pi_float = 3.1415;pi_double = 3.14159265358979;
pi_long_double = 3.141592653589793238;
Here Ive assigned constants representing themathematical constant pi to variables of thethree types, using as many digits of precision
as each type will allow. Figure 1-11 shows theamounts of memory required for all the datatypes except long double. You can initializevariables to specific values when they arefirst declared. Thus the six statements abovecould be condensed into
float pi_float = 3.1415;double pi_double = 3.14159265358979;
long double pi_long_double =
3.141592653589793238;
Whitespace
8/4/2019 C lecturenotes
56/344
C++ doesnt mind if you put extra spaces intoa program line. You can use them to alignthings so theyre easier to read. You could sayfloat pi_float = 3.1415;double pi_double = 3.14159265358979;
long double pi_long_double =
3.141592653589793238;
You can put as many spaces, tabs, and newlines as you want in your program. These
characters constitutewhitespace, and the C++ compiler ignoreswhitespace in almost all situations.Programmers use whitespace to make theprogram easier for humans to follow.
Comments
You can add comments to your programlisting to help yourselfand anyone else who
might need to look at your listingunderstand what it does. Comments arepreceded with a double slash: //.Heres a code fragment, taken from theprevious section, that uses a full-line
8/4/2019 C lecturenotes
57/344
comment and comments following each ofthree statements:// these variables are declared and
initialized at the same timefloat pi_float = 3.1415; // 5-digit
precision
double pi_double =
3.14159265358979; // 15-digit
precision
long double pi_long_double =3.141592653589793238; // 19-digit
precision Any text following the // symboluntil the end of the line is ignored by thecompiler.Another kind of comment allows you to write
comments that span multiple lines. Heres anexample:/*
if you have a really long multiline
comment it is easier to
use this arrangement than to write
the double-slash symbol beforeevery line
*/
The /* symbol starts the comment and the*/ ends it. The end of a line does notautomatically end a comment that starts with
8/4/2019 C lecturenotes
58/344
/* (as it does with those starting with //), soyou can write as many comment lines as youwant before terminating with the */ symbol.
This comment style is harder to type andrequires two symbols per comment instead ofone, so it is not usually used for single-linecomments.As you know, adding numerous comments toyour code makes it far more comprehensibleto anyone else who must understand yourprogram. And, difficult as it may be tobelieve, you yourself may find commentshelpful if you try to read a listing you haventseen for some time.
Introduction to Input/Output
The most important things that membe
functions do is : performing input and output.If you cant put data into objects and get itout again, theyre not going to be too useful.In this lesson, Im going to explore somebasics of performing input/output (I/O) in C++.
8/4/2019 C lecturenotes
59/344
Output to the Screen
Heres a statement that causes a line of textto be displayed on the screen:cout
8/4/2019 C lecturenotes
60/344
The text This text will appear on thescreen. is called a string constant. A stringconstant is surrounded by double quotes(unlike a character constant, which issurrounded by single quotes). The entirestatement, as with all C++ statements, isterminated with a semicolon.
You can output numerical constants the sameway. The statementcout
8/4/2019 C lecturenotes
61/344
You can also reformat such a statement sothat the put to operators line up vertically,thus making the statement easier to read:cout
8/4/2019 C lecturenotes
62/344
Some languages, such as BASIC,automatically move to a new line at the endof every output statement, but C++ does not.Nor are different variables in the samestatement placed on separate lines. New linesare not created automatically by the coutobject or the put to operator. For example,the statementscout
8/4/2019 C lecturenotes
63/344
Now I'll ask you some questions about
yourself.
First, enter your age:
The \n before First causes the secondstring constant to be displayed on a separateline from the first. (The '\n before Nowensures that the first line begins on a new lineas well, even if something else has alreadybeen printed by a preceding statement.)
You can use the escape sequence '\t togenerate tab characters. The codecout
8/4/2019 C lecturenotes
64/344
into a cout statement, endl causes thecursor to move to the start of the next line,
just as '\n does. (Also, endl flushes anyoutput that may be waiting in the outputbuffer to the display.)Earlier, I showed two lines that used the \nescape sequence to start text on a new line.Heres how to achieve the same result usingendl:cout
8/4/2019 C lecturenotes
65/344
The cin object (for C in) represents thekeyboard, and the get from operator (>>)takes whatever is on the left and puts it in thevariable on the right. When this statement isexecuted, the program waits for the user totype a number and press . Figure 5-2 showshow this looks.
Figure 5-2 Input with cin
Usually, of course, you want to prompt the
user before waiting for input:int age;
cout > age;
This produces the following interactionEnter your age: 34
where the user enters the 34. You can use theget from operator multiple times in the samestatement:int age;
float height;
cout
8/4/2019 C lecturenotes
66/344
cin >> age >> height;
Here the user presses ,, orafter each value before entering thenext one. However, its usually better toprompt the user for only one value at a time,to avoid any possibility of confusion.
Stream I/O
The techniques for input and output Iveshown here are called stream I/O. A stream isa general term for a flow of data. As youll seewhen you write a complete program, to usestream I/O, you need to include a file ofdeclarations in your program. This file,IOSTREAM.H, is called a headeror include file.
Old-Style C I/O
If you are a C programmer, you are familiarwith a completely different style of input andoutput using printf(),scanf(), and similar
8/4/2019 C lecturenotes
67/344
library functions (declared in STDIO.H). Youcan use these functions in C++ as well, butthe preferred approach is to use stream I/O.Why? First, its easier to avoid mistakes. Haveyou ever used the wrong format specifier inprintf() (e.g., %d instead of %f), so thatdata is displayed incorrectly? Its easy to do,and in scanf(), the wrong specifier can crashyour program as well. Second, the stream I/Oapproach lets you use cout and cin withclasses you write yourself. This allows you toperform I/O on any programming object thesame way its performed on basic data types.
This is a very powerful technique, which is
unavailable with standard C I/O. Some old-time C programers cant get the hang ofstream I/O and persist in using standard I/O,but they are missing out on some powerfuland important features of C++.
Member Functions
Data is one of the two parts of objects. Thesecond part: member functions. Typically aprogram calls an objects member functions
8/4/2019 C lecturenotes
68/344
to tell the object to do something. This is whycalling an objects member function is alsocalled sending a message to the object. In thehot dog stand example, there are threemember functions: initData(),SoldOneDog(), and displayData(). Earlier,for simplicity, I showed these functions withempty function bodies. Now its time to fill inthese functions and see what they canactually do.
Initializing the Data
At the start of each day, you want to initializethe number of hot dogs and buns at a stand.Use the initData() function for this. Thisrequires both cout (for the prompts) and cinstatements. Heres how it looks:void initData()
{
cout > HotDogsOnHand;
cout > BunsOnHand;
}
8/4/2019 C lecturenotes
69/344
An example of interaction with this functionwould beEnter dogs on hand: 30
Enter buns on hand: 52
where the program displays the prompts andthe user enters 30 and 52.
Recording a Sale
When a hot dog is sold, the stand operatorcalls Sally to tell her this fact. When shereceives such a call, she wants the programto decrease both the number of hot dogs andthe number of buns by one. Heres a memberfunction that does the job:void SoldOneDog()
{
HotDogsOnHand = HotDogsOnHand - 1; //
subtract 1 from variable
BunsOnHand = BunsOnHand - 1; //
subtract 1 from variable}
Here theres no interaction with the user, onlya little arithmetic.
8/4/2019 C lecturenotes
70/344
Figure 5-3 shows how Sally interacts with anobject of class HotDogStand, using itsmember functions.
Displaying Data
Remember that a HotDogStand objectrecords the numbers of hot dogs and buns on
hand, in the variables HotDogsOnHand andBunsOnHand. You can use cout statements todisplay these values. The resultingdisplayData() function looks like this:void displayData()
{
8/4/2019 C lecturenotes
71/344
cout
8/4/2019 C lecturenotes
72/344
Lecture No. 6
Basic Operators
Arithmetic OperatorsIn the SoldOneDog() function, shown above,you used the subtraction operator (-) tosubtract one from two values. C++ includesthe usual four arithmetic operators plus afifth, less common one, as shown in Table 6-1.Table 6-1 Arithmetic operators
Operator - Purpose+ - Addition- Subtraction- Multiplication/ - Division% - Remainder
The first four operators perform familia
operations. The remainder operator,%
(alsocalled the modulus operator), is used tocalculate the remainder when one integer isdivided by another. Thus the expression20 % 3 evaluates to 2, because 20 divided by3 is 6, with a remainder of 2.
8/4/2019 C lecturenotes
73/344
You can use any of the arithmetic operators just as you would in normal arithmetic oralgebra or most other programminglanguages. They are called binary operatorsbecause they operate on two quantities. Thatis, expressions involving them have the formalpha+beta, where the + operates on alphaand beta. Of course, you can make arithmeticexpressions as complicated as you want. Forexample,c = (f-32) * 5 / 9;
converts a temperature in Celsius to one inFahrenheit. Use parentheses so thesubtraction will be carried out first, despite itslower precedence. (The term precedencerefers to the order in which operations arecarried out. The * and / operators havehigher precedence than the + and -operators.)In C++, its perfectly all right to mix different
arithmetic types in the same expression. Forexample, in the above statements, f mightbe type int and c might be type float. Thecompiler would not complain. Instead, itwould automatically convert the types
8/4/2019 C lecturenotes
74/344
appropriately before carrying out thearithmetic.
Increment and Decrement Operators
In programming, there always seems to be aneed either to add 1 to something or tosubtract 1 from something, just as there wasin the example above. These situations are socommon that C++ includes two specialoperators that perform the task in a muchmore compact form than using the normaaddition and subtraction operators. Thedecrement operator subtracts 1 from avariable and the increment operatoradds 1 toit. Heres the SoldOneDog() function,rewritten to use the decrement operator:void SoldOneDog()
{
--HotDogsOnHand; // subtract 1 from
HotDogsOnHand--BunsOnHand; // subtract 1 from
BunsOnHand
}
The decrement operator consists of twominus signs together: . If HotDogsOnHand
8/4/2019 C lecturenotes
75/344
were 30 and BunsOnHand were 52, then afterexecuting this function, these two variableswould be 29 and 51.Similarly, the increment operator, ++,increases the variable its applied to by 1. Theincrement and decrement operators arecalled unary operators because they operateon only one variable. Their priority is higherthan that of arithmetic operators, so in theexpression ++x + 3, the value of x will beincremented before the addition is carriedout.
Relational Operators
Relational operatorscompare two values andevaluate to a true/false value, depending on
whether the comparison is true or not. Thereare six such operators, as shown in Table 6-2.Table 6-2 Relational operatorsSymbol - Meaning - Example
8/4/2019 C lecturenotes
76/344
== - equal to - a == b!= - not equal to - a != b< - less than - a < b> - greater than - a > b= b
The expressions in the Example column wilbe either true or false depending on thevalues ofa and b. For example, suppose a is9 and b is 10. Then a==b is not true, because9 does not equal 10, but a!=b is true, as area=bare false. You can compare characters as wellas numbers, because characters have
underlying (ASCII) numerical values. Thus, itstrue that a
8/4/2019 C lecturenotes
77/344
Logical Operators
Its often convenient to test the true/falsevalues of several expressions at the sametime and combine the results into a singletrue/false value. For instance, you might wantto create a true value any time both x
8/4/2019 C lecturenotes
78/344
expression is true if x is in the range of 1to 9.Similarly, the expressionch >= 'a' && ch
8/4/2019 C lecturenotes
79/344
}
will cycle until alpha becomes true(nonzero).Logical expressions can often be written inseveral ways. The expressiontemp75
could also be written!(temp>=65 && temp
8/4/2019 C lecturenotes
80/344
and the compiler just evaluated expressionsblindly from left to right, the compiler wouldobtain a different answer. Multiplying the 2sgives 4, adding the 3 makes 7, andmultiplying the result by 3 gives 21, which isnot what you expect. Thus precedence isimportant in normal arithmetic expressions.Its also importantwhen different C++ operators are used. Youmay have wondered why, when I say temp75 how I can be sure that thetrue/false value of temp75are evaluated first, before being ORedtogether. If the processor proceeded from leftto right, for example, temp
8/4/2019 C lecturenotes
81/344
precedence than relational operators. Table6-4 shows the precedence relations, with thehigher precedence operators higher in thetable.Table 6-4 Precedence relations
Operators | Operator Types |Precedence / % | Multiplicative | Higher + - | Additive < > = == != | Relational && || | Logical = | Assignment | LowerNotice that the assignment operator, =, has
the lowest precedence of all; that is, itsapplied after all the other operators.
8/4/2019 C lecturenotes
82/344
Lecture No. 7
Flow control statements: if else, switch
Simple Decisions
The if Statement
The simplest way to make a decision in C++is with the if statement. Heres an exampleof an if statement at work:if(denominator == 0)
cout
8/4/2019 C lecturenotes
83/344
An if statement consists of the keyword iffollowed by a test expression in parentheses.
The loop body, which follows, consists oeither a single statement or multiplestatements surrounded by braces. (With theexception of the keyword, an if statementhas the same syntax as a while statement.)Notice that there is no then keyword in C++,
as there is in some other languages. The bodyof the loop follows immediately after the testexpression.
Figure 7-1 shows the syntax of the ifstatement and Figure 7-2 show how it
operates.
The ifelse Statement
8/4/2019 C lecturenotes
84/344
In a simple if statement, something happensif the condition is true, but if the condition isnottrue, nothing happens at all. Suppose youwant something to happen either way: oneaction if the condition is true and a differentaction if the condition is false. To do this, youuse an ifelse statement. The followingfragment takes the hour of the day,expressed in 24-hour time, and displays it in12-hour time, with am or pm asappropriate:if(hours < 12)
cout
8/4/2019 C lecturenotes
85/344
Test Expression
The test expression in an if or an ifelsestatement can be just as complicated asexpressions in loops. For example, this ifelse statement advances the day fromFebruary 28 to either March 1 or February 29,depending on whether the year is a leap yearor not:// if it's Feb 28 and it's a leap year
if(day==28 && month==2 && year%4==0 &&
year%100 != 0)
day = 29; // then the next day is the
29thelse // otherwise,
{
day = 1; // next day is March 1st
month = 3;
}
Leap years occur when the year is divisible by4 (e.g., 1996 is a leap year), but not divisibleby 100 (so 1900 is nota leap year, although itis divisible by 4. The remainder operator (%)is used to find if the year is divisible by 4 (andby 100) with no remainder. The AND
8/4/2019 C lecturenotes
86/344
operators make sure that February 29 occursonly when all the conditions are true at once.
Nested ifelse Statements
You can nest ifelse statements within oneanother. Typically, the nested statements endup in the else body rather than in the ifbody. For exampleif(age
8/4/2019 C lecturenotes
87/344
else
cout 2)
if(age
8/4/2019 C lecturenotes
88/344
cout
8/4/2019 C lecturenotes
89/344
if(hours == 12) // second-level indent
cout
8/4/2019 C lecturenotes
90/344
The if that follows each else is simplymoved up onto the same line, thus creating asort of artificial else if construction andremoving the multiple levels of indentation.
This arrangement not only saves space, itpresents a clearer picture of the programslogic (at least, after youve gotten used to it).Notice that the else if construction is notreally a part of the syntax of the C++language; its merely a way to rewrite an ifelse ladder by rearranging the whitespaceon the page.
Fine-Tuning Loops
This is a good place to introduce the breakand continue statements, even though theypertain to loops, because they are used mosteffectively in conjunction with decisions. Also,
break is an important feature in the switchstatement. Usually loops work well with thestraightforward syntax I showed in the lastsession. However, sometimes you need tofudge things a bit to make a loop behave as
8/4/2019 C lecturenotes
91/344
you want. The break and continuestatements provide this addedflexibility.
The break Statement
The break statement causes you to exitimmediately from a loop, as shown in Figure7-3.
The break statement is often used to handleunexpected or nonstandard situations thatarise within a loop. For example, heres acode fragment that sets the variable isPrimeto 1 if an integer n is a prime number or to 0ifn is not a prime number. (A prime number
is divisible only by itself and 1.) To tell ifn isprime, Use the straightforward approach oftrying to divide it by all the numbers up to n-1. If any of them divide evenly (with noremainder), then its not prime.isPrime = 1; // assume n is prime
8/4/2019 C lecturenotes
92/344
for(j=2; j
8/4/2019 C lecturenotes
93/344
loopcausing the loop to continueratherthan causing an exit from the loop. Figure 7-4shows how this looks.
Whereas the break statement causes an exitfrom a loop, the continue statement causespart of the loop to be short-circuited orbypassed while the loop keeps running. That
is, following a continue, control goes back tothe top of the loop. Heres an example:do
{
cout > dividend;
cout > divisor;
if(divisor == 0) // if user error,
{
cout
8/4/2019 C lecturenotes
94/344
}
cout ch;
} while(ch != 'n');
Division by zero is illegal, so if the user enters0 for the divisor, control goes back to the topof the loop and the program prompts for a
new dividend and divisor so the user can tryagain. To exit from the loop, the user mustanswer n to the Do another question.
The switch Statement
The switch statement checks a variable androutes program control to any of a number ofdifferent sections of code, depending on thevalue of the variable. Heres an example:switch(diskSpeed)
{case 33: // if diskSpeed is 33
cout
8/4/2019 C lecturenotes
95/344
break;
case 78: // if diskSpeed is 78
cout
8/4/2019 C lecturenotes
96/344
default label (or, if there is no default, fallsthrough the bottom of the switch). Figure 7-5shows the syntax of the switch statementand Figure 7-6 shows its operation.
Fig 7-5
8/4/2019 C lecturenotes
97/344
Fig 7-6
The variable or expression used to determinewhich label is jumped to (diskSpeed, in this
example) must be an integer or a character ormust evaluate to an integer or a character.
The values following the cases must beormust evaluate tointeger or characterconstants. That is, you can use variablenames or expressions, such as alpha, j+20,
and ch+0, as long as alpha, j, and chalready have appropriate values. Once controlgets to a label, the statements following thelabel are executed one after the other fromthe label onward. In this example, the cout
8/4/2019 C lecturenotes
98/344
statement will be executed. Then what? If thebreak werent there, control would continuedown to the next cout statement, which isnot what you want. Labels dont delimit asection of code, they merely name an entrypoint. The break causes control to break outof the switch entirely. Heres anotherexample that might be used in the hot dog
stand program. It gives the user the choice ofthree stands for which to record the sale of ahot dog. The user types a digit from 1 to3, which is then used as the switchvariable.cin >> choice;
switch(choice)
{
case '1';
stand1.SoldOneDog();
break;
case '2';
stand2.SoldOneDog();
break;case '3';
stand3.SoldOneDog();
break;
}
8/4/2019 C lecturenotes
99/344
The Conditional Operator
The conditional operator was inventebecause a particular construction occurs oftenin C++ programs and it is nice to shorten it.Heres an example of the lengthy version ofthe code:if(alpha
8/4/2019 C lecturenotes
100/344
The conditional operator is the only C++operator that operates on three operands. Itconsists of two symbols: a question mark anda colon. First comes a test expression (withoptional parentheses), then the questionmark, then two values separated by thecolon. If the test expression is true, the entireexpression takes on the value before thecolon (here its alpha); if the test expressionis false, the entire expression takes on thevalue following the colon (beta). Figure 7-7shows the syntax of the conditional operatorand Figure 7-8 shows its operation.
Fig 7-7
8/4/2019 C lecturenotes
101/344
Fig 7-8
Heres another example. The statementabsvalue = (n
8/4/2019 C lecturenotes
102/344
Lecture No. 8
Loop control statements: while, do-while, for
To determine how many times to cyclearound a loop, all C++ loops check whetheran expression is true or false. This tells themwhether to cycle one more time or to exit theloop immediately. Thus, to understand loopsyou must first examine what makes anexpression true or false, and how to constructsuch true/false expressions. Then you canexamine specific kinds of loops: the whileloop, the do loop, and the for loop.
while Loops
A while loop lets you do something over andover until a condition changes. The conditionis something that can be expressed by atrue/false value. For example, a while loopmight repeatedly ask the user to enter a
8/4/2019 C lecturenotes
103/344
character. It would then continue to cycleuntil the user enters the character q (forquit).Heres an example of a while loop thatbehaves just this way:while(ch != 'q')
{
cout > ch;
}If the user does not press q, the loopcontinues. Some sample interaction mightlook like this:Enter a character: c
Enter a character: a
Enter a character: tEnter a character: s
Enter a character: q
A while loop consists of the keyword whilefollowed by a test expression (also called aconditional expression or condition) enclosed
in parentheses. The body of the loop isdelimited by braces (but no semicolon), justlike a function. Figure 7-9 shows how thislooks.
8/4/2019 C lecturenotes
104/344
Fig 7-9
If the body of the loop consists of only onestatement, you dont need the braces.while(n < 100)
n = n * 2;
8/4/2019 C lecturenotes
105/344
Note that the testexpression is checkedbefore the body of theloop is executed. If thecondition is false whenthe loop is entered,then the body of theloop will never beexecuted. This isappropriate in somesituations, but it meansyou must be carefulthat a variable in thetest expression has anappropriate valuebefore you enter theloop. The ch in the firstexample must not havea value of q whenyou enter the
loop, or the loop bodywill never be executed.The n in the secondloop must be initializedto a value less than
8/4/2019 C lecturenotes
106/344
Fig 7-10
do Loops
The do loop (often called the do while loop)operates like the while loop except that the
test expression is checked after the body ofthe loop is executed. This is nice when youalways want something (whatever is in thebody of the loop) done at least once, nomatter what the initial true/false state of thecondition is. Figure 7-11 (below) shows how
this looks.
8/4/2019 C lecturenotes
107/344
Fig 7-11 Fig 7-12
Heres an example of a do loop. Thisfragment repeatedly performs addition on twonumbers entered by the user. When the user
enters 0 for the first number, the loopterminates.do
{
cout > x >> y;cout
8/4/2019 C lecturenotes
108/344
parentheses, and finally a semicolon. Thisarrangement is shown in Figure 7-12 (above).
The do loop is the only loop that isterminated with a semicolon. The semicolonis necessary because the test expressionfollows the loop body, so the closing brace ofthe loop body cant act as a delimiter for theentire loop. The do loop has a slightlydubious reputation among C++ programmersbecause its syntax is not quite so clean andeasy to read as that of the while loop. Theconsensus is to use a while loop unlesstheres a really good reason to use a do loop.
for Loops
In both the while and do loops, you usuallydont know, at the time you enter the loop,how many times the loop will be executed.
The condition that terminates the loop arises
spontaneously inside the loop: The useranswers n instead ofy, for example. Thisis not the case with for loops.In a for loop, the number of times the loopwill be executed is (usually) stated at the
8/4/2019 C lecturenotes
109/344
beginning of the loop. Heres a loop thatprints 20 asterisks in a line across the page:int j; // define the loop variable
for(j=0; j
8/4/2019 C lecturenotes
110/344
Figure 7-13 shows the syntax of the for loop,and Figure 7-14 depicts its operation.
Fig 7-13 Fig 7-14How many times will the loop in the examplebe executed? 20 times. The first time through
the loop, j is 0; the last time, its 19. (It doesnot run from 1 to 20, as you might expect.)Starting at 0 and continuing until the loopvariable is 1 less than a constant is the mostcommon arrangement in for loops because,among other reasons, array indexes (whichyoull learn about in Chapter 3) typically startat 0 and go up to 1 less than the size of thearray. If you didwant the loop variable to runfrom 1 to 20, you could writefor(j=1; j
8/4/2019 C lecturenotes
111/344
// body of loop
where the less-than-or-equals operator isused instead of the less-than operator.However, this is not a common idiom in C++.Notice that, as in the while loop, the testexpression is evaluated before the loop bodyis executed the first time. Thus, the loop bodymay not be executed at all if the testexpression is false to begin with. Heresanother example of a for loop, this one withmultiple statements in the loop body. As inthe other loops, multiple statements must besurrounded by braces.int j; // define loop variable
int total = 0; // define and
initialize totalfor(j=0; j
8/4/2019 C lecturenotes
112/344
8/4/2019 C lecturenotes
113/344
statements in these expressions areseparated by commas. Another option is toleave out any or all of the three for loopexpressions entirely, retaining only thesemicolons. Generally, taking advantage ofthe flexibility of the for loop in these wayscauses more confusion than its worth, butbig-time C gurus enjoy it.
Nested LoopsYou can nest one loop inside another. Forexample, the following program fragmentprints a 10 by 10 square of Xs,like this:xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxx
in the upper-left corner of the screen.for(y=0; y
8/4/2019 C lecturenotes
114/344
{
for(x=0; x
8/4/2019 C lecturenotes
115/344
Lecture No. 9
Simple Functions
/
What is a function?
A function is a structure that has a number of program
statements grouped as a unit with a name given to the
unit. Function can be invoked from any part of the C++
program.
Features of Function:
To understand why the program structure is written
separately and given a name, the programmer must have aclear idea of the features and benefits of function. This
will encourage better understanding of function usage:
Use of Functions gives a Structured Programming
Approach
Reduces Program Size:The piece of code that needs to be executed, or the piece
of code that is repeated in different parts of the program,
can be written separately as a function and stored in a
place in memory. Whenever and wherever needed, the
8/4/2019 C lecturenotes
116/344
programmer can invoke the function and use the code to
be executed. Thus, the program size is reduced.
Having known about the function and its features let us
see how to declare, define and call a function in a C++
program.
Declaring a Function:
It has been discussed that, in order for a variable to beused, it must be declared. Just like variables, it follows
that function definitions must be declared. The general
method of declaring a function is to declare the function
in the beginning of the program.
The general format for declaring a function is
return_datatype function name(arguments);
Suppose we have a function named as exforsys which
return nothing from the function it is declared as
void exforsys( );
This declared would inform the compiler that the
presence of the function exforsys is there in the program.
In the above the return type void tells the compiler that
8/4/2019 C lecturenotes
117/344
the function has no return value and also the empty braces
( ) indicate that the function takes no arguments.
Defining a function:
The definition is the place where the actual function
program statements or in other words the program code is
placed.
The general format of the function definition is as
follows:return_datatype functionname(arguments) //Declarator
{
.. program statements //Function Body
.
}
In the above the declarator must match the functiondeclaration already made. That is the function name, the
return type and the number of arguments all must be same
as the function declaration made. In fact if arguments are
declared and defined. The order of arguments defined
8/4/2019 C lecturenotes
118/344
here must match the order declared in the function
declaration.
After the declarator the braces starts and the function
body is placed. The function body has the set of program
statements which are to be executed by the function. Then
the function definition ends with } ending braces.
For example let us see how to define a function exforsys
declared as void that prints first five integers.
void exforsys( ){ int i;
for (i=1;i
8/4/2019 C lecturenotes
119/344
functionname();
When the function is called the control, transfers to the
function and all the statements present in the function
definition gets executed and after which the control,
returns back to the statement following the function call.
In the above example when the programmer executes the
function exforsys, he can call the function in main as
follows:
exforsys();a complete program in C++ to help the programmer to
understand the function concepts described above:
#include
void main( )
{
void exforsys( ); //Function Declarationexforsys( ); //Function Called
cout
8/4/2019 C lecturenotes
120/344
What is an argument?
An argument is the value that is passed from the program
to the function call. This can also be considered as input
to the function from the program from which it is called.
How to declare a function passed with argument
Declaring a function:
The general format for declaring the function remains the
same as before except the data type passed as arguments
in functions are in the same order in which it is defined in
function.
The format for declaring a function with arguments is:
return_datatype functionname(datatype1,datatype2,..);
In this example, the data types are the types of data
passed in the function definition as arguments to the
function. Care must be taken to mention the number of
arguments and the order of arguments in the same way asin function definition.
For example, suppose a function named exforsys takes
two integer values as arguments in its functions definition
and returns an integer value. The function declaration of
exforsys would be written:
8/4/2019 C lecturenotes
121/344
int exforsys(int,int);
Function Definition:
The function definition has the same syntax as thefunction definition previously defined, but with added
arguments. The general format for defining a function
with arguments is written as:
return_datatype functionname(datatype1
variable1,datatype2 variable2,..){
Program statements
.
return( variable);
}
In the above example, the return data type defines thedata type of the value returned by the function. The
arguments are passed inside the function name after
parentheses with the data type and the variable of each
argument. Care must be taken to mention the number of
8/4/2019 C lecturenotes
122/344
arguments and the order of arguments in the same way as
in function declaration.
For example, if the function exforsys takes two integer
values x and y and adds them and returns the value z the
function definition would be defined as follows:
int exforsys(int x,int y)
{
int z;z=x+y;
return(z);
}
In the above program segment, a return statement takes
the general format
return(variable) ;
This value specified in the return as argument would be
returned to the calling program. In this example, the value
returned is z, which is an integer value, the data type
returned by the function exforsys is mentioned as int.
Calling the function by value:
The calling of function takes the same syntax as the name
of the function but with value for the arguments passed.
8/4/2019 C lecturenotes
123/344
The function call is made in the calling program and this
is where the value of arguments or the input to the
function definition is given.
The general format for calling the function with
arguments is
functionname(value1,value2,);
In the above exforsys function suppose integer value 5
and 6 are passed, the function call would be as follows:
exforsys(5,6);
As soon as the function call exforsys is made the control,
transfers to the function definition and the assignment of
5 to x and 6 to y are made as below.
int exforsys(int x,int y)
exforsys(5,6);It is possible to store the return value of the function in a
variable. In the above example, the assignment of the
function call to integer variable b can be produced as
follows:
8/4/2019 C lecturenotes
124/344
Int b;
b = exforsys(5,6);
The above statement assigns the returned value of the
function exforsys. The value z is then added to the value
of x and y to the variable b. So, variable b takes the value
11.
Let us see the whole program to understand in brief the
concept of function with arguments
The output of the above program would be
#include
int exforsys(int,int);
void main()
{int b;
int s=5,u=6;
b=exforsys(s,u);
coutx;
//The exforsys(x) gets replaced with code return 5*x1;cout
8/4/2019 C lecturenotes
136/344
return 5*x1;
}
A programmer must make wise choices when to use
inline functions. Inline functions will save time and are
useful if the function is very small. If the function islarge, use of inline functions must be avoided.
Default parameters
In a function definition a formal parameter can be given a
default value.
Example.
void init(int count=0, int start=1, int end=100)
{
// body ...
}
Call:
init(); //is equivalent toinit(0,1,100)
//or
init(22,23); //equivalent to
init(22,23,100);
Note: only trailing parameters can be defaulted:
8/4/2019 C lecturenotes
137/344
void init(int count=0,int start,int end); //ILLEGAL
Overloaded function names
Consider the following function addf, which adds floats.
float addf(float a, float b)
{
return a + b;}
If we want to provide an integer add, we might define:
int addi(int a, int b)
{
return a + b;
}However, in C++, through overloading of functionnames, we can use the more natural name add for both,
and the linker will bind the appropriate version -according to the types of the arguments:
float add(float a, float b)
{return a + b;
}
int add(int a, int b)
{
8/4/2019 C lecturenotes
138/344
return a + b;
}
Caller:
int i,j,k;
float x,y,z;
...
z = add(x,y); // float add(float a, float b); called
k = add(i,j); // float add(int a, int b); called
Function name overloading is made possible, by allowing
the parameter types to become part of function's identity.
Note: the return type is notused in this disambiguation.
Function name overloading finds extensive use in classes:
A class may have a number ofconstructors, all with thesame name, but each having a different parameter list.
To enable classes, especially within a class hierarchy, toexhibit uniformity of behaviour; e.g. trivially, many
classes can have an overloadedprint function.
8/4/2019 C lecturenotes
139/344
Lecture No. 12
Arrays
Array FundamentalsAn array is a way to group together a numberof variables of a single data type. Arrays areuseful primarily because the individualvariables stored in an array can be accessedusing an index number. This makes it easy tocycle through the array, accessing onevariable after another.
Defining an ArrayTo define an array, you tell the compiler toset aside storage for a given number of dataitems of a specified type. You also tell thecompiler the name of the array. Heres anexample of an array definition that createsstorage for four integers. Give this array thename age; perhaps it will be used to store theages of four people.int age[4];
The int specifies the type of data to bestored, age is the name of the array, and 4 isthe size of the array; that is, the maximum
8/4/2019 C lecturenotes
140/344
number of variables of type int that it willhold. Brackets [] (notbraces or parentheses)surround the size. Its the brackets that tellthe compiler Im defining an array and notsomething else, such as a function. Figure 12-1 shows the format of this array definition.
You can define arrays of any data type, ofcourse. Heres an array of 100 variables of
type float, called foo: float foo[100]; //100 floatsThere is also no problem defining arrays oftypes you have created yourself, usingclasses:airtime DenverDepartures[50]; // array
of 50 airtimesThe type of the array can be any kind of class,whether it behaves like a data type or not:HotDogStand stands[6]; // array of 6
hot dog stands
8/4/2019 C lecturenotes
141/344
Here you have an array of objects thatrepresent physical objects, not data types. Itdoesnt matter to the compiler.
Array Elements
Each variable stored in an array is called anelement. The elements are numbered. Thesenumbers are called index numbers orindexes. Some people also refer to them assubscripts. The index of the first arrayelement is 0, the index of the second is 1, andso on. If the size of the array is n, the lastelement has the index n-1. For example, inthe age array, which has a size of 4, theelements are numbered 0, 1, 2, and 3. Th