Vous êtes sur la page 1sur 107

Ali Asghar Manjotho (07CS20)

A Practical book of C++ OOP











Name: Ali Asghar
ID Number: 07CS20
Fathers Name: Imam Bux Manjotho
Subject: Object-Oriented Programming in C++
Department: Computer Systems Engineering
Institution: Mehran University of Engineering and
Technology, Jamshoro
























Certified that Mr. Ali Asghar bearing roll number 07CS20 has
carried out the necessary work as per course of studies
prevailed in the department of Computer Systems Engineering,
for the year 2007.



____________________
Prof. Muhammad Zahid Shaikh
Engg: Shahnawaz Talpur


















S.NO

OBJECTS

1
To become familiar with basics of C++ programming and IDE
environment.
2 To become familiar with Decision making statements.
3 To become familiar with loops.
4 To become familiar with functions in C++.
5 To become familiar with arrays and strings.
6 To become familiar with pointers.
7 To become familiar with structures.
8 To become familiar with classes and objects.
9 To become familiar with operator overloading.
10 To become familiar with Inheritance.
11 To become familiar with files and streams.





TO BECOME FAMILIAR WITH BASICS OF C++ PROGRAMMING AND IDE ENVIRONMENT.



OBJECT 1: INTRODUCING C++ ENVIRONMENT

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.


















1



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. 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 parentheses. 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
2


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. The 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;
3



OBJECT 2: VARIABLES, DATA TYPES AND CONSTANTS

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 situations. 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 keywordsthe 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 i.e. 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.
4


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 to 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
5


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.












6


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 TYPES

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= 100000000;

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=100000000L;

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();
}
7


FLOATING POINT DATA TYPE

The numeric data having fractional/decimal part is known as floating point data. The
floating point data type variables 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 10
38
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 10
308
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 10
4932
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 dont 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;
8


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.








9


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<<you have entered: <<ch;
getch();
}



10


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 10
38
7 4
double 1.7 x 10
-308
1.7 x 10
308
15 8
long double 1.2 x 10
-4932
1.2 x 10
4932
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 char 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,
11



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();
}


12



OBJECT 3: WORKING WITH 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


13


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();
}
14


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

15


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
16



EXERCISE


1) Write a program that will compute the area of a circle. The user must enter the
radius of the circle. Use the following formula for area A=3.14*R^2?

2) Write a program that will solve for the power dissipation of a resistor when the
voltage across the resistor and the current in the resistor are known. The relationship
for the power dissipation is: P=I^2*R?

3) Write a program that calculates the memory size of variable of different data type?

4) Develop a program that will convert the temperature from degree Celsius to degree
Fahrenheit. User input the temperature in Celsius. The relation is F=5/9*C+32?

5) (a): Execute the following code step-by-step using F8 key and observe how the
integer variables are declared, initialized and modified in the program.


#include <iostream.h>

void main()
{
int i=0;
int j=1;
cout<<i=<<i<<j=<<j<<endl;
i=10;
j=20;
cout<<i=<<i<<j=<<j<<endl;
}


5) (b): In the above code change

int i=0;
int j=1;
to
const int i=0;
const int j=1;

now compile it and find out the errors and try to understand the cause of the errors.




17



EXERCISE SOLUTIONS


====================================================

Program #01

#include <iostream.h>
#include <conio.h>

void main()
{
const float PI=3.14;
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();
}

====================================================

Program #02

#include <iostream.h>
#include <conio.h>

void main()
{
float V, I, R, P;

cout<<Enter the voltage across the resistor: ; cin>>V;
cout<<Enter the current through the resistor: ; cin>>I;
R=V/I;
P=(I*I)*R;
cout<<The power dissipation is <<P<< watts;

getch();
}

====================================================

18


====================================================

Program #03

#include <iostream.h>
#include <conio.h>

void main()
{
char a;
short b;
int c;
long d;
float e;
double f;
long double g;

cout<<Size of a: <<sizeof(a)<< byte<<endl;
cout<<Size of b: <<sizeof(b)<< bytes<<endl;
cout<<Size of c: <<sizeof(c)<< bytes<<endl;
cout<<Size of d: <<sizeof(d)<< bytes<<endl;
cout<<Size of e: <<sizeof(e)<< bytes<<endl;
cout<<Size of f: <<sizeof(f)<< bytes<<endl;
cout<<Size of g: <<sizeof(g)<< bytes;

getch();
}

====================================================

Program #04

#include <iostream.h>
#include <conio.h>

void main()
{
float Ctemp, Ftemp;

cout<<Enter the temperature in Celsius: ; cin>>Ctemp;
Ftemp=(9/5)*Ctemp+32;
cout<<endl<<The temperature in Fahrenheit is: <<Ftemp;

getch();
}
19


====================================================

Program #05(a)

#include <iostream.h>

void main()
{
int i=0;
int j=1;
cout<<i=<<i<<j=<<j<<endl;
i=10;
j=20;
cout<<i=<<i<<j=<<j<<endl;
}

In this program the variable i is initialized with the value 0 and the variable j is
initialized with 1. So in the first cout statement the values of the i and j are printed
and then the values of the variable i and j are altered i.e. i is now given the value
10 and j is given the value 20. Now in the second cout statement the value of i and
j are printed.

