You are on page 1of 138

Object Oriented Programming

(C++)

Virendra Sir
(Scholars Education)
UNIT-1

Introduction of object oriented concepts: Evolution of OOP, OOP paradigm, advantage


of OOP, Comparison between functional programming and OOP approach,
characteristic of objected language object, class, inheritance, reusability, user defined
data type, polymorphism , overloading.

Overview
 C++ is a compiled, general-purpose, case-sensitive programming language that
supports procedural, object-oriented programming.

 C++ is a High-level language, as it comprises a combination of both high-level and low-


level Language features.
 C++ was developed by BjarneStroustrup starting in 1979 at Bell Labs (AT&T).
 Modification to the C++ language and originally named C with Classes but later it was
renamed C++ comes in 1983.
 C++ is a superset of C.

Object-Oriented Programming

C++fully supports object-oriented programming, including the four Concept of object-oriented


development. There is various function of oops

Encapsulation

Data hiding

Inheritance

Polymorphism

TC Business School | BEST BCA College In JAIPUR 1


Use of C++

 C++ is used by hundreds of thousands of programmers in essentially every application


domain.
 C++ is being highly used to write device drivers and other software.
 C++ is widely used for teaching and research because it is clean sufficient for successful
teaching of basic concepts.

Environment Setup

Before you start doing programming using C++, you need the following two software‟s
available on your computer.

1) Text Editor:
This will be used to type your program. Examples of few editors include Windows Notepad, OS
Edit command etc.
Name and version of text editor can change on different operating systems. For example,
Notepad will be used on Windows and vim or vi can be used on windows as well as Linux, or
UNIX.
The files you create with your editor are called source files, and for C++ they typically are
named with the extension .cpp, .cp.

2) C++ Compiler:
This is actual C++ compiler, which will be used to compile your source code into final
executable program.
Most C++ compilers don't care what extension you give your source code, but if you don't
specify otherwise, many will use .cpp by default.

A Simple Program:
The simple program HELLO.CPP. "Getting started," have many interesting parts. This section
will review this program in more detail.

#include <iostream.h>
#include <conio.h>
void main()
{
TC Business School | BEST BCA College In JAIPUR 2
cout<< "Hello World!\n";
getch();
}

 The file iostream.h is included in the file. The first character is the # symbol, which is a
signal to the preprocessor. Each time you start your compiler, the preprocessor is run.
The preprocessor reads through your source code, looking for lines that begin with the
hash (Preprocessor) symbol (#).
 include is a preprocessor instruction that says, "What follows is a filename. Find that file
and read it in right here. Another way include is a keyword that include a header file in
our program.
 "The angle brackets { } tell the preprocessor to look in all the usual places for this file. If
your compiler is set up correctly, the angle brackets will cause the preprocessor to look
for the file iostream.h in the directory that holds all the H files for your compiler. The file
iostream.h (Input-Output-Stream) is used by cout, which helps with writing to the screen.
 The preprocessor runs before your compiler each time the compiler is invoked. The
preprocessor translates any line that begins with a hash (processor) symbol (#).
 2 Lines, begins the actual program with a function named main(). Every C++ program
has a main() function. Usually functions are invoked or called by other functions, but
main() is special. When your program starts, main() is called automatically.
 main(), must start what kind of value it will return. The return value type for main() in
HELLO.CPP is void, which means that this function will not return any value at all.
 All functions begin with an opening brace ({) and end with a closing brace (}). The braces
started aftermain() function are on lines 3 and 5. Everything between the opening and
closing braces is considered a part of the function.
 The line 4. The object cout is used to print a message to the screen. These two objects,
cout and cin, are used in C++ to print strings and values to the screen. A string is just a
set of characters.Here‟s cout is used
 cout, followed by the output redirection operator (<<). Whatever follows the output
redirection operator is written to the screen. If you want a string of characters written, be
sure to enclose them in double quotes ("), as shown on line 4.
 The symbol \n is a special formatting character. It tells cout to cout to put a new line after
the words Hello World!
 The main() function ends on line 5 with the closing brace.

TC Business School | BEST BCA College In JAIPUR 3


Brief Look at COUT:

To print a value to the screen, write the word cout, followed by the insertion operator (<<), which
you create by typing the less-than character (<) twice. know this is two characters, C++ treats it
as one.
Example::Using cout.
// using cout
#include <iostream.h>
void main()
{
cout<< "Hello.\n";
cout<< "Welcome to Scholars education Pvt Ltd.,Brahampuri,Jaipur.\n";
cout<< "Here is 5: " << 5 << "\n";
cout<< "The useendl writes a new line to the screen." <<endl;
cout<< "Here is a very big number:\t" << 90000 <<endl;
cout<< "Here is the sum of 2 and 5:\t" << 2+5 <<endl;
cout<< “Scholars.cpp is a C++ programmer!\n";
}

OUTPUT:
Hello .
Welcome to Scholars education Pvt Ltd.,Brahampuri,Jaipur.
Here is 5: 5
The useendl writes a new line to the screen.
Here is a very big number: 90000
Here is the sum of 2 and 5: 7
Scholars.cpp is a C++ programmer!

Comments:
 When you are writing a program, Some Code can be confusing and unclear. And you
are not sure how that confusion clears into your program, but you want to use
comments. That‟s means your aresure how that confusion clear into your program.
 Comments are simply text that is ignored by the compiler, but that may inform the reader
of what you are doing at any particular point in your program.

TC Business School | BEST BCA College In JAIPUR 4


Types of Comments:

C++ comments come in two ways:

1) The double-slash (//) comment, and the slash-star (/*) comment. The double-slash
comment, which will be referred to as a C++-style comment, tells the compiler to ignore
everything that follows this comment, until the end of the line. Double-slash (//)
commentis also called Single line Comment.
2) The slash-star comment mark tells the compiler to ignore everything that follows until it
finds a star-slash (*/) comment mark. These marks will be referred to as C-style
comments. Every /* must be matched with a closing */.Slash-star commentis also called
Multi line Comment.

Example Using Comments


//COMMENT.CPP
#include <iostream.h>
void main()
{
/* this is a comment
and it extends until the closing
star-slash comment mark */
cout<< "Hello World!\n";
// this comment ends at the end of the line
cout<< "That comment ended!\n";
// double slash comments can be alone on a line
/* as can slash-star comments */
}

OUTPUT :
Hello World!
That comment ended!

How to Compile and execute the Program

Source File Preprocessor Intermediate Program


(Scholars.cpp)

Compile Object File (.obj) Linker Execution File


r (.exe)
Figure (1)

TC Business School | BEST BCA College In JAIPUR 5


1) Write a program using Editor.
2) Save the file with .CPP extension.
3) To compile the program, we can select compile from compile menu and press enter or you
can press Alt+F9.
4) It will check the errors if program has any error it will terminate the program then we can find
out the error and we can correct it. After correcting the error we can compile the program
again. After compiling successfully it will create a object (.obj) file.

Source File Preprocessor Intermediate Program Compiler


(Scholars.cp
p)

Yes Error

No
Figure (2)
Object File (.obj)

5) Once the Source Program has been converted into an Object File, it is still not in the form
that we can run.
The reason behind this is that there may be some reference to the
standard library functions or user-defined functions in other object file, which are compiled
separately. Therefore, these object file are to be linked together along with standard library
functions that are contained in library files. To link on object file, select link from the compile
menu.
After this the .obj file will be compiled with the one or more library files. The
result of this linking process produces an executable file with .exe extension.

Object File-1 Object File-2 Object File-3

Linker

.Exe File

Figure (3)
TC Business School | BEST BCA College In JAIPUR 6
6) .Exe file is an executable file which can direct execute from command prompt.
7) After pressing Alt+F9 , it will complete the whole process creating .obj and .exe
8) To display the output of the program press Alt+F5

Evolution of OOPS
Object Oriented Programming Language OOp’s

Procedural Language

Assembly Language

Machine
Language

Object- Oriented Programming (OOP) is an approach to program organization and


development that attempts to eliminate some structured programming features with
several powerful new concepts.

Machine Language

TC Business School | BEST BCA College In JAIPUR 7


 The first language which is easily understood by the computer is machine
language. Which is based on (0,1) character A may be represented as
01100101.
 It is only binary language the computer understand without translate.
 But machine language was not easy for user because to learn any program in
machine language form (0, 1) is too difficult, so for overcome this problem the
new language was generated which was “Assembly language”.

Assembly Language

 We use short English words for instruction. Like Add, jump, multi etc. This is
easily to learn. It is a low-level symbolic code converted by an assembler.
 A program is written in source code (Text File) and translated into machine
language by an assembler.
 To execute a program assembler take a lot of time so to overcome this problem
the new language was generated which was “Procedural Language”.

Procedural Language
 Procedural language is a type of computer programming language that specifies
a series of well-structured steps and procedures with in programming.
 Are easy to read, write and maintain than machine and assembly language.
 Use a compiler or interpreter to translate code.

 C language is a structured, procedural computer programming language.


TC Business School | BEST BCA College In JAIPUR 8
Sample C program

Objects Oriented Programming Language OOP‟s language is a type of computer


programming language.

C++fully supports object-oriented programming, including the four Concept of object-oriented


development:

Encapsulation

Data hiding

Inheritance

Polymorphism

Sample C++ program

TC Business School | BEST BCA College In JAIPUR 9


OOPS Paradigm
 A programming paradigm is the pattern or model of programming that drives the
process of programming.
 Every middle and high-level programming language has a paradigm that guides
in problem solving with in a framework (class) and gives solution.
 Object oriented programming (OOP) is a programming paradigm based on the
concept of “object”, which are data structures that contain data and its function.

Advantage of OOPS
These are some of major advantage of OOPS:

1) Simplicitysoftware object model real world objects, so the complexity is


reduced and the program structure is very clear.
2) ModularityOOP provide a clear modular structure for programs which makes it
good for defining abstract data types where implementation details are hidden.
3) Modifiabilityit is easy to make minor changes in the data representation or the
procedures in an OO program. Changes inside a class do not affect any other
part of a program.
4) ExtensibilityAdding new features or responding to changing operating
environments can be solved by the introducing the concept of data classes
allows a programmer to create any new data type that is not already defined in
the language itself.
5) Securitysince a class defines the data when it createsa instance of that class is
run, the code will not be able to access other program data. The access specifier
is providing a security in C++.
6) Maintainabilityobject can be maintained separately.
7) Reusabilityobject can be reused in different programs. For example
inheritance, define subclass of data objects that share data some or all of the
main class is called inheritance.
8) Accurate codingOOP is creates an accurate coding because it creates a
separate class with separate data and its function.

TC Business School | BEST BCA College In JAIPUR 10


Structure of C++ language

Difference between function programming and OOPS


approach

S.NO Basic Functional Programming OOP Approach


Small Program are divided Program are divided into
1. Divided into into small parts are called small parts are called class.
function.
It follows bottom-up
2. Approach It follows top-down approach approach
3. Access Specifier Does not have access Have access specifier i.e.
specifier Private, Public, Protected

4.
Data Moving Data can moved freely from Data cannot move freely
function to function because of access specifier

5. Expansion It is not easy to add new data Easy ways to add feature
and function i.e. new data and functions.

6. Data Access Function use global data for Data cannot move easily
sharing that can be access from function to function
freely because of access specifier.

7. Data Secure Less Secure More Secure

TC Business School | BEST BCA College In JAIPUR 11


8. Over loading Not possible Possible using function or
operator overloading

9. Example C, VB, Pascal C++, JAVA, .NET

Difference b/w C and C++ language

C is a structure programming language where we have to write the all at a strut but C++
is a modular programming language (Processer programming language) where the
program are written in the form of Classes.

C is an excellent programming language and it has a limit in language if a


program extend from, 25,000 to 1,00,000 lines of code it become complex. That‟s way
we used to C++. C++ is also those extended version of C Language and it is implement
by Bajarnesleoustrup and it is invented in 1979. It is the most widely used language in
the world.

C was implementing by Dennis Ritchie in 1972. C++ is also known as Object


Oriented Programming language.

Characteristics of objected language


It is necessary to understand some of the concept used in object-oriented programming.
The characteristics/Function of OOP language are defined as follow:

Classes
 A class can be defined as a template/blueprint that describes the
behaviors/states that object of its type support.
 A class is a collection of object of similar type. Once a class is defined, any
