1.principals of Object Oriented Programming

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

Chapter 01

PRINCIPALS OF OBJECT ORIENTED


PROGRAMMING
14 Marks

Course Outcome: The student will be able to demonstrate the


basic Concepts of Object Oriented
Programing.
(C 223316.1)

Content:
Procedure Oriented Programming (POP) verses Object Oriented
Programming (OOP).
Basic concepts of Object Oriented Programming, Object Oriented
Languages, Applications of OOP.
C verses C++, Tokens, keywords, variables, constants, basic data types.
User defined data types, type casting, operators, and expressions.
Simple C++ Program.
Control structures: Decision making statements and Loops.
Scope resolution operator, memory management operators.
Arrays, Strings and Structures in C++.
Procedure Oriented Programming (POP) verses Object Oriented Programming
(OOP)

Procedure Oriented Programming (POP) Object Oriented Programming (OOP)

Mainly focus on function rather than Mainly focus on object rather than
object. function.

Programs are divided into functions. Programs are divided into object.

Data is hidden and cannot access by


Data moves freely from function to
external functions so the data does not
function.
move freely.

It does not provide security. It provides security.

It follows top down approach. It follows bottom up approach.

Inheritance is not allowed. Inheritance property is used.

It doesn’t use access specifier. It uses access specifier.

No data hiding. Encapsulation is used to hide the data.

No virtual function. Concept of virtual function.

Ex. C Programming Ex. C++, JAVA, Simula

1
Basic concepts of Object Oriented Programming

There are basic concepts needed for OOP as follows.

1. Objects
2. Classes
3. Data Abstraction
4. Data Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing

1. Objects

“Objects is basic run time entity"

An object can be thought of an entity that represent a person, thing, place, animal or any item that
the program has to handle or any user defined data.

Each object has a unique identity some definite state or characteristics and same behaviour

Object : Book

DATA :
book_name
auther
place

Functions :
getdata();
Putdata();

2. Classes :

"Class is a collection of similar types of objects which are having common properties and
common behaviour."

A class is a user defined data type which consists of data and member functions of an object.
Once class has been defined we can create any number of objects.
E.g. consider a class as fruit having objects as mango apple, orange

2
3. Data Abstraction:

"To show essential data by hiding background detail is known as data abstractions"

Abstraction refers to the act of representing the essential features without including the
background details or explanations. The process of defining a data type often called as abstract data
type [ADT] together with the concept of data hiding.

4. Data Encapsulation :

"Data encapsulation means wrapping or binding up data in to single unit”.

The data is not accessible to the function to the outside and only those functions which are
in the class access them. The process of protecting data from direct access is called as data hiding.

5. Inheritance:

"The ability to derive new class from old class by acquiring its properties and with its own
properties is known as inheritance".

It means one class of objects inherits the data and behaviour from another class. The
concept of inheritance provides the concept of reusability.

E.g. Vehicle is the base class and two other classes namely two wheeler and four wheeler from
vehicle class and other classes are derived from them.

Vehicle

Two Wheeler Four

Hero Honda Bajaj Tata Maruti

3
6. Polymorphism:

"The ability to take more than one form is known as polymorphism"

This name comes from Greek word ‘Poly’ means Many "Morphism'- form. It plays an
important role in allowing object having different structures to share the same internal interface.
This means general class of operations may be accessed in same manner even though
actions associated with each operation may differ.

Ball Pen
Write

Blue Object Red Object Black Object


Write (Blue) Write (Red) Write (Black)

7. Dynamic Binding:

“Selection of function at the time of execution or Run time selection is known as dynamic
binding."

It is also called as late binding. It implemented through virtual function.

8. Message Passing:

“Communication within an object to get something done is called as message passing”

The objects communicate with each other by message passing.

4
Object Oriented Languages
Following are the object oriented languages.

1. C++
2. JAVA
3. Python
4. Smalltalk

Applications of OOP

1. It is used in the area of user interface design such as

2. It used in export system.

3. It is used in Artificial Intelligence

4. It used in Management Information System (MIS).

5. It is wed in CAD/CAM, real time system.

5
Difference between C and C++

C C++

C++ was developed by Bjarne Stroustrup in


C was developed by Dennis M. Ritchie in 1973.
1979.

C does not support polymorphism, inheritance C++ supports inheritance polymorphism and
and data encapsulation. data abstraction.