====================================================

Program #05(b)

#include <iostream.h>

void main()
{
const int i=0;
cont int j=1;
cout<<i=<<i<<j=<<j<<endl;
i=10;
j=20;
cout<<i=<<i<<j=<<j<<endl;
}

In the above program the constant values are set to the variables i and j this means
that the values of the variable can not be altered. Now if the compiler compiles the
program it will give the error message that the values of the constant objects can not
be modified which is a fact. This is because the const qualifier is used which qualifies
the value of the variable constant through the function so any attempt made to alter
the variable will cause the error.

====================================================
20
Test Expression
Test Expression





OBJECT: TO BECOME FAMILIAR WITH DECISION MAKING STATEMENTS.


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 dont 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;
}
21


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
22
Test Expression
Test Expression


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 dont 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;
}
23


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
24
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


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;
}

25
True
True
True


FLOW CHART OF SWITCH STATEMENT
















































Switch variable
equals 1st case
constant
1
st
case body
Exit
False

Switch variable
equals 2nd
case constant

Switch variable
equals 3rd case
constant
2
nd
case body
3
rd
case body
Default body
False
False
26


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();
}



27



EXERCISE


1) Write a program that determines the year entered by user is leap year or not?


2) Write a program which gives the following output

Enter age>>

And prints the following:

If Age is greater than 45 then prints the message You are old stay at home and wait
for call

If Age is greater than 30 and less than 45 then prints Hey! man enjoy your life with
your kids

If Age is greater than 20 and less than 30 then prints Cool! have a search for your
best suit

If Age is greater than 10 and less than 20 then prints Work hard! Your days to
study

If Age is less than 10 then prints the message Oh! Kid your days to cry

Use if-else statement.


3) Write the above program #02 by using the switch statement?


4) Develop a C++ program which will compute the power dissipation of a resistor, when
the user inputs current value and the resistance. Program warns the user if power
dissipation is above 1 watt. The power dissipation is measured by P=I
2
R.










28


EXERCISE SOLUTIONS


===================================================


Program #01

#include <iostream.h>
#include <conio.h>

void main()
{
int year;

cout<<Enter the year: ;
cin>>year;

if(year%4==0)
cout<<year<< is the leap year;
else
cout<<year<< is not the leap year;

getch();
}

===================================================

Program #02

#include <iostream.h>
#include <conio.h>


void main()
{
int Age;

cout<<Enter the age: ;
cin>>Age;

if(Age>45)
cout<<You are old stay at home and wait for call;

else if(Age>30&&Age<45)
29


cout<<Hey! man enjoy your life with your kids;

else if(Age>20&&Age<30)
cout<<Cool! Have a search for your best suit;

else if(Age>10&&Age<20)
cout<<Work hard! Your days to study;

else if(Age<10)
cout<<Oh! Kid your days to cry;

getch();
}

===================================================


Program #03

#include <iostream.h>
#include <conio.h>


void main()
{
int Age;
cout<<"Enter the age: ";
cin>>Age;


switch(Age>45)
{
case 1:
cout<<"You are old stay at home and wait for call";
break;
}

switch(Age>30&&Age<45)
{
case 1:
cout<<"Hey! man enjoy your life with your kids";
break;
}

switch(Age>20&&Age<30)
{
case 1:
30


cout<<"Cool! Have a search for your best suit";
break;
}

switch(Age>10&&Age<20)
{
case 1:
cout<<"Work hard! Your days to study";
break;
}

switch(Age<10)
{
case 1:
cout<<"Oh! Kid your days to cry";
}

getch();
}

===================================================

Program #04

#include <iostream.h>
#include <conio.h>


void main()
{
float P, I, R;

cout<<Enter the resistance: ;
cin>>R;
cout<<Enter the current through the resistor: ;
cin>>I;

P=(I*I)*R;
cout<<the power dissipation is <<P<< watts<<endl;

if(P>1)
cout<<Alert! There is too much power dissipation;

getch();
}

===================================================
31
T
r
a
n
s
f
e
r

o
f

c
o
n
t
r
o
l


True
False







OBJECT: TO BECOME FAMILIAR WITH LOOPS


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 dont 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
21 32
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 dont 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
33
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
34

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 dont 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 dont 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
35
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
36
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 dont 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 dont 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);






37
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
38


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 dont 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
39




EXERCISE



1. With the help of For, While, Do While loops, generate the following series.

a. Even numbers b/w 1 and 40.
b. Numbers that are divided by 5, from 1 to 1000.

2. Write a program using for loop which inputs as integer and prints its factorial?

3. Write a program that will generate the following output

* * * * *
* * * *
* * *
* *
*
* *
* * *
* * * *
* * * * *

4. Write a program that counts blanks, digits, uppercase, lowercase letters, new lines
and other characters entered through the keyboard, use character t to terminate the
input.


5. Write a program using two nested loops to generate the following output. Note that
the last column contains the sum of the corresponding row.

1 2 3 4 10
5 6 7 8 26
9 10 11 12 42
13 14 15 16 58





40


EXERCISE SOLUTIONS


===================================================

Program #01 (a) With for loop

#include <constream.h>

void main()
{
clrscr();
for(int i=1; i<=40; i++)
{ if(i%2==0)cout<<i<<endl; }
getch();
}