number of objects can be created which belong to that class.
 The entire set of data and code of an objects can be made user-defined data
type with the help of a class, In fact object are variable of the type class.

TC Business School | BEST BCA College In JAIPUR 12


syntax of class
Class class-name
{
private:
data member //States
public:
member function //Behavior
};

Object
 Object is run time states (instances of a class) in an object-oriented system.
Programming problem is analyzed in terms of objects.
 Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors - wagging, barking, and eating. An object is an
instance of a class.
 In OOP class can be execute by instance of class.
 Another way we understand an object using diagram

Fig(1) Object Model

TC Business School | BEST BCA College In JAIPUR 13


Fig(2) Object Model

Encapsulation
C++ programs are composed of the following two fundamental elements:
 Program statements (code): This is the part of a program that performs actions
and they are called functions.
 Program data: The data is the information of the program which affected by
the program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data
and functions that manipulate the data, and that keeps both safe from outside
interference and misuse. Data encapsulation led to the important OOP concept of data
hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can contain
private, protected and public members. By default, all items defined in a class are
private.

TC Business School | BEST BCA College In JAIPUR 14


Data Abstraction
Abstraction refers to the act of representing features without including the background
details or explanation.
Classes use the concept of abstraction and are defined as list of abstract attributes.

Inheritance
 One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class,
which makes it easier to create and maintain an application.
 This also provides an opportunity to reuse the code functionality and fast
implementation time.
 When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called the base
class, and the new class is referred to as the derived class.
 The idea of inheritance implements in a relationship. (it create a new class from a
existing once. New class inherit code form a existing class)

Fig(1) Inheritance

TC Business School | BEST BCA College In JAIPUR 15


Reusability
In OOP, the concepts of inheritance provide the ideal of reusability. This means that we
can add additional features to an existing class with modifying it.
This is possible by deriving a new class from the existing one. The new class will have
combined features of both classes. The inheritance mechanism is allows the
programmer to reuse a class.

User defined data types


There are two type of user defined data types such as structure (struct) and union
(union) in C but C++ have a three type of data type such as structure (struct), union
(union) and class.

Polymorphism
Polymorphism is another important OOP concept. Polymorphism means the ability to
take more than one form.
Figure(1) example that a single function name can be used to handle different number
and different type of arguments. This is something similar to a particular word having
several different meaning (arguments). Using a single function name to perform
different types of tasks is known as function overloading.

Overloading
C++ allows you to specify more than one definition for a function name or an operator
inthe same scope, which is called function overloading and operator overloading
respectively.
An overloaded declaration is a declaration that had been declared with the same name
as a previously declared declaration in the same scope,

TC Business School | BEST BCA College In JAIPUR 16


Q1) WAP to print “Hello” without using class.

Output:

TC Business School | BEST BCA College In JAIPUR 17


Q2) WAP to print Hello & how r u without using class.

Output:

TC Business School | BEST BCA College In JAIPUR 18


Q3) WAP to print Hello & how r u using class.

Output:

TC Business School | BEST BCA College In JAIPUR 19


Q4) WAP add two numbers without using class.

Output:

TC Business School | BEST BCA College In JAIPUR 20


Q5) WAP add two numbers using class.

Output:

TC Business School | BEST BCA College In JAIPUR 21


UNIT-2

Introduction to C++:C++ tokens, data types, C++ operators, type conversion, variable
declaration, statements, expressions, conditional statements, jumping statements,
loops, array, Function, Pointers, Structures.

Introduction of C++
 C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form
programming language that supports procedural, object-oriented, and generic
programming.
 C++ is regarded as a High-level language, as it comprises a combination of low-level
language features.
 C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill and
originally named C with Classes but later it was renamed C++ in 1983.
 C++ is a superset of C.
 The purpose of learning a programming language is to become a better programmer;
that is, to become more effective at designing and implementing new systems and at
maintaining old ones.
 C++ is used by hundreds of thousands of programmers in essentially every application
domain.
 C++ is being highly used to write device drivers and other software that rely on direct
manipulation of hardware under real-time constraints.

Simple Program

// my first program in C++


#include <iostream.h>
#include <conio.h>
int main()
{
cout <<"Hello World!";
getch();
return 0;
}

Output:

Hello World!

TC Business School | BEST BCA College In JAIPUR 22


#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not
regular code lines with expressions but indications for the compiler's preprocessor. In
this case the directive #include<iostream>tells the preprocessor to include the iostream
standard file. This specific file (iostream) includes the declarations of the basic standard
input-output library in C++, and it is included because its functionality is going to be
used later in the program.
using namespace std;
All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std. So in order to access its functionality
we declare with this expression that we will be using these entities. This line is very
frequent in C++ programs that use the standard library.
int main ()
This line corresponds to the beginning of the definition of the main function. The main
function is the point by where all C++ programs start their execution, independently of
its location within the source code. The instructions contained within this function's
definition will always be the first ones to be executed in any C++ program. For that
same reason, it is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses (()). That is because it is
a function declaration, these parentheses may enclose a list of parameters within them.
Right after these parentheses we can find the body of the main function enclosed in
braces ({}). What is contained within these braces is what the function does when it is
executed.
cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can
actually produce some effect. cout represents the standard output stream in C++, and
the meaning of the entire statement is to insert a sequence of characters (in this case
the Hello World sequence of characters) into the standard output stream (which usually
is the screen).
cout is declared in the iostream standard file within the std namespace.

TC Business School | BEST BCA College In JAIPUR 23


Notice that the statement ends with a semicolon character (;). This character is used to
mark the end of the statement and in fact it must be included at the end of all
expression statements in all C++ programs (one of the most common syntax errors is
indeed to forget to include some semicolon after a statement).

Note:-

Void Main()Main() is a function which is system defined and the word Void means the
function doesn‟t return a Value.

return 0;
The return statement causes the main function to finish. return may be followed by a
return code (in our example is followed by the return code 0). A return code of 0 for the
main function is generally interpreted as the program worked as expected without any
errors during its execution. This is the most usual way to end a C++ console program.

Variables
Definition:
1. Variable is used to store the value. The value of a variable can be change during
the execution of program or a variable is the name of memory location where the
value is to be store.
2. Variable are declare at the starting of a Program with there data type.
3. Maximum length is 8.
As a programmer, you will frequently want your program to
"remember" a value. For example, if your program requests a value from the user, or if it
calculates a value, you will want to remember it somewhere so you can use it later. The
way your program remembers things is by using variables.
For example:
int b;
This line says, "I want to create a space called b that is able to hold one integer value."
A variable has a name (in this case, b) and a type (in this case, int, an integer). You
can store a value in b by saying something like:

TC Business School | BEST BCA College In JAIPUR 24


b = 5;
You can use the value in b by saying something like:
Cout<<b;
The Simplest C Program: What's Happening?
#include <iostream.h>
#include<conio.h>
void main ()
{
int a=10,b=20,c;
c=a+b;
cout<<“The sum of c=”;
cout<<c;
getch();
}

Rules of Declare the variable


Following rules are used to declare a variable
I. Variable name should be Short meaning-full also.
II. Variable name can be Capital case also.
III. No Blank space is allowed b/w the name of variable.
IV. Underscore ( _ ) and aspersion ( & ) can be used let in the name of
variable.
V. The First digit should be Character and can be followed by integer.

Identifiers
 Identifiers refer to the names of variables, functions and arrays.
 Identifier name must differ in spelling and case from any keywords.
 We cannot use keywords as identifiers; they are reserved for special use.
 Identifiers are user-defined names and consist of a sequence of letters
and digits, with a letter as a first character. Both uppercase and lowercase
letters are permitted. The underscore character is also permitted.
 A valid identifier is a sequence of one or more letters, digits or underscores
characters (_). Neither spaces nor punctuation marks or symbols can be
part of an identifier.
TC Business School | BEST BCA College In JAIPUR 25
 Only letters, digits and single underscore characters are valid. In addition,
variable identifiers always have to begin with a letter.

Note:
Very important: The C++ language is a "case sensitive" language. That means that
an identifier written in capital letters is not equivalent to another one with the same
name but written in small letters. Thus, for example, the
RESULT variable is not the same as the result variable or the Result variable. These
are three different variable identifiers.

Data Types
While writing program in any language, you need to use various variables to
store various information. Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve some space in
memory.
You may like to store information of various data types like character, wide
character, integer, floating point, double floating point, boolean etc. Based on the data
type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory.
Definition: Every Programming handles a different Type of Data and Value it depend
on Type of Data. There is a way to store a value in a variable is know as “Data Type”

Types of Data Type


There is various type of data type used in C++ language

TC Business School | BEST BCA College In JAIPUR 26


Note: class is also user defined data type.

A) Primary Data Type (Primitive Data Type)


C++ offers the programmer a rich assortment of built-in as well as user defined data
types. Following table lists down seven basic C++ data types:

Several of the basic types can be modified using one or more of these type modifiers:

How much memory it takes to store the value in memory, and what is maximum and
minimum value which can be stored in such type of variables. Following is the example,
which will produce correct size of various data types on your computer.

#include<iostream.h>
#include<conio.h>
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
getch();
return 0;

TC Business School | BEST BCA College In JAIPUR 27


}

This example uses endl, which inserts a new-line character after every line and<<
operator is being used to pass multiple values out to the screen. We are also using
sizeof() function to get size of various data types.
When the above code is compiled and executed, it produces the following result which
can vary from machine to machine:
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8

B) Secondary Data Type(Non-Primitive/Composite/Derived Data type)


There is Four Type of Primary Data Type
1) Array
2) Structure
3) Union
4) Pointer
C) User Define data type
There is three Type of Primary Data Type
1) enum
2) typedefine
3) class

1) Enum
An enumerated type declares an optional type name and a set of zero or more
identifiers that can be used as values of the type. Each enumerator is a constant
whose type is the enumeration.
Creating an enumeration requires the use of the keyword enum. The general
form of an enumeration type is:
enum enum-name { list of names } var-list;

TC Business School | BEST BCA College In JAIPUR 28


Here, the enum-name is the enumeration's type name. The list of names is
comma separated.
For example, the following code defines an enumeration of colors called colors
and the variable c of type color. Finally, c is assigned the value "blue".
enum color { red, green, blue } c;
c = blue;
By default, the value of the first name is 0, the second name has the value 1, and
the third has the value 2, and so on. But you can give a name, a specific value by
adding an initializer. For example, in the following enumeration, green will have
the value 5.
enum color { red, green=5, blue };
Here, blue will have a value of 6 because each name will be one greater than the
one that precedes it.

2) Typedef Declarations
You can create a new name for an existing type using typedef. Following is the
simple syntax to define a new type using typedef:
Syntax
typedef type newname;
For example, the following tells the compiler that feet is another name for int:
typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable
called distance:
feet distance;

3) Class(module, block)
All variable and methods are grouped in a class each class described and
individual object and each object is set to be instance of a class and each
instance of the class has its on variable and methods.
Classes are basically used for creating the user defined data type and the
functions of that class are called its member function. So classes is declared by

TC Business School | BEST BCA College In JAIPUR 29


using the keyword class and followed by the name of a class are open with
opening curlybracket ({) and semi column (;).
Class iskeywords which specify the type and scope of its member.
syntax of class
Class class-name
{
private:
data member
public:
member function
};

Practice Sheet-1
1) WAP to print the “welcome to C++ language” and “C is a Object Oriented
programming language” and “it is case sensitive”.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"Welcome to C language \n";
cout<<"C is a structured programming language \n";
cout<<"it is case sensitive";
getch();
}

2) WAP to find the sum of 2 given number.

#include<iostream.h>
#include<conio.h>
void main()
{
int x=10,y=20, sum;
clrscr();
sum=x+y;
cout<<sum is:";
cout<<sum;
getch();
TC Business School | BEST BCA College In JAIPUR 30
}

3) WAP to print the student roll no and marks- Hindi, English, math and find out
the sum and average.

#include<iostream.h>
#include<conio.h>
void main()
{
int rollno,hindi,english,math,sum;
float average;
clrscr();
cout<<"enter the roll no=";
cin>>rollno;
cout<<":: marks:: \n";
cout<<"Enter the marks hindi=";
cin>>hindi;
cout<<"Enter the marks english=";
cin>>english;
cout<<"Enter the marks hindi=";
cin>>math;
sum=hindi+english+math;
average=sum/3;
cout<<"the sum is="<<sum;
cout<<"the average is="<<average;
getch();
}