It does not provide security. It does provides security.

C contains 32 keywords C++ contains 52 keywords.

C provides information hiding. C++ provides information hiding.

It uses the printf and scanf. It use cout and cin.

It include stdio header files. It includes iostream header file.

It follows top down approach. It follows bottom-up approach.

6
Structure of C++ program

Header File Declaration


Section
Global Declaration Section

Class Declaration and


Function definition Section

Main Function

1. Header File declaration section:

In this section we can include header Files such as

<iostream.h>

<conio.h>

<math.h>

<Stack.h>

2. Global declaration section:

Global variables are declared here such as

Declaring structure.
Declaring Variable.

3. Class declaration and function definition:

This section can considered as sub section for the global declaration Section. Class declaration
and all methods defined here.

4. Main Function:

Each and every C++ program starts always with main function. This is entry point for all the
function. Each and every function is called indirectly through main. We can create objects of class
here.

7
Tokens
"The smallest individual and meaningful entity is called as Token"

The compiler recognise the following Types of

1. Keywords
2. Variables
3. Constants
4. Data Types

1. Keywords

“Keywords are the words which are reserved and predefined words and whose meaning does
not change throughout the program."

It cannot be used by programmer as variables and identifiers.

E.g. for, switch, cout, cin, Structure, class.

2. Variable:

“It is the container which can contain value and it may be change”.

Variables can be declared as follows.

Syntax :

Data_type variable_name;

int a;

float b;

char c;

3. Constants:

A constant value is the one which does not change during the execution of program.

8
4. Data Type:

“Mentioning the type of data is known as data type”.

C++ Data Type

User Defined Type Built In Type Derived Type

Structure Array
Union Function
Class Pointer
Enumerated

Integral Type Void Floating Type

int char float double

Data types are mainly divided in to three types as below.

1. User Defined Data Types


2. Built in Data Type
3. Derived Data Type

9
1. User Defined Data Type:
"The data types which are derived by user by using built in data type is known as user
defined data type

For example

a. Structure.
b. Union.
c. Class.
d. Enumeration.

a. Structure:
"Structure is a collection of different types of data types”
b. Union :
"Union is a collection of similar types of data types”
c. Class:
“Class is the collection of similar types of objects."
d. Enumeration:
“Enumeration (or enum) is a user defined data type in C. It is mainly used to assign
names to integral constants, the names make a program easy to read and maintain.”

2. Built in Data Type:


These are the data type, which are already declared in compiler

1. Integer:

It is data type which represent the numbers which does not containing decimal point

(eg. 1,2,3---- 00) it represent as int:

2. Float

It is the data type which represent the numbers which containing decimal points

(1·2,3.5, …..) which

3. Char:

It represent the character

4. Double

Double Floating Point data type is used for storing double precision floating point values or
decimal values.

10
3. Derived Data Type:
It is the data type which is derived from the build in data type such as

1. Array

An array is a collection of similar data items stored at contiguous memory locations


and elements can be accessed randomly using indices of an array.

2. Function

A function is a set of statements that take inputs, do some specific computation and

produces output.

3. Pointer

Pointers are symbolic representation of addresses. They enable programs to

simulate call-by-reference as well as to create and manipulate dynamic data structures.

Operator in C++
1. It supports all operators in C

2. << Insertion operator

3. >> Extraction operators 4 :: Scope Resolution Operator

4. :: Scope resolution Operator

5. -> Pointer to member operator

6. Sizeof() Size of operator


7. endl Line fedd operator
8. new Memory allocation operator
9. delele Memory release operator

Scope Resolution operator [::]

It uses for resolving the scope and make members visible to outside word. It is use for class
defining member function outside the Class.

The scope resolution operator [::] allows access to global variables even though there is local
variable of same name with in the main () function.

The use of the double colon instructs the system that we are interested in using the global
variable name rather than the local variable name.

11
The <iostream.h> File :

The #include <iostream.h> directive is used in the program. It is library having basic
Keywords of a C++ program.

The directive causes the pre-processor to add the content of the file to the program. The
header file should be included at the beginning of all programs that uses input /output statements.

Output operator /<< insertion operator:

It use to display the output of the It uses with cout keyword.

Syntax:

cout << “-------------------------“;


This statement is we for display the contents present in double inverted coming.

eg

cout << “Welcome to C++ programming";