Program #01 (a) With while loop

#include <constream.h>

void main()
{
clrscr();
int i=1;
while(i<=40)
{ if(i%2==0)cout<<i<<endl; i++; }
getch();
}


Program #01 (a) With do while loop

#include <constream.h>

void main()
{
clrscr();
int i=1;
do{ if(i%2==0)cout<<i<<endl; i++; }while(i<=40);
getch();
}

===================================================

41


===================================================

Program #01 (b) With for loop

#include <constream.h>

void main()
{
clrscr();
for(int i=1; i<=1000; i++)
{ if(i%5==0)cout<<i<<endl; }
getch();
}


Program #01 (b) With while loop

#include <constream.h>

void main()
{
clrscr();
int i=1;
while(i<=1000)
{ if(i%5==0)cout<<i<<endl; i++; }
getch();
}


Program #01 (b) With do while loop

#include <constream.h>

void main()
{
clrscr();
int i=1;
do{ if(i%5==0)cout<<i<<endl; i++; }while(i<=1000);
getch();
}

===================================================



42


===================================================

Program #02

#include <constream.h>

void main()
{
clrscr();
int num, fact=1;;
cout<<"Enter the number to calculate its factorial : ";
cin>>num;
for(int i=1; i<=num; i++)
fact*=i;
cout<<num<<"! = "<<fact;
getch();
}

===================================================

Program #03

#include <constream.h>

void main()
{
for(int i=5; i>=1; i--)
{
for(int j=1; j<=i; j++)
cout<<"*";
cout<<endl;
}

for(i=2; i<=5; i++)
{
for(int j=1; j<=i; j++)
cout<<"*";
cout<<endl;
}

getch();
}

===================================================



43


===================================================
Program #04

#include <constream.h>
#include <ctype.h>

void main()
{
clrscr();
int lower=0, upper=0, digits=0, escape=0, newlines=0,
spaces=0, tabs=0;
char ch;

while((ch=getche())!='t')
{
cout<<endl;
if(isalpha(ch)!=0)
{
if(islower(ch)!=0)lower++; else upper++;
}

else

if(isdigit(ch)!=0)
digits++;

else

if(isspace!=0)
{
escape++;
if(ch==13)newlines++; else
if(ch==9)tabs++; else
if(ch==32)spaces++;
}
}
cout<<endl<<endl;
cout<<"Lower: "<<lower<<endl;
cout<<"Upper: "<<upper<<endl;
cout<<"Digits: "<<digits<<endl;
cout<<"Escape Sequences: "<<escape<<endl;
cout<<"New Lines: "<<newlines<<endl;
cout<<"Tabs: "<<tabs<<endl;
cout<<"Spaces: "<<spaces;
getch();
}
===================================================
44


===================================================

Program #05

#include <constream.h>

void main()
{
clrscr();
int a=0,b=0;

for(int i=1; i<=4; i++)
{
for(int j=1; j<=4; j++)
{
b++;
a+=b;
cout<<b<<" ";
}

cout<<a<<endl;
a=0;
}
getch();
}

===================================================




















45





OBJECT: TO BECOME FAMILIAR WITH FUNCTIONS IN C++.


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 parameters 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 variableanother 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





OBJECT: TO BECOME FAMILIAR WITH ARRAYS ANS 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 09.









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 dont 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 subscriptits 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 dont 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 3
rd
location of the 3
rd

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



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. Lets 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 7
th
location will be occupied by the num character \0. Finally
the cout statement will sent the string string1 to the console screen.





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. Lets 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();
}






EXERCISE



1. Write a program using array that asks user to input any 10 numbers; the program
then sorts the numbers in ascending order and displays the sorted numbers.

2. Write a C++ program that gets 10 numbers entered by the user. The program also
asks the user to give any number to find it in the array, and passes the array and the
number (that is to be found) to a function as argument; the function displays the
result that whether number found or not.

3. Write a program that gets time in hours, minutes and seconds from the user, convert
the time into seconds using function. The function takes hours, minutes and seconds
as arguments and returns the time in seconds.

4. Write a program that gets user name (in an array), then swaps the entered name
using two functions one for getting input and other for swapping the name. For
example if user enters NAEEM, the swap function reverses the letters to MEEAN.

5. Write a program that asks user to enter two fractions say a/b and c/d; and then
displays the sum in fractional form.
For example:

Enter First Fraction: 1/2
Enter Second Fraction: 2/5
Sum = 9/10

6. Write a program using array that gets 10 numbers from the user. This program
calculates the average of those numbers. Use function that computes the average of
those numbers and return the average value.

















EXERCISE SOLUTIONS


===================================================

Program # 01

#include <constream.h>