4) WAP to calculate the area of square. (Area=length*length)


5) WAP to calculated the area of rectangle ( Area= l*b)
6) WAP to calculate the simple Interest. (SI=P*R*T/100 )

#include<iostream.h>
#include<conio.h>
void main()
{
float SI,P,R,T;
clrscr();
cout<<"Enter the value of Priniciple =";
cin>>P;
cout<<"Enter the value of Rate =";

TC Business School | BEST BCA College In JAIPUR 31


cin>>R;
cout<<”Enter the value of Time =";
cin>>T;
SI=P*R*T/100;
cout<<"Simple Interest ="<<SI;
getch();
}

7) WAP to convert the number of days into month and day.


8) WAP to swapping the value of two variable using third variables.

#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
cout<<"Enter the value of a=";
cin>>a;
cout<<"Enter the value of b=";
cin>>b;
c=a;
a=b;
b=c;
cout<<"\n After swapping value of a="<<a;
cout<<"\n After swapping value of b=”<<b;
getch();
}

9) WAP to print the net salary of employee where the Basic salary is given.

PF=5% of basic salary


TA=7% of basic salary
DA=8% of basic salary
Net salary=Basic + TA + DA – PF
#include<iostream.h>
#include<conio.h>
void main()
{
int salary;
float pf,ta,da,netsal;

TC Business School | BEST BCA College In JAIPUR 32


clrscr();
cout<<"Enter the basic salary=";
cin>>salary;
cout<<"\n Pf is less in the salary is = 5%";
cout<<"\n Ta add in the basic salary is=7%";
cout<<"\n da add in the basic salary is=8%";
pf=salary*.05;
ta=salary*.07;
da=salary*.08;
netsal=salary+ta+da-pf;
cout<<"\n netsalary of employee="<<netsal;
getch();
}

10) WAP to Print Series-

Sum=1-x2/∟2+ x4/∟4- x6/∟6

#include<iostream.h>
#include<conio.h>
void main()
{
float x,x2,x4,x6;
float sum;
clrscr();
cout<<"Enter the value of x=";
cin>>x;
x2=x*x;
x4=x2*x2;
x6=x4*x2;
sum=1-x2/2+x4/24-x6/720;
cout<<"sum of series="<<sum;
getch();
}

Keywords

 Keywords are the reserve words which have some special meaning
in the Programming Language.

TC Business School | BEST BCA College In JAIPUR 33


 All keywords have fixed meanings and these meaning can‟t be
changed.

 Keywords serve as basic building blocks for program statements. All


keywords must be written in lowercase.

C++ Keywords
The following list shows the reserved words in C++. These reserved words maynot be
used as constant or variable or any other identifier names.

TC Business School | BEST BCA College In JAIPUR 34


Note:-

 Keywords are the words whose meaning has already been explained to the C++
compiler.
 The keywords cannot be used as variable name because if we do so, we are
trying to assign a new meaning to the keyword, which is not allowed by the
computer. For Example: auto, break, case, char, float , for, goto, int etc

Practice Sheet-2

1) Write a program which reads two float numbers and display their product.
2) Rahul basic salary is input throughthe keyboard. His dearness allowance is 40%
of basic salary, and house rent allowance is 20% of basic salary. Calculate his
gross salary.

3) Swap of two no‟s without using third variable


#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
cout<<"Enter the first value a=";
cin>>a;
cout<<"Enter the second value b=";
cin>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<"\n After swapping value of a="<<a;
cout<<"\n After swapping value of b="<<b;
getch();
}

4) Calculate sum of 5 subjects and find percentage


5) WAP to convert temperature from degree centigrade to Fahrenheit
Fahrenheit. (Fahrenheit=(1.8* centigrade) +32)

#include<iostream.h>
#include<conio.h>
void main()
{
float f,c;
clrscr();
TC Business School | BEST BCA College In JAIPUR 35
cout<<"Enter value for Centigrade = ";
cin>>c;
f=1.8*c+32;
cout<<"Fahrenheit is = "<<f;
getch();
}

6) WAP to convert the number of days into week and day

#include<iostream.h>
#include<conio.h>
void main()
{
int tday,week,day;
clrscr();
cout<<"Enter total days = ";
cin>>tday;
week=tday/7;
day=tday%7;
cout<<"Total week is = "<<week;
cout<<"\nTotal day is = "<<day;
getch();
}

7) Write a program to convert the total rupees into dollar.


#include<iostream.h>
#include<conio.h>
void main()
{
float r,d;
clrscr();
cout<<"Enter total rupees = ";
cin>>r;
d=r/45;
cout<<"Total dollar is = "<<d;
getch();
}

TC Business School | BEST BCA College In JAIPUR 36


OPERATORS AND EXPRESSION

 Operators to process the data entered by a user.


 An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
 An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. Operators like + and – are used to
process variables and returns a value.
 An operator is a set of one or more characters that is used for computations
or comparisons.
 Operators can transform one or more data values, called Operands, into a
new data value.

Consider the following expression:

X+Y

The preceding expression uses two operands and one operator to add the value
stored in the variable.

 C++ is rich in built-in operators and provide the following types of operators:

l Operators

Operators in ‘C++’ can be classified as follows

1) Arithmetic Operators:
These operators are the symbols that are used to perform arithmetic operations on
variable. The following table describes the commonly used arithmetic operators.

TC Business School | BEST BCA College In JAIPUR 37


Operator Meaning Description Example

+ Addition or unary plus Used to add two X=Y+Z


numbers
If Y is equal to 20 and z is equal to 2,
X will have the value 22.

- Subtraction or unary minus Used to X=Y-Z


Subtract two
If Y is equal to 20 and z is equal to 2,
numbers
X will have the value 18.

* Multiplication Used to multiply X=Y*Z


two numbers
If Y is equal to 20 and z is equal to 2,
X will have the value 40.

/ Division (Quadrant) Used to divide X=Y/Z


one number by
If Y is equal to 21 and z is equal to 2,
another
X will have the value 10.

But, if Y is equal to 21.0 and Z is


equal to 2, x will have the value 10.5

% Modulo Division (Reminder) Used to divide X=Y%Z


two number and
If Y is equal to 21 and z is equal to 2,
return the
X will have the value 1.
remainder

Note:- There are 3 category of Operator

I. Unary Operator (needs one operands)


II. Binary Operator (needs two operands)
III. Ternary Operator (needs three or more than operands)

TC Business School | BEST BCA College In JAIPUR 38


the following C++ program in test.cpp file and compile and runthis program.

#include<iostream.h>
#include<conio.h>
void main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "Line 1 - Value of c is :" << c << endl ;
c = a - b;
cout << "Line 2 - Value of c is :" << c << endl ;
c = a * b;
cout << "Line 3 - Value of c is :" << c << endl ;
c = a / b;
cout << "Line 4 - Value of c is :" << c << endl ;
c = a % b;
cout << "Line 5 - Value of c is :" << c << endl ;
c = a++;
cout << "Line 6 - Value of c is :" << c << endl ;
c = a--;
cout << "Line 7 - Value of c is :" << c << endl ;
getch();
return 0;
}

When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is :31
Line 2 - Value of c is :11
Line 3 - Value of c is :210
Line 4 - Value of c is :2
Line 5 - Value of c is :1
Line 6 - Value of c is :21
Line 7 - Value of c is :22

2) Arithmetic Assignment Operator:


These operators are used to perform arithmetic operations to assign a value to an
operand. The simplest of these is the “=”. Its general form is, var=expression. The
following table lists the usage and describes the commonly used assignment operators.
C allows *= += /= -= operators.
For example:

TC Business School | BEST BCA College In JAIPUR 39


Operator Meaning Usage Description

= Equal X=5; Stores the value 5 in the


variable X.

+= Plus equal X+=Y; Same as:

(arithmetic X=X+Y;
assignment)

-= Minus equal X-=Y; Same as:

X=X-Y;

*= Multiplication equal X*=Y; Same as:

X=X*Y;

/= Division equal X/=Y; Same as:

X=X/Y;

%= Modular equal X%=Y; Same as:

X=X%Y;

Example:-
a=a+1 equivalent to a+=1
a=a-1 equivalent to a-=1
a=a%b equivalent to a%=b

The following C++ program in test.cpp file and compile and run this program-

#include<iostream.h>
#include<conio.h>
Void main()
{
int a = 21;
int c ;
c = a;
cout << "Line 1 - = Operator, Value of c = : " <<c<< endl ;
c += a;

TC Business School | BEST BCA College In JAIPUR 40


cout << "Line 2 - += Operator, Value of c = : " <<c<< endl ;
c -= a;
cout << "Line 3 - -= Operator, Value of c = : " <<c<< endl ;
c *= a;
cout << "Line 4 - *= Operator, Value of c = : " <<c<< endl ;
c /= a;
cout << "Line 5 - /= Operator, Value of c = : " <<c<< endl ;
c = 200;
c %= a;
cout << "Line 6 - %= Operator, Value of c = : " <<c<< endl ;
c <<= 2;
cout << "Line 7 - <<= Operator, Value of c = : " <<c<< endl ;
c >>= 2;
cout << "Line 8 - >>= Operator, Value of c = : " <<c<< endl ;
c &= 2;
cout << "Line 9 - &= Operator, Value of c = : " <<c<< endl ;
c ^= 2;
cout << "Line 10 - ^= Operator, Value of c = : " <<c<< endl ;
c |= 2;
cout << "Line 11 - |= Operator, Value of c = : " <<c<< endl ;
return 0;
}

When the above code is compiled and executed, it produces the following result:

Line 1 - = Operator, Value of c = : 21


Line 2 - += Operator, Value of c = : 42
Line 3 - -= Operator, Value of c = : 21
Line 4 - *= Operator, Value of c = : 441
Line 5 - /= Operator, Value of c = : 21
Line 6 - %= Operator, Value of c = : 11
Line 7 - <<= Operator, Value of c = : 44
Line 8 - >>= Operator, Value of c = : 11
Line 9 - &= Operator, Value of c = : 2
Line 10 - ^= Operator, Value of c = : 0
Line 11 - |= Operator, Value of c = : 2

3) Relational (Comparison) Operators:


 These operators are used to compare two values and perform an action on the
basis of the result of the comparison. Whenever you use comparison operator,
the expression results a Boolean value „true‟ or „false‟.

TC Business School | BEST BCA College In JAIPUR 41


 There are six possibilities in C: <, <=, >, >=, !=, and ==. The first four a self-
explanatory, the != stands for "not equals to" and == is "equivalent to".
 Here we can point out the difference between syntax and semantics. a = b is
different from a == b. Most C compilers will allow both statements to be used in
conditionals like if, but they have two completely different meanings. Make sure
your assignment operators are where you want them to be used and you‟re
relational where you want relational comparisons!
The following table explains the usage of commonly used comparison operators.
Operator Usage Description Example

(In the following examples, the value


of X is assumed to be 20 and the
value of Y is assumed to be 25)

< Expression1< Used to check whether bool Result;


expression1 is less then
expression2 expresson2 Result= X<Y;

Result will have the value true,

> Expression1> Used to check whether bool Result;


expression1 is greater then
expression2 expresson2 Result= X>Y;

Result will have the value false,

<= Expression1<= Used to check whether bool Result;


expression2 expression1 is less then or
equal to expresson2 Result= X<=Y;

Result will have the value true,

>= Expression1>= Used to check whether bool Result;


expression2 expression1 is greater then
or equal expresson2 Result= X>=Y;

Result will have the value false,

== Expression1== Used to check whether bool Result;


expression2 expression1 is equal to
expresson2 Result= X==Y;

TC Business School | BEST BCA College In JAIPUR 42


Result will have the value false,

!= Expression1! = Used to check whether bool Result;


expression1 is not equal to
expression2 expresson2 Result= X!=Y;

Result will have the value true,

The following C++ program in test.cpp file and compile and run this program

#include<iostream.h>
#include<conio.h>
void main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
cout << "Line 1 - a is equal to b" << endl ;
}
else
{
cout << "Line 1 - a is not equal to b" << endl ;
}
if ( a < b )
{
cout << "Line 2 - a is less than b" << endl ;
}
else
{
cout << "Line 2 - a is not less than b" << endl ;
}
if ( a > b )
{
cout << "Line 3 - a is greater than b" << endl ;
}
else
{
cout << "Line 3 - a is not greater than b" << endl ;
}
/* Let's change the values of a and b */
a = 5;