It also use for display the contents of variable

cout << " ------------- "<<variable_name;


eg.

cout << "in Addition = " << add ;


This statement use to display value present in add variable.

Input Operator / >> Extraction Operator:

It use to pass the input to the program or accept value in the variable by User.

Syntax:

cin>> variable-name;
e.g.

cin>> no;
By using above statement the value stored in the variable no.

The operator >> is called extraction operator

12
Basic Programs of C++
1.1 Write a C++ program for find area of circle

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int r;
float area;

cout<<"\n Enter the radius of circle : ";


cin>>r;

area=r*r*3.14;

cout<<" \n Area of Circle = "<<area;

getch();
}

OUTPUT

13
1.2 Write a C++ program to perform division and multiplication.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,add,sub,mul;
float div;

cout<<" \n Enter the first number : ";


cin>>a;
cout<<" \n Enter the second number : ";
cin>>b;

add = a+b;
sub = a-b;
mul = a*b;
div = a/b;

cout<<"\n Results\n";
cout<<" \n Addition = "<<add;
cout<<" \n Subtraction = "<<sub;
cout<<" \n Multiplication = "<<mul;
cout<<" \n Division = "<<div;

getch();
}

OUTPUT

14
1.3 Write a C++ program to calculate gross salary where
DA = 75%
HRA = 20%
Gross = basic + HRA + DA

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float basic,DA,HRA,gross;

cout<<" \n Enter the basic salary : ";


cin>>basic;

DA = (basic*75) / 100;
HRA = (basic*20) / 100;
Gross = basic + DA + HRA;

cout<<" \n Gross Salary = "<<gross;

getch();
}

OUTPUT

15
1.4 Write a C++ program to demonstrate the use of Operator by evaluating the
following expression.
X1=( -b + [√b^2-4ac]) / 2a
X2= [-b+(-√b^2-4ac)] / 2a

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

void main()
{
clrscr();
float a,b,c,p,q,x1,x2;

cout<<" \n Enter the value of A : ";


cin>>a;
cout<<" \n Enter the value of B : ";
cin>>b;
cout<<" \n Enter the value of C : ";
cin>>c;

p = (b*b -4*a*c);
q = sqrt( p );
x1 = (-b+p) / (2*a);
x2 = (-b-p) / (2*a);

cout<<" \n Expression X1 = "<<x1;


cout<<" \n Expression X2 = "<<x2;

getch();
}

OUTPUT

16
Control Structure
1. Decision Making
2. Loops

1. Decision Making
A. If

It is use for handle single condition. It can handle true or false condition.

START

If FALSE
(Condition)

TRUE

STATEMENTS

STOP
If condition satisfies then execute statement then exit.

If condition not satisfies then directly exit.

Syntax Example
If (condition) if (a>b)
{ {
-------------------- cout<<” \n A is greater than B”;
--------------------- Statements }
--------------------
--------------------
}

17
B. If – else

It is use for handling two conditions. If condition one satisfy then execute if loop

otherwise execute else loop.

START

FALSE
If
(Condition)

TRUE

STATEMENTS STATEMENTS

STOP

Syntax Example

If (condition)
{ if (a>b)
-------------------- {
--------------------- Statements cout<<” \n A is greater than B”;
-------------------- }
-------------------- else
} {
else cout<<”\n B is greater than A”;
{ }
--------------------
--------------------- Statements
--------------------
--------------------
}

18
C. If – else – if Ladder

It is used for handling multiple conditions.

Syntax Example
If (condition 1) If (a>b && a>c)
{ {
------------------------ cout<<”\n A is greater number”;
------------------------ Statements }
------------------------ else if (b>a && b>c)
------------------------ {
} cout<<”\n B is greater number”;
else if (condition 2) }
{ else if (c>a && c>b)
------------------------ {
------------------------ Statements cout<<”\n C is greater number”;
------------------------ }
------------------------ else
} {
else if (condition 3) cout<<”\n All are equal”;
{ }
------------------------
------------------------ Statements
------------------------
------------------------
}
else
{
------------------------
------------------------ Statements
------------------------
------------------------
}

19
D. switch case

It is use for handle multiple cases and use for developing menu driven

program.