void main()
{
int num[10], temp;

for(int i=0; i<10; i++)
{
cout<<"Enter number "<<i+1<<" : ";
cin>>num[i];
}

for(i=0; i<9; i++)
{
for(int j=i+1; j<10; j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}

for(i=0; i<10; i++)
cout<<num[i]<<endl;

getch();
}


===================================================








===================================================

Program # 02

#include <constream.h>

void location(int array[], int number);

void main()
{
clrscr();
int numb[10], search;

for(int i=0; i<10; i++)
{
cout<<"Enter the numbers "<<i+1<<" : ";
cin>>numb[i];
}
cout<<"Enter the number to find its location : ";
cin>>search;

location(numb, search);
getch();
}

void location(int array[], int number)
{
int found=0;

for(int i=0; i<10; i++)
{
if(number==array[i])
{
found=1;
cout<<"The number found at the location : "<<i;
}
}

if(found==0)
cout<<"Number not found at any location.";
}


===================================================






===================================================

Program # 03

#include <constream.h>

long time(int hrs, int min, int sec);

void main()
{
clrscr();
int hours, minutes, seconds;
cout<<"Enter the time:"<<endl;
cout<<"Hours : ";
cin>>hours;
cout<<"Minutes : ";
cin>>minutes;
cout<<"Seconds : ";
cin>>seconds;
cout<<"The time in seconds is : "<<time(hours, minutes, seconds);
getch();
}

long time (int hrs, int min, int sec)
{
int total_sec=0;
total_sec=((hrs*3600)+(min*60)+(sec));
return (total_sec);
}

===================================================






===================================================

Program # 04

#include<constream.h>
#include <string.h>


char name[15];

void getname();
void swapname();


void main()
{
clrscr();
getname();
swapname();
getch();
}


void getname()
{
cout<<"Enter your name: ";
cin>>name;
}


void swapname()
{
for(int i=strlen(name); i>=0; i--)
cout<<name[i];
}

===================================================





===================================================

Program # 05

#include <constream.h>

void main()
{
clrscr();
int a, b, c, d, numerator, denomenator;
char dummychar;

cout<<"Enter first fraction: ";
cin>>a>>dummychar>>b;
cout<<"Enter first fraction: ";
cin>>c>>dummychar>>d;
numerator=(a*d)+(b*c);
denomenator=b*d;

cout<<"Sum = "<<numerator<<dummychar<<denomenator;

getch();
}

===================================================









===================================================

Program # 06

#include <constream.h>

const int SIZE=10;
float average(int array[], int total_elements);

void main()
{
clrscr();
int numb[SIZE];
for(int i=0; i<SIZE; i++)
{
cout<<"Enter the number "<<i+1<<" : ";
cin>>numb[i];
}
cout<<"The average is : "<<average(numb, SIZE);

getch();
}


float average(int array[], int total_elements)
{
int sum=0, average=0.0;
for(int i=0; i<total_elements; i++)
sum+=array[i];

average=sum/total_elements;

return (average);
}

===================================================








OBJECT: TO BECOME FAMILIAR WITH POINTERS.


Introduction to Pointers

The pointer is a variable that holds a memory address. To understand the pointers we
should first understand a bit about the computer memory. Whenever any application is
executed, it is loaded in to the memory form the disk and all the elements and
components of that application will be located at the particular location somewhere in
the memory. Computer memory is divided into sequentially numbered memory locations
and each variable is located at a unique location in memory, known as its address.
These locations are usually referred as eight-bit (bytes) but actually the size of each
space depend upon the architecture of the particular machine and is usually called the
machines word size. Each memory location has its own unique address. The
address of these memory locations is typically represented in Hexadecimal format with
the prefix 0x before the number (e.g. 0x8f4ffff2).

When ever you execute a program the variables and the functions occupy certain
memory address in the memory.
























int var1
char var2
float var3
long var4



In the above figure you had seen that the variable in the program have occupied certain
spaces in the memory and these memory locations have certain address represented in
hexadecimal format. So the variable that stores these memory address is referred as
pointer.

The Address-of Operator &

As the variables stored in the memory have certain address, the address-of operator is
responsible for returning that address of the memory location in the hexadecimal format
with the prefix 0x. to return the address of the certain variables the address-of operator
is placed in front of the variable name as,

cout<<&var1;
cout<<&var2;
cout<<&var3;

Now the & used with the variables in the cout statement will return the addresses at
which these variable are located into the memory. Then the cout statement flows that
address on the console screen.


Program (address1.cpp)

#include <constream.h>

void main()
{
int var1=10;
float var2=20.1;

cout<<&var1<<endl;
cout<<&var2;

getch();
}


The output will be:

0x8f7efff4 //Memory address of var1;
0x8f7efff0 //Memory address of var2;






Example Program:


#include <iostream.h>
#include <conio.h>

int *ptra, *ptrb;

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<<endl<<"num1 = "<<num1<<endl;
cout<<"num2 = "<<num2<<endl;

ptra=&num1;
ptrb=&num2;

swap(ptra,ptrb);

cout<<"num1 = "<<num1<<endl;
cout<<"num2 = "<<num2;
getch();
}

void swap(int *a, int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}

Note: The pointer variable is always started with an Asterisk.











Note: semicolon here
Keyword struct
Structure name/tag
Structure members
Braces delimit
structure members






OBJECT: TO BECOME FAMILIAR WITH 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.



EXERCISE



1. Create a structure called volume that uses three variables of type Distance
(structure) to model the volume of a room. Initialize a variable of type volume to
specific dimensions, and then calculate the volume it represent and print out the
result.

2. Create a structure a type date that contains three members: the day, the month, the
year, all of type int. Here the user enter a date in the format 10/9/2007, store it in a
variable of type date, then retrieve the value form the variable and print them out in
the same format.