TC Business School | BEST BCA College In JAIPUR 43


b = 20;
if ( a <= b )
{
cout << "Line 4 - a is either less than or equal to b" << endl ;
}
if ( b >= a )
{
cout << "Line 5 - b is either greater than or equal to b" << endl ;
}
return 0;
}

When the above code is compiled and executed, it produces the following result:
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

4) Increment (++) operator /Decrement (--) operator:


 It is also called Unary Operators. These operators are used to increment or
decrement the value of an operand by 1.
 The two arithmetic operators that are used frequently are ++ and --. You can
place these in front or on the back of variables. ++ specifies increment, the --
specifies decrement. If the operator is placed in front, it is prefix if it is placed
behind, it is postfix. Prefix means, increment before any operations are
performed, postfix is increment afterwards. The following table explains the
usage of the increment and decrement operators.

Operator Usage Description Example

++ ++Operand; Used to Y=++X;


(Preincrement increment the If the initial value of X is 5, after
operator) value of an the execution of the preceding
OR, Operand by 1 statement, value of both X and Y
Operand++; will be 6.
(Postincrement Y=X++;
Operator) If the initial value of X is 5, after
the execution of the preceding
statement, value of both X will
be 6 and value of Y will be 5.

TC Business School | BEST BCA College In JAIPUR 44


-- --Operand; Used to Y=--X;
decrement the
(Predecrement If the initial value of X is 5, after
value of an
operator) the execution of the preceding
operand by 1
statement, value of both X and Y
OR,
will be 4.

Operand--;
Y=X--;
(Postdecrement
If the initial value of X is 5, after
Operator)
the execution of the preceding
statement, value of both X will
be 4 and value of Y will be 5.

5) Logical Operators:
 Logical operators are used to evaluate expression and return a Boolean value.
 Logical operators simulate Boolean algebra in C++.
 The following tables explain the usage of logical operators.
Operator Meaning Usage Description Example

&& logical Expression1 Returns true if int a,b;


AND && both
expression 1 cout<<"Enter the First value=";

Expression2 and cin>>a;


expression 2
are true cout<<"\n Enter the Second Value=";

cin>>b;

if((a==10)&&(b==20))

cout<<"True \n";

else

cout<<"False \n";

The message displays True if a has the

TC Business School | BEST BCA College In JAIPUR 45


value 10 and b has the value 20

|| logical OR Expression1 || Returns true if int a,b;


the expression
is false. cout<<"Enter the First value=";
Expression2
cin>>a;

cout<<"\n Enter the Second Value=";

cin>>b;

if((a==10)||(b==20))

cout<<"Condition is True\n";

else

cout<<"Condition is False \n";

The message displays True if one


condition is true in both two conditions.

! logical Expression1! Condition is int a,b;


NOT True, then
logical NOT cout<<"Enter the First value=";
Expression2
operator will cin>>a;
make false
cout<<"\n Enter the Second Value=";

cin>>b;

if(a!=10)

cout<<"Condition is False\n";

else

cout<<"Condition is True";

TC Business School | BEST BCA College In JAIPUR 46


if statement is true The message is
display false.

The following C++ program in test.cpp file and compile and run this
program
#include <iostream.h>
#include <conio.h>
void main()
{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
cout << "Line 1 - Condition is true"<< endl ;
}
if ( a || b )
{
cout << "Line 2 - Condition is true"<< endl ;
}
/* Let's change the values of a and b */
a = 0;
b = 10;
if ( a && b )
{
cout << "Line 3 - Condition is true"<< endl ;
}
else
{
cout << "Line 4 - Condition is not true"<< endl ;
}
if ( !(a && b) )
{
cout << "Line 5 - Condition is true"<< endl ;
}
return 0;
}

When the above code is compiled and executed, it produces the


following result:
Line 1 - Condition is true
Line 2 - Condition is true
Line 4 - Condition is not true
Line 5 - Condition is true

TC Business School | BEST BCA College In JAIPUR 47


6) Conditional Operators:
 It is also known as ternary operator which works on three operands and
used to evaluate conditional expression.
 A ternary operator pair “?:” is available in C++ to construct conditional
expressions of the form:

exp1? exp2: exp3


Working:
The exp1 is evaluated first; if it is nonzero (true) then the exp2 is evaluated and
becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value
becomes the value of the expression. Example:
a = 10;
b = 15;
x = (a>b)?a:b;
is equivalent to
if (a > b)
x = a;
else
x = b;

Note:-

exp1? exp2: exp3

Condition True False


value Value

Example:

a=5;

b=10;

m=a>b?a:b;

m=5>10?5:10;

output:

m=10; TC Business School | BEST BCA College In JAIPUR 48


7) Bitwise Operators:
These operators are used for testing the bits, or shifting them right or left. Bitwise operators may
not be applied to float or double.

Operator Meaning

& Bitwise AND

| Bitwise OR

<< Shift left

>> Shift right

~ 1’s complement

^ Bitwise exclusive OR

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^
are as follows:

Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
TC Business School | BEST BCA College In JAIPUR 49
A^B = 0011 0001
~A = 1100 0011

The following C++ program in test.cpp file and compile and run this program

#include<iostream.h>
#include<conio.h>
void main()
{
unsigned int a = 60; // 60 = 0011 1100
unsigned int b = 13; // 13 = 0000 1101
int c = 0;
c = a & b; // 12 = 0000 1100
cout << "Line 1 - Value of c is : " << c << endl ;
c = a | b; // 61 = 0011 1101
cout << "Line 2 - Value of c is: " << c << endl ;
c = a ^ b; // 49 = 0011 0001
cout << "Line 3 - Value of c is: " << c << endl ;
c = ~a; // -61 = 1100 0011
cout << "Line 4 - Value of c is: " << c << endl ;
c = a << 2; // 240 = 1111 0000
cout << "Line 5 - Value of c is: " << c << endl ;
c = a >> 2; // 15 = 0000 1111
cout << "Line 6 - Value of c is: " << c << endl ;
getch();
return 0;
}

When the above code is compiled and executed, it produces the following
result:

Line 1 - Value of c is : 12
Line 2 - Value of c is: 61
Line 3 - Value of c is: 49
Line 4 - Value of c is: -61
Line 5 - Value of c is: 240
Line 6 - Value of c is: 15

TC Business School | BEST BCA College In JAIPUR 50


Practice Sheet-3

1) WAP to explain all Logical operators in C++ language.

#include<iostream.h>
#include<conio.h>
void main()
{
/*Logical AND && */
char rs;
char ch1,ch2;
ch1='A';
ch2='B';
clrscr();
if((ch1=='A')&&(ch2=='B'))
{
cout<<"Both Condition are true in Logical AND \n";
}
else
{
cout<<"False \n";
}
getch();
}

/* Another Example of Logical Operator */

#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
cout<<"Enter the First Integer value=";
cin>>a;
cout<<"\n Enter the Second Integer Value=";
cin>>b;
/*Logical AND*/
if((a==10)&&(b==20))
{
cout<<"Both Condition are true in Logical AND \n";
}

TC Business School | BEST BCA College In JAIPUR 51


else
{
cout<<("False \n";
}
/*Logical OR*/

if(a||b)
{
cout<<"Condition is True \n";
}
else
{
cout<<"Condition is False";
}

/*Logical NOT */
if(a!=10)
{
cout<<"Condition is False\n";
}
else
{
cout<<"Condition is True";
}
getch();
}

2) WAP to explain all Increment (++)/Decrement (--) operators in C++ language.


#include<iostream.h>
#include<conio.h>
void main()
{
int x=5,y;
clrscr();
/*Pre-increment Operator*/
cout<<"initilize the value of x= "<<x;
y=++x;
cout<<"\n Preincrement value of x="<<x;
cout<<"\n Preincrement value of y="<<y;
/*Post-increment Operator*/
cout<<endln;
cout<<endln;
x=5;
cout<<"\n initilize the value of x= "<<x;

TC Business School | BEST BCA College In JAIPUR 52


y=x++;
cout<<"\n Preincrement value of x= "<<x;
cout<<"\n Preincrement value of y="<<y;
/*Pre-Decrement Operator*/
cout<<endln;
cout<<endln;

x=5;
cout<<"\n initilize the value of x= "<<x;
y=--x;
cout<<"\n Pre-Decrement value of x= "<<x;
cout<<"\n Pre-Decrement value of y="<<y;
/*Post-Decrement Operator*/
cout<<endln;
cout<<endln;

x=5;
cout<<"\n initilize the value of x="<<x;
y=x--;
cout<<"\n Post-Decrement value of x="<<x;
cout<<"\n Post-Decrement value of y=”<<y;
getch();
}

3) WAP to explain Conditional Operator operators in C++ language.

#include<iostream.h>
#include<conio.h>
void main()
{
int a=5;
int b=10;
int m;
clrscr();
m=(a>b)?a:b;
if(a>b)
{
m=a;
cout<<"m="<<m;
}
else
{
m=b;
cout<<"m="<<m;

TC Business School | BEST BCA College In JAIPUR 53


}
getch();
}

4) WAP to check the number is even and odd.


#include<iostream.h>
#include<conio.h>
void main()
{
int a;
clrscr();
cout<<"Enter Any Integer number=";
cin>>a;
if(a%2==0)
{
cout<<"\n Even";
}
else
{
cout<<"\n Odd";
}
getch();
}

5) WAP to calculate the Quadrant value and Reminder value using two variables
(Using Arithmetic Operator).
#include<iostream.h>
#include<conio.h>
void main()
{
int first,second,q,r;
clrscr();
cout<<"Enter the any no=";
cin>>first;
cout<<"Enter the second value=";
cin>>second;
q=first/second;
r=first%second;
cout<<"\n Quadrant="cout<<q;
cout<<"\n Reminder="cout<<r;
getch();
}

TC Business School | BEST BCA College In JAIPUR 54


6) WAP to find the year is leap year or not?
#include<iostream.h>
#include<conio.h>
void main()
{
/* Common Year,which has 365 days.Leap Year, Which has 366 days.
Leap Year, Occuring once every four years,Which has 366 days including 29
February.
List (2008-2032) of Leap Year(2008,2012,2016,2020,2024,2028,2032) */
int year;
clrscr();
cout<<"Enter the year= ";
cin>>year;
if(year%4==0)
{
cout<<"Leap Year ";
}
else
{
cout<<"Not a Leap Year";
}
getch();
}

7) Apple cost RS 60 per dozen. It is required to find the cost of 28 apples to the
nearest rupees and print the answer as Rupees.

#include<iostream.h>

#include<conio.h>

void main()
{
int rate=60,rup,total;
clrscr();
cout<<"Per dozen apples rate= "<<rate;
rup=rate/12;
cout<<"1 apple cost=”<<rup;
total=rup*28;
cout<<"28 apple cost="<<total;
getch();
}
8) Write a program to print any values and count thousand, hundred, ten and one.

#include<iostream.h>

TC Business School | BEST BCA College In JAIPUR 55


#include<conio.h>

void main()

int number,x,x1,x2,x3,x4,x5,x6;

clrscr();

cout<<"Ener the number= ";

cin>>number;

x=number/1000;

x1=number%1000;

cout<<"\n Thousand= "<<x;

x2=x1/100;

x3=x1%100;

cout<<"\n hundred="<<x2;

x4=x3/10;

x5=x3%10;

cout<<"\n Ten="<<x4;

x6=x5/1;

cout<<"\n One= "<<x6;

getch();

TC Business School | BEST BCA College In JAIPUR 56


DECISION-MAKING STATEMENTS
Decision making structures require that the programmer specify one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.
Following is the general from of a typical decision making structure found in most
of the programming languages:

C++ programming language provides following types of decision makingstatements.

TC Business School | BEST BCA College In JAIPUR 57


1)If Statement
An if statement consists of a Boolean expression followed by one or more
statements.

Syntax:

The syntax of an if statement in C++ is:

if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}

If the Boolean expression evaluates to true, then the block of code inside the if
statement will be executed. If Boolean expression evaluates to false, then the first set of
code after the end of the if statement (after the closing curly brace) will be executed.
Flow Diagram