Syntax Example
switch (ch) switch (ch)
{ {
case 1: case 1:
--------------------- cout<<”\n I am in 1st case”;
--------------------- break;
break; case 2:
case 2: cout<<”\n I am in 2nd case”;
--------------------- break;
--------------------- case 3:
break; cout<<”\n I am in 3rd case”;
. . break;
case 4:
. . cout<<”\n I am in 4th case”;
. . break;
. . default:
case n: cout<<”\n Wrong Choice”;
--------------------- break;
--------------------- }
break;
default:
---------------------
---------------------
break;
}

20
2. Loop

Loops are used for handling repetitive conditions.

A. While loop
It is used for handling the repetitive conditions where initialisation, condition

and increment or decrement are use separately.

START

INITIALISATION

FALSE
while
(Condition)

TRUE

INCREMENT / DECREMENT

STATEMENTS

STOP

In while loop first condition checked and then loop executed.

21
Syntax Example
Initialise; int I = 1;
while (condition) while (i<=10)
{ {
--------------------- cout<<”\n Cloud Computing”;
---------------------- Statements i++;
---------------------- }
Increment / Decrement;
}

It displays the “Cloud Computing” string 10 times like as below.

Cloud Computing
Cloud Computing
Cloud Computing
Cloud Computing
Cloud Computing
Cloud Computing
Cloud Computing
Cloud Computing
Cloud Computing
Cloud Computing

22
B. Do – while loop

It is same as while loop but in do while loop first loop executed then

condition checked. It is only one loop after which semicolon is used.

START

INITIALISATION

STATEMENTS

INCREMENT / DECREMENT

TRUE
while
(Condition)

FALSE

STOP

Syntax Example
initialisation; int I = 1;
do int I;
{ I = 1;
-------------------- {
-------------------- Statements cout<<”\n Cloud Computing”;
-------------------- i++;
Increment / Decrement; } while (i<=10);
} while (condition);

23
C. For loop

For is also used for representation and increment condition and init combinable.

Syntax Example

for(initialise ; final condition ; increment / decrement)


{ for(i=0;i<=9;i++)
---------------------- {
---------------------- Statements cout<<”\n Cloud Computing”;
---------------------- }
----------------------
}

24
C++ Programs on Decision making and control loop
1.5 C++ Programs to check number is greater.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int no1,no2;

cout<<"\n Enter the first number :";


cin>>no1;
cout<<"\n Enter the second number :";
cin>>no2;

if(no1 > no2)


{
cout<<"\n First number is greater";
}

getch();
}

1.6 C++ Programs to check number is odd or even.


#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int no;

cout<<"\n Enter the number :";


cin>>no;

if(no%2 == 0)
{
cout<<"\n The given umber is Even";
}

getch();
}

25
1.7 Write a C++ program to find greatest number from two numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int no1,no2;
cout<<"\n Enter the first number :";
cin>>no1;
cout<<"\n Enter the second number :";
cin>>no2;
if(no1 > no2)
{
cout<<"\n First number is greater";
}
else
{
cout<<"\n Second number is greater";
}
getch();
}

1.8 Write a C++ program to find the given number is odd or even.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int no;

cout<<"\n Enter the number :";


cin>>no;
if(no%2 == 0)
{
cout<<"\n The given umber is Even";
}
else
{
cout<<"\n The given number is Odd";
}
getch();
}

26
1.9 Write a C++ program to check entered year is leaf or not.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int year;

cout<<"\n Enter the year for checking :";


cin>>year;

if(year%4 == 0)
{
cout<<"\n Entered year is leaf year";
}
else
{
cout<<"\n Entered year is not leaf year";
}

getch();
}

1.10 Write a C++ program to display string 10 times.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i;
i=1;

while(i <= 10)


{
cout<<"\n Pravara Polytechnic, Loni";
i++;
}

getch();
}

27
1.11 Write a C++ program to display 1 to 100 number.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i;
i=1;
while(i <= 100)
{
cout<<i<<"\t";
i++;
}
getch();
}

1.12 Write a C++ program to display addition of 1 to 100 numbers.


#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,sum;
i=1;
sum=0;
while(i <= 100)
{
sum = sum+i;
i++;
}
cout<<"\n Addition of 1 to 100 ="<<sum;
getch();
}

28
1.13 Write a C++ program to check number is Armstrong or not.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int no, sum=0,temp,rem;
cout<<"\n Enter the number=";
cin>>no;
temp=no;
while(temp != 0)
{
rem = temp%10;
sum = sum+rem*rem*rem;
temp = temp/10;
}
if(no == sum)
{
cout<<"\n Entered number is armstrong...";
}
else
{
cout<<"\n Entered number is not armstrong...";
}
getch();
}