3. Create a structure called time. Its three members, all of type int, should be called
hours, minutes, and seconds. Write a program that prompts the user to enter a
time value in hours, minutes, and seconds. This can be in 12:30:50 format. The
program then stores the time in a variable of type time, and finally prints out the total
number of seconds.

4. Write a program that calculates the number of possible arguments for any number of
guests and any number of chairs. (Assume there will never be fewer guests than
chairs). A simple for loop should do it. For example the possible arrangement of six
guests in four chairs is 360.


5. Write a program that stores the numerator and denominator of two numbers in
fraction, after adding them the result is also stored into fraction format. Use structure
fraction to store these numbers and their result. (Both numerator and denominator
should be of type int).


















EXERCISE SOLUTIONS


===================================================

Program # 01


#include <constream.h>

struct Distance
{
int feet;
float inches;
};

struct Volume
{
Distance length;
Distance width;
Distance breadth;
};

void main()
{
Volume Room;

Room.length.feet=7;
Room.length.inches=5.7;
Room.width.feet=4;
Room.width.inches=15.2;
Room.breadth.feet=6;
Room.breadth.inches=4.5;

float l=Room.length.feet+Room.length.inches;
float w=Room.width.feet+Room.width.inches;
float b=Room.breadth.feet+Room.breadth.inches;

cout<<"The Volume of the Room is: "<<(l*w*b)<<" cubic feet";

getch();
}


===============================================================




===================================================

Program # 02

#include <constream.h>

struct date
{
int day;
int month;
int year;
};

void main()
{
date D1;
char dummych;

cout<<"Enter the date (dd/mm/yy): ";
cin>>D1.day>>dummych>>D1.month>>dummych>>D1.year;

cout<<"You entered date is: ";
cout<<D1.day<<'\/'<<D1.month<<'\/'<<D1.year;

getch();
}

===================================================

Program # 03

#include <constream.h>

struct time
{
int hours;
int minutes;
int seconds;
};

void main()
{
time T1;
char dummych;
int total_sec=0;

cout<<"Enter the time (hh:mm:ss): ";



cin>>T1.hours>>dummych>>T1.minutes>>dummych>>T1.seconds;
total_sec=T1.seconds+(T1.minutes*60)+(T1.hours*3600);
cout<<"Total Seconds are: "<<total_sec;

getch();
}

===================================================

Program # 05

#include <constream.h>

struct fraction
{
int Num;
int Deno;
int AnsNum;
int AnsDeno;
};

void main()
{
fraction f1, f2;
char dummych;

cout<<"Enter first fraction: ";
cin>>f1.Num>>dummych>>f1.Deno;

cout<<"Enter second fraction: ";
cin>>f2.Num>>dummych>>f2.Deno;

f1.AnsNum=(f1.Num*f2.Deno)+(f2.Num*f1.Deno);
f1.AnsDeno=(f1.Deno*f2.Deno);

cout<<"Addition of two fractions is: " <<f1.AnsNum<<dummych
<<f1.AnsDeno;

getch();
}

===================================================











OBJECT: TO BECOME FAMILIAR WITH CLASSES AND OBJECTS.



Objects and Classes

The objects and classes lie at the heart of the object oriented programming. As in
procedural languages the main emphasis is on the functions but here in the object
oriented programming the main emphasis is on the object and classes. It is an easy and
prominent method through which we can compare and declare the physical objects in
the programming. Object and the classes are the main features which are responsible
for the popularity of an object oriented programming. Almost all the programmers give
precedence to the object oriented programming than the procedural or structure
programming because it provides the most convenient way to organize the program.

The class is nothing more than the collection of the data items and the member
functions. Once you have created a class you can create number of its objects. Each
object will be now related directly or indirectly to that class. When you have created a
class it will not allocate any memory space until you have declared any object of that
class and each object will occupy same space in the memory unless it is the object of
any other class. Object has the same relationship to the class as the variable has to its
data type. An object is said to be the instance of the class.

As physically on this earth there are the number of classes of things and each class has
number of objects and each object has number of attributes. Like Jewelry is the class
whose objects are the Earrings, Bracelets, Bangles, Rings, Necklaces, lockets etc. each
object has the same relationship with the class and each has same attributes as they all
are made from gold and they are used for wearing etc.

Unlike C, C++ is the object oriented programming language. The C language almost is
compatible with the C++ programming language but the C++ is not compatible with the
C language.












Understanding the class and object in C++

In C++ you can create your class by using the keyword class so that the compiler can
understand that the thing you are writing is a class. First write the keyword class and
then place the data items and the member functions with in the braces terminated by
the semicolon at the last. In general the data items are declared as the private and the
member functions are declared as the private although it is not defined that every time
you perform this approach you can do inverse also.


Program (class1.cpp)

#include <constream.h>

class vehicle
{
private:
int modelno;
int maxspeed;

public:

void getdata(int mn, int ms)
{
modelno=mn;
maxspeed=ms;
}

void showdata()
{
cout<<Model Number: <<modelno<<endl;
cout<<Maximum speed: <<maxspeed<< km/h;
}
};

