SlideShare une entreprise Scribd logo
1  sur  93
Télécharger pour lire hors ligne
E-528-529, sector-7,

                                           Dwarka, New delhi-110075

                              (Nr. Ramphal chowk and Sector 9 metro station)

                                                Ph. 011-47350606,

                                                (M) 7838010301-04

                                                  www.eduproz.in

Educate Anytime...Anywhere...



"Greetings For The Day"

About Eduproz

We, at EduProz, started our voyage with a dream of making higher education available for everyone. Since its
inception, EduProz has been working as a stepping-stone for the students coming from varied backgrounds. The best
part is – the classroom for distance learning or correspondence courses for both management (MBA and BBA) and
Information Technology (MCA and BCA) streams are free of cost.

 Experienced faculty-members, a state-of-the-art infrastructure and a congenial environment for learning - are the few
things that we offer to our students. Our panel of industrial experts, coming from various industrial domains, lead
students not only to secure good marks in examination, but also to get an edge over others in their professional lives.
Our study materials are sufficient to keep students abreast of the present nuances of the industry. In addition, we give
importance to regular tests and sessions to evaluate our students’ progress.

 Students can attend regular classes of distance learning MBA, BBA, MCA and BCA courses at EduProz without
paying anything extra. Our centrally air-conditioned classrooms, well-maintained library and well-equipped laboratory
facilities provide a comfortable environment for learning.




Honing specific skills is inevitable to get success in an interview. Keeping this in mind, EduProz has a career
counselling and career development cell where we help student to prepare for interviews. Our dedicated placement
cell has been helping students to land in their dream jobs on completion of the course.




EduProz is strategically located in Dwarka, West Delhi (walking distance from Dwarka Sector 9 Metro Station and 4-
minutes drive from the national highway); students can easily come to our centre from anywhere Delhi and
neighbouring Gurgaon, Haryana and avail of a quality-oriented education facility at apparently no extra cost.




Why Choose Edu Proz for distance learning?
•   Edu Proz provides class room facilities free of cost.
   •   In EduProz Class room teaching is conducted through experienced faculty.
   •   Class rooms are spacious fully air-conditioned ensuring comfortable ambience.
   •   Course free is not wearily expensive.
   •   Placement assistance and student counseling facilities.
   •   Edu Proz unlike several other distance learning courses strives to help and motivate pupils to get high
       grades thus ensuring that they are well placed in life.
   •   Students are groomed and prepared to face interview boards.
   •   Mock tests, unit tests and examinations are held to evaluate progress.
   •   Special care is taken in the personality development department.




                                                         "HAVE A GOOD DAY"




                                   Karnataka State Open University



(KSOU) was established on 1st June 1996 with the assent of H.E. Governor of Karnataka

as a full fledged University in the academic year 1996 vide Government notification

No/EDI/UOV/dated 12th February 1996 (Karnataka State Open University Act – 1992).

The act was promulgated with the object to incorporate an Open University at the State level for
the introduction and promotion of Open University and Distance Education systems in the

education pattern of the State and the country for the Co-ordination and determination of
standard of such systems. Keeping in view the educational needs of our country, in general, and
state in particular the policies and programmes have been geared to cater to the needy.



Karnataka State Open University is a UGC recognised University of Distance Education Council
(DEC), New Delhi, regular member of the Association of Indian Universities (AIU), Delhi,
permanent member of Association of Commonwealth Universities (ACU), London, UK, Asian
Association of Open Universities (AAOU), Beijing, China, and also has association with

Commonwealth of Learning (COL).



Karnataka State Open University is situated at the North–Western end of the Manasagangotri
campus, Mysore. The campus, which is about 5 kms, from the city centre, has a serene
atmosphere ideally suited for academic pursuits. The University houses at present the
Administrative Office, Academic Block, Lecture Halls, a well-equipped Library, Guest House
Cottages, a Moderate Canteen, Girls Hostel and a few cottages providing limited
accommodation to students coming to Mysore for attending the Contact Programmes or Term-
end examinations.




BC0037-1.1 Introduction
Introduction

This unit has the following objectives

· To understand the importance of object oriented programming approach over procedural
languages

· To learn the basic features supported by OOP languages

· To learn the basic construct of a C++ program and learn to compile and execute it


BC0037-1.2 Evolution of Programming
methodologies
Evolution of Programming methodologies

The programming languages have evolved from machine languages, assembly languages to high
level languages to the current age of programming tools. While machine level language and
assembly language was difficult to learn for a layman, high level languages like C, Basic, Fortran
and the like was easy to learn with more English like keywords. These languages were also
known as procedural languages as each and every statement in the program had to be specified to
instruct the computer to do a specific job. The procedural languages focused on organizing
program statements into procedures or functions. Larger programs were either broken into
functions or modules which had defined purpose and interface to other functions.

Procedural approach for programming had several problems as the size of the softwares grew
larger and larger. One of the main problems was data being completely forgotten. The emphasis
was on the action and the data was only used in the entire process. Data in the program was
created by variables and if more than one functions had to access data, global variables were
used. The concept of global variables itself is a problem as it may be accidentally modified by an
undesired function. This also leads to difficulty in debugging and modifying the program when
several functions access a particular data.
The object oriented approach overcomes this problem by modeling data and functions together
there by allowing only certain functions to access the required data.

The procedural languages had limitations of extensibility as there was limited support for
creating user defined datatypes and defining how these datatypes will be handled. For example if
the programmer had to define his own version of string and define how this new datatype will be
manipulated, it would be difficult. The object oriented programming provides this flexibility
through the concept of class.

Another limitation of the procedural languages is that the program model is not closer to real
world objects . For example, if you want to develop a gaming application of car race, what data
would you use and what functions you would require is difficult questions to answer in a
procedural approach. The object oriented approach solves this further by conceptualizing the
problem as group of objects which have their own specific data and functionality. In the car
game example, we would create several objects such as player, car, traffic signal and so on.

Some of the languages that use object oriented programming approach are C++, Java, Csharp,
Smalltalk etc. We will be learning C++ in this text to understand object oriented programming.
C++ is a superset of C. Several features are similar in C and C++.

Self Assessment Questions

1. List the limitations of procedural languages

2. _______ is an OOP Language

3. In OOP approach programmers can create their own data types. True/False

4. In procedural languages, the programs are written by dividing the programs into smaller units
known as __________


BC0037-1.3 Introduction to OOP and its
basic features
Introduction to OOP and its basic features

As discussed earlier, one of the basic concept in Object Oriented Programming approach is
bundling both data and functions into one unit known as object. The functions of a particular
object can only access the data in the object providing high level of security for the data. The
functions in the object are known as member functions or sometimes as methods.

The key features of OOP programming languages are:

   •   Objects and Classes
An                                                                            Object
   is a program representation of some real-world thing (i.e person, place or an event).
   Objects can have both attributes(data) and behaviours (functions or methods).
   Attributes describe the object with respect to certain parameters and Behaviour or
   functions describe the functionality of the object.

Table 1.1 Example of Objects

Polygon Object                Bank Account
                                                 Behaviour
Attributes
               Behaviour
                              Attributes         Deduct Funds
               Move
Position
                              Account number Transferfunds
               Erase
Fill Color
                              Balance            DepositFunds
               Changecolor
Border color
                                                 Showbalance

According to Pressman, Objects can be any one of the following:

a) External entities
b) Things
c) Occurrences or events
d) Roles
e) Organisational units
f) Places
g) Data Structures

For example, objects can be an menu or button in an graphic user interface program or
it may be an employee in an payroll application. Objects can also represent a data
structure such as a stack or a linked list. It may be a server or a client in an networking
environment.

Objects        with     the       same       data       structure      and       behavior
are grouped together as class. In other words, Objects are “instances” of a class. Classes
are templates that provide definition to the objects of similar type. Objects are like
variables created whenever necessary in the program. For example, Employee may be a
class and Pawan, Sujay and Ganesh are objects of the class employees. Just as you can
create as many variables of a default datatype such as integer, you can create as many
objects of a class.

Classes and Objects support data encapsulation and data hiding which are key terms
describing object oriented programming languages. Data and functions are said to be
encapsulated in an single entity as object. The data is said to be hidden thus not allowing
accidental modification.
•   Inheritance

          Inheritance is one of the most powerful feature of Object Oriented Programming
          Languages that allows you to derive a class from an existing class and inherit all the
          characteristics and behaviour of the parent class. This feature allows easy
          modification of existing code and also reuse code. The ability to reuse components
          of a program is an important feature for any programming language

   •   Polymorphism and Overloading

          Operator overloading feature allows users to define how basic operators work with
          objects. The operator + will be adding two numbers when used with integer
          variables. However when used with user defined string class, + operator may
          concatenate two strings. Similarly same functions with same function name can
          perform different actions depending upon which object calls the function. This
          feature of C++ where same operators or functions behave differently depending
          upon what they are operating on is called as polymorphism (Same thing with
          different forms). Operator overloading is a kind of polymorphism.

       OOP approach offers several advantages to the programmers such as

   •   Code can be reused in situations requiring customization
          o Program modeling and development closer to real world situations and objects
   •   Easy to modify code
          o Only required data binded to operations thus hiding data from unrelated functions

       Self Assessment Questions

       1. _____________ feature in OOP allows to reuse code.

          2. The concept of bundling data and functions into single unit is termed as
          ___________

       3. Object is an __________ of a class

       4. Give an example of a class and an object

       5. ______________ is an advantage of OOP approach


BC0037-1.4 Basic components of a C++
Program and program structure
1.4 Basic components of a C++ Program and program structure
The C++ is a superset of C. At the basic level, the programs look similar in both C and C++. Every
statement in C++ ends with a semicolon (;). All the reserved words have to be written in small
case and the c++ compiler is case sensitive. Data in programming languages are stored in
variables. To create a variable, the variable should support an inbuilt datatype. The variable is a
name given to a particular location in the memory and the value stored in a variable can be
altered during program execution. The datatypes supported in C++ are listed below

Table 1.2 Basic Datatypes in c++

Data Type    Size (in bytes)     Values that can be taken
Int                  2           -32768 to 32767
Bool                 1           False and true / 0 and 1
Char                 1           -128 to 127
Long                 4           -2,147,483,648 to 2,147,483,647
Float                4           3.4 X 10-38 to 3.4 X 1038 (Precision 7)
Double               8           1.7 X 10-308 to 1.7 X 10308 (Precision 15)
Long double         10           3.4 X 10-4932 to 1.1 X 104932 (Precision 19)
Unsigned int         2           0 to 65,535

Variables can be named according to following rules

     •   Can comprise of 1 to 8 alphabets, digits or underscore
     •   First character should be an alphabet
     •   Names are case sensitive
     •   Reserve words of c++ cannot be used

Variables have to be declared before using them in the program. The declaration is done in the
following way:

datatype variablename

Eg: int data ;

The above declaration declares a integer variable named data. The value stored in int data by
default is a junk value. Values can also be assigned to the variable during declarations or
initialized separately using the assignment operator =.

Eg: int data=0;

Or

         int data;

data=0;
Constants are those which do not change during execution of a program. The constants in C++
can be numeric, character or string constants. Examples of each are shown in table 1.3

Table 1.3 Example of Constants

Constant        Example           Constraints
                23000
Numeric                         Can be negative or positive, cannot contain blanks or
Constant        450.6 (Floating commas, or $
                point)
Character                       Any character enclosed within single quotes, represented by
                ‘A’
Constant                        unique ASCII number in the memory
String                          Set of characters enclosed in double quotes, last character in
                “Hello”
Constant                        the string is null character ‘0′

Operators supported in C++ are listed below. Unary operators are used with one operand and
binary operator is used with two operands.

Table 1.4 Operators in C++

Arithmetic Operators   Type                    Action
-                      Unary as well as binary Subtraction for binary and minus for unary
+                      Binary                  Addition
*                      Binary                  Multiplication
/                      Binary                  Division
%                      Binary                  Modulus (remainder after dividing)
–                      Unary                   Decrement value by one
++                     Unary                   Increment value by one
Relational Operators   Type                    Action
>                      Binary                  Greater than
>=                     Binary                  Greater than or equal
<                      Binary                  Less than
<=                     Binary                  Less than equal
==                     Binary                  Comparision for equality
!=                     Binary                  Comparision for inequality
Logical Operators      Type                    Action
&&                     Binary                  AND
||                     Binary                  OR
!                      Unary                   NOT

Lets begin with a simple c++ program

// sum.cpp
#include<iostream.h>

void main()

{

int a,b,sum;

cout<<”Please enter any two numbers”<<endl;

cin>>a>>b;

sum=a+b;

cout<<”Sum of two numbers is “<<sum;

}

The above program asks the user to enter two numbers and displays the sum of the two
numbers. Iostream.h is a header file. The first statement of the above program is required if
you would like to include the cin and cout statements which is used for standard input or input
from keyboard and standard output or output to display screen. cin and cout are actually
predefined objects in C++. Iostream.h file contains the declarations for using the cin and cout
statements. There are several such header files which have to be included depending on the
functions you are using. We will come across many such header files as we progress.

Every C++ program should have a main() function. C++ allows you to create your own functions
in the program, like C. However the program execution always begins with the master function
main(). Paranthesis are used to group statements belonging to one function or program
statement. Every opening parathesis ({ ) should have a matching closing parathesis ( }).

The third statement declares three integer variables a, b and sum. The fourth statement displays
“Please enter any two numbers” on the display screen using cout statement. Cout (pronounced as
C out) uses << or insertion operator to push data to the output stream.

Operators known as manipulators can be used along with the << operator to modify the way
data is displayed. Endl is an operator which is similar to ‘n’ character in C that inserts a linefeed
into the output. The first cout statement in the program displays a statement where as the
second cout statement displays a statement and the value stored in the variable sum.

Cin (pronounced as c in) statement uses >> or extraction operator to feed the data to the input
stream. The above cin statement waits for user to enter two integers. The values entered by the
user is then stored in the variables a and b. Each variable in cin statement should separated by >>
operator.
Comment statements can be included in the program by prefixing the statement with “//” for
single line comments. Comments add clarity to the program. Multiple line comments can be
added by enclosing the statements between /* and */.

Self Assessment Questions

   1. ______________ is a header file used in c++ that handles input and output functions.

   2. ____________ statement is used to input data from the user in c++.

   3. ______________ statement is used to display data on the display screen in c++.

   4. ______________ is a master function required in all C++ program and program execution
   begins from the first statement of this function.


BC0037-1.5 Compiling and Executing C++
Program
Compiling and Executing C++ Program

1. There are three steps in executing a c++ program: Compiling, Linking and Running the
program. The c++ programs have to be typed in a compiler. All the programs discussed in the
book will be compiled on turbo c++ compiler. The turbo c++ compiler comes with an editor to
type and edit c++ program. After typing the program the file is saved with an extension .cpp.
This is known as source code. The source code has to be converted to an object code which is
understandable by the machine. This process is known as compiling the program. You can
compile your program by selecting compile from compile menu or press Alt+f9. After compiling
a file with the same name as source code file but with extension .obj. is created.

Second step is linking the program which creates an executable file .exe (filename same as
source code) after linking the object code and the library files (cs.lib) required for the program.
In a simple program, linking process may involve one object file and one library file. However in
a project, there may be several smaller programs. The object codes of these programs and the
library files are linked to create a single executable file. Third and the last step is running the
executable file where the statements in the program will be executed one by one.
Fig 1.1 shows the entire process. When you execute the program, the compiler displays the
output of the program and comes back to the program editor. To view the output and wait for
user to press any key to return to the editor, type getch() as the last statement in the program.
Getch() is an inbuilt predefined library function which inputs a character from the user through
standard input. However you should include another header file named conio.h to use this
function. Conio.h contains the necessary declarations for using this function. The include
statement will be similar to iostream.h.
Fig. 1.1: Compiling and Linking

During compilation, if there are any errors that will be listing by the compiler. The errors may be
any one of the following

1. Syntax error

This error occurs due to mistake in writing the syntax of a c++ statement or wrong use of
reserved words, improper variable names, using variables without declaration etc. Examples are :
missing semi colon or paranthesis, type integer for int datatype etc. Appropriate error message
and the statement number will be displayed. You can see the statement and make correction to
the program file, save and recompile it.

2. Logical error

This error occurs due to the flaw in the logic. This will not be identified by the compiler.
However it can be traced using the debug tool in the editor. First identify the variable which you
suspect creating the error and add them to watch list by selecting Debug ->Watches->Add watch.
Write the variable name in the watch expression. After adding all the variables required to the
watch list, go to the statement from where you want to observe. If you are not sure, you can go to
the first statement of the program. Then select Debug ->Toggle Breakpoint (or press ctrl + f8). A
red line will appear on the statement. Then Run the program by selecting Ctrl + f9 or Run option
from run menu. The execution will halt at the statement where you had added the breakpoint.
The watch variables and their values at that point of time will be displayed in the bottom in the
watch window. Press F8 to execute the next statement till you reach the end of the program. In
this way you can watch closely the values in the watch variables after execution of each and
every statement in the program. If you want to exit before execution of the last statement press
Ctrl + Break. To remove the breakpoint in the program go to the statement where you have
added breakpoint select Debug ->Toggle Breakpoint (or press ctrl + f8). Select Debug -> watch -
>remove watches to remove the variables in the watch list. This tool helps in knowing the values
taken by the variable at each and every step. You can compare the expected value with the actual
value to identify the error.

3. Linker error

This error occur when the files during linking are missing or mispelt

4. Runtime error
This error occurs if the programs encounters division by zero, accessing a null pointer etc during
execution of the program

Self Assessment Questions

1. ___________, ______________ and _____________ are phases in execution of a C++
program

2. The logical error is identified by the compiler. True/False

3. ________________ is the extension of C++ program source files

4. ________________ is the extension of C++ object code


BC0037-1.6 Summary
Summary

Object oriented Programming enables storing data and functions together which enables hiding
data from unnecessary exposure. Procedural languages differs from the Object oriented
programming in the approach used in solving the problem. While the former focuses on
organizing programs around functions, the later focuses organizing programs around classes.
Classes allow users to define their own datatypes and functionality. This allows extension of the
basic datatypes supported by the language. Reusability of code through inheritance allows users
to use the existing code without modifying it but also extend the functionality of the existing
code. The C++ programs are similar to C except for the object oriented programming features.
Every C++ program has a main function from where the execution starts. C++ programs goes
through two phases ie compiling and linking before execution.


BC0037-2.1 Introduction
Introduction

This unit has the following objectives

· To learn to use selection control statements in C++

· To learn to use loops or iteration in C++

· To implement programs using relational, logical, increment and decrement operators in C++
BC0037-2.2 Selection control statements in
C++
Selection control statements in C++

There are basically two types of control statements in c++ which allows the programmer to
modify the regular sequential execution of statements.They are selection and iteration
statements. The selection statements allow to choose a set of statements for execution depending
on a condition. If statement and switch statement are two statements which allow selection in
c++. There is also an operator known as conditional operator which enables selection.

If statement

Syntax : if (expression or condition)