TC Business School | BEST BCA College In JAIPUR 58


Example

#include <iostream.h>
#include <conio.h>
int main ()
{
// local variable declaration:
int a = 10;
// check the boolean condition
if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
getch();
return 0;
}

When the above code is compiled and executed, it produces the following result:

a is less than 20;


value of a is : 10

2) if…else Statement
An if statement can be followed by an optional else
statement, which executeswhen the Boolean expression is false.
Syntax
The syntax of an if...else statement in C++ is:

if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
else
{
// statement(s) will execute if the boolean expression is false
}

TC Business School | BEST BCA College In JAIPUR 59


If the boolean expression evaluates to true, then the if block of code will beexecuted,
otherwise else block of code will be executed.
Flow Diagram

Example

#include<iostream.h>
#include<conio.h>
int main ()
{
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
else
{
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:

a is not less than 20;


value of a is : 100

TC Business School | BEST BCA College In JAIPUR 60


3) if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is
very usefull to test various conditions using single if...else if statement.
The if statement checks whether the test condition is true or not. If the test
condition is true, it executes the code/s inside the body of if statement. But it the test
condition is false, it skips the code/s inside the body of if statement.

Flowchart

Syntax

TC Business School | BEST BCA College In JAIPUR 61


The syntax of an if...else if...else statement in C++ is:

if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}

Example

#include <iostream.h>
#include <conio.h>
int main ()
{
// local variable declaration:
int a = 100;
// check the boolean condition
if(a == 10)

{
// if condition is true then print the following
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
// if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
// if else if condition is true
cout << "Value of a is 30" << endl;
}
else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;

TC Business School | BEST BCA College In JAIPUR 62


}
cout << "Exact value of a is : " << a << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:

Value of a is not matching


Exact value of a is : 100

Q) WAP to find maximum and minimum value out of 3 values and find its mid value?

#include<iostream.h>

#include<conio.h>

void main()

int a,b,c,min,max,mid;

cout<<"Ener 3 no=";

cin>>a>>b>>c;

if(a>b && a>c)

max=a;

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

max=b;

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

max=c;

if(a<b && a<c)

min=a;

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

min=b;

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

min=c;

TC Business School | BEST BCA College In JAIPUR 63


mid=(a+b+c)-(min+max);

cout<<"max="<<max<<endl;

cout<<"min="<<min<<endl;

cout<<"mid value is="<<mid;

getch();

};

When the above code is compiled and executed, it produces the following result:

4) Nested if Statement
It is always legal to nest if-else statements, which means you can use one if orelse if
statement inside another if or else if statement(s).

Syntax

The syntax for a nested if statement is as follows:

if( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
}

You can nest else if...else in the similar way as you have nested if statement.

Example
#include <iostream.h>

TC Business School | BEST BCA College In JAIPUR 64


#include <conio.h>
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
// check the boolean condition
if( a == 100 )
{
// if condition is true then check the following
if( b == 200 )
{
// if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200

5) Switch Statement
A switch statement allows a variable to be tested for equality against a list ofvalues.
Each value is called a case, and the variable being switched on is checked for each
case.
Syntax

The syntax for a switch statement in C++ is as follows:

switch(expression)
{
case constant-expression :
statement(s);
break; //optional
case constant-expression :

TC Business School | BEST BCA College In JAIPUR 65


statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);
}

The following rules apply to a switch statement:


 The expression used in a switch statement must have an integral or enumerated
type, or be of a class type in which the class has a single conversion function to an
integral or enumerated type.
 You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in
the switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will
fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none of
the cases is true. No break is needed in the default case.
Flow Diagram

TC Business School | BEST BCA College In JAIPUR 66


Example

#include <iostream.h>
#include <conio.h>
int main ()
{
// local variable declaration:
char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;

case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
getch();

TC Business School | BEST BCA College In JAIPUR 67


return 0;
}

This would produce the following result:


You passed
Your grade is D

6) Nested switch Statements


It is possible to have a switch as part of the statement sequence of an outerswitch.
Even if the case constants of the inner and outer switch contain common values, no
conflicts will arise.
C++ specifies that at least 256 levels of nesting be allowed for switch statements.
Syntax

The syntax for a nested switch statement is as follows:

switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
}

Example

#include <iostream.h>
#include <conio.h>
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
switch(a)
{
case 100:
cout << "This is part of outer switch" << endl;
switch(b)

TC Business School | BEST BCA College In JAIPUR 68


{
case 200:
cout << "This is part of inner switch" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}

This would produce the following result:

This is part of outer switch


This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

The ? : Operator

We have covered conditional operator “? :” in previous chapter which can beused to


replace if...else statements. It has the following general form:
Exp1 ? Exp2 : Exp3;
Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a „?‟ expression is determined like this: Exp1 is evaluated. If it is true, then
Exp2 is evaluated and becomes the value of the entire „?‟ expression.
If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the
expression.

TC Business School | BEST BCA College In JAIPUR 69


LOOP TYPES
There may be a situation, when you need to execute a block of code several numbers of times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general from of a loop statement in most of the programming languages:

C++ programming language provides the following type of loops to handle looping
requirements.

TC Business School | BEST BCA College In JAIPUR 70


1) For Loop
The for loop is used to execute a block of statement of a specific number of times. It has three
parameters
1) initialization
2) termination (Condition)
3) increment/decrement
All the three Parameters are separated by semicolon (;)
Syntax
The following code is the syntax of the for loop construct
for (initialization; termination; increment/decrement)
{
Statements;
}
 The init step is executed first, and only once. The initialization expression initializes the
for loop construct. It is executed once at the beginning of the loop.
 Next, the condition is evaluated, The termination (condition) expression determines
when to terminate the loop. At the beginning of the loop, this expression is evaluated for
each iteration. When the expression evaluates to false, the loop terminates, through the
loop.
 The increment or decrement expression gets invoked after each iteration. All these
component are option.
Flow Diagram

TC Business School | BEST BCA College In JAIPUR 71


Example

#include <iostream.h>
#include <conio.h>
int main ()
{
// for loop execution
for( int a = 10; a < 20; a = a + 1 )
{
cout<<"value of a: " <<a <<endl;
}
return 0;
}

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Q1) WAP to check the given no is prime no or not?

#include<iostream.h>
#include<conio.h>
int main()
{
int a;
cout<<"enter any no ;"<<endl;
cin>>a;
if(a%2==0)
{
cout<<"no is not prime"<<endl;
}
else
{
cout<<"no is prime"<<endl;
}
getch();

TC Business School | BEST BCA College In JAIPUR 72


return 0;
}

Q2)WAP to print table using for loop in C++.

#include<iostream.h>
#include<conio.h>
int main()
{
int i,n,r=0;
cout<<"enter the value of table:";
cin>>n;
cout<<"table is:"<<endl;
for(i=1;i<=10;i++)
{
r=n*i;
cout<<n<<'*'<<i<<'='<<r<<endl;
}
getch();
return 0;
}

2) While Loop
It is also known as Entry control loop. The wile loop is used to execute a block of
statements for a definite number of times, depending on a condition. The while
statement always checks the condition before executing the statements within the loop.
When the execution reaches the last statement in the while loop, the control is passed
back to the beginning of the loop. It the condition still holds true, the statements within
the loop are executed again. The execution of the statement within the loop continues
until the condition evaluates to false.
Syntax

The syntax of a while loop in C++ is:

while(condition)
{
statement(s);
}

TC Business School | BEST BCA College In JAIPUR 73


Flow Diagram

While
Structure
Star
t

True
Conditio Statement
n

False

Stop

Example
#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}
return 0;
}

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

TC Business School | BEST BCA College In JAIPUR 74


Q) WAP to Enter the number upto the sum is to be displayed starting from 1 using while loop.

#include<iostream.h>
#include<conio.h>
int main()
{
int i,sum=0,n;
cout<<"Enter the number upto the sum is to be displayed starting from 1 : ";
cin>>n;
i=1;
while(i<=n)
{
sum=sum+i;
i++;
}
cout<<"Sum = "<<sum;
getch();
return 0;
}

3)do…while Loop
It is also known as exit control loop. Unlike for and while loops, which test the loop condition
at the top of the loop, the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax

The syntax of a do...while loop in C++ is:

do
{
statement(s);
}
while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.

TC Business School | BEST BCA College In JAIPUR 75


Flow Diagram

Example

#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}

When the above code is compiled and executed, it produces the following
result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

TC Business School | BEST BCA College In JAIPUR 76


Q) WAP to Enter the number upto the sum is to be displayed starting from 1 using do while
loop.

#include<iostream.h>
#include<conio.h>
int main()
{
int i,sum=0,n;
cout<<"Enter the number upto the sum is to be displayed starting from 1 : ";
cin>>n;
i=1;
do
{
sum=sum+i;
i++;
}while(i<=n);
cout<<"Sum = "<<sum;
getch();
return 0;
}

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
C++ supports the following control statements.

TC Business School | BEST BCA College In JAIPUR 77


Break Statement
The break statement has the following two usages in C++:
 When the break statement is encountered inside a loop, the loop is immediately terminated
and program control resumes at the next statement following the loop.
 It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop
the execution of the innermost loop and start executing the next line of code after the block.
Syntax
The syntax of a break statement in C++ is:
break;

Flow Diagram

Example

#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15)
TC Business School | BEST BCA College In JAIPUR 78
{
// terminate the loop
break;
}
}while( a < 20 );
return 0;
}

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

continue Statement
The continue statement works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any
code in between.
For the for loop, continue causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, program control passes to the conditional tests.
Syntax
The syntax of a continue statement in C++ is:
continue;
Flow Diagram

TC Business School | BEST BCA College In JAIPUR 79


Example

#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
if( a == 15)
{
// skip the iteration.
a = a + 1;
continue;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

goto Statement
goto statement is used to Break the normal execution of a Program. The goto require a
level In order to identify the place where the branch is to be made. The level must be followed
by colons (:)

Example:WAP to print natural number (1 to 50).

#include<iostream.h>
#include<conio.h>
void main()
{
int n=1,no;
TC Business School | BEST BCA College In JAIPUR 80
clrscr();
cout<<"Enter the natural no limit=";
cin>>no;
l1:
cout<<"natural no= "cout<<n;
n++;
if(n<=no)
goto l1;
getch();
}

Flow Diagram

Example

#include <iostream.h>
#include <conio.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
LOOP:do
{
if( a == 15)
{
// skip the iteration.
a = a + 1;
goto LOOP;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
TC Business School | BEST BCA College In JAIPUR 81
When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

The Infinite Loop


A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally
used for this purpose. Since none of the three expressions that form the „for‟ loop are required,
you can make an endless loop by leaving the conditional expression empty.
#include <iostream.h>
#include <conio.h>
int main ()
{
for( ; ; )
{
Cout<<"This loop will run forever.\n";
}
return 0;
}

When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the „for (;;)‟
construct to signify an infinite loop.
NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.

TC Business School | BEST BCA College In JAIPUR 82


ARRAY
 Array is a collection of values of the same data type and share a common name but
different Index value. For example, you can create an array that stores 10 integer type
values. The variables in an array are called the “array element”. Array elements are
accessed using a single name and an index number representing the position of the
element within the array. Array is a reference type data type.
 A variable can hold single value at a time but if we want to store multiple values at a time
then we have to declare an array store in the memory in continuous manner.
 An Array is a data structure, process multiple elements with the same data type.
 Each element of the array is given a number by which we can access that element.
 For an array of 100 elements, the first element is 0 (zero) and the last is 99. This
indexed access marks it very convenient to loop through each element of the array.

Size of Array
Declaring An Array &
Index
Datatype Arrayname[ ] &
Subscript
int a[3];

The explanation of the elements of the preceding statement is as follows:

 datatype: Is used to specify the data type for the elements, which will be stored in the
array.
 [ ]: Is used to specify the rank of the array. Rank is used to specify the size of the array. [
] is also called Index, Size, Subscript. Know in example [3] this size indicate that the
maximum number of elements we can stores in an array but the compiler Interpret the
first elements as „0‟.
 Arrayname: Is used to specify the name of the array using which the elements of the
array will be initialized and manipulated.
 BEWARE: In C++ Array subscripts start at 0 and end one less than the array number.

Array size, Array can be initialized by two ways:


1) int a[3]={10,20,30}
2) int a[ ]={10,20,30,40}

TC Business School | BEST BCA College In JAIPUR 83


For example:

#include<iostream.h>
#include<conio.h>
void main()
{
char ch[5]="SCHOLARS";
cout<<ch;
getch();
}

Use of character array with For Loop 

#include<iostream.h>
#include<conio.h>
void main()
{
char ch[5]="SCHOLARS";
// char ch[5]={'A','N','A','N','T'};
int i;
clrscr();
for(i=0;i<=4;i++)
{
cout<<ch[i];
}
getch();
}

Array are two type


1) Single dimensional (one dimensional)
2) Multidimensional array (two dimensional)