1.14 Write a program to display the table of 19


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

void main()
{
clrscr();
int i;

i=1;
do
{
cout<<"\n"<<i*19;
i++;
}while(i<=10);

getch();
}

29
1.15 Write a C++ program to display the string 10 times.

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

void main()
{
clrscr();
int i;

for(i=1;i<=10;i++)
{
cout<<"\n Cloud Computing ";
}

getch();
}

1.16 Write a C++ program to display even no from 1 to 100


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

void main()
{
clrscr();
int i;

for(i=1;i<=100;i++)
{
if(i%2==0)
{
cout<<i<<"\t";
}
}

getch();
}

30
1.17 Write a C++ Program to display following output
*
**
***
****
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr(); int i,j;
for(i=0;i<=3;i++)
{
for(j=0;j<=i;j++)
{
cout<<" *";
}
cout<<"\n";
}
getch();
}
1.18 Write a C++ Program to display following output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr(); int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<" "<<j;
}
cout<<"\n";
}
getch();
}

31
1.19 Write a C++ Program to display following output
1
2 3
4 5 6
7 8 9 10

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

void main()
{
clrscr();
int i,j,k;
k=1;

for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
cout<<" "<<k;
k++;
}
cout<<"\n";
}

getch();
}

32
1.20 Write a C++ Program for addition, subtraction, division multiplication.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,ch;
char ans;
cout<<"\n Enter the first number = ";
cin>>a;
cout<<"\n Enter the second number = ";
cin>>b;
do
{
cout<<"\n***********************";
cout<<"\n* 1. Addition *";
cout<<"\n* 2. Subtraction *";
cout<<"\n* 3. Multiplication *";
cout<<"\n* 4. Division *";
cout<<"\n***********************";
cout<<"\n\n Enter your choice = ";
cin>>ch;
switch(ch)
{
case 1: cout<<"\n Addition = "<<a+b;
break;

case 2: cout<<"\n Addition = "<<a-b;


break;

case 3: cout<<"\n Addition = "<<a*b;


break;

case 4: cout<<"\n Addition = "<<a/b;


break;

default:cout<<"\n Wrong Choice :";


break;
}
cout<<"\n\n Do you want to continue :";
cin>>ans;
}while(ans=='y'||ans=='Y');

getch();
}

33
Array
“Collection of similar types of variables is known as array”

It is divided in to two types

1. One Dimensional array


2. 2 Two Dimensional array

1. One Dimensional Array

The Array which can only one dimension means there is only column

and multiple rows are available. Array index Starts from 0 (zero).

A[0]

A[1]

A[2]

A[3]

A[4]

A[5]

A[6]

First element stored in first position means a[0] size is 07 then last element stored in a[6].

Declaration of array:

The array declared with data type and it depends with the number stored in

array. The array declared with following syntax.

Syntax data_type array_name [size];

Example int a[5];

It means in array the integer numbers are stored and maximum 05 elements are stored.

34
Initialisation of array

Array can be initialising by two ways.

1. Compile time Initialisation


Compile time Initialisation means value can be assign at the time of

declaration are as follow

Syntax data_type array_name[size]={ };

The number are saperated by comma.

Example int a[5]={7,10,12,13,20};

2. Run time Initialisation

Run time Initialisation means value can be assign at the time of

Execution it can be done with the help of for loop are as follow.

Example

Int a[5];
for (i=0;i<=4;i++)
{
Cin>>a[i];
}

35
1.21 Write a C++ Program to accept 05 elements in array and display the element.

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

void main()
{
clrscr();
int i,a[5];

cout<<"\n Enter element in array :";

for(i=0;i<=4;i++)
{
cout<<"\n a["<<i<<"] = ";
cin>>a[i];
}

cout<<"\n The array elements are :";

for(i=0;i<=4;i++)
{
cout<<"\n a["<<i<<"] = ";
cout<<a[i];
}

getch();
}

36
1.22 Write a C++ Program to perform addition of two dimensional array elements
and display addition.
include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int i,a[5],b[5],c[5];

cout<<"\n Enter element in first array :\n";