{ statement 1;

statement 2;

}

else

{ statement 3;

statement 4;

}

The expression or condition is any expression built using relational operators which either yields
true or false condition. If no relational operators are used for comparison, then the expression
will be evaluated and zero is taken as false and non zero value is taken as true. If the condition is
true, statement1 and statement2 is executed otherwise statement 3 and statement 4 is executed.
Else part in the if statement is optional. If there is no else part, then the next statement after the if
statement is exceuted, if the condition is false. If there is only one statement to be executed in the
if part or in the else part, braces can be omitted.

Following example program implements the if statement.

// evenodd.cpp

# include <iostream.h>

# include <conio.h>
void main()

{

int num;

cout<<”Please enter a number”<<endl;

cin>>num;

if ((num%2) == 0)

cout<<num <<” is a even number”;

else

cout<<num <<” is a odd number”;

getch();

}

The above program accepts a number from the user and divides it by 2 and if the remainder
(remainder is obtained by modulus operator) is zero, it displays the number is even, otherwise as
odd. We make use of the relational operator == to compare whether remainder is equal to zero or
not.

Nested If statement

If statement can be nested in another if statement to check multiple conditions.

If (condition1)

{ if (condition 2)

{ statement1;

Statement2;

}

else if (condition3)

{statement3;

}
}

else statement4;

The flowchart of the above example is shown below




Fig. 2.1: Nested If Statement

Multiple conditions can be checked using logical && operator(AND) and || operator (OR).

If ((condition1) && (condition2))

statement1;

else

statement2;

In the above example statement1 will be executed if both the condition1 and condition2 are true
and in all other cases statement2 will be executed.

If ((condition1 || (condition2))

statement1;

else

statement2;

In the above example statement1 will be executed if either condition1 or condition2 are true and
even if both are true. Statement2 will be executed if both the conditions are false. The following
program demonstrates the use of && operator and nested if statement.
//Large.cpp

# include <iostream.h>

void main()

{ int a,b,c;

cout<<”Please enter three numbers”;

cin>>a>>b>>c;

if ((a>b) && (b>c))

cout<<a<< “ is the largest number”;

else if ((b>a) && (b>c))

cout<<b<< “ is the largest number”;

else if ((c>a) && (c>b))

cout<<c<< “ is the largest number”;

}

The above program accepts three numbers from the user and displays which is the largest
number among the three.( assumption is that all the numbers are unique, the program has to be
modified if you would like to allow same number twice)

Switch statement

Nested ifs can be confusing if the if statement is deeply nested. One alternative to nested if is the
switch statement which can be used to increase clarity in case of checking the different values of
the same variable and execute statements accordingly.

Syntax :

Switch (variablename)

{ case value1: statement1;

break;

case value2: statement2;
break;

case value3: statement3;

break;

default: statement4;

}

If the variable in the switch statement is equal to value1 then statement1 is executed, if it is equal
to value2 then statement2 is executed, if it is value3 then statement3 is executed. If the variable
value is not in any of the cases listed then the default case statement or statement4 is executed.
The default case specification is optional, however keeping it is a good practice. It can also be
used for displaying any error message. Each case can have any number of statements. However
every case should have a break statement as the last statement. Break statement takes the control
out of the switch statement. The absence of the break statement can cause execution of
statements in the next case. No break is necessary for the last case. In the above example, default
case does not contain a break statement.

The flowchart for the switch statement is shown in Fig 2.2




Fig. 2.2: Switch Statement

The following program implements the switch statement

position.cpp

# include<iostream.h>

void main()
{ char pos;

int x=15, y=15;

cout << “ you are currently located at” <<x<<” “<<y<<endl;

cout>>”please choose the letter to move l for left, r for right, u for up and d for down” <<endl;

cin>>pos;

switch (pos)

{ case ‘l’: x–;

break;

case ‘r’: x++;

break;

case ‘u’: y++;

break;

case ‘d’: y–;

break;

default: cout<<”You selected a wrong option”;

}

cout<<“ you are now located at” <<x<<” “<<y;

}

The above program asks the user to enter l,r,u,d for allowing him to move left,right,up and down
respectively. The position is initialised to 15 and 15 which are x and y coordinates of his
position. Depending upon the what user has selected the the x and y co-ordinates are incremented
or decremented by one(x++ is same as x=x+1). If the user types a letter other than l,r,u,d, he gets
an error message. Since the switch variable is a character, l,u,r,d and enclosed within single
quote.

++ and — operator can be used as postfix or as prefix operator which has no effect if used as an
independent statement. However if it used as part of an expression, the prefix operator will be
operated and then the expression will be evaluated whereas the postfix operated will be evaluated
later.

For example in the statement x= a+ (b++), a will be added to b and then stored in x and then the
value of b will be incremented. If the same expression is written as x=a+(++b), the the b will be
incremented and then added to a and stored in x.

Conditional Operator

Conditional operator (?:) is a handy operator which acts like a shortcut for if else statement. If
you had to compare two variables a and b and then depending on which is larger, you wanted to
store that variable in another variable called large. You would do this using if else statement in
the following way:

if (a>b)

large=a;

else

large=b;

The above can be done using conditional operator in the following way:

large= (a>b) ? a : b ;

Self Assessment Questions

1. In if else statement, at any point of time statements in both the if and else part may be
executed. True/False

2. Conditional operator is an alternative to __________ statement

3. ++ operator increments the value of the operand by _________

4. The ++ operator used as postfix and prefix has the same effect. True or False

5. Each case in switch statement should end with _________ statement


BC0037-2.3 Iteration statements in C++
Iteration statements in C++
Iteration or loops are important statements in c++ which helps to accomplish repeatitive
execution of programming statements. There are three loop statements in C++ : while loop, do
while loop and for loop

While loop

Syntax: while (condition expression)

{

Statement1;

Statement 2;

}

In the above example, condition expression is evaluated and if the condition is true, then the
statement1 and statement2 are executed. After execution, the condition is checked again. If true,
the statements inside the while loop are executed again. This continues until the loop condition
becomes false. Hence the variable used in the loop condition should be modified inside the loop
so that the loop termination condition is reached. Otherwise the loop will be executed infinitely
and the program will hang when executed. Also the loop variable should be iniatialised to avoid
the variable taking junk value and create bugs in the program.

The flowchart for the While statement is shown in Fig 2.3.




Fig. 2.3: While Statement

The following program implements the while loop

// average1.cpp

# include <iostream.h>
void main()

{

int n=0,a;

int sum=0;

cout<< “enter five numbers”;

while (n<5)

{

cin>>a;

sum=sum+a;

n++;

}

cout<<”Average of the numbers is”<<(sum/n);

}

The above program accepts five numbers from the user and finds the average of the five
numbers. In the above while loop, the variable n is initialized to zero and this variable keeps
track of the count of numbers input from the user. It is incremented every time a number is input
from the user. The number accepted from the user is added to the value stored in the sum
variable. When n becomes 5 the while loop condition becomes false and the average of the
numbers is printed. Please note that there is no semicolon after while and condition expression.

Do..while loop

The do while loop is same as while loop except that the condition is checked after the execution
of statements in the do..while loop. Hence in do..while loop, statements inside the loop are
executed atleast once. However, in while loop, since the condition is checked before, the
statements inside the loop will not be executed if the loop condition is false.

Syntax:

do

{
Statement1;

Statement2

} while (condition expression);

In the above example the statement1 and statement2 are executed and the condition is checked. If
the condition is true then the statements are executed again and if the condition is false then the
control is transferred to the next statement after the do..while statement.

The flowchart for the do..while statement is shown in Fig 2.4




Fig. 2.4: Do..while Statement

Please note that there is no semicolon after do, but there is a semicolon after the condition
expression in while part. The average1.cpp program is rewritten using do..while loop as follows

// average2.cpp

# include <iostream.h>

void main()

{

int n=0,a;

int sum=0;

cout<< “enter five numbers”;

do

{
cin>>a;

sum=sum+a;

n++;

}while (n<5);

cout<<”Average of the numbers is”<<(sum/n);

}

The decision on whether to use while or do..while statement depends on whether the statements
inside the loop have to be executed atleast once or not. If it has to be executed atleast once, then
the do..while statement should be used.

For loop

The for loop is one of the popular control statement as it is compact and clear in specification.
The loop initialization, loop termination condition statement and statement for the next iteration
are all included in one statement.

Syntax:

for(initialization statement;loop termination condition;statement to increment/decrement the loop
variable)

{

Statement1;

Statement2;

}

In the above example, initiation statement is executed first and then the termination is checked. If
the condition is true, statement1 and statement2 will be executed. Then the third statement in the
for loop is executed which modifies the loop control variable.

The flowchart for the for statement is shown in Fig 2.5
Fig. 2.5: For Statement

Please note that there is no semicolon after the for statement.

The average2.cpp rewritten using for loop is as follows:

// average3.cpp

# include <iostream.h>

void main()

{

int a;

int sum=0;

cout<< “enter five numbers”;

for(int n=0;n<5;n++)

{

cin>>a;

sum=sum+a;

}

cout<<”Average of the numbers is”<<(sum/n);
}

In the above example n variable is loop variable which is initialized to zero. Please note that the
variable is also declared inside the for loop. So this variable can be accessible only inside the for
loop. The scope of the variables will be declared in detail in unit 4. The statements inside the
loop are executed until the loop termination condition n<5 becomes false. After every iteration,
the loop variable n is incremented.

The following program demonstrates the use of for loop using decrement operator to find the
factorial of a number.

// factorial.cpp

# include <iostream.h>

void main()

{

int number,fact=1;

cout<< “enter a number”;

cin>>number;

for(int i=number;i>1;i–)

fact=fact*i;

cout<<”Factorial of <<number<<“is”<<fact;

}

All the above loops can be nested. The inner loop is executed completely and then the outer loop
is executed. For every iteration of outer loop, all the iterations of the inner loop is executed.

The for statement can also have multiple initialization and decrement and increment statements
as shown in the following expression

for(i=0,j=0;i<=n;j++,i++)

{

statements;

}
Please note that in case of multiple statements, each statement should be separated by a comma.

Selection of which type of loop to be used depends on the programmer and his style. However
you should use for loop if you know in advance how many times the loop has to be executed. If
the loop has to be executed atleast once irrespective of whether the condition is true or false, then
do while loop should be used.

Self Assessment Questions

1. Which of the following loop will be executed atleast once even if the condition is false.

a. For loop b. while loop c. do..while loop d. None of the above

2. ___________ is the loop variable in the loop for(int k=n;k!=0;k=k-2)

3. The loop for(int i=0;i<n;i++) will be executed till the statement _________ becomes false.

4. If there is more than one statements inside a loop, then the statement should be enclosed
within ______________


BC0037-2.4 Break continue and exit
statements in C++
2.4 Break, continue and exit statements in C++

All the loops or iteration statements discussed in previous section are executed until the loop
condition becomes false. However if required, the control sequence can be changed by using
break, continue or exit statements.

Break statement transfers the control to the next statement after the loop and all the remaining
statements and the iterations in the loop are skipped. It is used if you would like to exit the loop
when a certain condition is met. In the switch statement break statement takes the control to the
next statement after the switch statement.

The following program demonstrates the use of break statement inside for loop.

// prime.cpp

# include <iostream.h>

void main()

{ int number;
int prime=0;

cout<<”Enter a number”;

cin>>number;

// check whether the number is divisible by any number from 2 to number/2

for (int i=2;i<=number/2;i++)

{

if ((number%i)==0)

{ prime=1;

break;

}

}

if (prime==0)

cout<<”The number is prime number”;

else

cout<<” The number is not a prime number”;

}

In the above program, the user is asked to enter a number and the program checks whether the
number is prime or not and displays the message accordingly. To check whether the number is
prime or not, the number is divided by 2,3… and so on till number/2. If the number is divisible
by any number, the variable prime is assigned a value one and the loop is terminated as there is
no need to check whether the number is divisible by rest of the numbers. The value 1 in the
prime indicates that the number was divisible by one of the numbers between 2 to number/2.

Continue statement is used to take the control to the next iteration of the loop. It is used if the
control has to be transferred to the next iteration of the loop based on a condition skipping all the
other statements in the loop. The following program shows the use of continue statement.

move.cpp

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

void main()

{ int x,y;

char choice=’y’;

do

{

clrscr();

cout<<”please enter the dividend”;

cin>>x;

cout<<”Please enter the divisor”;

cin>>y;

if (y==0)

{

cout<<”error!! Division by zero, try again”;

continue;

}

cout<<”The quotient is “<<(x/y);

cout<<”the remainder is”<<(x%y);

cout<<”do u wish to continue”;

cin>>choice;

}while (choice==’y’);

}
In the above example clrscr() function which is a library function is used to clear the screen
before accepting the input from the user. To use this function, conio.h header file must be
included.

Exit function in a program takes the control out of the program. Exit is an inbuilt library
function. To use this function process.h header file has to be included in the program. The syntax
of this function is exit(integer).While terminating the program, the integer is returned to the
operating system. Usually the function integer 0 is used to imply no error or successful
termination and non zero value implies error while exiting the program .

Go to statement is a statement which should be avoided. It take the control to a particular
statement. The statement should have a label.

Syntax: goto statement labelname

Statements can be given labels in the following way

labelname: statement

The use of goto statement should be avoided as it creates problems in program debugging and
the program may have confusing jumps from one statement to another.

Self Assessment Questions

1. _________ statement takes the control out of the loop.

2. __________ header file should be included to use exit function

3. __________ statement takes the control to the beginning of the loop.

4. ________ statement takes the control to a particular statement


BC0037-2.5 Summary
Summary

Selection and iteration statements allow to execute statements in the program based on a
condition bypassing the normal sequential execution. Selection is enabled through if statement,
switch statement and conditional operator. Switch statement is suitable when you have multiple
conditions to be checked and nested if can be avoided. Iteration is enabled in C++ through while,
do..while and for loops. Loops execute the statements repeatitively until a particular condition
becomes false. Break, continue and exit statements are used to transfer control out of the loop, to
the next iteration of the loop and out of the program respectively.
BC0037-3.1 Introduction
Introduction

This unit has the following objectives

· To understand what are arrays and how they are useful in C++ programming

· To learn to create and use multidimensional arrays

· To understand how strings are represented and used in C++


BC0037-3.2 Introduction to Arrays
Introduction to Arrays

Arrays are used when you want to store related data of same type together with the same name so
that you can access them easily. Arrays can be defined as datastructures that allow to store group
of data of same datatype. You can retrieve data stored in the array in any order. For example, let
us suppose you want to write a program which will help you to compute average marks scored
by students in a class of 60. To allow this computation, your program should store marks scored
by 60 students in a class separately, so that you can do any kind of computation when required. It
would be tedious, if you had to create 60 different variables to store marks of 60 students and
manage them separately. Arrays solves this problem, by grouping data of similar type with same
name but can be referred separately through the position or the index number.

Arrays should be declared like any other variable. However array size should be specified during
declaration which determines how many elements the array can store. The following is a
declaration of an integer array named data which can store 20 integers.

int data[20];

Please note that in the above declaration, data is the name of the array followed by the size of the
array enclosed within square brackets.The datatype of data stored by the array can be any default
datatypes supported by c++ or user defined datatypes.

Elements in the array can be accessed through index numbers. The data in the array are stored
with index numbers 0,1, and so on. Since the index number starts with 0 the last index number of
an array of size n will be n-1. The elements stored in the array are accessed by using the array
name followed by the index number within the square brackets. For example, in the above array,
the integers in the array can be accessed as data[0], data[1] and so on till data[19]. This makes it
very easy to store and access large number of data. The code can be simplified by including
common statements that needs to be performed on the array elements inside a loop and making
the loop variable as the variable that stores the index variable.
The following programs shows how you can store and retrieve data from the array

//max.cpp

#include<iostream.h>

void main()

{

int max=0, a[50];

for (int i=0; i<50;i++)

{

cin>>a[i];

if (a[i]>max)

max=a[i];

}

cout<<”Largest number in the array is”<<max;

}

In the above program, a is an array that stores 50 integers. The program accepts 50 integers from
the user, and stores in an array and finds out the maximum number in the array. The a[i]
represents a particular element in the array and i is the index number. As the iteration varies, the
value stored in i also varies.

Another interesting aspect of the array is that all the elements in the arrays are allotted
consecutive spaces in the memory by the operating system.

The following program sorts an array. Here nested for loops are used to enable this.

//sort.cpp

# include<iostream.h>

void main()

{
int a[10],temp;

for (int i=0; i<10;i++)

{

cin>>a[i];

}

cout<<”Array after sorting is “;

for(int j=0; j<9;j++)

for(i=0;i<9;i++)

{ if (a[i]>a[i+1])

{temp=a[i];

a[i]=a[i+1];

a[i+1]=temp;

}

}

for (i=0; i<10;i++)

{

cout<<a[i]<<endl;

}

}

Array elements can be initialized. All the elements in the array should be initialized. Every data
should be separated by a comma and all elements enclosed within flower brackets as shown
below

int data[5] = {3,5,7,4,9};

In the above initialization, data[0] is initialized to 3, data[1] is initialized to 5 and so on..
Self Assessment Questions

1. Arrays group data of __________ type

2. An array declared as int a[10] can store __________ integers

3. a[5] represents the _________ integer in the above array.

4. Array elements are accessed through _______________


BC0037-3.3 Multidimensional Arrays
Multidimensional Arrays

The arrays can be multidimensional as well to store the required data. For example a two
dimensional array can be created to store data about a matrix. A 3×4 matrix that has 12 data
elements can be created using the following declaration

int mat[3][4];

The above array has 3 rows and four columns. The elements in the array can be accessed by two
indexes. To refer to an element in the first row and second column mat[0][1] has to be used as
the index starts from zero.

The following program accepts from the user two 2×3 matrices and adds the two matrices.

//matrix.cpp

# include <iostream.h>

void main()

{ int a[2][3], b[2][3], c[2][3];
int i,j;

cout<<”Enter the elements for the first 2×3 matrix”;

for (i=0;i<2;i++)

for (j=0;j<3;j++)

{ cin>>a[i][j];}

cout<<”Enter the elements for the second 2×3 matrix”;

for (i=0;i<2;i++)

for (j=0;j<3;j++)

{

cin>>b[i][j];

c[i][j]=a[i][j]+b[i][j];

}

cout<<”The resultant matrix is”;

for ( i=0;i<2;i++)

{

for ( j=0;j<3;j++)

{

cout<<c[i][j]<<” “;

}

cout<< endl;

}

}

Multi dimensional arrays can also be initialized as follows
int a[2][2] = {{ 3,4},

{ 2, 7}}

Every row elements are initialized by enclosing them in separate flower brackets.In the above
example elements 3 and 4 will be initialized to a[0][0] and a[0][1] respectively.

Self Assessment Questions

1. An array with the declaration int x[4][5] can store ________ numbers

2. In the above array the number in the third row and fourth column can be accessed by
____________

3. int a[ ] [ ] is a valid declaration. True/False


BC0037-3.4 Strings and String related
Library Functions
Strings and String related Library Functions

Strings are nothing but character arrays. Strings are usually used to store data such as employee
name, address, product description, password etc. The size of the string is defined during
declaration like any other array. One basic difference between other arrays and strings is that the
compiler stores an extra null character (’/0′) for every string to mark the end of the string. This
enables a good means of identifying the end of the string as string variables usually store variable
length values. Strings, unlike other arrays can be input without using a loop. When inputting
strings using cin statement, the compiler stops taking input from the user once it encounters
space or linefeed (pressing enter key). For example, consider the following program statements:

char str[10];

cin>>str;

If the user inputs “HELLO” and presses enter key , the contents for the str variable will be as
follows:

H    str[0]
E    str[1]
L    str[2]
L    str [3]
O    str[4]
/0   str[5]
The strings can be also initialised as arrays. However they can be initialized by enclosing the
characters in the string constant with double quotes instead of initializing it character by
character. For example, the following statement initializes the str variable to “hello”:

char str[10]=”hello”;

Strings can also be defined without specifying the size, but in that case they have to be initialized
to a string constant as shown in the following example.

char str[]=”hello world”

However, there is no built in mechanism in C++ that disallows the user to enter characters than
the string maximum size. The extra characters entered by the user will be truncated. To keep a
check on the number of characters, setw() function can also be used. To use this function,
iomanip.h header file should be included.

#include<iostream.h>

#include<iomanip.h>

const int size=10;

void main()

{

Char str[size];

Cout<<”enter a string”;

Cin>>setw(size)>>str;

}

The above program allows user to enter only 9 characters(one character saved for null
character).While inputting strings, cin stops reading once it encounters space or linefeed
character( when user presses enter). To read blanks between the strings or to read multiple lines
of text, get function which is a member function of cin can be used.The following statement will
allow user to input a maximum of 39 characters which can even include blanks. It will stop
reading once it encounters linefeed character.

cin.get(str, 40);

To read multiple line of text from the user, you have to specify a terminating character which
will be used to recognize end of input. In the following example, the terminating character is $.
cin.get(str,40,$);

The above example will allow users to enter a maximum of 39 characters which can include
embedded blanks and linefeed.

C++ has several string related library functions that are used to manipulate strings. Some of
these are discussed below. To use these functions, header file string.h has to be included. Some
of the library functions such as strlen, strcpy, strrev, strcmp is discussed below.

Strlen Function

Strlen function is used to find the length of the string. The syntax of the strlen function is
strlen(string variable). The function returns the length of the string or the number of characters in
the string which is a integer.

Example :

int len;

char str[10]=”hello”;

len=strlen(str);

In the above example, the number of characters in the string str(five in this case) is stored in the
integer variable named len

Strrev function

Strrev function arranges the characters in the string variable in reverse order except for the null
character. The syntax of strrev function is strrev(string variable). It returns the reversed string.
For example, in the following program statement, the output will be olleh

The null character will be the last character of the string.

char str[10]=”hello”;

cout<<strrev(str);

Strcpy function

Strcpy function copies the contents of one string to another. The syntax of strcpy function is
strcpy(destination string, source string). The function returns the destination string value after
copying. For example, in the following program statement, the contents of the string str will be
copied to string name

char str[10]=”ravi”;
char name[10];

strcpy(name,str);

The strcpy can also use string constants to be assigned to a string variable like in the following
statement.

strcpy(name,”ravi”);

In the above statement the string constant ravi is assigned to the string variable name. The
assignment of a string variable cannot be done using an assignment operator. It should be done
using strcpy function. The following statement in a program will provide an compilation error:

name=”ravi”; //wrong statement

Strcmp function

Strcmp function is used to compare two strings. The syntax of strcmp is strcmp(string1,string2).
Every character of string1 will be compared with corresponding character of string2. The ASCII
values of the character will be used to decide the return value. The function returns an integer
and the value returned will differ based on the conditions as shown below:

If string1 < string2, value returned will be <0

If string1==string2, value returned will be 0

If string1> string2, value returned will be greater than zero.

Thus, a return value 0 implies that strings are equal and a non zero return value implies than the
two strings are not equal. Please note that the above function is case sensitive. Strcmpi() function
can be used if the two strings have to be compared without case sensitiveness.

The following program implements strcmp function

# include <iostream.h>

# include<string.h>

const char str[6] = “XYZPQR”

void main()

{

char pass[6];
int flag=0;

for(int i=0;i<3;i++)

{

cout<<”Please enter your password”;

cin>>pass;

if (strcmp(str, pass)==0)

{

cout<<”Welcome”;

flag=1;

break;

}

else

cout<<”Invalid password, try again”<<endl;

}

}

if (flag==0)

cout<<”Access denied”;

}