1) Single dimensional
In single dimensional array the list of items store only in one
dimensional. If the array is integer type then each value will take a space of 2 bytes.
int a[5}={10,20,30,40,50}

Fig(1) memory allocation in one dimensional array

TC Business School | BEST BCA College In JAIPUR 84


1) WAP to Reverse the given number (1 2 3 4).

#include<iostream.h>
#include<conio.h>
void main()
{
int a[4]={1,2,3,4};
int i;
clrscr();
for(i=0;i<=3;i++)
{
cout<<a[i];
}
for(i=3;i>=0;i--)
{
cout<<a[i];
}
getch();
}

2) WAP to calculate the average of given number in an array?

#include<iostream.h>
#include<conio.h>
void main()
{
int num[10],i,sum=0;
float avg;
clrscr();
for(i=0;i<=9;i++)
{
cout<<”enter the num=";
cin>>num[i];
sum=sum+num[i];
}
avg=sum/10;
cout<<"avg is= "<<avg;
getch();
}

TC Business School | BEST BCA College In JAIPUR 85


2) Multi-dimensional arrays
 In C++ language, one can have arrays of any dimensions. To understand the concept of
multidimensional arrays we consider the following 2×3 matrix:

Column number [j]


0 1 2
Row number [i] 0 a0,0 a0,1 a0,2

1 a1,0 a1,1 a1,2

 To access the particular element from the array we have to use two subscripts one for
row number and other for column number. The notation is of the form a[i][j], where I
stands for row subscripts and j stands for column subscripts.
 Thus, a[0][0] refers to the first element of the two-dimensional array and so on and
a[0][0] is same as a0,0
 We can also define and initialize the array as follow:
int values [3][4]={ {1,2,3,4}
{5,6,7,8}
{9,10,11,12}
};
 In Two dimensional arrays there is two dimensional known as X and Y and the value is
stored in two dimensional arrays in the form of table. Table is the combination of rows
and column matrix.
 Multi-dimensional arrays can be defined as follows:

int a[2][3]={10,20,30,40,50,60}

0 1 2 (0,0) (1,0)

0 10 20 30 (0,1) (1,1)

1 40 50 60 (0,2) (1,2)

Fig(2) Memory allocation of two-dimensional array

TC Business School | BEST BCA College In JAIPUR 86


3) WAP to print the Multiplication of two matrix array?

#include<stdio.h>
#include<conio.h>
#define m 2
#define n 2
#define p 2
void main()
{
int a[m][n],b[n][p],c[m][p],i,j,k;
clrscr();
printf("Enter values in matrix A ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
printf("Enter values in matrix B ");
for(i=0;i<n;i++)
{
for(j=0;j<p;j++)
scanf("%d",&b[i][j]);
}
clrscr();
printf("Entered matrix A is = \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%4d",a[i][j]);
printf("\n");
}
printf("Entered matrix B is = \n");
for(i=0;i<n;i++)
{
for(j=0;j<p;j++)
printf("%4d",b[i][j]);
printf("\n");
}

for(i=0;i<m;i++)
{
for(k=0;k<p;k++)

TC Business School | BEST BCA College In JAIPUR 87


{
c[i][k]=0;
for(j=0;j<n;j++)
c[i][k]+=a[i][j]*b[j][k];
}
}
printf("Multiplication is = \n");
for(i=0;i<m;i++)
{
for(j=0;j<p;j++)
printf("%4d",c[i][j]);
printf("\n");
}
getch();
}

Output….

Output for Multiplication of two matrix array can be calculated


 Multiply First row in First Matrix and First column in second matrix…….,
after addition b/w them. Like
1×5 + 2×3 1×4+ 2×2
5+6=11 4+4=8

 Multiply second row in First Matrix and First column in second matrix
……, after addition b/w them. Like

3×5 + 4×3 3×4+ 4×2


15+12=27 12+8=20

TC Business School | BEST BCA College In JAIPUR 88


Pointer
Introduction

 In C++ programming language we can not be perform task on Dynamic memory


allocation without using pointer. So it becomes necessary to learn pointer. Let‟s start
learning them in simple and easy steps.

Definition

 In computers memory is used for storing the information. Each cell has its address when
ever we declare the variable it stores in the memory in some places and each memory
allocation has a unique address. Pointer is a variable which is used to hold the address
of memory allocation.

Declaring An Pointer

Datatype *ptr_name;
char *ptr

How to use Pointers

 There are few important operations, which we help to declare the pointer very frequently.
a) We define a pointer variable
b) Assign the address of a variable to a pointer and
c) Finally access the value at the address variable in the pointer variable.
 Thus is done by using unary operator(*) that return the value of the variable located at
the address specified by its operand.

TC Business School | BEST BCA College In JAIPUR 89


Structure
Introduction

 C++ language allow you to define type of variable that can hold several data items of
the same types but structure is another ways to defined data type available in C++
programming, which allows you to combine data items of different types.
 Structure is used to represent a record, suppose you want to keep track of your books in
a library. You might want to track the following attributes about each book:
 Title
 Book ID
 Author
 Subject

Definition

 A structure in C++ is a collection of items of different types. You can think of a structure
as a "record".
 Structure is a collection of variable but under one name. In order to declare the structure
we use a keyword called “struct”. The keyword struct declare a structure to hold the
details of different data type like name, city, salary, commission.

Defining of structure

struct tagname
{
Datatype member1;
Datatype member2;
};

Declaration of structure

So how is a structure declared and initialized? Let's look at an example:

TC Business School | BEST BCA College In JAIPUR 90


struct student
{
char name;
int roll;
float marks;
};
 Here student is the name of the structure. So it should always we declare with
the tag name.
 It is a collection of values of different data type.
 At the end or Structure defining terminated by semicolon.

Accessing members of a structure


There are two types of operators used for accessing members of a structure:
1) Member operator (.)
2) Structure pointer operator ( )
 To access any member of a structure, we use the member access operator (.). The
member access operator is used between the structure variable name and the structure
member.
 You would use struct keyword to define variable of structure.
 Any member of a structure can be accessed as:
Structure_variable_name.member_name
 Suppose we want to access name of variable s, then it can be accessed as:
s.name;
 Following is the example to explain usage of structure

#include<iostream.h>
#include<conio.h>
struct student
{
char name;
int roll;
float marks;
};

TC Business School | BEST BCA College In JAIPUR 91


void main()
{
struct student s;
clrscr();
cout<<":Enter the information of Student:\n";
cout<<"Enter the name=";
cin>>s.name;
cout<<"Enter the roll number=";
cin>>s.roll;
cout<<"Enter the marks=";
cin>>s.marks;
cout<<"Name="<<s.name;
cout<<"RollNumber="<<s.roll;
cout<<"Marks="<<s.marks;
getch();
}

Declaration Array of structure

So how is a structure Array declared and initialized? Let's look at an example:

struct s1
{
int salary[10];
char name[10];
float comm[10];
};

Following is the example to explain usage structure of Array


#include<stdio.h>
#include<conio.h>
struct s1
{
int salary[10];

TC Business School | BEST BCA College In JAIPUR 92


char name[10];
float comm[10];
}s[3];
void main()
{
// struct s1 s[3];
int i;
clrscr();
for(i=0;i<3;i++)
{
cout<<"Enter the salary=";
cin>>s[i].salary;
cout<<"Enter the name=";
cin>>s[i].name;
cout<<"Enter the commission=";
cin>>s[i].comm;
}
getch();
}

TC Business School | BEST BCA College In JAIPUR 93


Union

Introduction

 A union is a special data type available in C++ that enables you to store different data
type in the same memory location.
 Union provides an efficient way of using the same memory location for multi-purpose.

Definition

 Union is just like the structure and it has the same syntax as a structure
 Both structure and union are used to group a number of different variables but there is a
major different between them.
 The structure (record) is it storage capacity used different memory location for every
variable but union used only one location for every variable
 union keyword is used to declare union and the size of the union is largest size of the
member variable.

Defining of Union
union tagname
{
Datatype member1;
Datatype member2;
};

Declaration of Union
So how is a union declared and initialized? Let's look at an example:
union student
{
char name;
int roll;
float marks;
};

TC Business School | BEST BCA College In JAIPUR 94


 Here student is the name of the union. So it should always we declare with the
tag name.
 It is a collection of values of different data type.
 At the end or union defining terminated by semicolon.

Accessing members of a Union


There are two types of operators used for accessing members of a union:
3) Member operator (.)
4) Union pointer operator ( )
 To access any member of a union, we use the member access operator (.). The member
access operator is used between the union variable name and the union member.
 You would use union keyword to define variable of Union.
 Any member of a union can be accessed as:
Union_variable_name.member_name
 Suppose we want to access name of variable s, then it can be accessed as:
s.name;
 Following is the example to explain usage of union
#include<iostream.h>
#include<conio.h>
union student
{
char name;
int roll;
float marks;
};
void main()
{
union student s;
clrscr();
cout<<":Enter the information of Student:\n";
cout<<"Enter the name=";
cin>>s.name;
cout<<"Enter the roll number=";

TC Business School | BEST BCA College In JAIPUR 95


cin>>s.roll;
cout<<"Enter the marks=";
cin>>s.marks;
cout<<"Name="<<s.name;
cout<<"RollNumber="<<s.roll;
cout<<"Marks="<<s.marks;
getch();
}

Declaration Array of Union


So how is a Union Array declared and initialized? Let's look at an example:

union s1
{
int salary[10];
char name[10];
float comm[10];
};

Following is the example to explain usage Union of Array


#include<stdio.h>
#include<conio.h>
union s1
{
int salary[10];
char name[10];
float comm[10];
}s[3];
void main()
{
// union s1 s[3];
int i;
clrscr();
for(i=0;i<3;i++)
{

TC Business School | BEST BCA College In JAIPUR 96


cout<<"Enter the salary=";
cin>>s[i].salary;
cout<<"Enter the name=";
cin>>s[i].name;
cout<<"Enter the commission=";
cin>>s[i].comm;
}
getch();
}

TC Business School | BEST BCA College In JAIPUR 97


UNIT-3

Classes and objects: Classes, objects, defining member functions, arrays of class
objects, pointers and classes, passing objects, constructors, type of constructors,
destructors, this pointers, access specifiers, friend functions, inline functions.

OOP’s
 As we know that C++ is an object oriented programming language structure.
 In C++ we use the concept of OBJECT &CLASS. We must create class in c++
and to access the member of class we create an object of class.
 Some feature of oop‟s
1) Encapsulation
Binding the data with code is called Encapsulation. In which private
member of class are accessible only the other member of same
class.
Example:
#include<iostream.h>
#include<conio.h>
class A
{
int x,y;
public:
void set(int a, int b)
{
x=a; y=b;
}
void show()
{
cout<<"x="<<x;
cout<<"y="<<y;
}
};

void main()
TC Business School | BEST BCA College In JAIPUR 98
{
A ob;
ob.set(10,20);
ob.show();
getch();
}
Result:

2) Abstraction
It is define as an act of representing essential feature without
including background detail. In other words, hiding the internal
detail from the outside world is called abstraction.
Example:
#include<iostream.h>
#include<conio.h>
class A
{
int a,b,c;
public:
void print()
{
cout<<"Enter two no";
cin>>a>>b;
c=a+b;
cout<<"sum is="<<c;
}

};

void main()
{
A ob;

TC Business School | BEST BCA College In JAIPUR 99


ob.print();
getch();
}
Result:

3) Polymorphism
Most important characteristic of oop‟s analysis and design is
“POLYMORPHISM”. Where “POLY” means “MANY” &
“MORPHISM” means “FORM”.
Following different way to achieve polymorphism
1) Function overloading
2) Operator overloading
3) Dynamic Binding
Example:
#include<iostream.h>
#include<conio.h>
class A
{
int a,b;
public:
void fun(int a)
{
cout<<"one argument a="<<a;
}
void fun(int a, int b)
{
cout<<"\n two argument a & b="<<a<<b;
}
};