for(i=0;i<=4;i++)
{
cout<<"a["<<i<<"] = ";
cin>>a[i];
}

cout<<"\n Enter element in Second array :\n";

for(i=0;i<=4;i++)
{
cout<<"a["<<i<<"] = ";
cin>>b[i];
}

for(i=0;i<=4;i++)
{
c[i]=a[i]+b[i];
}

cout<<"\n The addition of array is :\n";

for(i=0;i<=4;i++)
{
cout<<"\n a["<<i<<"] = ";
cout<<c[i];
}

getch();
}

37
1.23 Write a C++ Program to search an element from array.
#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int i,a[5],flag,k;
flag=0;

cout<<"\n Enter element in array :";

for(i=0;i<=4;i++)
{
cout<<"\n a["<<i<<"] = ";
cin>>a[i];
}

cout<<"\n Enter the element for the searching :";


cin>>k;

for(i=0;i<=4;i++)
{
if(a[i]==k)
{
flag=1;
break;
}
else
{
flag=0;
}
}

if(flag==1)
{
cout<<"\n The element "<<k<<" is present in a[";
cout<<i<<"] location";
}
else
{
cout<<"\n The element is not present in the array :";
}

getch();
}
1.24 Write a C++ Program to sort the elements in ascending order from array.

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

void main()
{
clrscr();
int i,j,a[7],temp;
temp=0;

cout<<"\n Enter element in array :\n";

for(i=0;i<=6;i++)
{
cout<<" a["<<i<<"] = ";
cin>>a[i];
}

for(i=0;i<=4;i++)
{
for(j=0;j<=6;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

cout<<"\n\nThe sorted elements are :";


for(i=0;i<=6;i++)
{
cout<<"\n a["<<i<<"] = ";
cout<<a[i];
}

getch();
}

39
2. Two Dimensional Array
Two dimensional array means handling rows and columns it with be

declared as follows.

Data_type array_name [size] [size];

The first size shows the rows and second sows the columns.

Int a[5][5];

It means it is the matrix having five rows and five columns.

40
1.25 Write a C++ Program to accept the elements in 3x3 matrixes and display the
elements.
#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int i,j,a[3][3];

cout<<"\n Enter element in matrix :\n";

for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<" a["<<i<<"] ["<<j<<"] = ";
cin>>a[i][j];
}
}

cout<<"\n Enter element present in matrix are :\n\n";

for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<"\t"<<a[i][j];
}
cout<<"\n\n";
}

getch();
}

41
1.26 Write a C++ Program to add two matrices and display the addition.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,j,a[3][3],b[3][3],c[3][3];
cout<<"\n Enter element in first matrix :\n";
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<" a["<<i<<"] ["<<j<<"] = ";
cin>>a[i][j];
}
}

cout<<"\n Enter element in second matrix :\n";

for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<" b["<<i<<"] ["<<j<<"] = ";
cin>>b[i][j];
}
}

for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
cout<<"\n The addition of matrix :\n";
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<"\t"<<c[i][j];
}
cout<<"\n\n";
}
getch();
}

42
1.27 Write a C++ Program to multiply two 3x3 matrices and display the resultant
array.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,j,k,a[3][3],b[3][3],c[3][3];
int sum=0;
cout<<"\n Enter element in first matrix :\n";
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<" a["<<i<<"] ["<<j<<"] = ";
cin>>a[i][j];
}
}
cout<<"\n Enter element in second matrix :\n";
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<" b["<<i<<"] ["<<j<<"] = ";
cin>>b[i][j];
}
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
for(k=0;k<3;k++)
{
sum=sum+a[i][k]*b[k][j];
}
c[i][j]=sum;
}
}
cout<<"\n The multiplication of matrices :\n";
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<"\t"<<c[i][j];
}
cout<<"\n\n";
}
getch();
}

43
Structure:
“Structure is the collection of different types of variable”.
Structure will be declared are as follows by using following syntax.
Syntax Example
struct struct_name
{
Variable 1; struct student
Variable 2; {
. . Int roll;
. . char name[10];
. . float per;
. . };
Variable n;
};
Object can be declared are as follows.
1. At the time of declaration of structure.

Syntax Example
struct struct_name
{
Variable 1; struct student
Variable 2; {
. . Int roll;
. . char name[10];
. . float per;
. . }s;
Variable n;
}object_name;

Creating multiple objects