Self Assessment Questions

    1. char str[ ]; is a valid statement. True/False
    2. char str[20] will allow maximum of ________ characters to stored in the string.
    3. _________ member function of cin allows user to input embedded blanks and linefeed
       within the string.
    4. _________ libray function can be used to copy the contents of one string to another
       string.
BC0037-3.5 Summary
Summary

Arrays are used to store large volumes of similar data together. The array elements can be
accessed by specifying array name followed by the number which indicates the position of the
element in the array. Arrays of basic datatypes such as integers, characters etc and user defined
datatypes such as structures, objects can be defined.

Arrays can be multidimensional to store data that are related.

Strings are character arrays that are handled slightly differently than other arrays. Every string
has a null character ‘0’ as its last character which marks the end of the string. There are several
string related library functions that can be used to manipulate strings


BC0037-4.1 Introduction
Introduction

This unit has the following objectives

· To understand what are functions and how they enable program organisation

· To understand different types of variables and their use in C++

· To learn to what are structures and grouping data of different data types together


BC0037-4.2 Introduction to Functions
Introduction to Functions

Functions provide an easy means to organize the programs into smaller modules and use them
again without rewriting all the code. It enables reuse of program code. Functions enable
programmers to group program code under one name and invoke them whenever required. We
have been using several library functions till now without worrying about the code to implement
them. Programmers can define their own functions in C++. In this unit, we will learn how to
implement user defined functions.

Every function has three components: return value, function name, and a set of arguments.
Function name enables users to refer to the functions and is also used when user wants to call
and execute the code defined in the function. Every function may or may not return a value.
During declaration of function, the datatype of the return value should be specified. If there is no
value returned it should be specified as void.The function main() which we had been using in all
the programs is one of the default functions which also has been defined as having no return
value. When you have several user defined functions in a program, the statements in the main()
function is executed first irrespective of where it is located in the program.

Every function can have no or any number of arguments. Arguments are input to the functions
and are used inside the function. During declaration of the function, the datatypes of the
arguments should be specified. Each argument should be separated with a comma. The
arguments should match during function call with respect to datatype and order of the arguments.
In case of default arguments the value need not be specified during call.

Every user-defined function should be declared in the program before it is used. The definition
can be present in any part of the program. The following is an example of declaration of a
function named square which inputs a number and returns the square of the number.

int square(int);

Please note that all the arguments are enclosed within brackets. If there are no arguments, void
should be specified within the brackets. The following is the declaration of a function which does
not have return value and does not have any arguments.

void xyz(void);

The functions can be invoked or called by referring to the function name followed by the
variables or constants that has to be passed as arguments. If there are no arguments that has to be
passed to the functions, then the function name should be followed by a pair of paranthesis. The
following program would invoke the xyz function:

xyz();

To invoke a square function which inputs a number and returns a number following statement
can be used:

s=square(n);

Where s and n are integer variables. The function will compute square of n and the result will be
stored in variable s. Please note that during function call, constants can also be passed.

To understand the relevance of functions and its use, let us take an example. Let us suppose you
would like to write a program that computes the combination of n items taken r at a time. The
mathematical formula for computing nCr is n!/(r!*(n-r)!). In this problem, the factorial of the
numbers have to be computed three times. The code for implementing factorial of a number has
been discussed in the unit 2.3 in factorial.cpp program. If the same code has to be directly
implemented without functions, the code has to be repeated three times in the program to
compute factorial of n, r and n-r. This would not only make programs unnecessarily big but also
difficult to correct or debug. To avoid this problem, we can define a user defined function named
fact which would input a number and compute the factorial of that number and return the result.
The declaration for the function will be as below

int fact(int);

We can compute the factorial of n just by specifying fact(n) which would call the function fact
and execute the statements. The complete program for implementing the above problem is as
below:

//function.cpp

# include <iostream.h>

int fact(int); // function declaration

void main()

{

int n,r,ncr ;

cout<< “enter n”;

cin>>n;

cout<< “enter r” ;

cin>>r ;

ncr=fact(n)/(fact(r)*fact(n-r));

cout<<”NCR=” <<ncr;

}

int fact(int number) //function definition

{

int f=1;

for(int i=number;i>1;i–)

f=f*i;

return f; //return computed value
}

In the above program, the user inputs value for n and r. To compute the value of ncr, the fact
function is invoked or called first by passing n variable. When the compiler encounters the first
statement of the function, it copies the value of the variable n to the variable number. The
variable number has scope only inside the function fact and is known as local variable. It cannot
be accessed outside the function and so is the variable f and i that has been defined in the
function. The factorial of the variable number (same value as n) is computed and then returned to
the calling program through the return statement. The return statement is used to return values or
results to the main program. This process is repeated for the values r and n-r as well. All the
results are then used in the formula in the main program to compute the value of ncr.

If the function does not have any return value, the return statement can be skipped. The control
goes back to the main program once the last statement in the program is encountered.
Alternatively, simply using the return statement without any variable would also imply that no
value is being returned to the main program.

Self Assessment questions

1. Functions enable to reuse code. True/False

2. void print() would return _______ value

3. ________ statement is used to return value to the main program.

4. Function call should always contain function name followed by paranthesis even if there are
no arguments. True/False


BC0037-4.2 Introduction to Functions
Introduction to Functions

Functions provide an easy means to organize the programs into smaller modules and use them
again without rewriting all the code. It enables reuse of program code. Functions enable
programmers to group program code under one name and invoke them whenever required. We
have been using several library functions till now without worrying about the code to implement
them. Programmers can define their own functions in C++. In this unit, we will learn how to
implement user defined functions.

Every function has three components: return value, function name, and a set of arguments.
Function name enables users to refer to the functions and is also used when user wants to call
and execute the code defined in the function. Every function may or may not return a value.
During declaration of function, the datatype of the return value should be specified. If there is no
value returned it should be specified as void.The function main() which we had been using in all
the programs is one of the default functions which also has been defined as having no return
value. When you have several user defined functions in a program, the statements in the main()
function is executed first irrespective of where it is located in the program.

Every function can have no or any number of arguments. Arguments are input to the functions
and are used inside the function. During declaration of the function, the datatypes of the
arguments should be specified. Each argument should be separated with a comma. The
arguments should match during function call with respect to datatype and order of the arguments.
In case of default arguments the value need not be specified during call.

Every user-defined function should be declared in the program before it is used. The definition
can be present in any part of the program. The following is an example of declaration of a
function named square which inputs a number and returns the square of the number.

int square(int);

Please note that all the arguments are enclosed within brackets. If there are no arguments, void
should be specified within the brackets. The following is the declaration of a function which does
not have return value and does not have any arguments.

void xyz(void);

The functions can be invoked or called by referring to the function name followed by the
variables or constants that has to be passed as arguments. If there are no arguments that has to be
passed to the functions, then the function name should be followed by a pair of paranthesis. The
following program would invoke the xyz function:

xyz();

To invoke a square function which inputs a number and returns a number following statement
can be used:

s=square(n);

Where s and n are integer variables. The function will compute square of n and the result will be
stored in variable s. Please note that during function call, constants can also be passed.

To understand the relevance of functions and its use, let us take an example. Let us suppose you
would like to write a program that computes the combination of n items taken r at a time. The
mathematical formula for computing nCr is n!/(r!*(n-r)!). In this problem, the factorial of the
numbers have to be computed three times. The code for implementing factorial of a number has
been discussed in the unit 2.3 in factorial.cpp program. If the same code has to be directly
implemented without functions, the code has to be repeated three times in the program to
compute factorial of n, r and n-r. This would not only make programs unnecessarily big but also
difficult to correct or debug. To avoid this problem, we can define a user defined function named
fact which would input a number and compute the factorial of that number and return the result.
The declaration for the function will be as below
int fact(int);

We can compute the factorial of n just by specifying fact(n) which would call the function fact
and execute the statements. The complete program for implementing the above problem is as
below:

//function.cpp

# include <iostream.h>

int fact(int); // function declaration

void main()

{

int n,r,ncr ;

cout<< “enter n”;

cin>>n;

cout<< “enter r” ;

cin>>r ;

ncr=fact(n)/(fact(r)*fact(n-r));

cout<<”NCR=” <<ncr;

}

int fact(int number) //function definition

{

int f=1;

for(int i=number;i>1;i–)

f=f*i;

return f; //return computed value

}
In the above program, the user inputs value for n and r. To compute the value of ncr, the fact
function is invoked or called first by passing n variable. When the compiler encounters the first
statement of the function, it copies the value of the variable n to the variable number. The
variable number has scope only inside the function fact and is known as local variable. It cannot
be accessed outside the function and so is the variable f and i that has been defined in the
function. The factorial of the variable number (same value as n) is computed and then returned to
the calling program through the return statement. The return statement is used to return values or
results to the main program. This process is repeated for the values r and n-r as well. All the
results are then used in the formula in the main program to compute the value of ncr.

If the function does not have any return value, the return statement can be skipped. The control
goes back to the main program once the last statement in the program is encountered.
Alternatively, simply using the return statement without any variable would also imply that no
value is being returned to the main program.

Self Assessment questions

1. Functions enable to reuse code. True/False

2. void print() would return _______ value

3. ________ statement is used to return value to the main program.

4. Function call should always contain function name followed by paranthesis even if there are
no arguments. True/False


BC0037- 4.4 Scope and Visibility of variables
in Functions
Scope and Visibility of variables in Functions

Functions save memory as all the calls to the function cause the same code to be executed.
However, with this there is overhead of execution time as there must be instructions for jump
to the function, saving data in registers, pushing arguments to stack and removing them,
restoring data, instructions for returning to the calling program and return values. To save
execution time of functions, one of the feature in c++ is inline functions. An inline function’s
code is put with the code in the calling program for every function call. The inline function is
written like any other function except that the function declaration begins with the keyword
inline. This type of function is suitable for small functions which has to be repeatedly called.
This enables the user to write programs using functions which would make programs look neat
and less lengthy, at the same time the actual code is inserted in all the places where the
function is called after compilation enabling faster execution of the program.
The several types of variables can be created in C++ which can be different in terms of life,
visibility and the way it is initialized. These are also known as storage classes.

We will discuss three types of storage classes in this section : Automatic, External and Static
variables.

Automatic variables is default variable in C++. All the variables we have created and used in
programs are automatic variables. These variables can also be declared by prefixing the keyword
auto. One of important characteristics of these variables are that they are created only when the
function or program block in which they are declared are called. Once the execution of function
or module execution is over, the variables are destroyed and the values are lost. The reason for
limiting the lifetime of automatic variables is to save memory. When the variables are not be
used by the function, they are removed from the memory. They can be accessed only within the
function where they are declared. Beyond which they are not idenfiable. By default the automatic
variables are not initialized to any specific values unless and until specified. They contain junk
value depending on the value stored in the memory. Therefore it is necessary to initialize
automatic variables to avoid problems in debugging.

External variables are variables external to any function. Thus they can be accessed by multiple
functions. This is the easiest way to share data among various functions. However too many
external variables can create problems in debugging as the programmer will have tough time
figuring out which function modified which data. Object oriented programming provides an
alternative to use external variables. This feature is just to support backward compatibility with
C. External variables are also known as global variables and are automatically initialized to zero.
These variables are declared before main and declaration statement does not belong to any
function.

The following program shows the difference between an external variable and an automatic
variable.

//external.cpp

# include<iostream.h>

int x;

void f1();

void f2();

void main()

{

x=x+2;
f1();

f2();

cout<<x;

}

void f1()

{ int x;

x=x*2;

}

void f2()

{ x++;

}

In the above program, we have defined an external variable x. This variable will be automatically
initialized to zero. The statement x=x+2; will store two in x. The function f1 will not have any
impact on the value of the external variable as there is another local automatic variable x defined
in the function which will be modified (Please note that when automatic and global variable have
same name, the local variable will override the global variable).

The function f2 will increment global variable by one. Thus the final output of the above
program will be 3.

External variables have a life of the file/program in which they are defined.

Static variables are a mix of external and automatic variables. They have the scope of the
function in which they are defined like automatic variables. But they can retain their values even
after the function execution is over and are automatically initialized to zero like external
variables. The following program shows the use of the static variables.

// static.cpp

# include <iostream.h>

void main()

