Upload
ali-asghar-manjotho
View
314
Download
22
Embed Size (px)
DESCRIPTION
C++ by Ali Asghar
Citation preview
Composed by Ali Asghar Manjotho (07CS20)
INTRODUCTION TO COMPUTER LANGUAGES
Language
Language is the means of communication. The communication can be between one person and another person or between a person and any other thing or between a thing
with another thing. It is the language through which a person can come to know that
what he or she wants or wants to say. There are two types of languages Natural languages and Artificial languages. Natural languages exists naturally in this universe
and these are the languages which are spoken by the peoples like English, Spanish,
French, Urdu, Sanskrit etc. where as on the other hand Artificial languages are created
by humans for different purposes and they can not be spoken by the persons like, Mathematical language, Binary language, Accounting and Computer languages. There
are many languages spoken all over the world. Every country has its own national
language and almost every region in that country has atleast one own regional language in addition to national language.
Language is not limited to the humans but strictly speaking the birds and animals also
have their own language through which they communicate with each other. Similarly to that computers have also their own language known as Computer language through
which we communicate with it. Unlike humans computer can only understand one and
only one language, the binary language. Binary language is the series of 0‟s and 1‟s hence it is very difficult language for people to understand. If you tell the computer to
solve the expression 2+3=?, it will be confused and will not respond to it because you
have instructed it in the language to which it is unfamiliar. So to make it understand you have to tell it the expression in its own language i.e. the binary language. But as we
know that the binary language is the most difficult language to understand then how an
ordinary person can communicate with the computer. Therefore the computer engineers
have found an easy way to overcome this frustrating job. They have created other types of computer languages that are easier to use as their code is readable and
understandable to a human. These languages are known as computer programming
languages.
Computer Languages
Computer languages are the means of communication between a user and the
computer. These are source through which a user can instruct the computer to work
accordingly and a source through which a computer can complain the user. Unlike humans the computer can only understand binary language (series of 0‟s and 1‟s) also
known as machine language, which is more difficult for humans to understand and it is
not every one‟s job to instruct the computer in binary language. To overcome this big problem and to make the computer more flexible by allowing the ordinary computer
users to instruct the computer in very easy manner other computer languages are
developed which are very easy for humans to understand known as computer
programming languages. These languages offer very easy interface to communicate with the computer as they use English like syntax instead of series of 0‟s and 1‟s. Almost all
the computer programming languages are identical as they use same keywords. The
computer programming languages are divided into three groups:
1) Low-Level Languages
2) Middle-Level Languages
3) High-Level Languages
1) Low-Level Languages
Low-Level computer programming languages are easy for computer to understand but difficult for humans to understand. In fact they are easier than binary language but are
very closer to it so an ordinary user can not access it very easily. Machine Language and
Assembly Language lie in the category of low-level languages.
2) Middle-Level Languages
Middle-Level languages are more easier and understandable than the low-level
languages. They you English like syntax. A Language, B Language, C Language and C++ lie in the category of middle-level languages.
3) High-Level Languages
High-Level Languages are the most easier computer programming languages. These are easier for humans but difficult for computer to understand. These languages also use
English like syntax but in very clear and easier way. Languages like, GW BASIC, Pascal,
COBOL, FORTRAN, ALGOL etc lie in the category of high-level languages.
Language Translators
A Language translator is basically a software that converts any computer programming
language code in to machine code (code is the any series of instructions given by user to
the computer). As the computer can not understand any language except binary language, the code written in any programming language is not understandable by the
computer therefore the code (source code) written in any programming language should
be first converted into machine language code so that the computer can make sense to it. As we know that the computer language is the interface between the computer and
the user so in this sense the language translator is the interface between this interface.
When ever you write any program, into any programming language you write some
series of instructions. Suppose you have written the statement cout<<”Ali Asghar”; which instructs the computer to print the string constant “Ali Asghar” on the console
screen but the computer is not familiar with this statement so when ever you execute
your written program the translator translates this block of code into machine code.
The translator writes the equivalent of the code written in any programming language
into machine code. Every computer programming language contains its own language
translator. There are basically three types of language translators:
1) Assembler
2) Interpreter
3) Compiler
1) Assembler
It is a type of language translator which is only used in assembly language. The assembler translates the code written in assembly language into the machine code.
Although assembly language is very closer to the binary language but even though the
code written in assembly language has to be translated into the machine code and assembler is responsible for doing this job.
2) Interpreter
Interpreter is the type of language translator which converts and executes immediately
the source code into the machine code step by step/line by line. BASIC, for example, has been a popular interpreted language. Traditional BASIC interpreters translate and
execute one line at a time, and then forget that the line has been translated. This makes
them slow, since they must re-translate any repeated code. Interpreters have many advantages one of them is that the transition from writing code to executing code is
almost immediate, and the source code is always available so the interpreter can be
much more specific when an error occurs.
3) Compiler
Compiler is the type of language translator which first translates the whole source code
at a time into machine code and then it executes it. This capability makes it faster then
the interpreter. The interpreter converts the source code into machine code line by line and when error occurs it indicates that error in that line and stops translating but the
compiler converts whole source code into machine code and shows the list of errors if
any.
INTRODUCTION TO C++ PROGRAMMING LANGUAGE
C++ Programming Language
C++ (pronounced "see plus plus") is a general-purpose Object Oriented Programming language with high-level and low-level capabilities. It is a statically typed, free-form, multi-paradigm, usually compiled language supporting procedural programming, data
abstraction, object-oriented programming, and generic programming. C++ is regarded
as a mid-level language. This indicates that C++ comprises a combination of both high-
level and low-level language features.
Bjarne Stroustrup developed C++ in 1979 at Bell Labs as an enhancement to the C programming language and named it "C with Classes". In 1983 it was renamed to C++.
Enhancements started with the addition of classes, followed by, among other features,
virtual functions, operator overloading, multiple inheritance, templates, and exception handling. The C++ programming language standard was ratified in 1998 as ISO/IEC
14882:1998, the current version of which is the 2003 version, ISO/IEC 14882:2003. A
new version of the standard (known informally as C++0x) is being developed.
History of C++
Stroustrup began work on C with Classes in 1979. The idea of creating a new language
originated from Stroustrup's experience in programming for his Ph.D. thesis. Stroustrup found that Simula had features that were very helpful for large software development,
but the language was too slow for practical use, while BCPL was fast but too low-level
and unsuitable for large software development. When Stroustrup started working in Bell Labs, he had the problem of analyzing the UNIX kernel with respect to distributed
computing. Remembering his Ph.D. experience, Stroustrup set out to enhance the C
language with Simula-like features. C was chosen because it is general-purpose, fast,
and portable. Besides C and Simula, some other languages which inspired him were ALGOL 68, Ada, CLU and ML. At first, the class, derived class, strong type checking,
inlining, and default argument features were added to C via Cfront. The first commercial
release occurred in October 1985.
In 1983, the name of the language was changed from C with Classes to C++. New features were added including virtual functions, function name and operator overloading,
references, constants, user-controlled free-store memory control, improved type
checking, and BCPL style single-line comments with two forward slashes (//). In 1985, the first edition of The C++ Programming Language was released, providing an
important reference to the language, as there was not yet an official standard. In 1989,
Release 2.0 of C++ was released. New features included multiple inheritance, abstract
classes, static member functions, const member functions, and protected members. In
1990, The Annotated C++ Reference Manual was published. This work became the basis for the future standard. Late addition of features included templates, exceptions,
namespaces, new casts, and a Boolean type.
As the C++ language evolved, a standard library also evolved with it. The first addition
to the C++ standard library was the stream I/O library which provided facilities to
replace the traditional C functions such as printf and scanf. Later, among the most
significant additions to the standard library, was the Standard Template Library.
After years of work, a joint ANSI-ISO committee standardized C++ in 1998 (ISO/IEC
148r82:1998). For some years after the official release of the standard in 1998, the
committee processed defect reports, and published a corrected version of the C++ standard in 2003. In 2005, a technical report, called the "Library Technical Report 1"
(often known as TR1 for short) was released. While not an official part of the standard, it
gives a number of extensions to the standard library which are expected to be included
in the next version of C++. Support for TR1 is growing in almost all currently maintained
C++ compilers.
C++ Object Oriented Characteristcs
1) Objects
2) Classes
3) Inheritance
4) Data Abstraction
5) Data Encapsulating
6) Polymorphism
7) Overloading
8) Reusabilty
1) Objects
The object is a unit which contains both the data and functions that operate on that
data. The function contained in the object is called the member function. The member functions are used to access that data form the objects. When ever you want the access
that data present in the object you call the member function and it returns you the
value. So in objects you can not access that data directly because it is hidden in the
object.
2) Classes
The classes are the units which contain the objects and object are the members of the classes. You can define many objects of same class and the class can be divided into
subclasses. A class serves as the template for objects. The main class is called the base
class and the subclasses are known as derived classes. Each subclass will share some
characteristics with the base class from which it is derived.
3) Inheritance
The class can be divided into the subclass but each subclass will have the characteristics
of the class from which it derived. This means that the same characteristics are shared between the subclasses. Like there is the class of vehicles and its subclasses are Buses,
Cars, Turks, and Motorcycles. All the above subclasses share some characteristics as
each class contains wheels, each need fuel to operate, each need a driver to operate.
This sharing of characteristics leads us to the idea of inheritance.
4) Data Abstraction
The C++ offers the built in data types like integer, character, and floating point. But the
C++ also offers another great advantage that you can create and use your own data
types. It helps a lot as if you want to work with a totally different data that can not be matched with the built in data types like complex data type or real data type then you
have to have a different data type that can support complex and real number data
types. This capability of offering to create new data types is referred as Data Abstraction.
5) Data Encapsulating
Encapsulating means to combine data and functions in to a single unit i.e. object. This
feature helps to built more clear and understandable codes. When we combine the data and function in to a single unit then we say that the data and functions are encapsulated
and the data enclosed in this unit will be hidden from others which keep the data safe
from any unauthorized alteration.
6) Polymorphism
Using operators or functions indifferent ways, depending on what they are operating on,
is called polymorphism. Like the operators “+”and “=” operate differently with the built
in data types and if we want to create our new data types and want to use these
operators to work on them in different way, this process of making the operators and functions to work in different way is referred to as polymorphism.
7) Overloading
When the existing operator is given the capability to work on new (user defined) data types, is said to be overloaded and overloading is the process of making the operator to
work on the new data types. Like the arithmetic operator “+” is predefined in C++ and
can work on the existing data types because it is programmed but when we create the
new data types there is no link between the new data type and the existing operator so to make the operator work on that data type we have to instruct the computer and this
is referred as overloading.
8) Reusability
To understand the term reusability consider that we have created one class in our own
program now if we handover this class to another programmer and he uses that class in
his own created programs, this is referred as reusability. Means a class created once can
be used in different programs. Suppose you want to develop a software that contains some pop-up menus. You can take a class created for pop-up menu from some other
programmer and add it in your own program and that will work. And if you want to add
a new feature to it then you have to create new class that will inherit the capabilities of the main class.
C++ Integrated Development Environment (IDE)
The C++ environment is the graphical user environment as it offers the capability of the
mouse. Like many application environments C++ environment is a window with work
area and formatting tool bar at the top. The blue area in the environment is the text
editor where the user writes source code (program). The cyan colored area below the text editor is the message window in which the compiler shows the list of errors,
messages and warnings. The green button at the left top of the text editor is the close
button, which when pressed closes the current source file and the green arrow at the right top is the minimize/maximize button. The name at the top-center is the name of
the source file with extension of the current activated source file.
The formatting bar at the top works same as in many other applications. To open a new
source file open File menu and click New, to open an existing source file click Open, to
save a source file click Save, to make a duplicate copy of the source file click Save As, to
quit from the C++ environment click Exit or press Alt+X. To compile the current source program open Compile menu and click Compile or press F9 key while holding down the
Alt Key. To run the current source program open Run menu and click Run or press F9
while holding down the Ctrl key.
In C++ text editor you can copy, paste, cut or delete certain block of code with some
hotkeys. Hotkeys for copy, paste, cut and delete are Ctrl+Insert, Shift+Insert, Shift+Delete, Ctrl+Delete respectively.
GETTING STARTED WITH C++
Starting with a basic C++ program
Whenever you start any objective you first deal with the basics because the basics are
roots through which you can gain command on that objective. So here also we will start
with a basic source program. You can write any C++ source program into the C++ editor or any other text editor like, Notepad or WordPad. Remember one thing that all
the C++ source files have the extension “.cpp”. So now without making more discussion
let us examine this simple C++ source program named (basic.cpp):
Program (basic.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
cout<<”My name is Ali Asghar”;
getch();
}
The program starts with the two lines containing a pound sign (#) and the keyword include. These are known as preprocessor directives. The preprocessor directives are the
instructions to the part of the compiler known as preprocessor which includes some
extra files (codes) to the basic source program. The files iostream.h and conio.h are
known as the header files which contain the definitions of some functions. The iostream.h header file contains the definition of standard input/output streams like, cout
and cin where as conio.h header file includes the definitions of function getch(), getche()
and others. As the computer is just a dumb machine and can not understand any thing until you instruct it and the keywords cout, cin are not understandable to the computer
so the header files tells the compile that cout is this thing and whenever used do this.
The words clrscr(), cout, and getch() are not known to the computer but the definitions
of these codes are written in header files and these definitions tell the computer how to deal with the words clrscr(), cout, and getch(). Simply speaking the preprocessor
directive #include is responsible for including the contents of the header files into the
source file.
The main() is the function as the function is always along with the parenthesis. The
main() function is the first executable function in any C++ program. No matter where the main() function is located always the first precedence goes to the main() function
and its contents. The contents of main function are enclosed in curly braces. The void
before the main function says that the function main has no return type value and at the
end of the function main() will not return any value.
The braces “{ and }” also known as curly braces, enclose the block of code present in
any function. “{“ is known as the opening brace and ”}” is known as closing brace.
Opening brace shows the starting of the main or any function and closing brace shows the ending of the main or any function. The code of each and every function is always
enclosed in the curly braces.
The function clrscr() is used to clear the console screen. As you work repetitively with
the console screen and output your results continuously with out rubbing the previous
output your console screen would be filled with a lot of text and your console screen will not fit your new output correctly and you also will not be able to examine your output
clearly. So the clrscr() function helps to clean the console screen.
The cout<<”My name is Ali Asghar” tells the computer to print the string constant “My name is Ali Asghar” on the console screen. However a computer cannot understand what
cout is but the coding written in iostream.h header file for cout makes the computer
understand what does cout mean. cout is the standard output stream which directs the flow of data to the console screen. What ever written in the double quotations in cout
statement is printed as it is on the console screen.
The getch() (get character) function waits to get the character from keyboard. If you run
your program without using getch() your program will show the result in just one blink
and will vanish out quickly. So to make the output console screen stop in order to
examine the results clearly we use getch() function. The definition of the function getch() is present in the header file “conio.h”.
The output of basic.cpp on the console screen may look like as shown in below figure;
Functions
Functions are the one of the fundamental building blocks of C++ language. The
functions are the sub programs which contain some block of code inside the curly
braces. The code enclosed inside the curly braces is known as the body of the function.
The functions always start with the return type and the function name followed by the parenthesis. The parentheses tell the compiler that it is a function not a variable or any
other thing. Sometimes the parentheses also contain arguments, which are the values
that the function passes through its body. As the statements are the instructions to the compiler and they are just executed from the place where they are placed but if we want
to execute the same block of statements at different places according to the situations of
the program then the function is way which provides us the facility to execute that same block of statements (codes) at different places. The block of code present in any function
can be executed at any place by calling that function at that point in the program. Any
C++ program can contain number of functions or atleast one i.e. main(). All the C++
programs always contain the main() function, because it is the gateway to enter in C++ and no program can run with out main() function.
In basic.cpp, the main() is only the function present. It contains the block of three line code. This three line code present in main() is always executed first in this program,
because the contents of the main() functions have the highest precedence as compared
to the contents of other functions.
Statements
Statements are the instructions to the computer to work accordingly. All the statements
are always terminated with the terminator “;”. This semicolon is known as terminator
because it terminates the statement and tells the compiler that the statement has ended. If we don‟t give the terminator at the end of any statement, the compiler will
think that the statement is still going on and will mix another statement or code with it
hence giving an error. In basic.cpp, there is only one statement cout<<”My name is Ali Asghar”; it just tells the computer to print the string constant present in quotation
marks on the console screen. So every statement is the instruction to the computer and
do remember to place the terminator at the end of each and every statement.
Preprocessor Directives and the Header Files
The preprocessor directives are the instruction to the part of the compiler known as
preprocessor. These preprocessor directives give the direction to the compiler before
compiling any source code. The preprocessor directive #include is used to include the
block of code of header files in to any source program with out writing the whole block of code of that header file. The #include preprocessor directive provides you the facility to
include thousands of lines of code of the header files into your source program. On the
other hand the header files are the files with the extension .h present in the INCLUDE directory of your C++ software. These header files are the files which contain the
definitions of certain functions of C++. As discussed earlier that a computer is just a
dumb machine which can not understand any thing and is unfamiliar to the words like
cout, cin, return, void, main etc. So in order to make the computer know what these words are we use header files, which contain the instructions to the computer that tells
it how to act when it faces these kinds of codes. Now we have made the computer
understand these words but the problem is this the instruction to make it understand
are made in thousands of lines of codes so we can not do such a lengthy process of writing thousands of line of codes for each tiny or long program. To overcome this major
problem we can include the entire block of code present in any header file into our
source file by just writing a single line statement i.e. #include <headerfilename.h>. In this way we are released from passing through such a lengthy and complex problem and
we feel calm to have this feature.
The preprocessor directives are always started with the “#” (hash/pound) sign which
tells the compiler that the thing that you are compiling is a preprocessor directive which
is different from other. And the header files are always enclosed in “< >” angle brackets
following the keyword include but in some cases it is enclosed in double quotation
marks. If you enclose the header file in the angle brackets it will start the search for the header file in the standard INCLUDE directory—the traditional directory holding the
header files i.e. TC\INCLUDE .
#include <iostream.h>
But when you want to include the user defined header file the header file is enclosed in quotation marks.
#include “ali.h”
The quotation marks tells the compiler to start the search for the header file in the
current directory—the directory usually containing the source files i.e. TC\BIN.
In basic.cpp, there are two header files included in the source program. One is
iostream.h which contains the definitions of standard input and output streams like, cout and cin. The other header file is conio.h which contains the basic definition of the
functions like, getch(), getche(), etc.
Standard Input and Output Streams
The term stream means the flow of the data. The data flown towards the system
through the input devices is known as input stream where as the data flown from the
system to some output devices is known as output stream. The standard input stream is
flown from the keyboard to the system and the standard output stream is flown from the system to the console screen. In order to control this flow of data to and from the
system there are two statements used. The first “cout” which controls the standard
output stream and the other “cin” which controls the standard input stream. The definitions of both the keywords is written in the header file iostream.h (input/output
stream), so to get access to these statements you must first include the header file
iostream.h in your source program.
Outputting with cout
The identifier cout is actually an object which is predefined in C++. The cout statement is responsible for displaying the text, numbers and some special characters and
graphical symbols on the console screen. The simplest structure of cout statement is
given as: cout<<”My name is Ali Asghar”;
In above syntax the keyword cout tells the compiler that it is a standard output stream
and treat it as accordingly. The text in the double quotation marks ”My name is Ali
Asghar” is the string constant and is printed on the console screen as it is. The operator
<< is known as insertion or put to operator. It directs the contents of the variable on its
right to the object on its left. The insertion operator can be used multiple times in single cout statement and it is perfectly legal as in below statement:
cout<<”My name is “<<”Ali Asghar”;
Except printing the string constants, the situation also come in which we have to print
out the values of certain variables on the console screen then we can use the variable
name in cout statement to print its value on the console screen as in below statement: cout<<”The addition of two numbers is: “<<Add;
To make the variable Add effective in cout statement it should be declared and defined
properly in the program. you can also print the values of several variables in using cout
statement as in below statement, which prints the number of apples and oranges in the box.
cout <<”There are “<<a<<”apples”<<”and “<<b<<”oranges in the box”;
As the cout is a statement therefore each and every cout statement should be
terminated with the terminator “;”.
Let‟s examine the following program to make the concept more clear about cout:
Program (SOS.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
cout<<”My name is Ali Asghar.\n”;
cout<<”I am the students of CS department.”;
cout<<endl<<”I live in S.U.C, Jamshoro.”;
getch();
}
The above program‟s code contain three cout statements. The first cout statement prints
the string constant “My name is Ali Asghar.” on the screen as it is where as “\n” is the escape sequence which moves the cursor to the new line so that the coming line will be
printed on the fresh line. Then the next cout statement flows the string constant ”I am
the students of CS department.”; to the console screen on the new line. In the last cout
statement we face a new unfamiliar word endl, it is known as the manipulator. The manipulators are the instructions to the output stream which modify or manipulate the
way the data is displayed in the console screen. The manipulator endl has the same
effect of causing a linefeed as the \n has but it is somewhat clearer. The endl manipulator also causes the buffer to be flushed. So, on conclusion the third cout
statement in SOS.cpp, flows the string constant ”I live in S.U.C, Jamshoro.” to the
console screen on new line.
The output of SOS.cpp is:
My name is Ali Asghar.
I am the students of CS department.
I live in S.U.C, Jamshoro.
Inputting with cin
The identifier cin is an object which is predefined in C++. The cin statement is
responsible for getting input and passing for processing during the run-time. The
simplest structure of cin statement is:
cin>>number;
In above syntax the keyword cin tells the compiler that it is a standard input stream and
treat it as accordingly. The operator >> is known as extraction or get from operator. It
takes the value from stream object on its left and places it in the variable on its right.
let‟s examine the following program to make the concept more clear about cin:
Program (SIS.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a, b, Ans;
cout<<”Enter first number: ”;
cin>>a;
cout<<”Enter second number: ”;
cin>>b;
Ans=a+b;
cout<<”The sum of two numbers is: ”<<Ans;
getch();
}
The above program first initializes that the variables a, b and Ans contain the integer
data type values. The first cout statement sends the message to enter first number from
your keyboard and when you enter any number, the cin statement places that number in the variable a. Then the program gives another message to enter second number and
when you enter any number that will be placed in the variable b. The statement
Ans=a+b then adds the two numbers and places the result in the variable Ans. Finally the last cout statement shows the addition of both numbers.
The output of SIS.cpp is: Enter first number: 12
Enter second number: 3
The sum of two numbers is: 15
Comments
Commenting is very effective feature in any programming language as it makes the
source program user friendly up to some extent. Comments are un-executable lines in
any source program. Comments make the program more readable and understandable
to the user or even an unknown reader. They help the programmer to make him remember that for this purpose you have written this portion of code. And also if a
person is unfamiliar with the program, the comments will help him by telling him what is
happening in a certain line or portion of the program. When you write a program and suppose you are not in touch with it for a two or three months so when you come back
to your program after such a long period you will forget that for what I had written it
and what it tell? So if you had given the comments in your program you would not be in such a great trouble.
In small programs it is not a huge problem to forget some code lines but in case of
working on some programs having hundreds or thousands of code line or working on a project you have to deal with several different blocks of codes so, in these situations
there are a lot of chances to forget the construction of your own program. So here the
comments play their key role.
There are two ways to comment in C++ source file. The first way it to start comment
with the two back slashes “//” , this causes the compiler to consider the whole line as a comment. The other way is to start the comment with a back slash and an asterisk “/*”
and terminate the comment with an asterisk and back slash “*/”, which cause the
certain block of line as a comment.
The first way only make a single line as a comment but if we want to make the 100 lines
as the comment then we can not use the double backslashes “//” hundred of times. But
at this situation the second way suites very well in which we will place “/*” the starting of the comment and “*/” at the ending of the comment.
Examine the following program: Program (comment.cpp)
/* This program illustrates
the concept of commenting
in a C++ program */
#include <iostream.h> //header file
#include <conio.h>
void main() // main function
{ // main function starts
clrscr(); // clears the screen
cout<<”Computer Systems Engineering”;
getch(); // gets a character
} // main function ends
Variables
The basic definition of the variable says that the variables are those memory locations
whose value can be varied/altered according to the particular situation. Like in other
programming languages variables are one of the major building blocks of C++
programming language. The variables set the location into the memory and give it certain name so you can store certain value and access the particular location of
memory. The name given to the variable is known as identifier. It is so called because it
identifies/indicates certain memory location. In C++ programming language there are certain rules for identifiers so, being in the boundary of those you can declare an
identifier.
Some of the rules are given as:
1) The identifier can contain letters form a-z, numbers form 0-9 and an underscore
sign.
2) The identifier can be in upper or lower case but the variable in upper case will differ
from the variable in lower i.e. ANS is not same as ans or Ans.
3) The first character of the identifier must be letter or an underscore sign.
4) The identifier should not contain any space (white space) within it.
5) You can also give underscore sign in the middle of the identifier as an space for
your ease for example, square_inch.
6) The identifier must not be same as the keywords—the words predefined in C++
which have their own specific meaning and function. Like, main, void, return, cout,
cin etc. are keywords so the identifier should not be like them.
7) The identifier can be as long as you like, but only the first 247 characters (in Visual
C++) or 250 characters (in C++ Builder) will be recognized.
8) The identifier must be unique through out the program i.e. if you have declared the
identifier Var1 so, to access or call it you must give its same name Var1.
Some valid identifiers are:
Var, var, VAR, Var1, VAR1, Var_one, _Var1, _Var_one_of_one etc.
Some of invalid identifiers are:
1Var, 1_var, void, cout, etc.
Hint: The standard and easy way to declare the identifier is to declare all characters of its in lower case like, var1, var2 etc.
Declaring and Defining a variable
You might think that the two words declaring and defining are equivalent but in fact
there is a lot of difference between both of them. The declaring is the process of giving a
name to the variable and its data type. The data type means that which type of value
will be stored in that variable where as the name of the variable must follow the identifier rules of C++.
int var1;
The above line is an example of declaring a variable in which the variable is given the
name var1 and integer data type declared for it which tells the computer that the value stored in the variable var1 must be an integer.
Where as the process of initializing certain value to the variable at the time of declaration is referred as defining a variable. The line below illustrated the concept of
defining a variable:
int var1=50;
In above line the variable var1 is initialized with the integer value 50.
In defining a variable we set/initialize some values to the variable before the compiling.
Memory Memory
var1 var1
Variable Declared Variable Defined
int var1; int var1=50;
50
Examine the below program (Var.cpp) which initializes and declares some variables:
Program (Var.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int mixture;
int ethane=5, methane=8, propane=2;
mixture=(ethane + methane + propane);
cout<<”There are ”<<ethane<<” dm cube of ethane”<<endl;
cout<<”There are ”<<methane<<” dm cube of methane”<<endl;
cout<<”There are ”<<propane<<” dm cube of propane”<<endl;
cout<<”There are ”<<mixture<<” dm cube cubes of mixture”;
getch();
}
The above program starts with two preprocessor directives which include two header
files which contain definitions of some functions and keywords as, cout and getch(). Then in main function one variable mixture is declared and three variables ethane,
methane and propane are defined. The first variable mixture is only declared as it is only
given the name and its data type and no value is set in the memory location of the
variable. Where as in the second variable initialization statement the memory location is set for the three variables and a certain value is initialized to the memory location of the
variables. The last four cout statements prints the values of the variable stored in to
them on the console screen with some strings.
Data Types
The variables are the fundamental building blocks of C++ as discussed earlier, which set
the memory location by giving them certain names. The variables can store certain
data/values into those memory locations but the data/values stored in to the variables
are of different types and occupy different sizes of memories.
Integer data type
The numeric data having no fractional/decimal part is known as integer data. The
integer data type variables can only store and represent integer data. The integer data type is of three types i.e. type int, type short and type long.
Type int occupies 4 bytes (32 bits) of memory. In type int you can store the integers
with in the rage of -2,147,483,648 to 2,147,483,647. To define or declare a type int variable use the keyword int before the variable name like,
int var1= 1000000000;
Type short occupies 2 bytes (16 bits) of memory. In type short you can store the
integers with in the range of -32,768 to 32,767. To define or declare a type short variable use the keyword short before the variable name like,
short var1=10;
Type long occupies 4 bytes (32 bits) of memory. In type long you can store the integers
with in the rage of -2,147,483,648 to 2,147,483,647. To define or declare a type long variable use the keyword long before the variable name and place the letter L after the
integer constant like,
long var1=1000000000L;
Program (integer.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a=10000;
long b=20000;
short c=5;
cout<<”Integer = ”<<a<<endl;
cout<<”Long = ”<<b<<endl;
cout<<”Short = ”<<c;
getch();
}
Floating point data type
The numeric data having fractional/decimal part is known as floating point data. The
floating point data can store and represent floating point data. The floating point data
type is of three types i.e. type float, type double and type long double.
Type float occupies 4 bytes (32 bits) of memory. In type float you can store the floating
point values with in the range of 3.8 x 10-38
to 3.8 x 1038
with the precision of seven (7)
digits. To define or declare a type float variable use the keyword float before the variable name and place the letter F after the floating point constant like,
float PI=3.1415F; but placing F is optional.
The other two floating point data types are same as type float but they offer wider range of values and precisions.
Type double occupies 8 bytes (64 bits) of memory. In type double you can store the
floating point values with in the range of 1.7 x 10-308
to 1.7 x 10308
with the precision of
fifteen (15) digits. To define or declare a type double variable use the keyword double
before the variable name like, double PI=3.141592654;
Type long double occupies 10 bytes (80 bits) of memory. In type long double you can
store the floating point values with in the range of 1.2 x 10-4932
to 1.2 x 104932
with the
precision of nineteen (19) digits. To define or declare a type long double variable use
the keyword long double before the variable name and place the letter L after the floating point constant like,
long double PI=3.141592654546845348645454L; but placing L is optional.
In floating point data types you can write the floating point constants using exponential
notation, which is the way to write very large or very small numbers in the power of ten.
Like instead of writing 2,000,000,0 you can write 1.0E7 in exponential notation.
Similarly for 52347.2 you can write 5.2E4 and for 0.0000006024 you can write 6.02E-7.
double atoms=6.02E-7;
If you want to define a floating point variable then in type float place a letter F in the
end of the constant number, in type double you don‟t have to identify the complier that it is a constant value it considers it as default but in type long double you have to place
the letter L after the constant number. But placing F and L is optional.
float PI=3.1415F;
double PI=3.141592654;
long double PI=3.141592654546845348645454L;
You can also make the value of the floating point variable constant through out the
function by using the constant qualifier i.e. const. To define a constant floating point
variable place the keyword const before the data type of the variable as in:
const float PI=3.1415F;
const double PI=3.141592654;
const long double PI=3.141592654546845348645454L;
Examine the following program:
Program (area.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
const float PI=3.14F;
int radius;
float area;
cout<<”Enter the radius of the circle: ”;
cin>>radius;
area=PI*(radius*radius);
cout<<”The area of the circle is: ”<<area;
getch();
}
This program defines the constant value of the variable PI and declares the integer
variable radius and a type float variable area. The program gets the value of radius
during the run-time in integer type and then puts it in the expression
area=PI*(radius*radius) and calculates the value of area and finally shows the value of
area.
Character Data Type
The data containing individual characters is known as character data. The character data
type variables can only store and represent the characters. The character data type
variables can only store single character at a time in a single variable.
Type char occupies 1byte (eight bits) of the memory. In type char you can store the
characters within the range of integers -128 to 127, where as the integers -128 to 127
represent the ASCII equivalents to the characters. To declare a character data type use keyword char before the variable name as in,
char ch;
The above declaration indicates that the variable ch is a character type data variable and
in the program it will only store the characters. And to define a variable you can either give the character in single quotation marks or you can give the ASCII equivalent to that
character. For example if we want to store the character A (capital A letter) in the
variable ch then we can write as in, char ch=‟A‟;
char ch=65;
In first line the character A is enclosed in single quotation marks so the character A will
be store in the variable ch where as in second line the number 65 is the ASCII
equivalent to the character A so the computer will translate it in to character A and will store it in the variable ch. No matter which method you perform the aim of both the
methods is same.
Examine the following program:
Program (char.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
char ch;
cout<<”Enter any character: ”;
cin>>ch;
cout<<endl<<”you have entered: ”<<ch;
getch();
}
Table 1.1, Data types and their ranges.
Numerical Range Digits of Bytes of
Keyword Low High Precision Memory
char -128 127 n/a 1
short -32,768 32,767 n/a 2
int -2,147,483,648 2,147,483,647 n/a 4
long -2,147,483,648 2,147,483,647 n/a 4
float 3.4 x 10-38
3.4 x 1038
7 4
double 1.7 x 10-308
1.7 x 10308
15 8
long double 1.2 x 10-4932
1.2 x 104932
19 10
Unsigned data types
The data types int, short, long and char have their range with in which they can store
certain values and these ranges start from some negative number to positive number.
So by eliminating negative numbers we can extend the size of the data types. Doing this will make the data types to store large values as twice as the signed data types do.
The unsigned data types are used when we are dealing with only positive numbers. To convert a signed data type into an unsigned data type place the keyword unsigned
before the data type as in,
unsigned int var1=12000;
Type unsigned char occupies 1 byte (8 bits) of memory. In type unsigned char you can
store the characters within the range of integers 0 to 255, where as the integers 0 to 255 represent the ASCII equivalents to the characters. To declare an unsigned data type
variable use keywords unsigned char before the variable name as in,
unsigned char ch=250;
Type unsigned short occupies 2 bytes (16 bits) of memory. In type unsigned short you can store the integers within the range of 0 to 65,535. To declare an unsigned short
data type variable use the keywords unsigned short before the variable name as in,
unsigned short var1=50;
Type unsigned int and type unsigned long occupy 4 bytes (32 bits) of memory. In both the data types you can store the integers within the range of 0 to 4,294,967,295. To
declare an unsigned int and unsigned long data type use the keywords unsigned int and
unsigned long respectively before the variable names as in,
unsigned int var1=10000;
unsigned long var1=10000;
Table 1.2, Unsigned data types and their ranges.
Numerical Range Bytes of Keywords Low High Memory
char 0 255 1
short 0 65,535 2
int 0 4,294,967,295 4
long 0 4,294,967,295 4
The Const Qualifier
The keyword const is known as the constant qualifier. It specifies that the value of the variable will remain constant and will no be altered through out the function. If any
attempt is made to alter the value of the variable the compiler will give the error. It is
always placed before the data type of the variable as in, const float PI=3.1415F;
It specifies that the variable PI stores the floating point number 3.1415 and this value
will not be altered and will remain constant.
Examine the following program:
Program (const.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
const int a=15;
int b=10,c;
b=b+1;
c=a+b;
cout<<c;
getch();
}
Assignment Statements
The statements that assign certain values to certain variables are known as assignment
statement. The assignment statements always contain an equal sign which is actually
the assigner of the values to the variables. Like other statements the assignment
statements always terminate with the terminator. The statements var1=10;
var1=var1+15
var1=var2+15;
are the assignments statements which assign the values to the variable var1. The assignment statements assign the value from the right of the = sign to the variable on
the left. To assign a variable it must be noted that the variable must be declared before
it is assigned.
The endl Manipulator
Manipulators are the instructions to the output stream that modify the output in various
ways. The endl manipulator is also the instruction to the output stream i.e. cout, which
manipulates/modifies the output displayed in the console screen. The endl manipulator used in output stream cout causes the line feed. When ever the endl manipulator comes
in cout statement it moves the cursor to the starting of the next line. It has same effect
as \n escape sequence has to cause the line feed but endl is some what clearer and it also causes the output buffer to be flushed. The endl causes the next string constant in
the cout statement to be printed on the new fresh line.
Examine the following program:
Program (manip.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
cout<<”Computer is an electronic device.”<<endl;
cout<<”It accepts the input.”<<endl;
cout<<”It produces the output.”<<endl;
cout<<”It can store huge amount of data.”<<endl;
getch();
}
The output must be as: Computer is an electronic device.
It accepts the input.
It produces the output.
It can store huge amount of data.
In this program the endl used at the end of the message in each cout statement causes
the next message to be printed on the next line.
White Spaces
The white spaces are the empty areas in the C++ editor. The compiler ignores these white spaces completely. The white spaces may be spaces, carriage return, line-feed,
tabs etc. It is possible for you to write several statements or even a whole block of code
on to a single line and the compiler will compile it with out any error but doing this will not be in your favour as you will not understand that at what place a particular
statement ends and the other starts. And also this is not the standard way to write a
program in C++.
Let‟s examine the following program:
Program (whtspc.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{ cout<<”Computer is an electronic device.”<<endl;
cout<<”It accepts the input.”
<<endl; cout<<”It produces the output.”<<endl; cout<<”It can store
huge amount of data.”<<endl; getch();
}
This program will be compiled with out any error but it is unreadable and is not understandable. You can write your program in this fashion as it is legal but it is not the
standard way. Try to make your program clear and readable.
Declaring and defining several variables with single data type keyword
You can declare or define several variables having same data type with a single data
type keyword. To do this first you have to write the data type of the variables and then
the variable names. Each variable name is separated by a commas “,”.
It is perfectly legal in C++ and it is very important feature in the situations where you
want to group the same data type variable in the same place. It also saves our some
space. The following multiple variable declarations and definitions are valid: int a, b, c, d, e;
float volt=1.5, resistance=50.9, current=2.5l;
short squares=50, triangles, polygons=10;
long double electrons=2.4E24, protons=2.4E24, neutrons;
char ch1=‟a‟, ch2=‟A‟;
The setw manipulator
The setw manipulator changes the field width of the output. It is the instruction to the
output stream to show the output in different manner. It aligns the output in right justified manner. It gets the integer type argument in the parenthesis as the field width
value. The setw requires the header file iomanip.h.
Examine the below program: Program (setwmanip.cpp)
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
void main()
{
int a=1, b=12, c=123, d=1234, e=12345;
cout<<”a”<<setw(8)<<a<<endl;
cout<<”b”<<setw(8)<<b<<endl;
cout<<”c”<<setw(8)<<c<<endl;
cout<<”d”<<setw(8)<<d<<endl;
cout<<”e”<<setw(8)<<e<<endl;
getch();
}
OPERATORS IN C++
ARITHMETIC OPERATORS
The arithmetic operators are those who perform some arithmetic operations on the numbers. There are five arithmetic operators +, -, *, / and %. These are used for
addition, subtraction, multiplication, division and remainder respectively. They have the
same purpose in C++ as in other languages. The first four operators have the same functionality as they posses in algebra. The fifth operator is known as remainder
operator it finds the remainder when one number divides another. It is also known as
modulus operator. It is denoted by % percentage sign. The first four arithmetic operators work on all data types but the remainder operator only works on integer
variable (type short, type int, type long).
Program (arith.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a=10, b=5;
cout<<(a+b)<<endl; // 15
cout<<(a-b)<<endl; // 5
cout<<(a*b)<<endl; // 50
cout<<(a/b)<<endl; // 2
cout<<(a%b)<<endl; // 0 getch();
}
In the first cout statement the variables a and b are added, in second the variables are
subtracted, in third the variables are multiplied, in fourth the variables are divided and in fifth the variable are remaindered. The output of this program is:
15
5 50
2
0
ARITHMETIC ASSIGNMENT OPERATORS
The operators used in assignment statements to shorten and clarify the code are known
as arithmetic assignment operators. They are +=, -=, *=, /= and %=. In some
situation probably you would have faced some statements like,
a=a+b;
b=b-10;
var1=var1*50;
var1=var1/var2;
In these statements a certain value is given to a variable by performing some arithmetic
operation but one variable is used twice in the statements which is really stretching
therefore C++ also offer other approach to shorten and make the assignment
statements more clearer. In this approach you can use the arithmetic assignment operators +=, -=, *=, /= and %= which have the same effects as above.
In C++ a=a+1; and a+=1; have the same effects. Some other equivalents are, electrons += 1; is same as electrons=electrons+1;
electrons -= 1; is same as electrons=electrons-1;
electrons *= 1; is same as electrons=electrons*1;
electrons /= 1; is same as electrons=electrons/1;
electrons %= 1; is same as electrons=electrons%1;
Program (arithassign.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int boxes=40;
cout<<boxes<<endl;
boxes += 10; //boxes = 50
cout<<boxes<<endl;
boxes -= 20; //boxes = 30
cout<<boxes<<endl;
boxes *= 2; //boxes = 60
cout<<boxes<<endl;
boxes /= 5; //boxes = 12
cout<<boxes<<endl;
boxes %= 5; //boxes = 2
cout<<boxes;
getch();
}
RELATIONAL OPERATORS
The relational operators are the operators which compares the operands. There are only
two possible values that the relational operators can give after performing the operation
on the operands i.e. 0 or 1. If the condition becomes true when the operands are
compared with relational operators we get the value 1. On the other hand if the condition becomes false when the operands are compared with relational operators we
get the value 0. There are six relational operators they are, Greater than >, Less than
<, Equal to =, Not equal to !=, Greater than or equal to >=, Less than or equal to <=. Program (relat.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a=10, b=5;
cout<<”a>b is ”<<(a>b)<<endl; // 1
cout<<”a<b is ”<<(a<b)<<endl; // 0
cout<<”a==b is ”<<(a==b)<<endl; // 0
cout<<”a!=b is ”<<(a!=b)<<endl; // 1
cout<<”a>=b is ”<<(a>=b)<<endl; // 1
cout<<”a<=b is ”<<(a<=b)<<endl; // 0
getch();
}
Table 1.3, Relational Operators.
Operator Meaning
> Greater than
< Less than
== Equal to
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
LOGICAL OPERATORS
Logical operators logically combine the Boolean variables (0 and 1). There are three
logical operators And &&, OR || and Not !. They have wide scope when used with
relational operators. They combine the Boolean value obtained by relational operators.
Like in relational operators we can only compare two operands and get the true or false value of only single comparison but if we want to make the condition satisfied only when
the two or more comparison are satisfied then we use logical operators.
And && operator combines the Boolean values and makes the condition satisfied only
when all the comparisons are satisfied as,
(a>b && a>c && a>d)
OR || operator combines the Boolean values and makes the condition satisfied when
atleast one comparison becomes true as,
(a>b || a>c || a>d)
Not ! operator combines the Boolean values and makes the condition satisfied only when
all the comparisons become false as,
(!(a>b)&& !(a>c)&& !(a>d))
Program (logic.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a=2, b=3, c=4;
cout<<(a>b && a>c)<<endl; // 0
cout<<(a>b || a>c)<<endl; // 0
cout<<(b>a || c>b)<<endl; // 1
cout<<(!(a>b) && !(a>c)); // 1
getch();
}
Table 1.4, Logical Operators.
Operator Effect
&& Logical AND
|| Logical OR
! Logical NOT
Increment Operators
The increment operators in C++ can increment or decrement the value of the variables
by one. The increment operators lie in the category of unary operates. In C++ unary
operators have the higher precedence than the other operators. To increment the
variable by the value of one the operator ++ is used and to decrement the variable by the value of one the operator -- is used. The operators ++ and -- can be used in the
two ways as a prefix or as a postfix. When the operator is used in the prefix, the
variable follows the operator and when the operator is used in the postfix the operator follows the variable. Look at the below codes:
int ans=10;
cout<<++ans; //operator used as prefix
int ans=10;
cout<<and++; //operator used as postfix
In first two line codes the value of the variable “ans” is incremented first and then it is printed on the console screen but in the second two line codes the value of the variable
“ans” is first printed on the console screen and then it is incremented the one. Operators
used as prefix and as postfix behave differently.
In C++,
Word=Word+1 is same as Word += 1 is same as ++Word
Word=Word-1 is same as Word -= 1 is same as --Word
Program (increment.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int Balls=10;
cout<<Balls<<endl; //10
cout<<Balls++<<endl; //10
cout<<++Balls<<endl; //12
cout<<Balls--<<endl; //12
cout<<--Balls<<endl; //10
getch();
}
DECISION MAKING STATEMENTS IN C++
DECISION MAKING STATEMENTS
Decision making statements are the statements which take the decisions to make the
conditions satisfied and execute their body. If the condition is satisfied (True) then the statement will cause its body to be executed and if the condition is not satisfied (False)
then the control will be transferred to the next condition or to the first statement after
the body of the conditional statement. There are three types of decision making statement also known as conditional statements. These are so called conditional
statements because they depend on certain conditions. They are,
1) The if Statement
2) The if-else Statement
3) The switch Statement
1) The if Statement
It is the simplest decision making/conditional statement. The if statement contains the
keyword if which is predefined in C++ followed by the condition in the parentheses () with some relational and logical operators. If the condition is satisfied then the body of
the if statement will be executed else the control will be transferred to the first existing
statement after the if statement. If the body of the if statement contains only single
statement then you don‟t have to enclose that statement in the braces but in case of multiple statements you should enclose the block of code in the curly braces. The
syntax of the if statement is given below;
if (a>b && a>c)
statement; Single Statement if body
if (a>b && a>c)
{
statement;
statement; Multiple Statement if body
statement;
}
Test Expression
Test Expression
FLOW CHART OF IF STATEMENT
Program (If.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int Age1=20, Age2=15, Age3=7;
if(Age1>Age2&&Age1>Age3)
{
cout<<”Person with Age1 is elder”<<endl;
cout<<”Persons with Age2 and Age3 are younger”;
}
getch();
}
Test
Expression
Body of if
Exit
False
True
2) The if-else Statement
The if-else statement is another decision making statement. The if-else statement
contains the keywords if and else which are predefined in C++. The condition is
contained in the parentheses () after the keyword if. If the condition is satisfied then the
block of code after the keyword if is executed while if the condition is not satisfied then the control is transferred to the else and the block of code contained after it is executed.
If you want to execute the single statement if the condition is either satisfied or not then
you don‟t have to enclose it in the curly braces but if you want to execute certain block of code (multiple statements) then you have to enclose the block of code in the curly
braces. The syntax of the if-else statement is given below;
if (a>b && a>c)
statement; Single Statement if body
else
statement; Single Statement else body
if (a>b && a>c)
{
statement;
statement; Multiple Statement if body
statement;
}
else
{
statement;
statement; Multiple Statement else body
statement;
}
Test Expression
Test Expression
FLOW CHART OF IF-ELSE STATEMENT
Program (IfElse.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int num1=100, num2=50;
if(num1>num2)
{
cout<<”First number is greater”<<endl;
cout<<”Second number is smaller”;
}
else
{
cout<<”First number is smaller”<<endl;
cout<<”Second number is greater”;
}
getch();
}
Test
Expression
Body of if
Exit
False
True
Body of else
3) The switch Statement
The switch statement is also the decision making statement like if statement and if-else
statement. The switch statement is used when the bunch of decisions depend on the
same variable. It works as if and if-else statements but it is some what clearer and
easily understandable at glance. The switch statement starts with the keyword switch (lower case) followed by the variable in the parentheses (). The switch statement takes
the decision according to the values of the variable in the parenthesis. The whole body
of the switch statement is enclosed by curly braces. Then the switch statement matches the values of the variable with the cases in its body. The keyword case followed by the
choice and the colon makes the block of code below it to be executed if the value of the
switch variable matches with the choice in the case. You can give multiple cases in the switch statement and the switch statement will try to match the value of the variable
with the cases and if no case is matched the control is returned to the default. The key
word default followed by the colon causes the block of code below it to be executed if
the switch statement does not match any of the case. The break statement is used after the block of code in each case, which causes the control to be transferred out of the
switch statement when ever the case executes its block of code. The syntax of the
switch statement is given below;
switch (ch)
{
case 1:
statement;
statement;
break;
case 2:
statement;
statement;
break;
case 3:
statement;
statement;
break;
default:
statement;
statement;
}
Integer or character variable
Note: no semicolon here
Integer or character constant
First case body
Causes exit from switch
Second case body
Third case body
Default case body
Note: no semicolon here
True
True
True
FLOW CHART OF SWITCH STATEMENT
Switch variable equals 1st case
constant 1st case body
Exit
False
Switch variable
equals 2nd
case constant
Switch variable equals 3rd case
constant
2nd case body
3rd case body
Default body
False
False
Program (Switch.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a, b;
char ch;
cout<<”Enter first number: “;
cin>>a;
cout<<”Enter second number: “;
cin>>b;
cout<<”Enter the operator: “;
ch=getche();
cout<<endl;
switch(ch)
{
case „+‟:
cout<<”a + b = ”<<a+b;
break;
case „-‟:
cout<<”a - b = ”<<a-b;
break;
case „*‟:
cout<<”a * b = ”<<a*b;
break;
case „/‟:
cout<<”a / b = ”<<a/b;
break;
default:
cout<<”You have entered the wrong operator”;
}
getch();
}
The break Statement
The break statement breaks the loop and transfers the control to the first executable
statement after that loop. It causes the exit from the loop. In the loop when ever the
break statement appears the loop is broken. The break statement can also be used in
the conditional statements as if, if-else and switch statement. The break statement is widely used in the switch statement in which when ever the case body execution ends
the control is transferred off the switch statement.
Program (break.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a=1, b=1;
for (a=1; a<=10; a++)
{
b+=a;
if (b==5)break;
}
getch();
}
No
rm
al Lo
op
retu
rn
End of loop
Condition in loop
break;
The continue statement
The continue statement transfers the control to the top of the loop. When ever the
continue statement is places with in the loop then the control will not go below that
point but will go to the top of the loop.
Program (break.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int num;
for (int a=1; a<=10; a++)
{
cout<<”enter the roll number: “;
cin>>num;
if (num==0)
{
cout<<”Invalid roll number”<<endl;
continue;
}
else
cout<<”Your roll number is: “<<num;
}
getch();
}
No
rm
al Lo
op
retu
rn
Start of loop
Condition
in loop continue;
The goto statement
It is used to break the sequence of the program and transfer the control to any point of
the program. The goto statement transfers control to its label. The label is any group of
characters terminated by the colon like SessionOne: The keyword goto is used followed
by the label name and semicolon like goto SessionOne;
Program (break.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int num;
cout<<”Enter any positive number: “;
cin>>num;
if (num<=0)
goto InvalidSelection;
else
{
cout<<”Your positive number is: ”<<num;
goto End;
}
InvalidSelection:
cout<<”You have entered a non-positive number”;
End:
getch();
}
Tran
sfe
r o
f co
ntr
ol
True
False
LOOPING IN C++
INTRODUCING LOOPING AND LOOPS
Looping is the process of executing a particular portion of program multiple times with
out writing that code multiple number of times. Suppose if you have to print your name
infinite number of times then you can not write the output statement infinite number of time. To overcome this major hurdle loops are introduced in almost all the programming
languages. Loops are techniques, predefined in any programming language which are
used to execute the particular block of code multiple number of times. The major advantage of using loops is that you don‟t have to write the code multiple number of
times which can save your much time, another advantage is that using loops can reduce
the size of the program dramatically. The loops are constructed in such a way that when
ever the control reaches the end of the loop then the loop transfers the control to the top of the loop and this process of transferring control from bottom to top and top to
bottom continues until a certain condition of the loop becomes false. Figure 3.1, shows
the operation of the loop. In C++ there are three types of loops:
1) The for loop
2) The while loop
3) The do while loops
Figure 3.1, Operation of the loop.
Start of the Loop
End of the Loop
Termination of the
Loop
Initialization Expression
Test Expression
Increment Expression
Note: no semicolon here
Note: no semicolon here
Note: no semicolon here
1) The for loop
The for loop is used to execute the particular block of code fixed number of times with
out writing that block of code multiple number of time. The for loop is used when we
know that how many times the loop will be executed. The for loop uses the keyword for followed by the three expressions in the parentheses. The three expressions in
parentheses are Initialization Expression, Test Expression and Increment Expression.
The Initialization Expression initializes the loop variable and it is executed first and only once in the loop. It tells that from which value the loop will start. The Test Expression is
executed each time the loop is repeated and it contains relational operators which tests
the value of the loop variable. If the condition becomes true in the test expression then
the loop will be executed once more else the loop will be terminated. The Increment Expression increments or decrements the value of the loop variable. It is always
executed at the end of the loop. In single statement for loop body you don‟t have to
enclose the body of the loop in the braces but in case of multiple statement for loop body you have to enclose the body of the loop in the braces. The structure of the for
loop is given below:
for (i=1; i<=10; i++)
statement; Single Statement for loop body
for (i=1; i<=10; i++)
{
statement;
statement; Multiple Statement for loop body
statement;
}
2
False
True
FLOW CHART OF FOR LOOP
Program (forloop.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a;
for(a=1; a<=10; a++)
{
cout<<a;
cout<<endl;
}
getch();
}
Test
Expression
Body of loop
Exit
Initialization Expression
Increment
Expression
Test Expression
Note: no semicolon here
Note: no semicolon here
Note: no semicolon here
2) The while loop
The while loop is used to execute the particular block of code multiple number of times
until the certain condition becomes false. The while loop is used when we don‟t know
that how many times the loop will be executed. The while loop uses the keyword while
followed by the test expression in the parentheses. The test expression in parentheses contains relational operators which tests the value of the loop variable. If the condition
becomes true then the loop will be executed once more else the loop will be terminated.
In single statement while loop body you don‟t have to enclose the body of the loop in the braces but in case of multiple statement while loop body you have to enclose the
body of the loop in the braces. The structure of the while loop is given below:
while (a!=0)
statement; Single Statement while loop body
while (x<=y)
{
statement;
statement; Multiple Statement while loop body
statement;
}
2
False
True
FLOW CHART OF WHILE LOOP
Program (whileloop.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a=1;
while(a!=10)
{
cout<<a<<endl;
a++;
}
getch();
}
Test
Expression
Body of loop
Exit
Note: semicolon here
Test Expression
Note: no semicolon here
Note: semicolon here
Test Expression
Note: no semicolon here
3) The do while loop
The do while loop is used to execute the particular block of code atleast once. The do
while loop is used when we don‟t know that how many times the loop will be executed
but we know that atleast once the loop will be executed. The do while loop uses the
keywords do and while. The do while loop starts with the keyword do and then the body of the loop is to be written and at the last the keyword while is used followed by the test
expression in the parentheses. The semicolon “;” is used after the keyword while so
that the loop will be terminated when the test expression fails. The test expression in parentheses contains relational operators which tests the value of the loop variable. If
the condition becomes true then the loop will be executed once more else the loop will
be terminated. In single statement do while loop body you don‟t have to enclose the body of the loop in the braces but in case of multiple statement do while loop body you
have to enclose the body of the loop in the braces. The structure of the do while loop is
given below:
do
statement; Single Statement do while loop body
while (ch!=‟n‟);
do
{
statement;
statement; Multiple Statement do while loop body
statement;
}
while (ch!=‟n‟);
False
True
FLOW CHART OF DO WHILE LOOP
Program (dowhileloop.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
int a=1;
do
{
cout<<a<<endl;
a++;
}
while(a!=10);
getch();
}
Test
Expression
Body of loop
Exit
THE DIFFERENCE BETWEEN THE THREE LOOPS
The three loops for, while and do while execute particular block of code multiple number
of times. The difference between these three is only of how many times they execute
the particular block of code. In case of for loop we already know that how many times
the loop will be executed but in case of while and do while loops we don‟t know that how many times will the loop be executed but in do while loop we know that the block of
code will be executed atleast once. In for and while loops the test expression is at top
and executed first but in do while loop firstly the body of the loop is executed and then the condition is tested. The while and do while loops can executed certain block of code
infinite number of times but the for loop can only execute the block of code finite
number of times.
Finite number of times Infinite number of times Infinite number of times
FUNCTIONS
Function
The function is one of the fundamental building blocks of C++ programming language. A function is a sub program that contains some program statements. The function collects
a number of program statements and forms a unit with a particular name. This function
then can be called at any stage in the program. The function name declaration follows the same rules of identifiers. The parentheses () are always followed by the function
name in the function. The basic idea to create the functions is to divide a large program
containing hundreds of statements in the small units or blocks so that the program
becomes more clearer and conceptable. A single program may contain hundreds or even thousands of function but each program should contain the main function because main
function is the gate way to enter in C++. The function also contains some return type
and parameters. The return type is type of some data that will be returned by the function at its end. The return type may be of type int, type float, type long, type long
double, type char, void (empty) or user defined data type. The return type is given
before the function name. The parameters are the series of variables separated by comma contained in the parentheses that pass the arguments through the function.
void point(int x, int y)
{
statement;
statement;
statement;
}
Parameters
Function name
Return type
Function Body
The Function Declaration
In case of variables we observed that we cannot use variables without declaring them,
here the scenario is same i.e. we cannot use our own defined functions without declaring
them because the compiler is unfamiliar with the functions developed by the users so
the programmer should first tell the compiler that there is a function which has this return type data and takes these arguments. The function should be declared before it is
called otherwise the compiler will complain. The function declaration includes the
function return type, the function name and the declaration of its parameters in the parentheses and the semicolon at the last. The function declaration is also known as
prototype because it is the blueprint for the function. The function declaration tells the
compiler that the function looking like this is on the way in the program and do not be confused with it. The syntax for declaring a function is,
int charline(int a, char ch);
In above function declaration syntax a user defined function named charline is declared.
It has integer return type and the two parameters i.e. integer a and character ch. Note
that the function can have any return type and can contain number of parameters in the
parentheses.
The Function Definition
The function definition tells the actual purpose and process of the function. The function
definition contains the block of code that is executed when ever that function is called. The whole definition of the function resides in the curly braces of the function body. The
function definition starts with the declarator. Declarator is same as declaration but with
out the semicolon i.e. void charline(int a, char ch) then the body of the function follows.
The function return type, the function name and the parameters in the parentheses should match the function declaration correspondents. If the function is first declared
before the calling then you can place the function definition in any place through out the
program but if you do not have declared the function then you should place the function definition first before its calling. This approach of placing the definition first by
eliminating the function declaration is not considered as standard approach and suits
only in very small programs. The better approach is to declare the function at the top before it is called rather than by placing definition first.
Parameters
Function name
Return type
Note: semicolon here
Note: no semicolon here
Note: semicolon here
Note that the declarator is always not terminated by the terminator. When ever the
function is called each time the control is transferred to the body of the that function. The syntax of the function definition is as under,
int charline(int a, char ch)
{
for(int i=1; i<=a; i++)
cout<<ch;
cout<<endl;
}
Function calling
When the function is declared and defined, now to utilized and make the most of
function, the function is called. The function calling transfers the control from the point
of calling directly to the function definition. The function calling carries the constant
values or variables in the arguments in the parentheses (if used) and passes them from the function definition and evaluates the result. The function calling does not contain
the return type and always terminated by the terminator. The same function can be
called multiple number of time in a program, which evaluates the beauty of the breaking the program in to functions. The syntax of calling the function is given as,
charline(10, „*‟);
Declarator
Function body
Function name
Constant arguments
Table 6.1, Function components.
Component Purpose Example
Declaration
(Prototype)
Specifies function name, argument types, and
return value. Alerts compiler (and programmer)
that function is coming up later.
void funct();
Call Causes the function to be executed. funct();
Defining
Function
The function itself. Contains the lines of code that
constitute the {// lines of code} void funct()
Declarator First line of definition void funct()
The simple function
Program (funct.cpp)
#include <iostream.h>
#include <conio.h>
void charline(int a, char ch);
void main()
{
clrscr();
charline(45, ‟*‟);
charline(45, ‟_‟);
charline(25, „+‟);
getch();
}
void charline(int a, char ch)
{
for(int i=1; i<=a; i++)
cout<<ch;
cout<<endl;
}
The output must be:
*********************************************
---------------------------------------------
+++++++++++++++++++++++++
Passing arguments to the function
The arguments are the data with any data type, which are passed through the function.
When the user creates certain function, the function provides some parameters and the
arguments are the data that are placed in the place parameters to pass those data
through that function. The data type of the arguments and the data type of the parameters should match with each other. You can pass an argument through the
function either by constants or by variables.
Passing constant as arguments
For passing the constant arguments you have to place the constants of any data type in
the arguments where as the data types of the constant arguments and the parameters
should match. When you have passed the constants as the arguments now you can get
a fixed particular result. Examine the below program:
Program (ConstArg.cpp)
#include <iostream.h>
#include <conio.h>
void charline(int a, char ch);
void main()
{
clrscr();
charline(45, ‟*‟);
charline(45, ‟_‟);
charline(25, „+‟);
getch();
}
void charline(int a, char ch)
{
for(int i=1; i<=a; i++)
cout<<ch;
cout<<endl;
}
In the above program the constant arguments are passed through the function
charline. In first function call the integer constant 45 and the character constant „*‟
are passed as the arguments. In second function call the integer constant 45 and the
character constant „-„ are passed as the arguments and in the last function call the integer constant 25 and the character constant „+‟ are passed as the arguments. Now
these constant arguments are place in the memory of the parameter variable, the
integer constants 45, 45, 25 are placed in the parameter a and the character constants
„*‟, „-‟, „+‟ are place in the parameter ch. In the body of the function charline the for
loop is executed integer constant number of time and prints the character constant that
much number of time.
So if you are passing the constants as arguments then the values for the arguments are
set to remain constant and can not be altered. Also the data type of the constant
arguments should match the corresponding parameter‟s data type.
Passing variables as arguments
The phrase “passing the variable” does not mean that the whole variable is passed as
the argument but the data/value stored in that variable is passed thought the function
as the argument. When passing the variable as arguments the data type of the variable should match the data type of the corresponding parameter. The advantage of the
variable arguments is that unlike constant arguments, you can place the values in the
arguments according to the situation and make the function and program general purpose. Examine the below program:
Program (VarArg.cpp)
#include <iostream.h>
#include <conio.h>
void charline(int a, char ch);
void main()
{
int intin;
char chin;
clrscr();
cout<<”Enter the character: “;
cin>>chin;
cout<<”Enter the number of times: “;
cin>>intin;
charline(intin, chin);
getch();
}
void charline(int a, char ch)
{
for(int i=1; i<=a; i++)
cout<<ch;
cout<<endl;
}
In the above program the variables intin and chin are passed through the function as
the arguments. The program at the startup will ask you to enter the values of character
chin and the integer intin then it passes the value placed in the these variable as the
arguments through the function. In this program you can pass the arguments according
to the situation so the program has become generalized by the use of variable arguments.
Returning Value from the function
The function can return a value after passing the arguments through its definition by the
return statement. When you define a function you first give its return type that can be
integer, floating point, character or void (empty). The return statement in the function body returns a value of the type that was declared as the return type of the function
when the function completes its execution. This return value is send to the calling of the
function. The data type declared as the return type of the function should match with the value that the function returns. Examine the below program:
Program (ReturnValue.cpp)
#include <iostream.h>
#include <conio.h>
int add(int a, int b);
void main()
{
int num1, num2;
clrscr();
cout<<”Enter first number: “;
cin>>num1;
cout<<”Enter second number: “;
cin>>num2;
cout<<”The addition is: “<<add(num1,num2);
getch();
}
int add(int a, int b)
{
return (a + b);
}
In the above program the function add is declared with the return type of integer,
which means that when ever the function is called it will return an integer type value
and contains two integer type parameters i.e. a and b. When the function add is called,
the values of num1 and num2 are passed through the function definition and the addition
of num1 and num2 is returned to the calling as the integer type value.
Reference Arguments
When we pass the argument with the variables the copy of that variable is passed
through the function and no effect is implemented on the actual variable but when the
variables are passed by the reference the actual variables are affected and modified by
the function. The reference provides another name for what ever the variable is used and the address of the variable is passed through the function. The references are most
commonly used for passing the arguments through the function. We use the reference
argument when we need to modify the actual variable. When declaring a reference variable the ampersand sign “&” is used which tells the compiler that the variable used is
a reference variable―another name for what ever the variable is used in the arguments.
The ampersand sign can be used with the variable name or with the data type as:
int &var1; //Perfectly Legal
int& var1; //Perfectly Legal
Program (Reference.cpp)
#include <iostream.h>
#include <conio.h>
void swap(int& a, int& b);
void main()
{
int num1, num2;
clrscr();
cout<<”Enter first number: “;
cin>>num1;
cout<<”Enter second number: “;
cin>>num2;
cout<<”num1 = “<<num1<<endl;
cout<<”num2 = “<<num2<<endl;
swap(num1, num2);
cout<<”num1 = “<<num1<<endl;
cout<<”num2 = “<<num2<<endl;
getch();
}
void swap(int& a, int& b)
{
int temp;
temp=a;
a=b;
b=temp;
}
In above program the user defined function swap is declared, which contains two
reference arguments and a and b are two reference variables which will pass through
the body of the function and the effects will be found on these variables. The program
first will input the values of num1 and num2 from the user then these variables are
passed through the function swap which will swap the values of num1 and num2. Now
you will observe that the values of num1 and num2 are swapped which is the indication
that some effect is implemented on these variables by the function.
Data type of array
Name of array
Size of array
Arrays and Strings
Array
Array is the collection of data storage locations, each of which holds the same type of data. Each storage location is called the element of the array. The basic idea behind the
array is to group together similar data items. In array all the data storage locations
should have same data type. The array is the convenient way to group together hundred or even thousands of data item. Each element in the array is stored on a particular
location. The array can be of one dimension or multidimensions. The one dimensional
array is just a series of data items.
Declaring the Array
Like variables and functions the array is also first declared so that the compiler comes to
know that what sort of code is that. Array is declared by writing its data type first which
tells the compiler that all the elements in this array will hold particular data type. Then the array name follows, which follows the same rules of identifier then in the square
brakets the index or subscript or array size is used which tells the compiler that how
many number of data items will the array can hold. Note that the index is always in
integer numbers because the item numbers can only be in the whole number form. int MyArray[10];
In the above array declaration the array named as MyArray is declared with the integer
data type which tells that all the elements of this array will hold the integer values and
the 10 in the square brackets is the index/array size/subscript which tells that
this array will hold 10 integer data items. Note that the array counts the data item form
0 so; in this array the data item will be located at the positions from 0―9.
int MyArray[10];
Array Elements
The data storage locations/items in an array are referred as the array elements and they
all posses same data type. These array elements are responsible for storing certain data
in to them. In an array the array elements start from the location 0 (zero) and onwards.
Let an array named mass contains 5 data items each having floating point data type and
values then;
mass[0]=10.1 is first data item containing value 10.1,
mass[1]=20.4 is second data item containing value 20.4,
mass[2]=8.7 is third data item containing value 8.7,
mass[3]=5.9 is fourth data item containing value 5.9 and
mass[4]=0.01 is fifth data item containing value 0.01.
int mass[5];
You can also initialize the array elements by assigning them the values after declaring
the array as,
int number[7];
number[0]=10;
number[1]=30;
number[2]=17;
number[3]=67;
number[4]=54;
number[5]=14;
number[6]=19;
Note that when you are initializing the array elements you don‟t have to give the data
type but you have to give in the array declaration.
10.1
20.4
8.7
5.9
0.01
mass[0]
mass[1]
mass[2]
mass[3]
mass[4]
Accessing array elements
After you have set the values to the array elements now you can access them by using
the subscript―its location in the array. To access the particular location/element write
the array name followed by the subscript in the square brackets as,
cout<<number[5]; OR
int a=5;
cout<<number[a];
In the above statements the element at the location number 5 is accessed from the
array number. You can also use the variable or expression in the subscript which
evaluates a single integer data type number as the variable a in above declaration does.
Note the difference that in array declaration we use data type but when we are
accessing certain element of the array we don‟t have to give the data type.
Initializing the Array
Initializing the array means setting the values to the array elements at the time of writing the program. Like variables you can also give certain values to the array
elements. To do this the values are assigned to the array by placing an equal to sign
and placing the values in the curly bracket separated by comma following the equal to sign as,
int MyArray[]={10, 20, 30, 40, 50};
int MyArray[5]={10, 20, 30, 40, 50};
In above initialization the array MyArray is initialized with 5 values so,
10 will be assigned to MyArray[0],
20 will be assigned to MyArray[1],
30 will be assigned to MyArray[2],
40 will be assigned to MyArray[3] and
50 will be assigned to MyArray[4].
It is optional that you place the array size in the array initialization or not . But assigning the value more than the array size is not in the interest of the compiler.
int MyArray[4]={10, 20, 30, 40, 50}; //Compiler will complain
int MyArray[8]={10, 20, 30, 40, 50}; //It is legal but not recommended
Program (array1.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
float temp[5];
float sum=0.0, average=0.0;
for(int i=0; i<5; i++)
{
cout<<”Enter the temperature “<<i+1<<” : “;
cin>>temp[i];
cout<<endl;
}
for(i=0; i<5; i++)
sum+=temp[i];
average=sum/5;
cout<<endl<<”The average temperature is : “<<average;
getch();
}
Output:
Enter the temperature 1 : 37.7
Enter the temperature 2 : 35.9
Enter the temperature 3 : 27.5
Enter the temperature 4 : 39.1
Enter the temperature 5 : 38.6
The average temperature is : 35.760002
Multidimensional Array
As we saw that the one dimensional array is a series of elements stored into the array
but the array can also contain multiple dimensions as two, three and so on. In two
dimensional arrays two subscripts are used, in three dimensional arrays three subscripts
are used and the sequence continues. int MultiArray2[2][2]; //Two Dimensional Array
int MultiArray3[3][2][5]; //Three Dimensional Array
int MultiArray5[2][3][7][3][5]; //Five Dimensional Array
Initializing Multidimensional (Two-Dimensional) Array elements
Like one dimensional array you can also initialize the multidimensional array but the
difference is only that in multidimensional element the location of the elements is nested
into the subscripts. The two dimensional array behaves as the matrix having rows and columns.
int TwoDim[3][3]=25;
The above declaration assigns the value 25 to the element in the 3rd location of the 3rd
location of the fist subscript. This means that the locations in the multidimensional arrays are nested in to the subscripts.
0 1 2 3
0
1
2
3 3
0
0
0
0
TwoDim[3][3]=25
0
0
0
0
0
0
0
0
0
0
0
25
Initializing Multidimensional (Two Dimensional) Array
Like one dimensional array you can also set the values to the elements of
multidimensional array at the time of writing the program. To do this you have to place
the values in the separate curly brackets separated by the commas and for every
location of first subscript you have to place separate braces as, int matrix[][]={{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; OR
int matrix[3][3]={{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Note both the criteria are legal.
matrix[0][0]=1;
matrix[0][1]=2;
matrix[0][2]=3;
matrix[1][0]=4;
matrix[1][1]=5;
matrix[1][2]=6;
matrix[2][0]=7;
matrix[2][1]=8;
matrix[2][2]=9;
1
2
3
4
5
matrix[0][0]
matrix[0][1]
matrix[0][2]
matrix[1][0]
matrix[1][1]
6
7
8
9
matrix[1][2]
matrix[2][0]
matrix[2][1]
matrix[2][2]
Strings in C++
String is the collection/sequence of characters. In C++ we can work with strings by
either using the character array or the predefined string class. In character data
type only single byte of the memory is occupied while in string multiple number of bytes
of memory are engaged.
Character Array (C-String)
Character array is the simple array with the data type of char used to hold the
strings/sequence of characters. These strings are also known as C-String because they
were only the kind of strings available in C language and in early version of C++ language. The array variable used to hold the string is known as C-String. To declare C-
String variable, as traditionally, we use the data type in front of the C-String variable
but the data type must be type char. Then in square bracket the size of the string is
initialized. As for each character 1 byte of the memory is engaged, but in strings special
null character, represented by `\0', is appended to the end of the string to indicate the end of the string. Hence if a string has n characters then it requires an n+1 element
array (at least) to store it. Thus the character `a' is stored in a single byte, whereas the
single-character string "a" is stored in two consecutive bytes holding the character `a' and the null character. Let‟s examine the below program:
Program (CString.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
char string1[7];
cout<<”Enter the string: “;
cin>>string1;
cout<<”Your string is: “<<string1;
getch();
}
Firstly the program will initialize the C-String variable string1 holding 7 elements. Now
say you have entered Asghar then this string will occupy 6 memory locations of the
character array and the 7th
location will be occupied by the num character „\0‟. Finally
the cout statement will sent the string string1 to the console screen.
Initializing the C-String variable
As other variables and arrays you can also initialize the C-String variable. There are two
ways by which you can initialize the C-String variable either you place the sting in the
double quotation marks in with the equal to sing following the C-String variable or you
can place every character of the string enclosed in single quotation marks in the curly braces following the C-String variable and equal to sign.
char string1[11]=”Ali Asghar”;
char string1[11]={„A‟, ‟l‟, ‟i‟, ‟ „, ‟A‟, ‟s‟, ‟g‟, ‟h‟, ‟a‟, ‟r‟};
Both the ways of declaration are legal. Most programmer do not prefer second way
because it is more starching but in some situation it is very help full.
Program (CString2.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
char string1[11]=”Ali Asghar”;
char string2[11]={„A‟,‟l‟,‟i‟,‟ „,‟A‟,‟s‟,‟g‟,‟h‟,‟a‟,‟r‟};
cout<<string1<<endl;
cout<<string2;
getch();
}
In CString2.cpp the C-String variables string1 and string2 are initialized in two
different ways but both will have same impact. Note that in second criteria however we
have initialized 10 characters i.e. „A‟,‟l‟,‟i‟,‟ „,‟A‟,‟s‟,‟g‟,‟h‟,‟a‟,‟r‟ but
at the last location the null character „\0‟ is stored hence all the locations of the
character array are engaged.
Reading Embedded Blanks and cin.get() function
In program CString.cpp it would be observed that when ever you enter the string say
Ali Asghar then in the cout statement only the word Ali is displayed. Now what is
happened to the other characters, the operator >> in the cin considers the blank space
as the terminating character and will terminate the string when ever the blank space is
entered. So the rest of the characters vanish out. To overcome this hurdle another
function cin.get() is used to get the C-Sting input. cin.get() means that get() is
the member function of the stream class of which cin is an object. The syntax of the
cin.get() is as,
cin.get(ArrayName, ARRAYSIZE); //Syntax 1
cin.get(ArrayName, ARRAYSIZE, „Character‟); //Syntax 2
In syntax 1 the function takes two arguments first the array name i.e. the array in
which the entered string will be place and in the second argument the number of
characters in the string that the function gets/array size is entered.
In syntax 2 the function takes three arguments first is for the array name, second for
the array size/number of character in the string and in the third argument some
character is place which is used to break the reading of the string input. The default
argument for this character is „\n‟ (new line).
Program (cinget.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
char string1[11], string2[20];
cout<<”Enter the First string : “;
cin.get(string1, 11);
cout<<”Enter the Second string : “;
cin.get(string2, 20, ‟$‟);
cout<<”Your First string is: “<<string1;
cout<<”Your Second string is: “<<string2;
getch();
}
In the string 2 you can input the string in as much lines as you can but note that to
terminate the string input you still have to press the ENTER key after entering the
character „$‟.
Concatenating C-Strings with strcat()
The standard C++ also offer the feature to concatenate (combine) the C-Strings. The
function to perform this task is strcat(). The syntax for the function strcat() is as,
strcat(destination, source);
Examine the below program:
Program (concatinate.cpp)
#include <iostream.h>
#include <conio.h>
#include <cstring.h> //contains the definition of strcat()
void main()
{
char string1[]=”Ali ”,
char string2[]=”Asghar ”;
strcat(string1, string2);
cout<<”Your full name is: “<<string1;
getch();
}
In the above program the character array string1 is assigned to the string constant
“Ali “ and the character array string2 is assigned to the string constant “Asghar”.
The strcat() function then concatenates the string2 in to the string1 so now the
string1 is the combination of string2 and itself.
The string1 after concatenation become “Ali Asghar”.
Note that the function strcat() needs the access of the header file cstring.h. It also
should be noted that the concatenation occurs in the first argument i.e. destination.
Array of Strings
In an string array you can store array of sequence of characters. String array is the two
dimensional array in which first dimension tells how many strings will be stored in the
string array and the second dimension tells about how many characters each string will
hold. Let‟s examine the below program:
Program (ArrayString.cpp)
#include <iostream.h>
#include <conio.h>
void main()
{
char day[7][11]={ “Monday”, “Tuesday”, “Wednesday”, “Thursday”,
“Friday”, “Saturday”, “Sunday”};
for(int i=0; i<7; i++)
cout<<”Day ”<<i+1<<” : “<<day[i]<<endl;
getch();
}
In the above program the array day is initialized with the two dimensions. First
dimension declares the number of strings to be store in the array day and the second
dimension determines the number of characters in each string to be store, 11 in this
program which are enough to store the name of any day.
In the cout statement you will find that there is only single dimension used and in the
declaration we have initialized two dimensions then what happened to the other
dimension. As we know that two dimensional array is the nested array (array of arrays) so we can access each outer array containing the entire element for this we use only
single index.
The Standard C++ String Class
As previously we used to store the string in the arrays so it was very complicated, time
consuming and stretching. So the standard C++ includes a string class which defines an
easy way to store and access the strings. The string class also offers many advantages as you can also concatenate(combine) two or more strings. The String class is more
safer and convenient way to store the strings and work with them then the C-Strings.
Declaring and Defining the string Objects
You can declare the string object by using the keyword string with some variable then
the variable used will hold the data type of type string and can store the string of any
length. To define or assign the string object we place the string constant in the double quotation marks followed by the equal to sign after the string object. You can also define
and string object by placing the string constant in the parenthesis delimited by the
double quotation marks.
You can also assign one string object to another string object by using the arithmetic
operator “+”. It is just like grouping two or more strings in one string object.
Note that working with string objects you should have access to the string.h and
cstring.h header files. Therefore you should first include the header files string.h
and cstring.h at the top of your program.
string s1; //Declaring string object
string s2=”Ali Asghar”; //Defining string object way 1
string s3(“Ali Asghar”); //Defining string object way 2
Program (StringClass1.cpp)
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <cstring.h>
void main()
{
string s1=”Ali “;
string s2=”Asghar”;
string s3;
s3=s1+s2;
cout<<s3;
getch();
}
In the above program the string objects s1 and s2 are defined and assigned with some
string constant, s1 is assigned with the string constant “Ali “ and s2 is assigned with
the string constant “Asghar”. Then third string object s3 is declared and is assigned to
the combination of the string objects s1 and s2 so the string object s3 will contain the
both s1 and s2.
Inputting string objects with getline()
As inputting character array we used the function cin.get() but when inputting string
objects we have a different structure. The function used to input string objects is the
getline() function which gets the string from the user and puts in the desired string
object. The syntax for the getline() function is as,
getline(cin, stringObject); //Syntax 1
getline(cin, stringObject, „character‟); //Syntax 2
In Syntax 1 the function has two arguments first is cin and the other is for the string
object in which the string will be placed.
In Syntax 2 the function has three arguments, the first is cin, the second is for the
string object and the third argument gets any character which when entered during the
string input will terminate the string input.
Program (getline.cpp)
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <cstring.h>
void main()
{
string s1, s2;
cout<<”Enter your names : “;
getline(cin, s1,‟$‟);
cout<<”Enter your cast : “;
getline(cin, s2);
cout<<”Your full name: “<<(s1+s2);
getch();
}
Finding string objects
The standard C++ offers variety of other member function with the string class. One of
which is for finding the location of the string or sub-string in the string object. find()
and find_first() are the two member function used to find the location of the string
or sub-string in the string class. The syntax for the find()and find_first() is as,
stringObject.find(“string/sub-string”); //for find()
stringObject.find_first(“string/sub-string”); //for find_first()
Program (findstring.cpp)
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <cstring.h>
void main()
{
string s1=”strings are the sequence of characters”;
int location1, location2;
location1=s1.find(“are”);
location2=s1.find_first(“oabs”);
cout<<”The word “are” found at: “<<location1;
cout<<”The second string found at: “<<location2;
getch();
}
In the above program the statement location1=s1.find(“are”); means that the
sub-string “are” is to be searched in the string s1 and the location will be stored is
the variable location1. And the statement location2=s1.find_first(“oabs”);
means that the first character in the double quotation marks is to be searched in the
string object s1 and the location of that will be stored in the variable location2. The
program then shows the locations at which the sub-string are found.
It should be noted that the compiler start counting the location from 0 (zero) so the
value of the variable location1 will be 8 and the value of the variable location2 will
be 25.
Note: semicolon here
Keyword “struct”
Structure name/tag
Structure members
Braces delimit structure members
STRUCTURES
Structures
The structure is the collection of simple variables. There can be any number of variables
in an structure. In an structure the variables can of different data types unlike an array in which all the elements have the same data type. The data items in an structure are
referred as the members of the structure. In C++ structures are the continent way to
understand the two fundamental building blocks of C++ the class and the object. But
the difference is only that the structure is the collection of variables whereas the class
is the collection of data and the functions.
Declaring the structure
As we know that in C++ every thing defined by the user must be declared so the
compiler makes sense to it. The declaration provides the blueprint for the compiler so
when ever such things appear in front of the compiler it does not worry about it. To
declare an structure the keyword struct is used at the starting and then the structure
name follows. The structure name is also refereed as the tag. Then in the curly braces
the variables with their data types are declared and these variables are known as the
members of the structure. And at the last the structure is terminated by the
semicolon. The syntax for the simple structure is as,
struct car
{
int modelnumber;
float maxspeed;
float price;
};
In above declaration the structure named car is declared with three members one of
type int (i.e. modelnumber) and two of type float (i.e. maxspeed, price)
delimited by the curly braces and the structure is terminated at the end by the
semicolon. It should be noted that the declaration does not set a side the memory for the member it just provides the blue print for the compiler.
Defining Structure Variables
As in above when the structure is declared now it will behave as the new data type i.e.
the structure name (car) will be the data type and the variables attached to it will have
the data type of type car. To define the structure variables we declare the variables
following the structure name as, (car MercedesBenz). You can define as many
structure variables as you can. The syntax for the structure variable definition is as,
StructureName variable_1, variable_2, . . . . . . , variable_n;
Defining structure variable Example,
struct car
{
int modelnumber;
char color[10];
int model;
};
car Bedford, Mercedes, MercedesBenz, Ferrari;
In the above example the structure variables Bedford, Mercedes, MercedesBenz
and Ferrari of structure car are defined and it should be noted each structure
variable will contain entire structure members.
The definition of the structure variables set aside the memory for the variables. The
amount of memory depends up on the number and type of the members of the
structure. In the above structure the variables Bedford, Mercedes, MercedesBenz
and Ferrari will occupy 18 bytes of memory (4 bytes of int modelnumber, 10
bytes of char color[10]; and 4 bytes of int model).
Combining Declaration and Definition
As above we declared the structure first and then we defined its variable in separate
statement but the C++ also offers the feature that you can combine the structure declaration and definition. To do this we eliminate the structure name/tag and the
structure variable is place between the closing brace of the structure and the semicolon
that terminates the structure but what it lacks is that in this method we can only define a single structure variable so it is less flexible and is not recommended as the standard
way to declare and define the structure.
Combined Declaration and Definition Example,
struct
{
int modelnumber;
char color[10];
int model;
}Bedford;
Accessing and Assigning Structure Members
Once the structure is declared and the structure variables are defined now you can
access the structure member with the help of dot operator “.” actually known as
member access operator. To access the structure members first we use the structure
variable name then the dot operator and finally the structure member name e.g.
(Bedford.modelnumber). You can also assign certain values to the member like,
Bedford.modelnumber=2007; but it should be noted that the value assigned to the
member should match with the data type declared for that member in the structure.
Program (struct1.cpp)
#include <iostream.h>
#include <conio.h>
struct car
{
int modelnumber;
float maxspeed;
float price;
};
void main()
{
car Bedford;
Bedford.modelnumber=2007;
Bedford.maxspeed=500.0;
Bedford.price=4500000.0;
cout<<”Model Number: “<<Bedford.modelnumber<<endl;
cout<<”Top Speed: “<<Bedford.maxspeed<<endl;
cout<<”Total Price: “<<Bedford.price<<” Pak rupees”;
getch();
}
Initializing Structure Variables
Like other variables you can also initialize the structure variables. To do this the values
to be assigned to the structure members are placed in the curly braces and separated by
the commas following the structure variable and equal to sign. It should be noted that
the values placed in the curly braces should be of same data type that the structure members contain and also the sequence must be same as,
car Bedford={2007, 500.0, 4500000.0};
car Mercedes={2007, 600.0, 6000000.0};
car MercedesBenz={2007, 800.0, 9000000.0};
In above initializations the first value in the curly braces is to be assigned to the first
structure member, second to the second structure member and third to the third structure member. You can also assign the same values of one structure variable to the
other structure variable of same structure like,
Bedford=Mercedes; //All values assigned to the Mercedes
Mercedes=MercedesBenz; //All values assigned to the MercedesBenz
Program (struct2.cpp)
#include <iostream.h>
#include <conio.h>
struct car
{
int modelnumber;
float maxspeed;
float price;
};
void main()
{
car Bedford={2007, 500.0, 450000.0};
car Mercedes=Bedford;
cout<<”Bedford:”<<endl<<endl;
cout<<”Model Number: “<<Bedford.modelnumber<<endl;
cout<<”Top Speed: “<<Bedford.maxspeed<<endl;
cout<<”Total Price: “<<Bedford.price<<” Pak rupees”<<endl;
cout<<endl<<”Mercedes:”<<endl<<endl;
cout<<”Model Number: “<<Mercedes.modelnumber<<endl;
cout<<”Top Speed: “<<Mercedes.maxspeed<<endl;
cout<<”Total Price: “<<Mercedes.price<<” Pak rupees”<<endl;
getch();
}
Nested Structures
The mechanism obtained after putting one structure with in another structure is called
the nested structure. As in the nested loops we write one loop in the body of another loop but here the criteria different, the nested structure does not mean that we have to
put the body of one structure in to another structure. In the nested structure the data
type of the members of the second structure will be the name of the first structure and
the data type of the members of the third structure will be the name of the second structure and so on hence the depth is created that is responsible for nesting the
structures. See the below example,
======================
struct student
{
int Rollno;
int AC;
int BEE;
int ITC;
};
======================
struct university
{
student CS;
student SW;
student ES;
student TL;
student BM;
student EL;
};
======================
In above example the first structure student is declared which has four members
(Rollno, AC, BEE, and ITC), each having data type of type int. And the second
structure university is nested in the first structure and its members (CS, SW, ES,
TL, BM and EL) contain the data type of type student, which is the name of the
first structure. So the above example illustrates the concept of nested structures.
Accessing nested structure members and Initializing nested structures
As in the nested structure one structure is nested in to another structure therefore to
access the members in the inner structure we have to first go through the outer
structure then to the inner structure. To access the nested structure member we have
to use the dot operator multiple number of time. If there are three nested structure
then to access the inner structure member we have to use the dot operator three times.
As in the above example the structure student is nested in to the structure
university. So to access the student structure member,
Suppose if we initialize the department structure variable MUET;
MUET.CS.Rollno; MUET.SW.Rollno; MUET.TL.Rollno;
MUET.CS.AC; MUET.SW.AC; MUET.TL.AC;
MUET.CS.BEE; MUET.SW.BEE; MUET.TL.BEE;
MUET.CS.ITC; MUET.SW.ITC; MUET.TL.ITC;
The procedure of initializing the nested structure is same as initializing the simple
structure. But here multiple numbers of braces are used as,
CS SW ES
university MUET={{10,80,85,90},{95,80,81,82},{11,87,84,81},
{45,85,84,83},{65,75,74,85},{21,87,89,88} };
TL BM EL
{10,80,85,90}
Here the four values in the first inner braces are initialized to the four members of the
nested structure CS, second to the SW, third to the ES, fourth to TL , fifth to the BM and
sixth to the EL.
Program (NestStruc.cpp) “In Borland C++ V5.02”
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <cstring.h>
struct student
{
int Rollnum;
string Name;
};
struct university
{
student CS;
student SW;
};
void main()
{
university MUET, Oxford;
MUET.CS.Rollnum=20;
MUET.CS.Name=”Ali Asghar”;
MUET.SW.Rollnum=181;
MUET.SW.Name=”Kamran”;
Oxford.CS.Rollnum=118;
Oxford.CS.Name=”Martin”;
Oxford.SW.Rollnum=79;
Oxford.SW.Name=”Davidson”;
cout<<”MUET, Computer Systems:“<<endl<<endl;
cout<<”Roll Number: “<<MUET.CS.Rollnum<<endl;
cout<<”Name: “<<MUET.CS.Name<<endl<<endl;
cout<<”MUET, Software:“<<endl<<endl;
cout<<”Roll Number: “<<MUET.SW.Rollnum<<endl;
cout<<”Name: “<<MUET.SW.Name<<endl<<endl;
cout<<”Oxford, Computer Systems:“<<endl<<endl;
cout<<”Roll Number: “<<Oxford.CS.Rollnum<<endl;
cout<<”Name: “<<Oxford.CS.Name<<endl<<endl;
cout<<”Oxford, Software:“<<endl<<endl;
cout<<”Roll Number: “<<Oxford.SW.Rollnum<<endl;
cout<<”Name: “<<Oxford.SW.Name<<endl<<endl;
getch(); }
Program (NestStruc2.cpp) “In Borland C++ V5.02”
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <cstring.h>
struct student
{
int Rollnum;
string Name;
};
struct university
{
student CS;
student SW;
};
void main()
{
university MUET[10];
for(int i=0; i<10; i++)
{
cout<<”Enter the Roll number of student CS no “<<(i+1)<<” : “;
cin>>MUET[i].CS.Rollnum;
cout<<”Enter the Name of the student CS no “<<(i+1)<<” : “;
cin>>MUET[i].CS.Name;
cout<<”Enter the Roll number of student SW no “<<(i+1)<<” : “;
cin>>MUET[i].SW.Rollnum;
cout<<”Enter the Name of the student SW no “<<(i+1)<<” : “;
cin>>MUET[i].SW.Name;
}
clrscr();
for(int i=0; i<10; i++)
{
cout<<”Roll no CS“<<MUET[i].CS.Rollnum<<endl;
cout<<”Name: “<<MUET[i].CS.Name<<endl<<endl;
}
for(i=0; i<10; i++)
{
cout<<”Roll no SW“<<MUET[i].SW.Rollnum<<endl;
cout<<”Name: “<<MUET[i].SW.Name<<endl<<endl;
}
getch(); }