Syntax Example
struct struct_name
{
Variable 1; struct student
Variable 2; {
. . Int roll;
. . char name[10];
. . float per;
. . }s1,s2,s3;
Variable n;
}obj1,obj2,……,objn;

44
2. In the main function.

structure_name object_name;
student s;

Accessing member of structure:


Data member declared with structure cannot access directly. It can
be access with the help of object as follows.

Object.variable_name;
s.roll;

45
1.28 Write a C++ Program to declare structure students having data member roll,
name, and percentage accept and display data for one student.
#include<iostream.h>
#include<conio.h>
struct student
{
int roll;
char name[20];
float per;
}s;
void main()
{
clrscr();
cout<<"\n Enter roll number of student : ";
cin>>s.roll;
cout<<"\n Enter name of student : ";
cin>>s.name;
cout<<"\n Enter percentage of student : ";
cin>>s.per;
cout<<"\n\n\n Name = "<<s.name;
cout<<"\n Roll Number = "<<s.roll;
cout<<"\n Percentage = "<<s.per;
getch();
}
1.29 Write a C++ program to declare structure employee accept and display data
for employee.
#include<iostream.h>
#include<conio.h>
struct employee
{
int emp_id;
char name[20];
float sal;
}e;
void main()
{
clrscr();
cout<<"\n Enter employee ID of employee : ";
cin>>e.emp_id;
cout<<"\n Enter name of employee : ";
cin>>e.name;
cout<<"\n Enter salary of employee : ";
cin>>e.sal;
cout<<"\n\n\n Name of emplyee = "<<e.name;
cout<<"\n Employee ID = "<<e.emp_id;
cout<<"\n Salary = "<<e.sal;
getch();
}

46
1.30 Write a C++ program to declare structure book accept and display information
of book.
#include<iostream.h>
#include<conio.h>
struct book
{
char auther[40];
char name[40];
float price;
}b;
void main()
{
clrscr();
cout<<"\n Enter the book name : ";
cin>>b.name;
cout<<"\n Enter the auther name : ";
cin>>b.auther;
cout<<"\n Enter the price of book : ";
cin>>b.price;
cout<<"\n\n\n Name of book = "<<b.name;
cout<<"\n Auther of book = "<<b.auther;
cout<<"\n Price of book = "<<b.price;
getch();
}
1.31 Write a C++ program to declare structure vehicle accept and display
information of vehicle.
#include<iostream.h>
#include<conio.h>
struct vehicle
{
int cc;
char model[20];
float price;
}v;
void main()
{
clrscr();
cout<<"\n Enter the vehicle name : ";
cin>>v.model;
cout<<"\n Enter the cubik capacity of vehicle : ";
cin>>v.cc;
cout<<"\n Enter the price of vehicle : ";
cin>>v.price;
cout<<"\n\n\n Name of vehicle = "<<v.model;
cout<<"\n Cubik Capasity of Vehicle = "<<v.cc;
cout<<"\n Price of vehicle = "<<v.price;
getch();
}

47
1.32 Write a C++ program to declare structure students accept and display
information of two students.
#include<iostream.h>
#include<conio.h>
struct student
{
int roll;
char name[20];
float per;
}s1,s2;
void main()
{
clrscr();
cout<<"\n Enter roll number of student : ";
cin>>s1.roll;
cout<<"\n Enter name of student : ";
cin>>s1.name;
cout<<"\n Enter percentage of student : ";
cin>>s1.per;
cout<<"\n Enter roll number of student : ";
cin>>s2.roll;
cout<<"\n Enter name of student : ";
cin>>s2.name;
cout<<"\n Enter percentage of student : ";
cin>>s2.per;
cout<<"\n\n Information of first student :";
cout<<"\n\n Name = "<<s1.name;
cout<<"\n Roll Number = "<<s1.roll;
cout<<"\n Percentage = "<<s1.per;
cout<<"\n\n Information of second student :";
cout<<"\n\n Name = "<<s2.name;
cout<<"\n Roll Number = "<<s2.roll;
cout<<"\n Percentage = "<<s2.per;
getch();
}

48
1.33 Write a C++ program to declare structure staff accept and display information
of two staff.

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

struct staff
{
int id;
char desig[20];
float sal;
}f1,f2;