TC Business School | BEST BCA College In JAIPUR 100


void main()
{
clrscr();
A ob1;
ob1.fun(10);
A obj2;
obj2. fun(10,20);
getch();
}

Result:

4) Inheritance
Inheritance is one of the most key features of C++. Inheritance
allow to user to create a new class [child class] from an existing
class [Base class].
Though inheritance concept the derived class inherit all the feature
from a base class & derived class can have additional feature of its
own.
Inheritance is used to increase “Reusability” of class.
Type of Inheritance
1) Single level

TC Business School | BEST BCA College In JAIPUR 101


2) Multi level

3) Hierarchical

4) Hybrid

TC Business School | BEST BCA College In JAIPUR 102


5) Multiple

Q) Example of class & objects

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

class x
{
int a; // member variable a of the class x
public:
void getval() // member function of class x
{
cout<<"Enter value of a :";
cin>>a;
}

void show()
{
cout<<"You entered value for a : "<<a;
}
};

int main()
{
x o;
o.getval(); // accessing of member function through the object o
o.show();
getch();
return 0;
}

Q)WAP to calculate Area of circle calculation using class


TC Business School | BEST BCA College In JAIPUR 103
#include<iostream.h>
#include<conio.h>
class AOC
{
double pi,r,ar;
public:
void setpi() // function to set the value of pi
{
pi=3.14;
}

void getrad() // function to get radius


{
cout<<"Enter radius :";
cin>>r;
}

void area() // function to calculate area of circle


{
ar=pi*r*r;
cout<<"Area of circle is :"<<ar;
}
};
int main()
{
AOC o;
o.setpi();
o.getrad();
o.area();
getch();
return 0;
}

Q) WAP to find greater then 2 value.

#include<iostream.h>
#include<conio.h>
int main()
{

TC Business School | BEST BCA College In JAIPUR 104


int a,b;
cout<<"Enter two numbers:";
cin>>a>>b;
if(a>b)
cout<<a<<" is greater than "<<b;
else
cout<<b<<" is greater than "<<a;

getch();
return 0;
}
Q) WAP to find greater then 3 value.

#include<iostream.h>
#include<conio.h>
int main()
{
int a,b,c;
cout<<"Enter three numbers:";
cin>>a>>b>>c;
if((a>b)&&(a>c))
cout<<a<<" is greater than "<<b<<" and "<<c;
else if((b>a)&&(b>c))
cout<<b<<" is greater than "<<a<<" and "<<c;
else
cout<<c<<" is greater than "<<a<<" and "<<b;
getch();
return 0;
}
Q) WAP Using switch case greater than 4 value program

#include<iostream.h>
#include<conio.h>
int main()
{
int a,b,c,d,flag;
cout<<"Enter four numbers:";
cin>>a>>b>>c>>d;

if((a>b)&&(a>c)&&(a>d))
flag=0;
TC Business School | BEST BCA College In JAIPUR 105
else if((b>a)&&(b>c)&&(b>d))
flag=1;
else if((c>a)&&(c>b)&&(c>d))
flag=2;
else
flag=3;

switch(flag)
{
case 0:
cout<<a<<" is greater than "<<b<<" "<<c<<" and "<<d;
break;
case 1:
cout<<b<<" is greater than "<<a<<" "<<c<<" and "<<d;
break;
case 2:
cout<<c<<" is greater than "<<a<<" "<<b<<" and "<<d;
break;
default:
cout<<d<<" is greater than "<<a<<" "<<b<<" and "<<c;
break;
}
getch();
return 0;
}

Constructor
 A class constructor is a special member function of a class that the constructor is
automatically called when an object is created of that class.
 A constructor will have exact same name as the class and it does not have any return
type at all, not even void.
 There are several forms in which a constructor can take its shape namely
1) Default Constructor

2) Parameterized Constructors

3) Copy constructor

TC Business School | BEST BCA College In JAIPUR 106


1) Default Constructor
 This constructor has no arguments in it.
 Default Constructor is also called as no argument constructor.
Example:
#include<iostream.h>
#include<conio.h>
class demo
{
public:
demo()
{
cout<<" it is a Default Contructor";
}
void get()
{
cout<<"\n It is a function";
}
};

void main()
{
clrscr();
demo obj;
obj.get();
getch();
}

Result

Example
#include<iostream.h>
#include<conio.h>
class creature
{
private:

TC Business School | BEST BCA College In JAIPUR 107


intyearofBirth;
public:
creature()
{
cout<<"Contructor called";
}
};

int main()
{
creature obj;
getch();
return 0;
}

Result:

2) Parameterized Constructors 
 A parameterized constructor is just one that has parameters specified in it.
 A constructor that can take arguments are called parameterized constructors.
 A default constructor does not have any parameter, but if you need, aconstructor can
have parameters. This helps you to assign initial value to anobject at the time of its
creation as shown in the following example:
Example:

#include<iostream.h>
#include<conio.h>
class Creature
{
private:
intyearOfBirth;
public:
Creature(int year)
{ //Parameterized Constructor

TC Business School | BEST BCA College In JAIPUR 108


yearOfBirth = year;
cout<<"Year Of Birth="<<yearOfBirth;
}
};

int main()
{
clrscr();
Creature obj(1994);
getch();
return 0;
}

Result:

3) Copy constructor 

 The copy constructor is a constructor which creates an object by initializing itwith an


object of the same class.
 Initialize one object from another of the same type.
 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.
 If a copy constructor is not defined in a class, the compiler itself defines one.Ifthe class
has pointer variables and has some dynamic memory allocations, thenit is a must to
have a copy constructor.
 Copy Constructor is used to declare and initialize an object from another object.
For example the statement:

TC Business School | BEST BCA College In JAIPUR 109


abc c2(c1);
 Would define the object c2 and at the same time initialize it to the value of c1.
 The process of initializing through a copy constructor is known as copy initialization.
Example:

#include<iostream.h>
#include<conio.h>
class abc
{
int a, b;
public:
abc(int x, int y)
{
a = x;
b = y;
}
abc::abc(abc&p)
{
//If you like, you can define the same function outside the
class using the scope resolution operator (::)
a = p.a;
b = p.b;
}
void showdata()
{
cout<< a << " " << b <<endl;
}
};

void main()
{
clrscr();
abc c1(10, 20);
abc c2(c1);
c1.showdata();
c2.showdata();
getch();
}

Result:

TC Business School | BEST BCA College In JAIPUR 110


Example:

#include<iostream.h>
#include<conio.h>
class product
{
int code;
public:
product()
{
//Default Constructor
}
product(int x) //Parameterized Constructor
{
code=x;
}
product(product &y) //Copy Constructor
{
code=y.code;
}
void display()
{
cout<<code<<endl;
}
};
void main()
{
product p1(10);
product p2(p1); //Copy Constructor Call
product p3=p2; //again copy Constructor call
p1.display();
p2.display();
p3.display();
getch();
}

Result:

Example:
#include<iostream.h>
#include<conio.h>
class product

TC Business School | BEST BCA College In JAIPUR 111


{
int code;
public:
product() //default constructor
{

}
product(int x) //Parameterized Constructor
{
code=x;
}
product(product &y) //class constructor
{
code=y.code; //copy the value
}
void display()
{
cout<<code<<"\n";
}
};
int main()
{
clrscr();
product p1(10);
product p2(p1); //copy constructor called
product p3=p1; //again copy constructor called
p1.display();
p2.display();
p3.display();
getch();
return 0;
}

Result:

Example

Q)WAP to find factorial no of given value using copy constructor.

#include<iostream.h>
#include<conio.h>
class copy
{
doublevar, fact;
public:

TC Business School | BEST BCA College In JAIPUR 112


copy(int temp)
{
var=temp;
}
double calculate()
{
fact=1;
for(double i=1;i<=var;i++)
{
fact=fact*i;
}
return fact;
}
};

void main()
{
clrscr();
double n;
cout<<"\n Enter the number:";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"number "<<n<<" factorial is="<<obj.calculate();
cout<<"\nnumber "<<n<<" factorial is="<<cpy.calculate();
getch();
}

Result:

Constructor overloading
In case of constructor overloading we can have two or
more than two constructor but the list of argument should be different.

TC Business School | BEST BCA College In JAIPUR 113


Example:
#include<iostream.h>
#include<conio.h>
class demo
{
public:
demo()
{
cout<<"It is constructure without argument";
}
demo(int a)
{
cout<<"Constructor overloading, value of="<<a;
}
};

void main()
{
clrscr();
demo d();
demo d1(10);
getch();
}

Result:

Example:
#include<iostream.h>
#include<conio.h>
class point
{
int x,y;
public:

TC Business School | BEST BCA College In JAIPUR 114


point() //no argument constructor
{
x=0;
y=0;
}
point(int a) //one argument constructor
{
x=y=a; //x=a;
//y=a;
}
point(int m,int n) //two argument
{
x=m;
y=n;
}
void show()
{
cout<<"x= "<<x<<" ";
cout<<"y= "<<y<<"\n";
}
};
void main()
{
clrscr();
point p1;
point p2(5);
point p3(7,11);
p1.show();
p2.show();
p3.show();
getch();
}

TC Business School | BEST BCA College In JAIPUR 115


Result:

Some important points about constructors:


 Automatically called when an object is created.

 We can define our own constructors

 A constructor takes the same name as the class name.

 We can‟t define a constructor in the private section.

 No return type is specified for a constructor.

 Constructor must be defined in the public. The constructor must be a public member.

Overloading of constructors is possible.

 if an object is copied from another object then the copy constructor is called.

Destructors 

 A destructor is a special member function of class which is destroy class object.


 A destructor is a special member function of class which is used to delete the object
created by constructor.
 A destructor is called automatically by the compiler when the object goes out of the
space. A destructor takes no argument and no return type.
 A destructor is used to destroy the objects that have been created by constructor.
 A destructor is also a member function whose name is the same as class name but the
prefixed with tilde (~) before use it.
 General Syntax of Destructors

~ classname();

 A destructor will have exact same name as the class prefixed with a tilde (~) symbol
before use it, and it can neither return a value nor can it take any parameters. Destructor

TC Business School | BEST BCA College In JAIPUR 116


can be very useful for releasing resources before coming out of the program like closing
files, releasing memories etc.
Following example explains the concept of destructor
1) Destructors are special member functions.

2) Release dynamic allocated memory.

3) Destructors are automatically call.

4) Takes the same name of class name.

Some important points about destructors:


 Take the same name as class name.
 Defined in the public.
 Destructors cannot be overloaded.
 No return type is specified.
 It does not take argument.

Example 1:
#include<iostream.h>
#include<conio.h>
class sample
{
public:
sample() // Constructor
{
cout<<"object created \n";
}

~sample() //Destructor
{
cout<<"Object Destory \n";
}
};
int main()
{
sample s;
getch();
return 0;
}

TC Business School | BEST BCA College In JAIPUR 117


Result:

Example 2:

class creature
{
private:
intyearofBirth;
public:
creature()
{
yearofBirth=1970;
cout<<"constructure called"<<endl;
cout<<yearofBirth<<endl;
}
~creature()
{
cout<<"destructure called"<<endl;
}
};

int main()
{
cout<<"main start"<<endl;
creature obj;
cout<<"main end"<<endl;
getch();
return 0;
}

Result:

TC Business School | BEST BCA College In JAIPUR 118


Note:

Destructor is used to free the allotted memory to object at run time, so that free memory
can be reused by other program or object.
To allot memory to an object new operator is used in constructor function and in
destructor function. Delete operator is used to free the allotted memory.
For Example:
#include<iostream.h>
#include<conio.h>
class sample
{
char *t;
public:
sample(int length)
{
t=new char[length];
cout<<"Character arary of length="<<length<<" Created";
}
~sample()
{
delete t;
cout<<"\n Memory de-allocated for the character array\n";
}
};
int main()
{
sample s(10);
getch();
return 0;
}

Result:

TC Business School | BEST BCA College In JAIPUR 119


Access specifiers
 Data hiding is one of the important features of Object Oriented Programming.
 The members of class have private, public and protected. The keywords public,