{
int num;

char ch;

do

{

cout<<”Enter a number”;

cin>>num;

f1(num);

cout<<”Do u want to enter another number”;

cin>>ch;

}while (ch==’y')

}

void f1(int x)

{ static int sum, n;

sum=sum+x;

n=n+1;

avg=sum/n;

cout<< “Average is”<<avg;

}

The above program allows the user to enter any number of integers and computes the average of
the numbers till then. The static variables sum and n are intitialised to zero. They are updated
when user enters a new number and the function is called. The values of these variables are
retained even after the function returns back to the main program.

The summary of all three storage classes is shown below:

                 Automatic         Static                                  External
Visibility       Function          Function                                Program
Lifetime         Function          Program                                 Program
Intialised      Junk value in
                                     Zero                                      Zero
to              memory
                                     Same as automatic but the value
                Variables used by                                              Variables used by
Purpose                              should be retained when function
                single function                                                several functions
                                     terminates

Self Assessment questions

     1. Inline functions help in saving ______________ of programs

     1. Static variables are initialized to _________ automatically.
     2. External variables are accessible throughout the _________.


BC0037-4.5 Structures in C++
Structures in C++

We have seen in unit three how we can group data of same type together with arrays. Data that
are of different types but are logically related can also be grouped together. This can be done
through structures. Structures are a group of dissimilar data that are related with each other. For
example, if you want to store all the details of an employee such as employee id (integer), name
(string), department code(integer), and salary as one entity, you can do this using structure as
shown below:

struct employee

{ int empid;

char name[35];

int deptcode;

float salary;

};

Structure is a feature in C++ that enables you to define a user-defined datatype. Once you specify
the definition of the structure, you can create variables of that structure. In the above definition,
we have defined a structure using the keyword struct followed by the name of the structure
(employee). All the data items that needs to be defined are defined by specifying the datatype
and name of the variable. Once the definition is done, variables of type employee can be created.
For example, the following statement creates a variable e1 of type employee.

employee e1;
Structure variables can be initialized during declaration. The values for all the members should
be specified separated by comma and all the values enclosed within flower brackets as shown
below

employee e1= {1234, “Ajay”, 12, 6900.00};

Structure variables can be copied and assigned to another structure variable as shown below

employee e2;

e2=e1;

To access the members of the structure variables, dot operators can be used. For example to
access empid of structure variable e1, you would say e1.empid (structure variable.
membervariable name).

Structures can be nested within each other. When accessing the members and submembers dot
operators can be used. Let us suppose you have defined a structure named distance with two
members length and width as declared below:

struct distance

{ int feet;

int inches;

}

Let us define now a structure named room which contains variables of type distance

struct room

{ distance length;

distance width;

distance height;

} bedroom;

In the above definition, we have declared a variable bedroom of type room along with the
definition.

To access the members of the bedroom we can use

bedroom.length.feet
bedroom.length.inches

bedroom.width.feet

bedroom.width.inches and so on

To initialize nested structures you have to group together all the elements of the structure

room dining = {{12, 3},{13,0},{11,2}}

In the above declaration, the values 12 and 3 refer to dining.length.feet and dining.length.inches
repectively. Similarly the second and third set of values represent feet and inches of width and
height respectively.

Array of structures can be created. The index number should be specified immediately after the
structure variable. For example, the statement

employee emp[50] ;

will create a array of structure employee.

To access the first array member, you can say emp[0].empid

The following program implements a structure point with x and y co-ordinates.

#include<iostream.h>

#include<conio.h>

# include<math.h>

struct point

{ int x,y;

} p1,p2;

void main()

{

int s;

cout<< “Enter the co-ordinates for first co-ordinate” ;

cin>> p1.x>>p1.y;
cout<<”enter the co-ordinates for second co-ordinate”;

cin>>p2.x>>p2.y;

s=sqrt(((p2.y-p1.y)*(p2.y-p1.y))+((p2.x-p1.x)*(p2.x-p1.x))) ;

cout<<endl<<”the distance between the two points is”<<s;

getch();

}

In the above program we have defined a structure point which stores x and y co-ordinates of the
point. Along with the declaration we have also created two point variables p1 and p2. This is a
way to create variables along with the structure decalaration. This can be a separate statement
also as discussed earlier. The program accepts two points from the user and displays the distance
between them.

Structures are good mechanism of creating userdefined datatypes. C++ specifies another method
known as enumerated data type to enable users create their own datatypes. Enumerated data
types can store fixed set of values and you can perform arithmetic on them as well. They are
defined using the keyword enum. The following program creates an enumerated datatype which
stores different days of the week.

//enumerated.cpp

#include <iostream.h>

enum weekday {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

void main ( )

{ weekday day1,day2;

day1=Mon;

day2= Fri;

int diff=day2-day1;

cout<<”days between =”<<diff;

if (day1<day2)

cout<<”day1 comes before day2”;
}

In the above program enumerated datatype weekday is created. The first value (Sun) is assigned
zero by default and so on. The variables day1 and day2 can be assigned only the values specified
in the datatype declaration or their integer equivalent. They cannot be assigned any other value.

Self Assessment Questions

1. Structures group data of similar type. True/False

2. ___________ keyword is used to create structures.

3. Member data of the structure are accessed by ________ operator


BC0037-4.6 Summary
Summary

Functions provide good mechanism to organize data. Functions are given a name which can be
used to call the function and execute the statements in the functions. Functions can also take
input which are known as arguments which passed during function call. Arguments can be
passed either by value or by reference. They can also have return value which can return an
computed value back to the main program. Inline functions enable programmers to save
processing time by reducing the overheads involved in function call.

Programs can make use of automatic, external and static variables which have different types of
utility depending on the way the variable should be accessed and whether the value has to be
retained.

Structures and enumerated data types enable to users to create user defined datatypes. Structure
group data items that have different datatypes. Enumerated datatypes create datatypes that can
store pre-defined and fixed set of values


BC0037-5.1 Introduction
Introduction

This unit has the following objectives

· To understand what are classes and Objects and learn to implement them

· To learn to use constructors and destructors in a class

· To understand static variables and functions with respect to a class
BC0037-5.2 Creating classes and objects
Creating classes and objects

In the unit 1, we had a brief discussion of objects and classes. In this section, we will see how we
can implement them. Classes provide users a method to create user defined datatypes. We have
seen two types of user defined datatypes structures and enumeration in the last unit. Both are
primarily used for modeling data only. In several real life situation, you would require to model
functionality of the datatype along with the data. Classes enable you to bind data and functions
that operate on data together. However, in C++ you can use structures same as classes by binding
functions with data. But usually the structures are only used when you want to group data and
classes when you want to group both data and functions.

Classes can model either physical or real things such as employee, product, customer etc or it can
model a new datatype such user defined string, distance, etc.

Objects has the same relationship to a class that a variable has to a datatype. Object is an instance
of a class. Class is a definition, objects are used in the program that enables you to store data and
use them.

To understand the various syntactical requirements for implementing a class, let us take an
example.

// distance.cpp

#include<iostream.h>

class distance

{ private:

int feet;

int inches;

public:

void setdistance(int a, int b)

{ feet=a;

inches=b;

}
void display()

{ cout<<feet<<”ft”<<inches<<”inches;}

};

void main()

{ distance d1;

d1. setdistance(10, 2);

d1.display();

}

In the above program, we have created a class called distance with two data members feet and
inches and two functions or methods setdistance and display (). Classes are defined with the
keyword class followed by the name of the class. The object of this class is d1. Every objects of
a class have their own copy of data, but all the objects of a class share the functions. No separate
copy of the methods is created for each and every object. Objects can access the data through the
methods. To invloke a method, objectname.methodname is used. The methods defined in the
class can only be invoked by the objects of the class. Without an object, methods of the function
cannot be invoked.

You can see in the above program, the data elements feet and inches are defined as private. The
methods are defined as public. These are known as access specifiers. Data and functions in a
class can have any one access specifiers: private, public and protected. Protected access specifier
we will discuss later in unit 7 along with inheritance. Private data and functions can be accessed
only by the member functions of the class. None of the external functions can access the private
data and member functions. Public data and member functions can be accessed through the
objects of the class externally from any function. However to access these data and functions,
you need to have an object of that class. This feature of object oriented programming is
sometimes referred to as data hiding. The data is hidden from accidently getting modified by an
unknown function. Only a fixed set of functions can access the data. In a class, the data and
functions are private by default so private keyword can be omitted.




Fig. 5.1: Access specifiers in a class
Certain object oriented programming languages refer to methods as messages. Thus d1.display()
is a message to d1 to display itself

Usually, data are declared as private and functions as public. However, in certain case you may
even declare private functions and public data.

Please note that the class definition has a semicolon in the end.

Array of objects can also be created. It is similar to array of structures.

distance d[10]; creates a array of objects of type distance. If the first distance object accesses the
member function display you can use d[0].display()

Let us see how we can perform operations on the objects data. We will see a program which
implements an add member function to the distance class. We can do this in two ways. The
prototypes of the function is shown below:

void add(distance, distance);

or

distance add(distance);

The first function takes two distance objects as arguments and stores the result in the object
invoking the member function. It can be implemented as follows:

//adddist1.cpp

#include<iostream.h>

class distance

{ private:

int feet;

int inches;

public:

void setdistance(int a, int b)

{ feet=a;

inches=b;
}

void display()

{ cout<<feet<<”ft”<<inches<<”inches;}

void add(distance dist1, dist2)

{ feet=dist1.feet+dist2.feet;

inches=dist1.inches+dist2.inches;

if (inches>12)

{ feet++;

inches=inches-12;

}

}

};

void main()

{ distance d1,d2,d3;

d1. setdistance(10, 2);

d2.setdistance(2,4);

d3.add(d1,d2);

d3.display();

}

In the above program, object d3 invokes the add function so the feet and inches refers the
invoking object’s data members. After adding the respective data of d1 and d2 it is stored in d3
object.

Alternatively, the above program can be implemented in a different way as shown below

//adddist2.cpp
#include<iostream.h>

class distance

{ private:

int feet;

int inches;

public:

void setdistance(int a, int b)

{ feet=a;

inches=b;

}

void display()

{ cout<<feet<<”ft”<<inches<<”inches;}

distance add(distance dist)

{ distance temp;

temp.feet=dist.feet+feet;

temp.inches=dist.inches+inches;

if (temp.inches>12)

{ temp.feet++;

temp.inches=temp.inches-12;

}

return temp;

}

};
void main()

{ distance d1,d2,d3;

d1. setdistance(10, 2);

d2.setdistance(2,4);

d3 =d1.add(d2);

d3.display();

}

In the above program, we have implemented the add function which is invoked by d1 object and
d2 is passed as an argument. Since the calling objects data are passed automatically, d1 objects
data members can be accessed in the function. They are referred directly as feet and inches
without the objectname (as it is implicit in the member function). The add function stores the
summed value in a temporary variable and then returns it to the calling program.

Self Assessment Questions

1. Private data members can be accessed only by the __________ of the class

2. Public data members can be accessed directly in the main function without an object.
True/False

3. Every object of a class has its own copy of the data and functions. True/False


BC0037-5.3 Constructors and Destructors
Constructors and Destructors

Constructors and destructors are very important components of a class. Constructors are member
functions of a class which have same name as the class name. Constructors are called
automatically whenever an object of the class is created. This feature makes it very useful to
initialize the class data members whenever a new object is created. It also can perform any other
function that needs to be performed for all the objects of the class without explicitly specifying
it.

Destructors on the other hand are also member functions with the same name as class but are
prefixed with tilde (~) sign to differentiate it from the constructor. They are invoked
automatically whenever the object’s life expires or it is destroyed. It can be used to return the
memory back to the operating system if the memory was dynamically allocated. We will see
dynamic allocation of memory in Unit 7 while discussing pointers.
The following program implements the constructor and destructors for a class

// constdest.cpp

# include<iostream.h>

class sample

{ private:

int data;

public:

sample() {data=0; cout<<”Constructor invoked”<<endl;}

~sample() {cout<<”Destructor invoked”;}

void display()

{ cout<<”Data=”<<data<<endl;}

};

void main()

{ sample obj1;

obj.display();

}

If you run the above program you will get the output as follows:

Constructor invoked

Data=0

Destructor invoked

When object of sample class, obj is created, automatically the constructor is invoked and data is
initialized to zero. When the program ends the object is destroyed which invokes the destructor.
Please note that both the constructor and destructor is declared as public and they have no return
value. However, constructors can have arguments and can be overloaded so that different
constructors can be called depending upon the arguments that is passed. Destructors on the other
hand cannot be overloaded and cannot have any arguments. The following program implements
the overloaded constructors for the distance class.

//overloadconst.cpp

#include<iostream.h>

class distance

{ private:

int feet;

int inches;

public:

distance()

{ feet=0;

inches=0;}

distance(int f, int i)

{ feet=f;

inches=i;}

void display()

{ cout<<feet<<”ft”<<inches<<”inches;}

};

void main()

{ distance d1, d2(10,2);

d1.display();

d2.display()

}
In the above program, the setdistance function is replaced with the two constructors. These are
automatically invoked. When object d1 is created the first constructor distance() is invoked.
When object d2 is created the second constructor distance (int f, int i) is invoked as two
arguments are passed. Please note that to invoke a constructor with arguments, argument values
have to be passed along with the object name during declaration.

Self Assessment Questions

1. Constructors are member functions of the class which is invoked when ________ is created.

2. Destructors have same name as a class but are prefixed with ________ sign

3. Destructors can be overloaded. True/False

4. Constructors can be overloaded. True/False


BC0037-5.4 Static variables and Functions in
class
Static variables and Functions in class

We have seen that when an object is created, a separate copy of data members is created for each
and every object. But static data member in a class is an exception. Static data member of the
class is one data member that is common for all the objects of the class and are accessible for the
class. It is useful to store information like count of number of objects created for a particular
class or any other common data about the class. Static data member is declared by prefixing the
keyword static.

We have learnt that to invoke a member function of a class, you need to have object. Suppose we
have a static data member which keeps track of the total objects created and there is a showtotal
function which displays the total value. We will not be able to know the total if there are no
objects which is a serious limitation. Static functions are the solution for this. Static functions are
special type of functions which can be invoked even without an object of the class. Static
functions are also defined by prefixing the keyword static. It is called using classname followed
by scope resolution operator and function name. The following program implements the static
data and functions

//classstatic.cpp

# include <iostream.h>

class A {

static int total;
int id;

public:

A()

{ total++;

id=total;

}

~A()

{ total–;

cout<<”n destroying ID number=”<<id;

}

static void showtotal()

{cout<<”endl “<<total;}

void showid()

{cout<<”endl “<<id;}

};

int A::total=0;

void main()

{

A::showtotal();

A a1,a2;

A::showtotal();

a1.showid();

a2.showid();
}

The output of the above program

0

2

1

2

In the above program total is an static variable which is shared by all objects of the class A. The
static variables of the class have to be explicitly initialised outside the class using the class name
followed by scope resolution operator (::) and static variable name.

Please note that you have to specify the datatype but need not specify the keyword static during
initialization. The variable total is incremented in the constructor which will increment the total
whenever a new object is created. Similarly, it is decremented through the destructor when the
object is destroyed. The function showtotal is a static function which is invoked without the
object and using the classname.

The fig 5.2 summarises member functions and data of a class




Fig. 5.2: Data and Functions in a class

Self Assessment Questions

1. Static data member of a class can be modified by all objects of the class. True/False

2. Static functions are accessed using __________

3. Static data need not be initialized. True/False


BC0037-5.5-Summary
Summary

Class enable user to create user-defined datatypes and define their functionality. Objects are
instances of classes. Class can contain both data and functions. Class data can be initialized using
constructors which are invoked when the objects of a class are created. Destructors are member
functions which are invoked when the objects are destroyed. Member functions can be accessed
only through the objects of the class. Static functions can be accessed without objects. Static data
can be accessed by all the objects of the class and only one copy of this data is maintained.


BC0037-6.1 Introduction
Introduction

This unit has the following objectives

· To learn how C++ supports operator overloading

· To learn to overload different types of unary and binary operators

· To understand limitations of operator overloading


BC0037-6.2 Operator Overloading in C++
Operator Overloading in C++

Operator overloading is an interesting feature of C++ that allows programmers to specify how
various arithmetic, relational and many other operators work with user defined datatypes or
classes. It provides a flexible way to work with classes and can make program code look
obvious. In the unit 5, we had written an add function for the class distance. To perform addition
of two distance objects we used a call d3.add(d1,d2). Instead of such statements it would be
more clear if we could use statements like d3=d1+d2. This is possible only if we inform compiler
about how + operator works with distance class. This is exactly what operator overloading
feature in C++ does. It helps to use the default operators with the user defined objects for making
the code simpler.

However there are several problems with operator overloading which you should be aware of.
When using operator overloading, the operator should perform only the most obvious function.
Otherwise it will lead to more confusion. If you are overloading + operator for distance class it
should add two distance objects, and should not do something else. However some syntactical
characteristics of operators cannot be changed even if you want to. For example, you cannot
overload a binary operator to be a unary operator and vice versa.

Several operators such as dot operator, scope resolution (::) operator, conditional operator (?:) etc
cannot be overloaded.
Therefore operator overloading should be used for a class where it is required to perform obvious
functions with the default operators and there can be no other meaning for the same.

Self Assessment Questions

1. Operator overloading feature helps to change the functionality of operators with any datatype.
True/False

2. You can overload all operators in C++. True/False

3. It is necessary to overload operators for all classes. True/False


BC0037-6.3 Overloading Unary Operators
Overloading Unary Operators

We have seen that unary operators are those operators which work on one operator. Some of the
unary operators are ++, –, and minus (-).

Operator overloading works similar to any member function of a class. But it is not invoked
using dot operator. Just like member function the operator has a return value and takes
arguments. It is invoked by the operand which uses it. In case of overloading of unary operators,
the calling operand can be either left or right of the operator like in case of increment and
decrement operators. While defining the operator functionality for the class the keyword operator
is used. Let us overload the increment operator for a class.

//unary.cpp

# include <iostream.h>

class counter

{ unsigned int count;

public:

counter()

{count=0;}

int getcount()

{return count;}

void operator ++()
{ count++;}

};

void main()

{ counter c1;

c1++;

++c1;

cout<<c1.getcount();

}

In the above example, the operator ++ is defined to return void and take no arguments. All unary
operators do not take no arguments as it operates on only one operand and that operand itself
invokes the operator. Therefore the operand is sent by default. However the above
implementation cannot be used in statements such as c2=c1++; where c1 and c2 are counter
variables. This is because the operator ++ returns void which makes an counter variable being
assigned void value. To overcome this, you can make the operator return an counter variable as
shown below

//incremnt.cpp

# include <iostream.h>

class counter

{ unsigned int count;

public:

counter()

{count=0;}

counter(int c)

{count=c;}

int getcount()

{return count;}
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123
C++123

Contenu connexe

En vedette

En vedette (9)

Result online june july 11
Result online june july 11Result online june july 11
Result online june july 11
 
Database design for HPC
Database design for HPCDatabase design for HPC
Database design for HPC
 
Maths
MathsMaths
Maths
 
Communication skill
Communication skillCommunication skill
Communication skill
 
Introduction to computers
Introduction to computersIntroduction to computers
Introduction to computers
 
Marketing
MarketingMarketing
Marketing
 
Communication skills in english
Communication skills in englishCommunication skills in english
Communication skills in english
 
Book
BookBook
Book
 
Book
BookBook
Book
 

Similaire à C++123

Programming in c
Programming in cProgramming in c
Programming in cedudivya
 
Lecture_01.1.pptx
Lecture_01.1.pptxLecture_01.1.pptx
Lecture_01.1.pptxRockyIslam5
 
Database management system
Database management systemDatabase management system
Database management systemedudivya
 
CIS_515_Week_3_Assignment352866 (1).docUniversity Database .docx
CIS_515_Week_3_Assignment352866 (1).docUniversity Database  .docxCIS_515_Week_3_Assignment352866 (1).docUniversity Database  .docx
CIS_515_Week_3_Assignment352866 (1).docUniversity Database .docxclarebernice
 
Personal Competence Development in Learning Networks
Personal Competence Development in Learning NetworksPersonal Competence Development in Learning Networks
Personal Competence Development in Learning Networkstelss09
 
Dr Daniel J Clouse Resume
Dr Daniel J Clouse ResumeDr Daniel J Clouse Resume
Dr Daniel J Clouse ResumeDaniel Clouse
 
Dr DanielJ Clouse resumeobf
Dr DanielJ Clouse resumeobfDr DanielJ Clouse resumeobf
Dr DanielJ Clouse resumeobfDaniel Clouse
 
Academic Innovation Data Showcase 2-14-19
Academic Innovation Data Showcase 2-14-19Academic Innovation Data Showcase 2-14-19
Academic Innovation Data Showcase 2-14-19umichiganai
 
Computer fundamentals & window based application
Computer fundamentals & window based applicationComputer fundamentals & window based application
Computer fundamentals & window based applicationedudivya
 
Operating systems
Operating systemsOperating systems
Operating systemsedudivya
 
Project Management Application Form (Fully Customizable Template)
Project Management Application Form (Fully Customizable Template)Project Management Application Form (Fully Customizable Template)
Project Management Application Form (Fully Customizable Template)MarjoToska
 
Data Structure Syllabus.pdf
Data Structure Syllabus.pdfData Structure Syllabus.pdf
Data Structure Syllabus.pdfMarvin158667
 
eLumen Educause Presentation on Competency-Based Approaches
eLumen Educause Presentation on Competency-Based ApproacheseLumen Educause Presentation on Competency-Based Approaches
eLumen Educause Presentation on Competency-Based ApproachesJoel Hernandez
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering conceptsKomal Singh
 
Computer fundamentals & window based application
Computer fundamentals & window based applicationComputer fundamentals & window based application
Computer fundamentals & window based applicationedudivya
 
Preliminry report
 Preliminry report Preliminry report
Preliminry reportJiten Ahuja
 

Similaire à C++123 (20)

Programming in c
Programming in cProgramming in c
Programming in c
 
Lecture_01.1.pptx
Lecture_01.1.pptxLecture_01.1.pptx
Lecture_01.1.pptx
 
Database management system
Database management systemDatabase management system
Database management system
 
CIS_515_Week_3_Assignment352866 (1).docUniversity Database .docx
CIS_515_Week_3_Assignment352866 (1).docUniversity Database  .docxCIS_515_Week_3_Assignment352866 (1).docUniversity Database  .docx
CIS_515_Week_3_Assignment352866 (1).docUniversity Database .docx
 
Personal Competence Development in Learning Networks
Personal Competence Development in Learning NetworksPersonal Competence Development in Learning Networks
Personal Competence Development in Learning Networks
 
ds_mod1.pdf
ds_mod1.pdfds_mod1.pdf
ds_mod1.pdf
 
Dr Daniel J Clouse Resume
Dr Daniel J Clouse ResumeDr Daniel J Clouse Resume
Dr Daniel J Clouse Resume
 
Dr DanielJ Clouse resumeobf
Dr DanielJ Clouse resumeobfDr DanielJ Clouse resumeobf
Dr DanielJ Clouse resumeobf
 
Academic Innovation Data Showcase 2-14-19
Academic Innovation Data Showcase 2-14-19Academic Innovation Data Showcase 2-14-19
Academic Innovation Data Showcase 2-14-19
 
Computer fundamentals & window based application
Computer fundamentals & window based applicationComputer fundamentals & window based application
Computer fundamentals & window based application
 
Digvijaysinh
DigvijaysinhDigvijaysinh
Digvijaysinh
 
Operating systems
Operating systemsOperating systems
Operating systems
 
Project Management Application Form (Fully Customizable Template)
Project Management Application Form (Fully Customizable Template)Project Management Application Form (Fully Customizable Template)
Project Management Application Form (Fully Customizable Template)
 
Data Structure Syllabus.pdf
Data Structure Syllabus.pdfData Structure Syllabus.pdf
Data Structure Syllabus.pdf
 
Lesson-1-2.pptx
Lesson-1-2.pptxLesson-1-2.pptx
Lesson-1-2.pptx
 
eLumen Educause Presentation on Competency-Based Approaches
eLumen Educause Presentation on Competency-Based ApproacheseLumen Educause Presentation on Competency-Based Approaches
eLumen Educause Presentation on Competency-Based Approaches
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering concepts
 
Computer fundamentals & window based application
Computer fundamentals & window based applicationComputer fundamentals & window based application
Computer fundamentals & window based application
 
Preliminry report
 Preliminry report Preliminry report
Preliminry report
 
MadhuMathi Kannan
MadhuMathi KannanMadhuMathi Kannan
MadhuMathi Kannan
 

Plus de edudivya

Database management system
Database management systemDatabase management system
Database management systemedudivya
 
Computer system and peripherals
Computer system and peripheralsComputer system and peripherals
Computer system and peripheralsedudivya
 
Operating system 1
Operating system 1Operating system 1
Operating system 1edudivya
 
Database management system
Database management systemDatabase management system
Database management systemedudivya
 
Computer system and peripherals
Computer system and peripheralsComputer system and peripherals
Computer system and peripheralsedudivya
 
Communication skills in english
Communication skills in englishCommunication skills in english
Communication skills in englishedudivya
 
Computer organisation nd architecture
Computer organisation nd architectureComputer organisation nd architecture
Computer organisation nd architectureedudivya
 
Managerial economics
Managerial economicsManagerial economics
Managerial economicsedudivya
 
Ksou need result june july exam session
Ksou need result june july exam sessionKsou need result june july exam session
Ksou need result june july exam sessionedudivya
 
Ksou need result june july exam session
Ksou need result june july exam sessionKsou need result june july exam session
Ksou need result june july exam sessionedudivya
 
Ksou examination datesheet jan 201
Ksou examination datesheet jan 201Ksou examination datesheet jan 201
Ksou examination datesheet jan 201edudivya
 
Principles & practices of management
Principles & practices of managementPrinciples & practices of management
Principles & practices of managementedudivya
 
Managerial economics
Managerial economicsManagerial economics
Managerial economicsedudivya
 

Plus de edudivya (16)

Book
BookBook
Book
 
Book
BookBook
Book
 
Database management system
Database management systemDatabase management system
Database management system
 
Computer system and peripherals
Computer system and peripheralsComputer system and peripherals
Computer system and peripherals
 
Operating system 1
Operating system 1Operating system 1
Operating system 1
 
Database management system
Database management systemDatabase management system
Database management system
 
Computer system and peripherals
Computer system and peripheralsComputer system and peripherals
Computer system and peripherals
 
Communication skills in english
Communication skills in englishCommunication skills in english
Communication skills in english
 
Computer organisation nd architecture
Computer organisation nd architectureComputer organisation nd architecture
Computer organisation nd architecture
 
Marketing
MarketingMarketing
Marketing
 
Managerial economics
Managerial economicsManagerial economics
Managerial economics
 
Ksou need result june july exam session
Ksou need result june july exam sessionKsou need result june july exam session
Ksou need result june july exam session
 
Ksou need result june july exam session
Ksou need result june july exam sessionKsou need result june july exam session
Ksou need result june july exam session
 
Ksou examination datesheet jan 201
Ksou examination datesheet jan 201Ksou examination datesheet jan 201
Ksou examination datesheet jan 201
 
Principles & practices of management
Principles & practices of managementPrinciples & practices of management
Principles & practices of management
 
Managerial economics
Managerial economicsManagerial economics
Managerial economics
 

Dernier

Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 

Dernier (20)

Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

C++123

  • 1. E-528-529, sector-7, Dwarka, New delhi-110075 (Nr. Ramphal chowk and Sector 9 metro station) Ph. 011-47350606, (M) 7838010301-04 www.eduproz.in Educate Anytime...Anywhere... "Greetings For The Day" About Eduproz We, at EduProz, started our voyage with a dream of making higher education available for everyone. Since its inception, EduProz has been working as a stepping-stone for the students coming from varied backgrounds. The best part is – the classroom for distance learning or correspondence courses for both management (MBA and BBA) and Information Technology (MCA and BCA) streams are free of cost. Experienced faculty-members, a state-of-the-art infrastructure and a congenial environment for learning - are the few things that we offer to our students. Our panel of industrial experts, coming from various industrial domains, lead students not only to secure good marks in examination, but also to get an edge over others in their professional lives. Our study materials are sufficient to keep students abreast of the present nuances of the industry. In addition, we give importance to regular tests and sessions to evaluate our students’ progress. Students can attend regular classes of distance learning MBA, BBA, MCA and BCA courses at EduProz without paying anything extra. Our centrally air-conditioned classrooms, well-maintained library and well-equipped laboratory facilities provide a comfortable environment for learning. Honing specific skills is inevitable to get success in an interview. Keeping this in mind, EduProz has a career counselling and career development cell where we help student to prepare for interviews. Our dedicated placement cell has been helping students to land in their dream jobs on completion of the course. EduProz is strategically located in Dwarka, West Delhi (walking distance from Dwarka Sector 9 Metro Station and 4- minutes drive from the national highway); students can easily come to our centre from anywhere Delhi and neighbouring Gurgaon, Haryana and avail of a quality-oriented education facility at apparently no extra cost. Why Choose Edu Proz for distance learning?
  • 2. Edu Proz provides class room facilities free of cost. • In EduProz Class room teaching is conducted through experienced faculty. • Class rooms are spacious fully air-conditioned ensuring comfortable ambience. • Course free is not wearily expensive. • Placement assistance and student counseling facilities. • Edu Proz unlike several other distance learning courses strives to help and motivate pupils to get high grades thus ensuring that they are well placed in life. • Students are groomed and prepared to face interview boards. • Mock tests, unit tests and examinations are held to evaluate progress. • Special care is taken in the personality development department. "HAVE A GOOD DAY" Karnataka State Open University (KSOU) was established on 1st June 1996 with the assent of H.E. Governor of Karnataka as a full fledged University in the academic year 1996 vide Government notification No/EDI/UOV/dated 12th February 1996 (Karnataka State Open University Act – 1992). The act was promulgated with the object to incorporate an Open University at the State level for the introduction and promotion of Open University and Distance Education systems in the education pattern of the State and the country for the Co-ordination and determination of standard of such systems. Keeping in view the educational needs of our country, in general, and state in particular the policies and programmes have been geared to cater to the needy. Karnataka State Open University is a UGC recognised University of Distance Education Council (DEC), New Delhi, regular member of the Association of Indian Universities (AIU), Delhi, permanent member of Association of Commonwealth Universities (ACU), London, UK, Asian Association of Open Universities (AAOU), Beijing, China, and also has association with Commonwealth of Learning (COL). Karnataka State Open University is situated at the North–Western end of the Manasagangotri campus, Mysore. The campus, which is about 5 kms, from the city centre, has a serene atmosphere ideally suited for academic pursuits. The University houses at present the Administrative Office, Academic Block, Lecture Halls, a well-equipped Library, Guest House
  • 3. Cottages, a Moderate Canteen, Girls Hostel and a few cottages providing limited accommodation to students coming to Mysore for attending the Contact Programmes or Term- end examinations. BC0037-1.1 Introduction Introduction This unit has the following objectives · To understand the importance of object oriented programming approach over procedural languages · To learn the basic features supported by OOP languages · To learn the basic construct of a C++ program and learn to compile and execute it BC0037-1.2 Evolution of Programming methodologies Evolution of Programming methodologies The programming languages have evolved from machine languages, assembly languages to high level languages to the current age of programming tools. While machine level language and assembly language was difficult to learn for a layman, high level languages like C, Basic, Fortran and the like was easy to learn with more English like keywords. These languages were also known as procedural languages as each and every statement in the program had to be specified to instruct the computer to do a specific job. The procedural languages focused on organizing program statements into procedures or functions. Larger programs were either broken into functions or modules which had defined purpose and interface to other functions. Procedural approach for programming had several problems as the size of the softwares grew larger and larger. One of the main problems was data being completely forgotten. The emphasis was on the action and the data was only used in the entire process. Data in the program was created by variables and if more than one functions had to access data, global variables were used. The concept of global variables itself is a problem as it may be accidentally modified by an undesired function. This also leads to difficulty in debugging and modifying the program when several functions access a particular data.
  • 4. The object oriented approach overcomes this problem by modeling data and functions together there by allowing only certain functions to access the required data. The procedural languages had limitations of extensibility as there was limited support for creating user defined datatypes and defining how these datatypes will be handled. For example if the programmer had to define his own version of string and define how this new datatype will be manipulated, it would be difficult. The object oriented programming provides this flexibility through the concept of class. Another limitation of the procedural languages is that the program model is not closer to real world objects . For example, if you want to develop a gaming application of car race, what data would you use and what functions you would require is difficult questions to answer in a procedural approach. The object oriented approach solves this further by conceptualizing the problem as group of objects which have their own specific data and functionality. In the car game example, we would create several objects such as player, car, traffic signal and so on. Some of the languages that use object oriented programming approach are C++, Java, Csharp, Smalltalk etc. We will be learning C++ in this text to understand object oriented programming. C++ is a superset of C. Several features are similar in C and C++. Self Assessment Questions 1. List the limitations of procedural languages 2. _______ is an OOP Language 3. In OOP approach programmers can create their own data types. True/False 4. In procedural languages, the programs are written by dividing the programs into smaller units known as __________ BC0037-1.3 Introduction to OOP and its basic features Introduction to OOP and its basic features As discussed earlier, one of the basic concept in Object Oriented Programming approach is bundling both data and functions into one unit known as object. The functions of a particular object can only access the data in the object providing high level of security for the data. The functions in the object are known as member functions or sometimes as methods. The key features of OOP programming languages are: • Objects and Classes
  • 5. An Object is a program representation of some real-world thing (i.e person, place or an event). Objects can have both attributes(data) and behaviours (functions or methods). Attributes describe the object with respect to certain parameters and Behaviour or functions describe the functionality of the object. Table 1.1 Example of Objects Polygon Object Bank Account Behaviour Attributes Behaviour Attributes Deduct Funds Move Position Account number Transferfunds Erase Fill Color Balance DepositFunds Changecolor Border color Showbalance According to Pressman, Objects can be any one of the following: a) External entities b) Things c) Occurrences or events d) Roles e) Organisational units f) Places g) Data Structures For example, objects can be an menu or button in an graphic user interface program or it may be an employee in an payroll application. Objects can also represent a data structure such as a stack or a linked list. It may be a server or a client in an networking environment. Objects with the same data structure and behavior are grouped together as class. In other words, Objects are “instances” of a class. Classes are templates that provide definition to the objects of similar type. Objects are like variables created whenever necessary in the program. For example, Employee may be a class and Pawan, Sujay and Ganesh are objects of the class employees. Just as you can create as many variables of a default datatype such as integer, you can create as many objects of a class. Classes and Objects support data encapsulation and data hiding which are key terms describing object oriented programming languages. Data and functions are said to be encapsulated in an single entity as object. The data is said to be hidden thus not allowing accidental modification.
  • 6. Inheritance Inheritance is one of the most powerful feature of Object Oriented Programming Languages that allows you to derive a class from an existing class and inherit all the characteristics and behaviour of the parent class. This feature allows easy modification of existing code and also reuse code. The ability to reuse components of a program is an important feature for any programming language • Polymorphism and Overloading Operator overloading feature allows users to define how basic operators work with objects. The operator + will be adding two numbers when used with integer variables. However when used with user defined string class, + operator may concatenate two strings. Similarly same functions with same function name can perform different actions depending upon which object calls the function. This feature of C++ where same operators or functions behave differently depending upon what they are operating on is called as polymorphism (Same thing with different forms). Operator overloading is a kind of polymorphism. OOP approach offers several advantages to the programmers such as • Code can be reused in situations requiring customization o Program modeling and development closer to real world situations and objects • Easy to modify code o Only required data binded to operations thus hiding data from unrelated functions Self Assessment Questions 1. _____________ feature in OOP allows to reuse code. 2. The concept of bundling data and functions into single unit is termed as ___________ 3. Object is an __________ of a class 4. Give an example of a class and an object 5. ______________ is an advantage of OOP approach BC0037-1.4 Basic components of a C++ Program and program structure 1.4 Basic components of a C++ Program and program structure
  • 7. The C++ is a superset of C. At the basic level, the programs look similar in both C and C++. Every statement in C++ ends with a semicolon (;). All the reserved words have to be written in small case and the c++ compiler is case sensitive. Data in programming languages are stored in variables. To create a variable, the variable should support an inbuilt datatype. The variable is a name given to a particular location in the memory and the value stored in a variable can be altered during program execution. The datatypes supported in C++ are listed below Table 1.2 Basic Datatypes in c++ Data Type Size (in bytes) Values that can be taken Int 2 -32768 to 32767 Bool 1 False and true / 0 and 1 Char 1 -128 to 127 Long 4 -2,147,483,648 to 2,147,483,647 Float 4 3.4 X 10-38 to 3.4 X 1038 (Precision 7) Double 8 1.7 X 10-308 to 1.7 X 10308 (Precision 15) Long double 10 3.4 X 10-4932 to 1.1 X 104932 (Precision 19) Unsigned int 2 0 to 65,535 Variables can be named according to following rules • Can comprise of 1 to 8 alphabets, digits or underscore • First character should be an alphabet • Names are case sensitive • Reserve words of c++ cannot be used Variables have to be declared before using them in the program. The declaration is done in the following way: datatype variablename Eg: int data ; The above declaration declares a integer variable named data. The value stored in int data by default is a junk value. Values can also be assigned to the variable during declarations or initialized separately using the assignment operator =. Eg: int data=0; Or int data; data=0;
  • 8. Constants are those which do not change during execution of a program. The constants in C++ can be numeric, character or string constants. Examples of each are shown in table 1.3 Table 1.3 Example of Constants Constant Example Constraints 23000 Numeric Can be negative or positive, cannot contain blanks or Constant 450.6 (Floating commas, or $ point) Character Any character enclosed within single quotes, represented by ‘A’ Constant unique ASCII number in the memory String Set of characters enclosed in double quotes, last character in “Hello” Constant the string is null character ‘0′ Operators supported in C++ are listed below. Unary operators are used with one operand and binary operator is used with two operands. Table 1.4 Operators in C++ Arithmetic Operators Type Action - Unary as well as binary Subtraction for binary and minus for unary + Binary Addition * Binary Multiplication / Binary Division % Binary Modulus (remainder after dividing) – Unary Decrement value by one ++ Unary Increment value by one Relational Operators Type Action > Binary Greater than >= Binary Greater than or equal < Binary Less than <= Binary Less than equal == Binary Comparision for equality != Binary Comparision for inequality Logical Operators Type Action && Binary AND || Binary OR ! Unary NOT Lets begin with a simple c++ program // sum.cpp
  • 9. #include<iostream.h> void main() { int a,b,sum; cout<<”Please enter any two numbers”<<endl; cin>>a>>b; sum=a+b; cout<<”Sum of two numbers is “<<sum; } The above program asks the user to enter two numbers and displays the sum of the two numbers. Iostream.h is a header file. The first statement of the above program is required if you would like to include the cin and cout statements which is used for standard input or input from keyboard and standard output or output to display screen. cin and cout are actually predefined objects in C++. Iostream.h file contains the declarations for using the cin and cout statements. There are several such header files which have to be included depending on the functions you are using. We will come across many such header files as we progress. Every C++ program should have a main() function. C++ allows you to create your own functions in the program, like C. However the program execution always begins with the master function main(). Paranthesis are used to group statements belonging to one function or program statement. Every opening parathesis ({ ) should have a matching closing parathesis ( }). The third statement declares three integer variables a, b and sum. The fourth statement displays “Please enter any two numbers” on the display screen using cout statement. Cout (pronounced as C out) uses << or insertion operator to push data to the output stream. Operators known as manipulators can be used along with the << operator to modify the way data is displayed. Endl is an operator which is similar to ‘n’ character in C that inserts a linefeed into the output. The first cout statement in the program displays a statement where as the second cout statement displays a statement and the value stored in the variable sum. Cin (pronounced as c in) statement uses >> or extraction operator to feed the data to the input stream. The above cin statement waits for user to enter two integers. The values entered by the user is then stored in the variables a and b. Each variable in cin statement should separated by >> operator.
  • 10. Comment statements can be included in the program by prefixing the statement with “//” for single line comments. Comments add clarity to the program. Multiple line comments can be added by enclosing the statements between /* and */. Self Assessment Questions 1. ______________ is a header file used in c++ that handles input and output functions. 2. ____________ statement is used to input data from the user in c++. 3. ______________ statement is used to display data on the display screen in c++. 4. ______________ is a master function required in all C++ program and program execution begins from the first statement of this function. BC0037-1.5 Compiling and Executing C++ Program Compiling and Executing C++ Program 1. There are three steps in executing a c++ program: Compiling, Linking and Running the program. The c++ programs have to be typed in a compiler. All the programs discussed in the book will be compiled on turbo c++ compiler. The turbo c++ compiler comes with an editor to type and edit c++ program. After typing the program the file is saved with an extension .cpp. This is known as source code. The source code has to be converted to an object code which is understandable by the machine. This process is known as compiling the program. You can compile your program by selecting compile from compile menu or press Alt+f9. After compiling a file with the same name as source code file but with extension .obj. is created. Second step is linking the program which creates an executable file .exe (filename same as source code) after linking the object code and the library files (cs.lib) required for the program. In a simple program, linking process may involve one object file and one library file. However in a project, there may be several smaller programs. The object codes of these programs and the library files are linked to create a single executable file. Third and the last step is running the executable file where the statements in the program will be executed one by one. Fig 1.1 shows the entire process. When you execute the program, the compiler displays the output of the program and comes back to the program editor. To view the output and wait for user to press any key to return to the editor, type getch() as the last statement in the program. Getch() is an inbuilt predefined library function which inputs a character from the user through standard input. However you should include another header file named conio.h to use this function. Conio.h contains the necessary declarations for using this function. The include statement will be similar to iostream.h.
  • 11. Fig. 1.1: Compiling and Linking During compilation, if there are any errors that will be listing by the compiler. The errors may be any one of the following 1. Syntax error This error occurs due to mistake in writing the syntax of a c++ statement or wrong use of reserved words, improper variable names, using variables without declaration etc. Examples are : missing semi colon or paranthesis, type integer for int datatype etc. Appropriate error message and the statement number will be displayed. You can see the statement and make correction to the program file, save and recompile it. 2. Logical error This error occurs due to the flaw in the logic. This will not be identified by the compiler. However it can be traced using the debug tool in the editor. First identify the variable which you suspect creating the error and add them to watch list by selecting Debug ->Watches->Add watch. Write the variable name in the watch expression. After adding all the variables required to the watch list, go to the statement from where you want to observe. If you are not sure, you can go to the first statement of the program. Then select Debug ->Toggle Breakpoint (or press ctrl + f8). A red line will appear on the statement. Then Run the program by selecting Ctrl + f9 or Run option from run menu. The execution will halt at the statement where you had added the breakpoint. The watch variables and their values at that point of time will be displayed in the bottom in the watch window. Press F8 to execute the next statement till you reach the end of the program. In this way you can watch closely the values in the watch variables after execution of each and every statement in the program. If you want to exit before execution of the last statement press Ctrl + Break. To remove the breakpoint in the program go to the statement where you have added breakpoint select Debug ->Toggle Breakpoint (or press ctrl + f8). Select Debug -> watch - >remove watches to remove the variables in the watch list. This tool helps in knowing the values taken by the variable at each and every step. You can compare the expected value with the actual value to identify the error. 3. Linker error This error occur when the files during linking are missing or mispelt 4. Runtime error
  • 12. This error occurs if the programs encounters division by zero, accessing a null pointer etc during execution of the program Self Assessment Questions 1. ___________, ______________ and _____________ are phases in execution of a C++ program 2. The logical error is identified by the compiler. True/False 3. ________________ is the extension of C++ program source files 4. ________________ is the extension of C++ object code BC0037-1.6 Summary Summary Object oriented Programming enables storing data and functions together which enables hiding data from unnecessary exposure. Procedural languages differs from the Object oriented programming in the approach used in solving the problem. While the former focuses on organizing programs around functions, the later focuses organizing programs around classes. Classes allow users to define their own datatypes and functionality. This allows extension of the basic datatypes supported by the language. Reusability of code through inheritance allows users to use the existing code without modifying it but also extend the functionality of the existing code. The C++ programs are similar to C except for the object oriented programming features. Every C++ program has a main function from where the execution starts. C++ programs goes through two phases ie compiling and linking before execution. BC0037-2.1 Introduction Introduction This unit has the following objectives · To learn to use selection control statements in C++ · To learn to use loops or iteration in C++ · To implement programs using relational, logical, increment and decrement operators in C++
  • 13. BC0037-2.2 Selection control statements in C++ Selection control statements in C++ There are basically two types of control statements in c++ which allows the programmer to modify the regular sequential execution of statements.They are selection and iteration statements. The selection statements allow to choose a set of statements for execution depending on a condition. If statement and switch statement are two statements which allow selection in c++. There is also an operator known as conditional operator which enables selection. If statement Syntax : if (expression or condition) { statement 1; statement 2; } else { statement 3; statement 4; } The expression or condition is any expression built using relational operators which either yields true or false condition. If no relational operators are used for comparison, then the expression will be evaluated and zero is taken as false and non zero value is taken as true. If the condition is true, statement1 and statement2 is executed otherwise statement 3 and statement 4 is executed. Else part in the if statement is optional. If there is no else part, then the next statement after the if statement is exceuted, if the condition is false. If there is only one statement to be executed in the if part or in the else part, braces can be omitted. Following example program implements the if statement. // evenodd.cpp # include <iostream.h> # include <conio.h>
  • 14. void main() { int num; cout<<”Please enter a number”<<endl; cin>>num; if ((num%2) == 0) cout<<num <<” is a even number”; else cout<<num <<” is a odd number”; getch(); } The above program accepts a number from the user and divides it by 2 and if the remainder (remainder is obtained by modulus operator) is zero, it displays the number is even, otherwise as odd. We make use of the relational operator == to compare whether remainder is equal to zero or not. Nested If statement If statement can be nested in another if statement to check multiple conditions. If (condition1) { if (condition 2) { statement1; Statement2; } else if (condition3) {statement3; }
  • 15. } else statement4; The flowchart of the above example is shown below Fig. 2.1: Nested If Statement Multiple conditions can be checked using logical && operator(AND) and || operator (OR). If ((condition1) && (condition2)) statement1; else statement2; In the above example statement1 will be executed if both the condition1 and condition2 are true and in all other cases statement2 will be executed. If ((condition1 || (condition2)) statement1; else statement2; In the above example statement1 will be executed if either condition1 or condition2 are true and even if both are true. Statement2 will be executed if both the conditions are false. The following program demonstrates the use of && operator and nested if statement.
  • 16. //Large.cpp # include <iostream.h> void main() { int a,b,c; cout<<”Please enter three numbers”; cin>>a>>b>>c; if ((a>b) && (b>c)) cout<<a<< “ is the largest number”; else if ((b>a) && (b>c)) cout<<b<< “ is the largest number”; else if ((c>a) && (c>b)) cout<<c<< “ is the largest number”; } The above program accepts three numbers from the user and displays which is the largest number among the three.( assumption is that all the numbers are unique, the program has to be modified if you would like to allow same number twice) Switch statement Nested ifs can be confusing if the if statement is deeply nested. One alternative to nested if is the switch statement which can be used to increase clarity in case of checking the different values of the same variable and execute statements accordingly. Syntax : Switch (variablename) { case value1: statement1; break; case value2: statement2;
  • 17. break; case value3: statement3; break; default: statement4; } If the variable in the switch statement is equal to value1 then statement1 is executed, if it is equal to value2 then statement2 is executed, if it is value3 then statement3 is executed. If the variable value is not in any of the cases listed then the default case statement or statement4 is executed. The default case specification is optional, however keeping it is a good practice. It can also be used for displaying any error message. Each case can have any number of statements. However every case should have a break statement as the last statement. Break statement takes the control out of the switch statement. The absence of the break statement can cause execution of statements in the next case. No break is necessary for the last case. In the above example, default case does not contain a break statement. The flowchart for the switch statement is shown in Fig 2.2 Fig. 2.2: Switch Statement The following program implements the switch statement position.cpp # include<iostream.h> void main()
  • 18. { char pos; int x=15, y=15; cout << “ you are currently located at” <<x<<” “<<y<<endl; cout>>”please choose the letter to move l for left, r for right, u for up and d for down” <<endl; cin>>pos; switch (pos) { case ‘l’: x–; break; case ‘r’: x++; break; case ‘u’: y++; break; case ‘d’: y–; break; default: cout<<”You selected a wrong option”; } cout<<“ you are now located at” <<x<<” “<<y; } The above program asks the user to enter l,r,u,d for allowing him to move left,right,up and down respectively. The position is initialised to 15 and 15 which are x and y coordinates of his position. Depending upon the what user has selected the the x and y co-ordinates are incremented or decremented by one(x++ is same as x=x+1). If the user types a letter other than l,r,u,d, he gets an error message. Since the switch variable is a character, l,u,r,d and enclosed within single quote. ++ and — operator can be used as postfix or as prefix operator which has no effect if used as an independent statement. However if it used as part of an expression, the prefix operator will be
  • 19. operated and then the expression will be evaluated whereas the postfix operated will be evaluated later. For example in the statement x= a+ (b++), a will be added to b and then stored in x and then the value of b will be incremented. If the same expression is written as x=a+(++b), the the b will be incremented and then added to a and stored in x. Conditional Operator Conditional operator (?:) is a handy operator which acts like a shortcut for if else statement. If you had to compare two variables a and b and then depending on which is larger, you wanted to store that variable in another variable called large. You would do this using if else statement in the following way: if (a>b) large=a; else large=b; The above can be done using conditional operator in the following way: large= (a>b) ? a : b ; Self Assessment Questions 1. In if else statement, at any point of time statements in both the if and else part may be executed. True/False 2. Conditional operator is an alternative to __________ statement 3. ++ operator increments the value of the operand by _________ 4. The ++ operator used as postfix and prefix has the same effect. True or False 5. Each case in switch statement should end with _________ statement BC0037-2.3 Iteration statements in C++ Iteration statements in C++
  • 20. Iteration or loops are important statements in c++ which helps to accomplish repeatitive execution of programming statements. There are three loop statements in C++ : while loop, do while loop and for loop While loop Syntax: while (condition expression) { Statement1; Statement 2; } In the above example, condition expression is evaluated and if the condition is true, then the statement1 and statement2 are executed. After execution, the condition is checked again. If true, the statements inside the while loop are executed again. This continues until the loop condition becomes false. Hence the variable used in the loop condition should be modified inside the loop so that the loop termination condition is reached. Otherwise the loop will be executed infinitely and the program will hang when executed. Also the loop variable should be iniatialised to avoid the variable taking junk value and create bugs in the program. The flowchart for the While statement is shown in Fig 2.3. Fig. 2.3: While Statement The following program implements the while loop // average1.cpp # include <iostream.h>
  • 21. void main() { int n=0,a; int sum=0; cout<< “enter five numbers”; while (n<5) { cin>>a; sum=sum+a; n++; } cout<<”Average of the numbers is”<<(sum/n); } The above program accepts five numbers from the user and finds the average of the five numbers. In the above while loop, the variable n is initialized to zero and this variable keeps track of the count of numbers input from the user. It is incremented every time a number is input from the user. The number accepted from the user is added to the value stored in the sum variable. When n becomes 5 the while loop condition becomes false and the average of the numbers is printed. Please note that there is no semicolon after while and condition expression. Do..while loop The do while loop is same as while loop except that the condition is checked after the execution of statements in the do..while loop. Hence in do..while loop, statements inside the loop are executed atleast once. However, in while loop, since the condition is checked before, the statements inside the loop will not be executed if the loop condition is false. Syntax: do {
  • 22. Statement1; Statement2 } while (condition expression); In the above example the statement1 and statement2 are executed and the condition is checked. If the condition is true then the statements are executed again and if the condition is false then the control is transferred to the next statement after the do..while statement. The flowchart for the do..while statement is shown in Fig 2.4 Fig. 2.4: Do..while Statement Please note that there is no semicolon after do, but there is a semicolon after the condition expression in while part. The average1.cpp program is rewritten using do..while loop as follows // average2.cpp # include <iostream.h> void main() { int n=0,a; int sum=0; cout<< “enter five numbers”; do {
  • 23. cin>>a; sum=sum+a; n++; }while (n<5); cout<<”Average of the numbers is”<<(sum/n); } The decision on whether to use while or do..while statement depends on whether the statements inside the loop have to be executed atleast once or not. If it has to be executed atleast once, then the do..while statement should be used. For loop The for loop is one of the popular control statement as it is compact and clear in specification. The loop initialization, loop termination condition statement and statement for the next iteration are all included in one statement. Syntax: for(initialization statement;loop termination condition;statement to increment/decrement the loop variable) { Statement1; Statement2; } In the above example, initiation statement is executed first and then the termination is checked. If the condition is true, statement1 and statement2 will be executed. Then the third statement in the for loop is executed which modifies the loop control variable. The flowchart for the for statement is shown in Fig 2.5
  • 24. Fig. 2.5: For Statement Please note that there is no semicolon after the for statement. The average2.cpp rewritten using for loop is as follows: // average3.cpp # include <iostream.h> void main() { int a; int sum=0; cout<< “enter five numbers”; for(int n=0;n<5;n++) { cin>>a; sum=sum+a; } cout<<”Average of the numbers is”<<(sum/n);
  • 25. } In the above example n variable is loop variable which is initialized to zero. Please note that the variable is also declared inside the for loop. So this variable can be accessible only inside the for loop. The scope of the variables will be declared in detail in unit 4. The statements inside the loop are executed until the loop termination condition n<5 becomes false. After every iteration, the loop variable n is incremented. The following program demonstrates the use of for loop using decrement operator to find the factorial of a number. // factorial.cpp # include <iostream.h> void main() { int number,fact=1; cout<< “enter a number”; cin>>number; for(int i=number;i>1;i–) fact=fact*i; cout<<”Factorial of <<number<<“is”<<fact; } All the above loops can be nested. The inner loop is executed completely and then the outer loop is executed. For every iteration of outer loop, all the iterations of the inner loop is executed. The for statement can also have multiple initialization and decrement and increment statements as shown in the following expression for(i=0,j=0;i<=n;j++,i++) { statements; }
  • 26. Please note that in case of multiple statements, each statement should be separated by a comma. Selection of which type of loop to be used depends on the programmer and his style. However you should use for loop if you know in advance how many times the loop has to be executed. If the loop has to be executed atleast once irrespective of whether the condition is true or false, then do while loop should be used. Self Assessment Questions 1. Which of the following loop will be executed atleast once even if the condition is false. a. For loop b. while loop c. do..while loop d. None of the above 2. ___________ is the loop variable in the loop for(int k=n;k!=0;k=k-2) 3. The loop for(int i=0;i<n;i++) will be executed till the statement _________ becomes false. 4. If there is more than one statements inside a loop, then the statement should be enclosed within ______________ BC0037-2.4 Break continue and exit statements in C++ 2.4 Break, continue and exit statements in C++ All the loops or iteration statements discussed in previous section are executed until the loop condition becomes false. However if required, the control sequence can be changed by using break, continue or exit statements. Break statement transfers the control to the next statement after the loop and all the remaining statements and the iterations in the loop are skipped. It is used if you would like to exit the loop when a certain condition is met. In the switch statement break statement takes the control to the next statement after the switch statement. The following program demonstrates the use of break statement inside for loop. // prime.cpp # include <iostream.h> void main() { int number;
  • 27. int prime=0; cout<<”Enter a number”; cin>>number; // check whether the number is divisible by any number from 2 to number/2 for (int i=2;i<=number/2;i++) { if ((number%i)==0) { prime=1; break; } } if (prime==0) cout<<”The number is prime number”; else cout<<” The number is not a prime number”; } In the above program, the user is asked to enter a number and the program checks whether the number is prime or not and displays the message accordingly. To check whether the number is prime or not, the number is divided by 2,3… and so on till number/2. If the number is divisible by any number, the variable prime is assigned a value one and the loop is terminated as there is no need to check whether the number is divisible by rest of the numbers. The value 1 in the prime indicates that the number was divisible by one of the numbers between 2 to number/2. Continue statement is used to take the control to the next iteration of the loop. It is used if the control has to be transferred to the next iteration of the loop based on a condition skipping all the other statements in the loop. The following program shows the use of continue statement. move.cpp # include<iostream.h>
  • 28. # include<conio.h> void main() { int x,y; char choice=’y’; do { clrscr(); cout<<”please enter the dividend”; cin>>x; cout<<”Please enter the divisor”; cin>>y; if (y==0) { cout<<”error!! Division by zero, try again”; continue; } cout<<”The quotient is “<<(x/y); cout<<”the remainder is”<<(x%y); cout<<”do u wish to continue”; cin>>choice; }while (choice==’y’); }
  • 29. In the above example clrscr() function which is a library function is used to clear the screen before accepting the input from the user. To use this function, conio.h header file must be included. Exit function in a program takes the control out of the program. Exit is an inbuilt library function. To use this function process.h header file has to be included in the program. The syntax of this function is exit(integer).While terminating the program, the integer is returned to the operating system. Usually the function integer 0 is used to imply no error or successful termination and non zero value implies error while exiting the program . Go to statement is a statement which should be avoided. It take the control to a particular statement. The statement should have a label. Syntax: goto statement labelname Statements can be given labels in the following way labelname: statement The use of goto statement should be avoided as it creates problems in program debugging and the program may have confusing jumps from one statement to another. Self Assessment Questions 1. _________ statement takes the control out of the loop. 2. __________ header file should be included to use exit function 3. __________ statement takes the control to the beginning of the loop. 4. ________ statement takes the control to a particular statement BC0037-2.5 Summary Summary Selection and iteration statements allow to execute statements in the program based on a condition bypassing the normal sequential execution. Selection is enabled through if statement, switch statement and conditional operator. Switch statement is suitable when you have multiple conditions to be checked and nested if can be avoided. Iteration is enabled in C++ through while, do..while and for loops. Loops execute the statements repeatitively until a particular condition becomes false. Break, continue and exit statements are used to transfer control out of the loop, to the next iteration of the loop and out of the program respectively.
  • 30. BC0037-3.1 Introduction Introduction This unit has the following objectives · To understand what are arrays and how they are useful in C++ programming · To learn to create and use multidimensional arrays · To understand how strings are represented and used in C++ BC0037-3.2 Introduction to Arrays Introduction to Arrays Arrays are used when you want to store related data of same type together with the same name so that you can access them easily. Arrays can be defined as datastructures that allow to store group of data of same datatype. You can retrieve data stored in the array in any order. For example, let us suppose you want to write a program which will help you to compute average marks scored by students in a class of 60. To allow this computation, your program should store marks scored by 60 students in a class separately, so that you can do any kind of computation when required. It would be tedious, if you had to create 60 different variables to store marks of 60 students and manage them separately. Arrays solves this problem, by grouping data of similar type with same name but can be referred separately through the position or the index number. Arrays should be declared like any other variable. However array size should be specified during declaration which determines how many elements the array can store. The following is a declaration of an integer array named data which can store 20 integers. int data[20]; Please note that in the above declaration, data is the name of the array followed by the size of the array enclosed within square brackets.The datatype of data stored by the array can be any default datatypes supported by c++ or user defined datatypes. Elements in the array can be accessed through index numbers. The data in the array are stored with index numbers 0,1, and so on. Since the index number starts with 0 the last index number of an array of size n will be n-1. The elements stored in the array are accessed by using the array name followed by the index number within the square brackets. For example, in the above array, the integers in the array can be accessed as data[0], data[1] and so on till data[19]. This makes it very easy to store and access large number of data. The code can be simplified by including common statements that needs to be performed on the array elements inside a loop and making the loop variable as the variable that stores the index variable.
  • 31. The following programs shows how you can store and retrieve data from the array //max.cpp #include<iostream.h> void main() { int max=0, a[50]; for (int i=0; i<50;i++) { cin>>a[i]; if (a[i]>max) max=a[i]; } cout<<”Largest number in the array is”<<max; } In the above program, a is an array that stores 50 integers. The program accepts 50 integers from the user, and stores in an array and finds out the maximum number in the array. The a[i] represents a particular element in the array and i is the index number. As the iteration varies, the value stored in i also varies. Another interesting aspect of the array is that all the elements in the arrays are allotted consecutive spaces in the memory by the operating system. The following program sorts an array. Here nested for loops are used to enable this. //sort.cpp # include<iostream.h> void main() {
  • 32. int a[10],temp; for (int i=0; i<10;i++) { cin>>a[i]; } cout<<”Array after sorting is “; for(int j=0; j<9;j++) for(i=0;i<9;i++) { if (a[i]>a[i+1]) {temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; } } for (i=0; i<10;i++) { cout<<a[i]<<endl; } } Array elements can be initialized. All the elements in the array should be initialized. Every data should be separated by a comma and all elements enclosed within flower brackets as shown below int data[5] = {3,5,7,4,9}; In the above initialization, data[0] is initialized to 3, data[1] is initialized to 5 and so on..
  • 33. Self Assessment Questions 1. Arrays group data of __________ type 2. An array declared as int a[10] can store __________ integers 3. a[5] represents the _________ integer in the above array. 4. Array elements are accessed through _______________ BC0037-3.3 Multidimensional Arrays Multidimensional Arrays The arrays can be multidimensional as well to store the required data. For example a two dimensional array can be created to store data about a matrix. A 3×4 matrix that has 12 data elements can be created using the following declaration int mat[3][4]; The above array has 3 rows and four columns. The elements in the array can be accessed by two indexes. To refer to an element in the first row and second column mat[0][1] has to be used as the index starts from zero. The following program accepts from the user two 2×3 matrices and adds the two matrices. //matrix.cpp # include <iostream.h> void main() { int a[2][3], b[2][3], c[2][3];
  • 34. int i,j; cout<<”Enter the elements for the first 2×3 matrix”; for (i=0;i<2;i++) for (j=0;j<3;j++) { cin>>a[i][j];} cout<<”Enter the elements for the second 2×3 matrix”; for (i=0;i<2;i++) for (j=0;j<3;j++) { cin>>b[i][j]; c[i][j]=a[i][j]+b[i][j]; } cout<<”The resultant matrix is”; for ( i=0;i<2;i++) { for ( j=0;j<3;j++) { cout<<c[i][j]<<” “; } cout<< endl; } } Multi dimensional arrays can also be initialized as follows
  • 35. int a[2][2] = {{ 3,4}, { 2, 7}} Every row elements are initialized by enclosing them in separate flower brackets.In the above example elements 3 and 4 will be initialized to a[0][0] and a[0][1] respectively. Self Assessment Questions 1. An array with the declaration int x[4][5] can store ________ numbers 2. In the above array the number in the third row and fourth column can be accessed by ____________ 3. int a[ ] [ ] is a valid declaration. True/False BC0037-3.4 Strings and String related Library Functions Strings and String related Library Functions Strings are nothing but character arrays. Strings are usually used to store data such as employee name, address, product description, password etc. The size of the string is defined during declaration like any other array. One basic difference between other arrays and strings is that the compiler stores an extra null character (’/0′) for every string to mark the end of the string. This enables a good means of identifying the end of the string as string variables usually store variable length values. Strings, unlike other arrays can be input without using a loop. When inputting strings using cin statement, the compiler stops taking input from the user once it encounters space or linefeed (pressing enter key). For example, consider the following program statements: char str[10]; cin>>str; If the user inputs “HELLO” and presses enter key , the contents for the str variable will be as follows: H str[0] E str[1] L str[2] L str [3] O str[4] /0 str[5]
  • 36. The strings can be also initialised as arrays. However they can be initialized by enclosing the characters in the string constant with double quotes instead of initializing it character by character. For example, the following statement initializes the str variable to “hello”: char str[10]=”hello”; Strings can also be defined without specifying the size, but in that case they have to be initialized to a string constant as shown in the following example. char str[]=”hello world” However, there is no built in mechanism in C++ that disallows the user to enter characters than the string maximum size. The extra characters entered by the user will be truncated. To keep a check on the number of characters, setw() function can also be used. To use this function, iomanip.h header file should be included. #include<iostream.h> #include<iomanip.h> const int size=10; void main() { Char str[size]; Cout<<”enter a string”; Cin>>setw(size)>>str; } The above program allows user to enter only 9 characters(one character saved for null character).While inputting strings, cin stops reading once it encounters space or linefeed character( when user presses enter). To read blanks between the strings or to read multiple lines of text, get function which is a member function of cin can be used.The following statement will allow user to input a maximum of 39 characters which can even include blanks. It will stop reading once it encounters linefeed character. cin.get(str, 40); To read multiple line of text from the user, you have to specify a terminating character which will be used to recognize end of input. In the following example, the terminating character is $.
  • 37. cin.get(str,40,$); The above example will allow users to enter a maximum of 39 characters which can include embedded blanks and linefeed. C++ has several string related library functions that are used to manipulate strings. Some of these are discussed below. To use these functions, header file string.h has to be included. Some of the library functions such as strlen, strcpy, strrev, strcmp is discussed below. Strlen Function Strlen function is used to find the length of the string. The syntax of the strlen function is strlen(string variable). The function returns the length of the string or the number of characters in the string which is a integer. Example : int len; char str[10]=”hello”; len=strlen(str); In the above example, the number of characters in the string str(five in this case) is stored in the integer variable named len Strrev function Strrev function arranges the characters in the string variable in reverse order except for the null character. The syntax of strrev function is strrev(string variable). It returns the reversed string. For example, in the following program statement, the output will be olleh The null character will be the last character of the string. char str[10]=”hello”; cout<<strrev(str); Strcpy function Strcpy function copies the contents of one string to another. The syntax of strcpy function is strcpy(destination string, source string). The function returns the destination string value after copying. For example, in the following program statement, the contents of the string str will be copied to string name char str[10]=”ravi”;
  • 38. char name[10]; strcpy(name,str); The strcpy can also use string constants to be assigned to a string variable like in the following statement. strcpy(name,”ravi”); In the above statement the string constant ravi is assigned to the string variable name. The assignment of a string variable cannot be done using an assignment operator. It should be done using strcpy function. The following statement in a program will provide an compilation error: name=”ravi”; //wrong statement Strcmp function Strcmp function is used to compare two strings. The syntax of strcmp is strcmp(string1,string2). Every character of string1 will be compared with corresponding character of string2. The ASCII values of the character will be used to decide the return value. The function returns an integer and the value returned will differ based on the conditions as shown below: If string1 < string2, value returned will be <0 If string1==string2, value returned will be 0 If string1> string2, value returned will be greater than zero. Thus, a return value 0 implies that strings are equal and a non zero return value implies than the two strings are not equal. Please note that the above function is case sensitive. Strcmpi() function can be used if the two strings have to be compared without case sensitiveness. The following program implements strcmp function # include <iostream.h> # include<string.h> const char str[6] = “XYZPQR” void main() { char pass[6];
  • 39. int flag=0; for(int i=0;i<3;i++) { cout<<”Please enter your password”; cin>>pass; if (strcmp(str, pass)==0) { cout<<”Welcome”; flag=1; break; } else cout<<”Invalid password, try again”<<endl; } } if (flag==0) cout<<”Access denied”; } Self Assessment Questions 1. char str[ ]; is a valid statement. True/False 2. char str[20] will allow maximum of ________ characters to stored in the string. 3. _________ member function of cin allows user to input embedded blanks and linefeed within the string. 4. _________ libray function can be used to copy the contents of one string to another string.
  • 40. BC0037-3.5 Summary Summary Arrays are used to store large volumes of similar data together. The array elements can be accessed by specifying array name followed by the number which indicates the position of the element in the array. Arrays of basic datatypes such as integers, characters etc and user defined datatypes such as structures, objects can be defined. Arrays can be multidimensional to store data that are related. Strings are character arrays that are handled slightly differently than other arrays. Every string has a null character ‘0’ as its last character which marks the end of the string. There are several string related library functions that can be used to manipulate strings BC0037-4.1 Introduction Introduction This unit has the following objectives · To understand what are functions and how they enable program organisation · To understand different types of variables and their use in C++ · To learn to what are structures and grouping data of different data types together BC0037-4.2 Introduction to Functions Introduction to Functions Functions provide an easy means to organize the programs into smaller modules and use them again without rewriting all the code. It enables reuse of program code. Functions enable programmers to group program code under one name and invoke them whenever required. We have been using several library functions till now without worrying about the code to implement them. Programmers can define their own functions in C++. In this unit, we will learn how to implement user defined functions. Every function has three components: return value, function name, and a set of arguments. Function name enables users to refer to the functions and is also used when user wants to call and execute the code defined in the function. Every function may or may not return a value. During declaration of function, the datatype of the return value should be specified. If there is no value returned it should be specified as void.The function main() which we had been using in all
  • 41. the programs is one of the default functions which also has been defined as having no return value. When you have several user defined functions in a program, the statements in the main() function is executed first irrespective of where it is located in the program. Every function can have no or any number of arguments. Arguments are input to the functions and are used inside the function. During declaration of the function, the datatypes of the arguments should be specified. Each argument should be separated with a comma. The arguments should match during function call with respect to datatype and order of the arguments. In case of default arguments the value need not be specified during call. Every user-defined function should be declared in the program before it is used. The definition can be present in any part of the program. The following is an example of declaration of a function named square which inputs a number and returns the square of the number. int square(int); Please note that all the arguments are enclosed within brackets. If there are no arguments, void should be specified within the brackets. The following is the declaration of a function which does not have return value and does not have any arguments. void xyz(void); The functions can be invoked or called by referring to the function name followed by the variables or constants that has to be passed as arguments. If there are no arguments that has to be passed to the functions, then the function name should be followed by a pair of paranthesis. The following program would invoke the xyz function: xyz(); To invoke a square function which inputs a number and returns a number following statement can be used: s=square(n); Where s and n are integer variables. The function will compute square of n and the result will be stored in variable s. Please note that during function call, constants can also be passed. To understand the relevance of functions and its use, let us take an example. Let us suppose you would like to write a program that computes the combination of n items taken r at a time. The mathematical formula for computing nCr is n!/(r!*(n-r)!). In this problem, the factorial of the numbers have to be computed three times. The code for implementing factorial of a number has been discussed in the unit 2.3 in factorial.cpp program. If the same code has to be directly implemented without functions, the code has to be repeated three times in the program to compute factorial of n, r and n-r. This would not only make programs unnecessarily big but also difficult to correct or debug. To avoid this problem, we can define a user defined function named
  • 42. fact which would input a number and compute the factorial of that number and return the result. The declaration for the function will be as below int fact(int); We can compute the factorial of n just by specifying fact(n) which would call the function fact and execute the statements. The complete program for implementing the above problem is as below: //function.cpp # include <iostream.h> int fact(int); // function declaration void main() { int n,r,ncr ; cout<< “enter n”; cin>>n; cout<< “enter r” ; cin>>r ; ncr=fact(n)/(fact(r)*fact(n-r)); cout<<”NCR=” <<ncr; } int fact(int number) //function definition { int f=1; for(int i=number;i>1;i–) f=f*i; return f; //return computed value
  • 43. } In the above program, the user inputs value for n and r. To compute the value of ncr, the fact function is invoked or called first by passing n variable. When the compiler encounters the first statement of the function, it copies the value of the variable n to the variable number. The variable number has scope only inside the function fact and is known as local variable. It cannot be accessed outside the function and so is the variable f and i that has been defined in the function. The factorial of the variable number (same value as n) is computed and then returned to the calling program through the return statement. The return statement is used to return values or results to the main program. This process is repeated for the values r and n-r as well. All the results are then used in the formula in the main program to compute the value of ncr. If the function does not have any return value, the return statement can be skipped. The control goes back to the main program once the last statement in the program is encountered. Alternatively, simply using the return statement without any variable would also imply that no value is being returned to the main program. Self Assessment questions 1. Functions enable to reuse code. True/False 2. void print() would return _______ value 3. ________ statement is used to return value to the main program. 4. Function call should always contain function name followed by paranthesis even if there are no arguments. True/False BC0037-4.2 Introduction to Functions Introduction to Functions Functions provide an easy means to organize the programs into smaller modules and use them again without rewriting all the code. It enables reuse of program code. Functions enable programmers to group program code under one name and invoke them whenever required. We have been using several library functions till now without worrying about the code to implement them. Programmers can define their own functions in C++. In this unit, we will learn how to implement user defined functions. Every function has three components: return value, function name, and a set of arguments. Function name enables users to refer to the functions and is also used when user wants to call and execute the code defined in the function. Every function may or may not return a value. During declaration of function, the datatype of the return value should be specified. If there is no value returned it should be specified as void.The function main() which we had been using in all the programs is one of the default functions which also has been defined as having no return
  • 44. value. When you have several user defined functions in a program, the statements in the main() function is executed first irrespective of where it is located in the program. Every function can have no or any number of arguments. Arguments are input to the functions and are used inside the function. During declaration of the function, the datatypes of the arguments should be specified. Each argument should be separated with a comma. The arguments should match during function call with respect to datatype and order of the arguments. In case of default arguments the value need not be specified during call. Every user-defined function should be declared in the program before it is used. The definition can be present in any part of the program. The following is an example of declaration of a function named square which inputs a number and returns the square of the number. int square(int); Please note that all the arguments are enclosed within brackets. If there are no arguments, void should be specified within the brackets. The following is the declaration of a function which does not have return value and does not have any arguments. void xyz(void); The functions can be invoked or called by referring to the function name followed by the variables or constants that has to be passed as arguments. If there are no arguments that has to be passed to the functions, then the function name should be followed by a pair of paranthesis. The following program would invoke the xyz function: xyz(); To invoke a square function which inputs a number and returns a number following statement can be used: s=square(n); Where s and n are integer variables. The function will compute square of n and the result will be stored in variable s. Please note that during function call, constants can also be passed. To understand the relevance of functions and its use, let us take an example. Let us suppose you would like to write a program that computes the combination of n items taken r at a time. The mathematical formula for computing nCr is n!/(r!*(n-r)!). In this problem, the factorial of the numbers have to be computed three times. The code for implementing factorial of a number has been discussed in the unit 2.3 in factorial.cpp program. If the same code has to be directly implemented without functions, the code has to be repeated three times in the program to compute factorial of n, r and n-r. This would not only make programs unnecessarily big but also difficult to correct or debug. To avoid this problem, we can define a user defined function named fact which would input a number and compute the factorial of that number and return the result. The declaration for the function will be as below
  • 45. int fact(int); We can compute the factorial of n just by specifying fact(n) which would call the function fact and execute the statements. The complete program for implementing the above problem is as below: //function.cpp # include <iostream.h> int fact(int); // function declaration void main() { int n,r,ncr ; cout<< “enter n”; cin>>n; cout<< “enter r” ; cin>>r ; ncr=fact(n)/(fact(r)*fact(n-r)); cout<<”NCR=” <<ncr; } int fact(int number) //function definition { int f=1; for(int i=number;i>1;i–) f=f*i; return f; //return computed value }
  • 46. In the above program, the user inputs value for n and r. To compute the value of ncr, the fact function is invoked or called first by passing n variable. When the compiler encounters the first statement of the function, it copies the value of the variable n to the variable number. The variable number has scope only inside the function fact and is known as local variable. It cannot be accessed outside the function and so is the variable f and i that has been defined in the function. The factorial of the variable number (same value as n) is computed and then returned to the calling program through the return statement. The return statement is used to return values or results to the main program. This process is repeated for the values r and n-r as well. All the results are then used in the formula in the main program to compute the value of ncr. If the function does not have any return value, the return statement can be skipped. The control goes back to the main program once the last statement in the program is encountered. Alternatively, simply using the return statement without any variable would also imply that no value is being returned to the main program. Self Assessment questions 1. Functions enable to reuse code. True/False 2. void print() would return _______ value 3. ________ statement is used to return value to the main program. 4. Function call should always contain function name followed by paranthesis even if there are no arguments. True/False BC0037- 4.4 Scope and Visibility of variables in Functions Scope and Visibility of variables in Functions Functions save memory as all the calls to the function cause the same code to be executed. However, with this there is overhead of execution time as there must be instructions for jump to the function, saving data in registers, pushing arguments to stack and removing them, restoring data, instructions for returning to the calling program and return values. To save execution time of functions, one of the feature in c++ is inline functions. An inline function’s code is put with the code in the calling program for every function call. The inline function is written like any other function except that the function declaration begins with the keyword inline. This type of function is suitable for small functions which has to be repeatedly called. This enables the user to write programs using functions which would make programs look neat and less lengthy, at the same time the actual code is inserted in all the places where the function is called after compilation enabling faster execution of the program.
  • 47. The several types of variables can be created in C++ which can be different in terms of life, visibility and the way it is initialized. These are also known as storage classes. We will discuss three types of storage classes in this section : Automatic, External and Static variables. Automatic variables is default variable in C++. All the variables we have created and used in programs are automatic variables. These variables can also be declared by prefixing the keyword auto. One of important characteristics of these variables are that they are created only when the function or program block in which they are declared are called. Once the execution of function or module execution is over, the variables are destroyed and the values are lost. The reason for limiting the lifetime of automatic variables is to save memory. When the variables are not be used by the function, they are removed from the memory. They can be accessed only within the function where they are declared. Beyond which they are not idenfiable. By default the automatic variables are not initialized to any specific values unless and until specified. They contain junk value depending on the value stored in the memory. Therefore it is necessary to initialize automatic variables to avoid problems in debugging. External variables are variables external to any function. Thus they can be accessed by multiple functions. This is the easiest way to share data among various functions. However too many external variables can create problems in debugging as the programmer will have tough time figuring out which function modified which data. Object oriented programming provides an alternative to use external variables. This feature is just to support backward compatibility with C. External variables are also known as global variables and are automatically initialized to zero. These variables are declared before main and declaration statement does not belong to any function. The following program shows the difference between an external variable and an automatic variable. //external.cpp # include<iostream.h> int x; void f1(); void f2(); void main() { x=x+2;
  • 48. f1(); f2(); cout<<x; } void f1() { int x; x=x*2; } void f2() { x++; } In the above program, we have defined an external variable x. This variable will be automatically initialized to zero. The statement x=x+2; will store two in x. The function f1 will not have any impact on the value of the external variable as there is another local automatic variable x defined in the function which will be modified (Please note that when automatic and global variable have same name, the local variable will override the global variable). The function f2 will increment global variable by one. Thus the final output of the above program will be 3. External variables have a life of the file/program in which they are defined. Static variables are a mix of external and automatic variables. They have the scope of the function in which they are defined like automatic variables. But they can retain their values even after the function execution is over and are automatically initialized to zero like external variables. The following program shows the use of the static variables. // static.cpp # include <iostream.h> void main() {
  • 49. int num; char ch; do { cout<<”Enter a number”; cin>>num; f1(num); cout<<”Do u want to enter another number”; cin>>ch; }while (ch==’y') } void f1(int x) { static int sum, n; sum=sum+x; n=n+1; avg=sum/n; cout<< “Average is”<<avg; } The above program allows the user to enter any number of integers and computes the average of the numbers till then. The static variables sum and n are intitialised to zero. They are updated when user enters a new number and the function is called. The values of these variables are retained even after the function returns back to the main program. The summary of all three storage classes is shown below: Automatic Static External Visibility Function Function Program Lifetime Function Program Program
  • 50. Intialised Junk value in Zero Zero to memory Same as automatic but the value Variables used by Variables used by Purpose should be retained when function single function several functions terminates Self Assessment questions 1. Inline functions help in saving ______________ of programs 1. Static variables are initialized to _________ automatically. 2. External variables are accessible throughout the _________. BC0037-4.5 Structures in C++ Structures in C++ We have seen in unit three how we can group data of same type together with arrays. Data that are of different types but are logically related can also be grouped together. This can be done through structures. Structures are a group of dissimilar data that are related with each other. For example, if you want to store all the details of an employee such as employee id (integer), name (string), department code(integer), and salary as one entity, you can do this using structure as shown below: struct employee { int empid; char name[35]; int deptcode; float salary; }; Structure is a feature in C++ that enables you to define a user-defined datatype. Once you specify the definition of the structure, you can create variables of that structure. In the above definition, we have defined a structure using the keyword struct followed by the name of the structure (employee). All the data items that needs to be defined are defined by specifying the datatype and name of the variable. Once the definition is done, variables of type employee can be created. For example, the following statement creates a variable e1 of type employee. employee e1;
  • 51. Structure variables can be initialized during declaration. The values for all the members should be specified separated by comma and all the values enclosed within flower brackets as shown below employee e1= {1234, “Ajay”, 12, 6900.00}; Structure variables can be copied and assigned to another structure variable as shown below employee e2; e2=e1; To access the members of the structure variables, dot operators can be used. For example to access empid of structure variable e1, you would say e1.empid (structure variable. membervariable name). Structures can be nested within each other. When accessing the members and submembers dot operators can be used. Let us suppose you have defined a structure named distance with two members length and width as declared below: struct distance { int feet; int inches; } Let us define now a structure named room which contains variables of type distance struct room { distance length; distance width; distance height; } bedroom; In the above definition, we have declared a variable bedroom of type room along with the definition. To access the members of the bedroom we can use bedroom.length.feet
  • 52. bedroom.length.inches bedroom.width.feet bedroom.width.inches and so on To initialize nested structures you have to group together all the elements of the structure room dining = {{12, 3},{13,0},{11,2}} In the above declaration, the values 12 and 3 refer to dining.length.feet and dining.length.inches repectively. Similarly the second and third set of values represent feet and inches of width and height respectively. Array of structures can be created. The index number should be specified immediately after the structure variable. For example, the statement employee emp[50] ; will create a array of structure employee. To access the first array member, you can say emp[0].empid The following program implements a structure point with x and y co-ordinates. #include<iostream.h> #include<conio.h> # include<math.h> struct point { int x,y; } p1,p2; void main() { int s; cout<< “Enter the co-ordinates for first co-ordinate” ; cin>> p1.x>>p1.y;
  • 53. cout<<”enter the co-ordinates for second co-ordinate”; cin>>p2.x>>p2.y; s=sqrt(((p2.y-p1.y)*(p2.y-p1.y))+((p2.x-p1.x)*(p2.x-p1.x))) ; cout<<endl<<”the distance between the two points is”<<s; getch(); } In the above program we have defined a structure point which stores x and y co-ordinates of the point. Along with the declaration we have also created two point variables p1 and p2. This is a way to create variables along with the structure decalaration. This can be a separate statement also as discussed earlier. The program accepts two points from the user and displays the distance between them. Structures are good mechanism of creating userdefined datatypes. C++ specifies another method known as enumerated data type to enable users create their own datatypes. Enumerated data types can store fixed set of values and you can perform arithmetic on them as well. They are defined using the keyword enum. The following program creates an enumerated datatype which stores different days of the week. //enumerated.cpp #include <iostream.h> enum weekday {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; void main ( ) { weekday day1,day2; day1=Mon; day2= Fri; int diff=day2-day1; cout<<”days between =”<<diff; if (day1<day2) cout<<”day1 comes before day2”;
  • 54. } In the above program enumerated datatype weekday is created. The first value (Sun) is assigned zero by default and so on. The variables day1 and day2 can be assigned only the values specified in the datatype declaration or their integer equivalent. They cannot be assigned any other value. Self Assessment Questions 1. Structures group data of similar type. True/False 2. ___________ keyword is used to create structures. 3. Member data of the structure are accessed by ________ operator BC0037-4.6 Summary Summary Functions provide good mechanism to organize data. Functions are given a name which can be used to call the function and execute the statements in the functions. Functions can also take input which are known as arguments which passed during function call. Arguments can be passed either by value or by reference. They can also have return value which can return an computed value back to the main program. Inline functions enable programmers to save processing time by reducing the overheads involved in function call. Programs can make use of automatic, external and static variables which have different types of utility depending on the way the variable should be accessed and whether the value has to be retained. Structures and enumerated data types enable to users to create user defined datatypes. Structure group data items that have different datatypes. Enumerated datatypes create datatypes that can store pre-defined and fixed set of values BC0037-5.1 Introduction Introduction This unit has the following objectives · To understand what are classes and Objects and learn to implement them · To learn to use constructors and destructors in a class · To understand static variables and functions with respect to a class
  • 55. BC0037-5.2 Creating classes and objects Creating classes and objects In the unit 1, we had a brief discussion of objects and classes. In this section, we will see how we can implement them. Classes provide users a method to create user defined datatypes. We have seen two types of user defined datatypes structures and enumeration in the last unit. Both are primarily used for modeling data only. In several real life situation, you would require to model functionality of the datatype along with the data. Classes enable you to bind data and functions that operate on data together. However, in C++ you can use structures same as classes by binding functions with data. But usually the structures are only used when you want to group data and classes when you want to group both data and functions. Classes can model either physical or real things such as employee, product, customer etc or it can model a new datatype such user defined string, distance, etc. Objects has the same relationship to a class that a variable has to a datatype. Object is an instance of a class. Class is a definition, objects are used in the program that enables you to store data and use them. To understand the various syntactical requirements for implementing a class, let us take an example. // distance.cpp #include<iostream.h> class distance { private: int feet; int inches; public: void setdistance(int a, int b) { feet=a; inches=b; }
  • 56. void display() { cout<<feet<<”ft”<<inches<<”inches;} }; void main() { distance d1; d1. setdistance(10, 2); d1.display(); } In the above program, we have created a class called distance with two data members feet and inches and two functions or methods setdistance and display (). Classes are defined with the keyword class followed by the name of the class. The object of this class is d1. Every objects of a class have their own copy of data, but all the objects of a class share the functions. No separate copy of the methods is created for each and every object. Objects can access the data through the methods. To invloke a method, objectname.methodname is used. The methods defined in the class can only be invoked by the objects of the class. Without an object, methods of the function cannot be invoked. You can see in the above program, the data elements feet and inches are defined as private. The methods are defined as public. These are known as access specifiers. Data and functions in a class can have any one access specifiers: private, public and protected. Protected access specifier we will discuss later in unit 7 along with inheritance. Private data and functions can be accessed only by the member functions of the class. None of the external functions can access the private data and member functions. Public data and member functions can be accessed through the objects of the class externally from any function. However to access these data and functions, you need to have an object of that class. This feature of object oriented programming is sometimes referred to as data hiding. The data is hidden from accidently getting modified by an unknown function. Only a fixed set of functions can access the data. In a class, the data and functions are private by default so private keyword can be omitted. Fig. 5.1: Access specifiers in a class
  • 57. Certain object oriented programming languages refer to methods as messages. Thus d1.display() is a message to d1 to display itself Usually, data are declared as private and functions as public. However, in certain case you may even declare private functions and public data. Please note that the class definition has a semicolon in the end. Array of objects can also be created. It is similar to array of structures. distance d[10]; creates a array of objects of type distance. If the first distance object accesses the member function display you can use d[0].display() Let us see how we can perform operations on the objects data. We will see a program which implements an add member function to the distance class. We can do this in two ways. The prototypes of the function is shown below: void add(distance, distance); or distance add(distance); The first function takes two distance objects as arguments and stores the result in the object invoking the member function. It can be implemented as follows: //adddist1.cpp #include<iostream.h> class distance { private: int feet; int inches; public: void setdistance(int a, int b) { feet=a; inches=b;
  • 58. } void display() { cout<<feet<<”ft”<<inches<<”inches;} void add(distance dist1, dist2) { feet=dist1.feet+dist2.feet; inches=dist1.inches+dist2.inches; if (inches>12) { feet++; inches=inches-12; } } }; void main() { distance d1,d2,d3; d1. setdistance(10, 2); d2.setdistance(2,4); d3.add(d1,d2); d3.display(); } In the above program, object d3 invokes the add function so the feet and inches refers the invoking object’s data members. After adding the respective data of d1 and d2 it is stored in d3 object. Alternatively, the above program can be implemented in a different way as shown below //adddist2.cpp
  • 59. #include<iostream.h> class distance { private: int feet; int inches; public: void setdistance(int a, int b) { feet=a; inches=b; } void display() { cout<<feet<<”ft”<<inches<<”inches;} distance add(distance dist) { distance temp; temp.feet=dist.feet+feet; temp.inches=dist.inches+inches; if (temp.inches>12) { temp.feet++; temp.inches=temp.inches-12; } return temp; } };
  • 60. void main() { distance d1,d2,d3; d1. setdistance(10, 2); d2.setdistance(2,4); d3 =d1.add(d2); d3.display(); } In the above program, we have implemented the add function which is invoked by d1 object and d2 is passed as an argument. Since the calling objects data are passed automatically, d1 objects data members can be accessed in the function. They are referred directly as feet and inches without the objectname (as it is implicit in the member function). The add function stores the summed value in a temporary variable and then returns it to the calling program. Self Assessment Questions 1. Private data members can be accessed only by the __________ of the class 2. Public data members can be accessed directly in the main function without an object. True/False 3. Every object of a class has its own copy of the data and functions. True/False BC0037-5.3 Constructors and Destructors Constructors and Destructors Constructors and destructors are very important components of a class. Constructors are member functions of a class which have same name as the class name. Constructors are called automatically whenever an object of the class is created. This feature makes it very useful to initialize the class data members whenever a new object is created. It also can perform any other function that needs to be performed for all the objects of the class without explicitly specifying it. Destructors on the other hand are also member functions with the same name as class but are prefixed with tilde (~) sign to differentiate it from the constructor. They are invoked automatically whenever the object’s life expires or it is destroyed. It can be used to return the memory back to the operating system if the memory was dynamically allocated. We will see dynamic allocation of memory in Unit 7 while discussing pointers.
  • 61. The following program implements the constructor and destructors for a class // constdest.cpp # include<iostream.h> class sample { private: int data; public: sample() {data=0; cout<<”Constructor invoked”<<endl;} ~sample() {cout<<”Destructor invoked”;} void display() { cout<<”Data=”<<data<<endl;} }; void main() { sample obj1; obj.display(); } If you run the above program you will get the output as follows: Constructor invoked Data=0 Destructor invoked When object of sample class, obj is created, automatically the constructor is invoked and data is initialized to zero. When the program ends the object is destroyed which invokes the destructor. Please note that both the constructor and destructor is declared as public and they have no return value. However, constructors can have arguments and can be overloaded so that different constructors can be called depending upon the arguments that is passed. Destructors on the other
  • 62. hand cannot be overloaded and cannot have any arguments. The following program implements the overloaded constructors for the distance class. //overloadconst.cpp #include<iostream.h> class distance { private: int feet; int inches; public: distance() { feet=0; inches=0;} distance(int f, int i) { feet=f; inches=i;} void display() { cout<<feet<<”ft”<<inches<<”inches;} }; void main() { distance d1, d2(10,2); d1.display(); d2.display() }
  • 63. In the above program, the setdistance function is replaced with the two constructors. These are automatically invoked. When object d1 is created the first constructor distance() is invoked. When object d2 is created the second constructor distance (int f, int i) is invoked as two arguments are passed. Please note that to invoke a constructor with arguments, argument values have to be passed along with the object name during declaration. Self Assessment Questions 1. Constructors are member functions of the class which is invoked when ________ is created. 2. Destructors have same name as a class but are prefixed with ________ sign 3. Destructors can be overloaded. True/False 4. Constructors can be overloaded. True/False BC0037-5.4 Static variables and Functions in class Static variables and Functions in class We have seen that when an object is created, a separate copy of data members is created for each and every object. But static data member in a class is an exception. Static data member of the class is one data member that is common for all the objects of the class and are accessible for the class. It is useful to store information like count of number of objects created for a particular class or any other common data about the class. Static data member is declared by prefixing the keyword static. We have learnt that to invoke a member function of a class, you need to have object. Suppose we have a static data member which keeps track of the total objects created and there is a showtotal function which displays the total value. We will not be able to know the total if there are no objects which is a serious limitation. Static functions are the solution for this. Static functions are special type of functions which can be invoked even without an object of the class. Static functions are also defined by prefixing the keyword static. It is called using classname followed by scope resolution operator and function name. The following program implements the static data and functions //classstatic.cpp # include <iostream.h> class A { static int total;
  • 64. int id; public: A() { total++; id=total; } ~A() { total–; cout<<”n destroying ID number=”<<id; } static void showtotal() {cout<<”endl “<<total;} void showid() {cout<<”endl “<<id;} }; int A::total=0; void main() { A::showtotal(); A a1,a2; A::showtotal(); a1.showid(); a2.showid();
  • 65. } The output of the above program 0 2 1 2 In the above program total is an static variable which is shared by all objects of the class A. The static variables of the class have to be explicitly initialised outside the class using the class name followed by scope resolution operator (::) and static variable name. Please note that you have to specify the datatype but need not specify the keyword static during initialization. The variable total is incremented in the constructor which will increment the total whenever a new object is created. Similarly, it is decremented through the destructor when the object is destroyed. The function showtotal is a static function which is invoked without the object and using the classname. The fig 5.2 summarises member functions and data of a class Fig. 5.2: Data and Functions in a class Self Assessment Questions 1. Static data member of a class can be modified by all objects of the class. True/False 2. Static functions are accessed using __________ 3. Static data need not be initialized. True/False BC0037-5.5-Summary
  • 66. Summary Class enable user to create user-defined datatypes and define their functionality. Objects are instances of classes. Class can contain both data and functions. Class data can be initialized using constructors which are invoked when the objects of a class are created. Destructors are member functions which are invoked when the objects are destroyed. Member functions can be accessed only through the objects of the class. Static functions can be accessed without objects. Static data can be accessed by all the objects of the class and only one copy of this data is maintained. BC0037-6.1 Introduction Introduction This unit has the following objectives · To learn how C++ supports operator overloading · To learn to overload different types of unary and binary operators · To understand limitations of operator overloading BC0037-6.2 Operator Overloading in C++ Operator Overloading in C++ Operator overloading is an interesting feature of C++ that allows programmers to specify how various arithmetic, relational and many other operators work with user defined datatypes or classes. It provides a flexible way to work with classes and can make program code look obvious. In the unit 5, we had written an add function for the class distance. To perform addition of two distance objects we used a call d3.add(d1,d2). Instead of such statements it would be more clear if we could use statements like d3=d1+d2. This is possible only if we inform compiler about how + operator works with distance class. This is exactly what operator overloading feature in C++ does. It helps to use the default operators with the user defined objects for making the code simpler. However there are several problems with operator overloading which you should be aware of. When using operator overloading, the operator should perform only the most obvious function. Otherwise it will lead to more confusion. If you are overloading + operator for distance class it should add two distance objects, and should not do something else. However some syntactical characteristics of operators cannot be changed even if you want to. For example, you cannot overload a binary operator to be a unary operator and vice versa. Several operators such as dot operator, scope resolution (::) operator, conditional operator (?:) etc cannot be overloaded.
  • 67. Therefore operator overloading should be used for a class where it is required to perform obvious functions with the default operators and there can be no other meaning for the same. Self Assessment Questions 1. Operator overloading feature helps to change the functionality of operators with any datatype. True/False 2. You can overload all operators in C++. True/False 3. It is necessary to overload operators for all classes. True/False BC0037-6.3 Overloading Unary Operators Overloading Unary Operators We have seen that unary operators are those operators which work on one operator. Some of the unary operators are ++, –, and minus (-). Operator overloading works similar to any member function of a class. But it is not invoked using dot operator. Just like member function the operator has a return value and takes arguments. It is invoked by the operand which uses it. In case of overloading of unary operators, the calling operand can be either left or right of the operator like in case of increment and decrement operators. While defining the operator functionality for the class the keyword operator is used. Let us overload the increment operator for a class. //unary.cpp # include <iostream.h> class counter { unsigned int count; public: counter() {count=0;} int getcount() {return count;} void operator ++()
  • 68. { count++;} }; void main() { counter c1; c1++; ++c1; cout<<c1.getcount(); } In the above example, the operator ++ is defined to return void and take no arguments. All unary operators do not take no arguments as it operates on only one operand and that operand itself invokes the operator. Therefore the operand is sent by default. However the above implementation cannot be used in statements such as c2=c1++; where c1 and c2 are counter variables. This is because the operator ++ returns void which makes an counter variable being assigned void value. To overcome this, you can make the operator return an counter variable as shown below //incremnt.cpp # include <iostream.h> class counter { unsigned int count; public: counter() {count=0;} counter(int c) {count=c;} int getcount() {return count;}