void main()
{
clrscr();
cout<<"\n\n Enter the data for first staff ";
cout<<"\n Enter the staff id, designation and salary";
cin>>f1.id>>f1.desig>>f1.sal;
cout<<"\n\n Enter the data for second staff ";
cout<<"\n Enter the staff id, designation and salary";
cin>>f2.id>>f2.desig>>f2.sal;

cout<<"\n\n Information of first staff :";


cout<<"\n ID :"<<f1.id<<"\n Designation :"<<f1.desig;
cout<<"\n Salary :"<<f1.sal;
cout<<"\n\n Information of second staff :";
cout<<"\n ID :"<<f2.id<<"\n Designation :"<<f2.desig;
cout<<"\n Salary :"<<f2.sal;

getch();
}

49
1.34 Write a C++ program to declare structure car accept and display information of
ten car.

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

struct car
{
int no;
char compony[20];
float price;
}c[10];

void main()
{
clrscr();
int i;

cout<<"\n\n Enter the data of cars ";


for(i=0;i<=9;i++)
{
cout<<"\n Enter car no, company name and price :\n";
cin>>c[i].no>>c[i].compony>>c[i].price;
}

cout<<"\n\n Information of cars ";


for(i=0;i<=9;i++)
{
cout<<"\n Car no :"<<c[i].no;
cout<<"\n Company name :"<<c[i].compony;
cout<<"\n Price :"<<c[i].price;
}

getch();
}

50
1.35 Write a C++ program to declare structure furniture accepts and display
information of five furniture.

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

struct furniture
{
int height,width;
char color[20];
float price;
}f[5];

void main()
{
clrscr();
int i;

cout<<"\n\n Enter the data of furniture ";


for(i=0;i<=4;i++)
{
cout<<"\n Enter height, width, color and price of furniture:\n";
cin>>f[i].height>>f[i].width>>f[i].color>>f[i].price;
}

cout<<"\n\n Information of Furniture ";


for(i=0;i<=4;i++)
{
cout<<"\n Height :"<<f[i].height;
cout<<"\n Width :"<<f[i].width;
cout<<"\n Color :"<<f[i].color;
cout<<"\n Price :"<<f[i].price;
}

getch();
}

51
1.36 Write a C++ program to declare structure city having data members name,
population and area and display the city having population greater than
50000 [Accept information of 10 cities].
#include<iostream.h>
#include<conio.h>

struct city
{
char name[20];
int pop;
float area;
}c[10];

void main()
{
int i;
clrscr();
for(i=0;i<=
9;i++)
{
cout<<"\n Enter the information"<<i<<"city :";
cin>>c[i].name>>c[i].pop>>c[i].area;
}

for(i=0;i<=9;i++)
{
if((c[i].pop)>50000)
{
cout<<c[i].name<<c[i].pop<<c[i].area;
}
}

getch();
}

52
C++ Strings
The C-style character string originated within the C language and continues to be supported within
C++. This string is actually a one-dimensional array of characters which is terminated by
a null character '\0'. Thus a null-terminated string contains the characters that comprise the string
followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold the
null character at the end of the array, the size of the character array containing the string is one more
than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization, then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
above-mentioned string –
#include <iostream>

using namespace std;

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello

53
C++ supports a wide range of functions that manipulate null-terminated strings −

Sr.No Function & Purpose

1 strcpy(s1, s2);

Copies string s2 into string s1.

2 strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

3
strlen(s1);

Returns the length of string s1.

4 strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

#include <iostream>
#include <cstring>

int main () {
Output-
char str1[10] = "Hello"; strcpy( str3, str1) : Hello
char str2[10] = "World"; strcat( str1, str2): HelloWorld
char str3[10]; strlen(str1) : 10
int len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

return 0;
}

54
The String Class in C++

The standard C++ library provides a string class type that supports all the operations mentioned
above, additionally much more functionality. Let us check the following example −

#include <iostream>
#include <string>

using namespace std;

int main () {

string str1 = "Hello";


string str2 = "World";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total length of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as follows −
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10

#include <iostream.h>
#include <string.h>
int main ()
{
char frst [20] = "Programming";
char sec [20] = "Programming";
cout<<"Content of frst string: " <<frst <<"\n";
cout<<"Content of sec string: " <<sec <<"\n";
int result = strcmp (frst, sec);
cout<<" String comparison between " <<frst <<" and " <<sec<<" : " <<result <<"\n";
return 0;
}

55

You might also like