void main()
{
vehicle car, bus;

car.getdata(2007,500);
car.showdata();
bus.getdata(2004,100);
bus.showdata();

getch();
}




In the above program a class vehicle is created in which the data items modelno and
maxspeed are declared as private so that they can not be accidentally accessed any
where outside the class and the member function getdata and showdata are declared as
public so that they are accessible from out side the class. These member functions are
also called the methods. In the main program the two objects car and bus are created so
now they both will have the same function/methods that are declared in the class. To
access the member function the dot operator is used between the object and the
member function.

The member function car.getdata() will set the data for the object car and the member
function bus.getdata will set the data for the object bus; the member function
car.showdata() will show the data of object car and the member function
bus.showdata() will show data of the object bus.



Private, Public and Protected

The keyword private is used when we want that the data should be protected from
accidental accessed from outside the class or from the derived class. The keyword public
is used when we want that the data or function should be accessed from any where
outside the class. The keyword protected is used when we want that the data or function
should be protected from the accidental access outside the class but it should be
accessed from the derived class.

In general the data is set as the private and the methods are declared as the private.






















EXERCISE



1. Create a class called Rectangle that contains variables and functions to compute the
area and perimeter of rectangle. The class also contains functions to get data from the
user to calculate the area and perimeter, and then a function prints out the calculated
results.

2. Create a class Arithmetic that contains variables and functions say addition,
subtraction, multiplication and division to compute the arithmetic
operations. In addition, the class also contains other functions for getting input from
the user and to display the desired output.


3. Create a class called QuadraticEquation. The class contains the variables and
functions to solve the quadratic equation (ax
2
+bx+c=0). The class has getvalues()
and displayRoots() functions to get data from user and display roots of equations.

4. Write a program using classes that finds the maximum and minimum values of an
array. The program gets the data from the user in an array and displays the maximum
and minimum value along with index of the array.

5. Create a class Matrix that gets two matrices of same size from the user and display
the addition and multiplication of those matrices. The class contains all necessary
functions to calculate the operations.























EXERCISE SOLUTIONS


===================================================

Program # 01

#include <constream.h>

class rectangle
{
private:
int length;
int height;
int Area;
int perimeter;
public:
void getdata(int ln, int hg)
{
ln=length;
hg=height;
Area=length*height;
perimeter=2*(length+height);
}

void showdata()
{
cout<<"The Area is: "<<Area<<endl;
cout<<"The perimeters are: "<<perimeter;
}
};

void main()
{
rectangle R1;

R1.getdata(4,5);
R1.showdata();

getch();
}


===================================================





===================================================

Program # 02


#include <constream.h>

class arithmetic
{
private:
int num1;
int num2;
char oper;

int add(int n1, int n2){return(n1+n2);}
int sub(int n1, int n2){return(n1-n2);}
int mul(int n1, int n2){return(n1*n2);}
int div(int n1, int n2){return(n1/n2);}

public:

void getdata(int n1, int n2, char opt)
{
num1=n1;
num2=n2;
oper=opt;
}

void showdata()
{
if(oper=='+')cout<<num1<<" + "<<num2<<" = "<<add(num1,num2)
<<endl;
else
if(oper=='-')cout<<num1<<" - "<<num2<<" = "<<sub(num1,num2)
<<endl;
else
if(oper=='*')cout<<num1<<" * "<<num2<<" = "<<mul(num1,num2)
<<endl;
else
if(oper=='/')cout<<num1<<" / "<<num2<<" = "<<div(num1,num2)
<<endl;
}
};

void main()
{
arithmetic Arith1, Arith2, Arith3, Arith4;




Arith1.getdata(2,3,'+');
Arith2.getdata(5,3,'-');
Arith3.getdata(2,3,'*');
Arith4.getdata(8,4,'+');

Arith1.showdata();
Arith2.showdata();
Arith3.showdata();
Arith4.showdata();

getch();
}


===================================================

Program # 04

#include <constream.h>

const int SIZE=10;