private, and protected are called access specifiers.
 A class can have multiple public, protected, or private variable and function The
default access for members and classes is private.
 Syntex

class Base {
public:
// public members go here
private:
// private members go here
protected:
// protected members go here
};

1) public Members
The data members and member functions declared public can be accessed by other
classes.
class PublicAccess

public: // public access specifier

int x; // Data Member Declaration

void display(); // Member Function decaration

To use the public data members using the dot (.) operator and the respective object of
class.

Example
#include<iostream.h>
#include<conio.h>
TC Business School | BEST BCA College In JAIPUR 120
class Base
{
public:
int a;
protected:
int b;
private:
int c;
};

class Derived:public Base


{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};

void main()
{
clrscr();
Derived obj;
obj.doSomething(); // Not Allowed, because we can not access public function
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
cout<<obj.a;
getch();
}

2) private Members

TC Business School | BEST BCA College In JAIPUR 121


Private member defines that the members or methods can be accessed within the same
class only.
Private keyword, means that no one can access the class members declared private
outside that class. If someone tries to access the private member, they will get a compile
time error.
Only the class and friend functions can access private members.
By default all the members of a class would be private.

class PrivateAccess

private: // private access specifier

int x; // Data Member Declaration

void display(); // Member Function decaration

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

class Student
{
private: // private data member
int rollno;
public: // public access of functions
int getRollno()
{
return rollno;
}

void setRollno(int i)
{
rollno=i;
}

};

TC Business School | BEST BCA College In JAIPUR 122


void main()
{
Student A;
A.rollono=1; //Compile time error
cout<<A.rollno; //Compile time error

A.setRollno(1); //Rollno initialized to 1


cout<<A.getRollno(); //Output will be 1
getch();
}

Example-2)
#include<iostream.h>
#include<conio.h>

Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};

class Derived:private Base //Not mentioning private is OK because for classes it defaults
to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};

class Derived2:public Derived


{

TC Business School | BEST BCA College In JAIPUR 123


void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};

int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
getch();
}

3) protected Members
A protected member variable or function is very similar to a private member but it
provided one additional benefit that they can be accessed in child classes which are
called derived classes.
The protected access specfiers used inheritance.
class ProtectedAccess

protected: // protected access specifier

int x; // Data Member Declaration

void display(); // Member Function decaration

Example-1)

#include<iostream.h>
#include<conio.h>
class Declare
{
private:
int a;
public:
int b;
protected:
int c;
public:

TC Business School | BEST BCA College In JAIPUR 124


void call()
{
cout<<"Enter the value of a=";
cin>>a;
cout<<"Enter the value of b=";
cin>>b;
cout<<"Enter the value of c=";
cin>>c;
cout<<"Declare variable values"<<endl;
//Every members can be access as all are in the same class
cout<<"Value of a = "<<a<<endl;
cout<<"Value of b = "<<b<<endl;
cout<<"Value of c = "<<c<<endl;
}
};

class Inherit:public Declare


{
public:
void call()
{
cout<<"\n Inherit variable values"<<endl;
//As 'a' is private member so 'a' cannot be accessed by another class
//cout<<"Value of a = "<<a<<endl;
//'b' is declared as public, so it can be accessed from any class which is inherited
cout<<"Value of b = "<<b<<endl;
//'c' is declared as protected, so it can be accessed from class which is inherited
cout<<"Value of c = "<<c<<endl;
}
};

void main()
{
clrscr();
Declare d;
d.call();

Inherit i; //= new Inherit();


i.call();

cout<<"\n Accessing variable of declare outside declare class"<<endl;


//'a' cannot be accessed as it is private
//cout<<"value of a = "<<d.a<<endl;

TC Business School | BEST BCA College In JAIPUR 125


//'b' is public as can be accessed from any where
cout<<"value of b = "<<d.b<<endl;

//'c' is protected and cannot be accesed here


//cout<<"value of c = "<<d.c<<endl;
getch();
}
Output

Example-2) Simple program using public and private access specifiers.


#include<iostream.h>
#include<conio.h>
class demo
{
Int roll_no, age;
char grade;
public:
void get()
{
cout<<"Enter Roll No=";
cin>>roll_no;
cout<<"Enter age=";
cin>>age;
cout<<"Enter Grade=";
cin>>grade;
}
void display()
{
cout<<"Grade is="<<grade<<endl;
cout<<"Age is="<<age<<endl;
cout<<"Roll Number is="<<roll_no;

TC Business School | BEST BCA College In JAIPUR 126


}
};

void main()
{
clrscr();
demo d;
d.get();
cout<<"===============Result Display=====================";
cout<<endl;
d.display();
getch();
}

Result

Friend function
 A friend function is permitted full access to private and protected members of different
class.
 A friend function of a class is defined outside that class scope but it has the right to
access all private and protected members of the class.
 To understand the important to friend. There are certain situations, where we need to
share our private or protected data with non-members. Than the concept the friend
comes. A friend class is a class whose member function can access another class‟s with
private and protected member.
 To declare the friend function the declension is started with the keyword friend.
 Syntex
class class_name

TC Business School | BEST BCA College In JAIPUR 127


{
friend show(class_name);
}
 If a function is define as a friend function that private or protected data member can be
access from that function. The compiler knows the given function is a friend function by
its keyword friend. The declaration of friend function should be made inside the body of
class with its keyword friend.
 For Example
#include<iostream.h>
#include<conio.h>
class A
{
int a,b,c;
friend void show(A);
};

void show(A o) //o is a reference variable


{
cout<<"Enter value of a=";
cin>>o.a;
cout<<"Enter value of b=";
cin>>o.b;
o.c=o.a+o.b;
cout<<"sum="<<o.c;
}

void main()
{
clrscr();
A obj;
show(obj);
getch();
}
Result

TC Business School | BEST BCA College In JAIPUR 128


Example

#include<iostream.h>
#include<conio.h>
class test
{
int x,y,z;
public:
void getdata(int a,int b)
{
x=a;
y=b;
}
friend int sum(test t);
};
void sum(test t)
{
t.z=t.x+t.y;
}

void main()
{
test obj;
int no1,no2;
cout<<"Enter first digit=";
cin>>no1;
cout<<"Enter second digit=";
cin>>no2;
obj.getdata(no1,no2);
sum(obj); //obj.sum(obj);
getch();
}

Result

Note:

The Friend function and friend class are the techniques used to access the private members
of a class by using friend keyword. The common difference between friend function and friend
class is that when friend function is used the private class members can be accessed but in
friend class, only the names of the friend class is accessed not the private members of the
class.

TC Business School | BEST BCA College In JAIPUR 129


Definition of Friend Function

The friend function is used to access the private and protected members of another class. In
this type of function, a friend keyword is used before the function name at the time of
declaration. There are some restrictive conditions applied to friend function. The first condition is
that friend function is not inherited by a child class. The second condition is that storage class
specifier may not be present in friend function, which means that it can not be declared as static
and extern.

The friend function is not called with an invoking object of the class.

#include<iostream.h>
#include<conio.h>
class XYZ
{
private:
int num=100;
char ch='Z';
public:
friend void disp(XYZ obj);
};
//Global Function
void disp(XYZ obj)
{
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
}
Void main()
{
XYZ obj;
disp(obj);
getch();
}

Output
A
11

Definition of Friend Class:


A friend class is a class that can access the private and protected members of a class in which
it is declared as friend. This is needed when we want to allow a particular class to access the
private and protected members of a class.

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

TC Business School | BEST BCA College In JAIPUR 130


{
private:
char ch='A';
int num = 11;
public:
/* This statement would make class ABC
* a friend class of XYZ, this means that
* ABC can access the private and protected
* members of XYZ class.
*/
friend class ABC;
};
class ABC {
public:
void disp(XYZ obj)
{
cout<<obj.ch<<endl;
cout<<obj.num<<endl;
}
};
void main()
{
ABC obj;
XYZ obj2;
obj.disp(obj2);
getch();
}

Output:
100
Z

Inline function
 With an inline function, the compiler tries to expand the code in the body of the function
in place of a call to the function.
 The main objectives of using function in program is to save some memory space, which
become appreciable when a function is likely to be called many time. However, every
time a function is called, it takes a lot of extra time in executed time for task such as
jumping to the function and execution time may be save, solution of this problem is to
use macro.

TC Business School | BEST BCA College In JAIPUR 131


 Macro is popular in c and c++ propose a new feature called inline function. An inline
function is a function that is expended in inline when it is invoked. Inline function is
created used the keyword inline.
 There are some situation where inline function may not work
1) If a loop, switch or goto statement.
2) If function contain static variable.
3) If inline function are recursive.
 C++ inline function is powerful concept that is commonly used with classes. If a function
is inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.
 To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.
Example

#include<iostream.h>
#include<conio.h>
class inline_function
{
public:
inline float mul(float x,float y)
{
return(x*y);
}
};
void main()
{
clrscr();
inline_function inlineF;
cout<<"multiplication of two digit="<<inlineF.mul(10,20);
getch();
}

Result

Q) WAP to fine the multiplication value and the cubic value using inline function

TC Business School | BEST BCA College In JAIPUR 132


#include<iostream.h>
#include<conio.h>
class line
{
public:
inline float mul(float x, float y)
{
return (x*y);
}
inline float cube(float x)
{
return (x*x*x);
}
};

void main()
{
clrscr();
line obj;
float val1,val2;
cout<<"Enter two value=";
cin>>val1>>val2;
cout<<"\n Multiplication value is="<<obj.mul(val1,val2);
cout<<"\n cube value is="<<obj.cube(val1)<<endl<<obj.cube(val2);
getch();
}

Result

TC Business School | BEST BCA College In JAIPUR 133


This pointer
 Every object has a special pointer this which points to the object itself.
 Every object in C++ has access to its own address through an important pointer called
this pointer.
 Friend functions do not have this pointer, because friends are not members ofa class.
Only member functions have this pointer.
 If we use this pointer it is used to denote current pointer. The this pointer pass as a
hidden to all non static member function calls & is available as a local variable within a
body of all non-static function.
 This pointer is a constant pointer that holds the memory address of the current object,
this pointer is not available in static member function because static member function
can be called without any object (with class name).
 Example
#include<iostream.h>
#include<conio.h>
class A
{
int x;
public:
void set(int x)
{
this->x=x;
}
void show()
{
cout<<"value of x="<<x;
}
};
void main()
{
clrscr();
Aobj;
obj.set(10);

TC Business School | BEST BCA College In JAIPUR 134


obj.show();
getch();
}
Result

Static Data Member/Static Function


1) Static Data Member
Data member of a class can also be declared as static.
Feature of static data member are
1) When it‟s initial value is zero, then it‟s first object of class is created.
2) Only one copy of this data member is created which is shared by all other objects.

Example
#include<iostream.h>
#include<conio.h>
class data
{
static int x;
int y;
public:
void getdata(int a)
{
y=a;
x++;
}
void show_x()
{
cout<<"x="<<x<<"\n";
}
};
int data::x; //static member defination

void main()
{
clrscr();
data d1,d2;
d1.show_x();

TC Business School | BEST BCA College In JAIPUR 135


d2.show_x();
d1.getdata(10);
d2.getdata(20);
cout<<"After reading data="<<"\n";
d1.show_x();
d2.show_x();
getch();
}

Result

Note:
In above program when object are declared then initial value of static data member is
zero.
Whenever Function is called its value is increased by 1.

Object d1 object d1

Y=10 Y=20

X=2
Fig(1) Static Data Member

Know, this variable (x) is shared between both object, So the value of x is display 2.

2) Static Member Function


Member function declared with static keyword is called as
“static member function”.

Feature of static member function are as follows

1) It can only access other static data member and member function.

2) It can call with name of class.

TC Business School | BEST BCA College In JAIPUR 136


Example

#include<iostream.h>
#include<conio.h>
class test
{
int x;
static int y;
public:
void set_xy(int a)
{
x=a;
y++;
}
void show_x()
{
cout<<"x="<<x<<"\n";
}
static void show_y()
{
cout<<"y="<<y;
}
};
int test::y;
void main()
{
clrscr();
test t1,t2;
t1.set_xy(10);
t2.set_xy(20);
t1.show_x();
t2.show_x();
test::show_y(); //calling static function
getch();
}

Result

TC Business School | BEST BCA College In JAIPUR 137

You might also like