class MaxMin
{
private:
int array[SIZE];
int temp;

public:

void getdata()
{

for(int i=0; i<SIZE; i++)
{
cout<<"Enter Number "<<(i+1)<<" : ";
cin>>array[i];
}
}

void showdata()
{
for(int i=0; i<SIZE-1; i++)
{
for(int j=0; j<SIZE; j++)
{



if(array[i]>array[j])
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}

cout<<"Maximum Number = "<<array[SIZE]<<endl;
cout<<"Minimum Number = "<<array[0]<<endl;
cout<<"Array index = "<<SIZE<<endl;
}
};

void main()
{
MaxMin MM1;

MM1.getdata();
MM1.showdata();

getch();
}


===================================================

Program # 05

#include <constream.h>

const int SIZE1=3;
const int SIZE2=3;
int i, j, k, temp=0;

class Matrix
{
private:
int MatA[SIZE1][SIZE2];
int MatB[SIZE1][SIZE2];
int MatC[SIZE1][SIZE2];
int MatD[SIZE1][SIZE2];

void add()
{
for(i=0; i<SIZE1; i++)



{
for(j=0; j<SIZE2; j++)
{
MatC[i][j]=MatA[i][j]+MatB[i][j];
}
}
}

void mult()
{
for(i=0; i<SIZE1; i++)
{
for(j=0; j<SIZE2; j++)
{
for(k=0; k<SIZE1; k++)
{
MatD[i][j]+=MatA[i][k]*MatB[k][i];
}
}
}
}

public:

void getmat()
{
for(i=0; i<SIZE1; i++)
{
for(j=0; j<SIZE2; j++)
{
cout<<"Enter the Element A["<<(i+1)<<"]["<<(j+1)<<"] : ";
cin>>MatA[i][j];
}
}

for(i=0; i<SIZE1; i++)
{
for(j=0; j<SIZE2; j++)
{
cout<<"Enter the Element B["<<(i+1)<<"]["<<(j+1)<<"] : ";
cin>>MatB[i][j];
}
}
}

void showmat()
{



cout<<"Addition:"<<endl<<endl;
add();
for(i=0; i<SIZE1; i++)
{
for(j=0; j<SIZE2; j++)
{
cout<<MatC[i][j]<<" ";
}
cout<<endl<<endl;
}

cout<<endl<<endl<<"Multiplication:"<<endl<<endl;
mult();

for(i=0; i<SIZE1; i++)
{
for(j=0; j<SIZE2; j++)
{
cout<<MatD[i][j]<<" ";
}
cout<<endl<<endl;
}
}
};


void main()
{
Matrix M1;
clrscr();
M1.getmat();
M1.showmat();
getch();
}


===================================================
















OBJECT: TO BECOME FAMILIAR WITH OPERATOR OVERLOADING.


Operator Overloading

Operator overloading is one of the main feature of object oriented programming. The
operator overloading means adding the functionality of the operators to the user defined
data types. As suppose there are three variables a, b, & c all of type int then,

int a;
int b;
int c;

a+b+c;

The above statement (a+b+c) is legal as you can use the addition operator with the
integer type data but when you want to use the same addition operator with your own
defined data types then what use will do, here the concept of operator overloading help
to solve this hurdle.

The operator overloading gives you the opportunity to redefine the C++ programming
language. As you can also overload or change the functionality of the operators with the
predefined data types. By using the classes and the operator overloading you can
extend the functionality of C++ language in many ways.



The Keyword Operator

To teach the compiler that we are overloading we use the keyword operator in the
decelerator of the member function in the class with the return type and the operator
follows the keyword operator and at last the parenthesis come enclosing the arguments
in to it like in below decelerator:

void operator ++()

Here the operator ++ is to be overloaded and in the decelerator the return type is void
and there are no arguments in the decelerator.










Overloading Unary Operators

The unary operators are those which require one operand to operate. Like the increment
and decrement operators.


Program (OptOver.cpp)


#include <constream.h>

class Counter
{

private:
int count;

public:
Counter(){count=0;}

int get_count(){return count;}
void operator ++(){++count;}
};

void main()
{
Counter C1, C2;

cout<<C1 = <<C1.get_count()<<endl;
cout<<C2 = <<C2.get_count()<<endl;

++C1;
++C2;
++C2;

cout<<C1 = <<C1.get_count()<<endl;
cout<<C2 = <<C2.get_count()<<endl;

getch();
}

In the above program the unary operator ++ is overloaded with the objects C1 and C2
in which it increments both the objects by the value of one as it does with other
predefined data type.






====================================================================

Program (OptOver2.cpp)


#include <constream.h>

class Counter
{

private:
int count;

public:
Counter(){count=0;}

int getcount(){return count;}
void operator ++(){count--;}
};


void main()
{
Counter C1, C2;
cout<<C1.getcount()<<endl;
cout<<C2.getcount()<<endl;

int g=++C1;
cout<<endl<<g;

++C2;
++C2;

int h=C2;
cout<<endl<<h;

getch();
}


====================================================================












OBJECT: TO BECOME FAMILIAR WITH INHERITANCE.



Inheritance

When ever we deal with classes they will lead us to the idea of inheritance. To
understand the inheritance lets take an example of our physical world; in this world we
commonly group certain things in the classes and subclasses, like vehicle is the class
and the buses, cars, trucks etc are the subclasses; computer is the class and the
supercomputer, mainframe, minicomputer and desktop PCs are the subclasses;
Educational institutions is the class and the School, College, University and Madarsa are
the subclasses.
In all above subclasses we will notice a thing that each subclass shares some common
features from the class form which it is derived. Like School and Madarsa are the two
subclasses of the Educational Institution School and Madarsa have the same function of
making the students learn means they share a feature but is possible that School or
college may have their own extra features also. In object oriented programming there is
the same concept that once you have created a class you can also create many
subclasses of it then all the subclasses will inherit some features of the main class from
which they are derived and they may have some extra features also. The main class ids
called the Base Class and the subclass is called the Derived Class.


























Educational Institution
School
Madarsa
Education
Behavior
Education
Behavior
Education
Behavior
General
Knowledge
Religious
Knowledge



Base Class and Derived Class

The first main class is called the Base class. The base class contains the capabilities
which are shared between the derived classes and the subclass which is derived from
the base class is called the Derived class. The derived class inherits all the features that
are present in the base class but the derived class can have extra capabilities which are
not present in the base class.


Program (inherit1.cpp)

#include <constream.h>

class Counter
{
protected:
int count;

public:
Counter(){count=0;}
Counter(int c){count=c;}

int get_count(){return count;}

int operator ++(){return (++count);}
};


class countDN:public Counter
{
public:

int operator -(){return (--count);}
};

void main()
{
countDN C1;

cout<<C1.get_count();
++C1; ++C1; ++C1;
cout<<C1.get_count();
--C1; --C1;
cout<<C1.get_count();

getch();
}



Program (inherit2.cpp)

#include <constream.h>
#include <string.h>

class TUI_OS
{
protected:
char name[15];
int version;
char file_system[10];

public:
void setdata(char nm[], int ver, char fs[])
{
strcpy(name,nm);
strcpy(file_system,fs);
version=ver;
}

void showdata()
{
cout<<"Operating System = "<<name<<endl;
cout<<"Version = "<<version<<endl;
cout<<"File System = "<<file_system<<endl<<endl;
}
};

class GUI_OS:public TUI_OS
{
private:
char edition[20];

public:
void setdata2(char nm[], int ver, char fs[],char edt[])
{
strcpy(name,nm);
strcpy(file_system,fs);
version=ver;
strcpy(edition,edt);
}

void showdata2()
{
cout<<"Operating System = "<<name<<endl;
cout<<"Version = "<<version<<endl;
cout<<"File System = "<<file_system<<endl;



cout<<"Edition = "<<edition<<endl<<endl;
}
};

void main()
{
clrscr();

TUI_OS PC_DOS, MS_DOS;
GUI_OS Win_98, Win_2000,Win_XP;

PC_DOS.setdata("PC-DOS",1970,"FAT");
MS_DOS.setdata("MS-DOS",1972,"FAT");

Win_98.setdata2("Windows 98",1998,"FAT32",
"Professional Edition");
Win_2000.setdata2("Windows 2000",2000,"NTFS",
"Professional Edition");
Win_XP.setdata2("Windows XP",2006,"NTFS",
"Home Edition");

PC_DOS.showdata();
MS_DOS.showdata();

Win_98.showdata2();
Win_2000.showdata2();
Win_XP.showdata2();

getch();
}


The above program contain the base class TUI_OS in which there are three features,
name, version and file system and the derived class GUI_OS contains these three
features as well as an extra feature the Edition which is not present in the TUI_OS. It is
general that the Text User Interface Operating Systems have no Edition but Version and
the Graphical User Interface Operating Systems as Windows XP has certain Editions, as
Home, Professional and Server etc.













OBJECT: TO BECOME FAMILIAR WITH FILES AND STREAMS.

Files and streams
Generally file is the unit to store the data and the term stream refers to the flow of data,
the flow of data can be in any direction. In C++ a stream is represented by an object of
a particular class. Different streams are used to represent different kinds of data flow.
For example, the ifstream class represents data flow from input disk files.
In order to take the advantage of making the data safe we place the data into the files
and we can also read those files at any time. To work with disk files we require a set of
class: ifstream for input, ofstream for output and fstream for both the input and
output. The objects of these classes can be associated with disk files, and we can use
their member functions to read and write to the files.
ifstream is derived from istream and ofstream is derived from ostream, where as
fstream is derived from iostream. The declaration of all the ifstream, ofstream
and fstream classes are in the fstream.h header file.

File Input and Output
Streams provide a uniform way of dealing with data coming from the keyboard or the
hard disk and going out to the screen or hard disk. In either case, you can use the
insertion and extraction operators or the other related functions and manipulators. To
open and close files, you create ifstream and ofstream objects.

ofstream
The particular objects used to read from or write to files are called ofstream objects.
These are derived from the iostream objects. To get started with writing to a file,
you must first create an ofstream object, and then associate that object with a particular
file on your disk. To use ofstream objects, you must be sure to include fstream.h in your
program.
NOTE: Because fstream.h includes iostream.h, there is no need for you to include
iostream explicitly.




Writing Data to the file


Program (stream1.cpp)

#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include <conio.h>

void main()
{
char ch=x;
int j=77;
double d=6.02;
string str1=My;
string str2=File;

ofstream outfile(fdata.txt);
outfile<<ch
<<j
<<
<<d<<str1<< <<str2;

cout<<File Written;
getch();
}

In the above program the outfilethe object of class ofstream is created and at the
same time it is initialized fdata.txt file. The outfile object here will work same as the
cout does so we can use insertion operator << to output the variables to the file
fdata.txt.
Here the notable point is that you should separate the numbers such as 77 and 6.02
with the nonnumber characters so that when we data is read from the same file the
insertion operators should come to know that here one number starts and here it stops
and the next begins. Also the strings should also be separated by a single space
character for the same reason.




Reading Data from the file


Program (stream2.cpp)

#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include <conio.h>

void main()
{
char ch;
int j;
double d;
string str1;
string str2;

ifstream infile(fdata.txt);
outfile>>ch>>j>>d>>str1>>str2;

cout<<ch<<endl
<<j<<endl
<<d<<endl
<<str1<<endl
<<str2<<endl;

getch();
}

In the above program the object of class ifstream infile is created. The outfile object
here will work same as the cin does so we can use extraction operator >> to read the
variables from the file fdata.txt. the output of the program must be as:
x
77
6.02
My
File

Vous aimerez peut-être aussi