0% found this document useful (0 votes)
121 views

DSTC Unit-I

1) The document discusses various topics related to data structures and C++ classes including abstract data types, linear and non-linear data structures, declaring class objects, invoking member functions, constructors, destructors, and operator overloading. 2) Key concepts include data abstraction, encapsulation, and different access specifiers for data members and member functions. Common data structures like arrays, linked lists, stacks, queues, trees and graphs are also mentioned. 3) Examples are provided to demonstrate declaring classes, defining member functions, and using constructors and destructors to initialize and free the memory of class objects.

Uploaded by

thumuvsreddy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views

DSTC Unit-I

1) The document discusses various topics related to data structures and C++ classes including abstract data types, linear and non-linear data structures, declaring class objects, invoking member functions, constructors, destructors, and operator overloading. 2) Key concepts include data abstraction, encapsulation, and different access specifiers for data members and member functions. Common data structures like arrays, linked lists, stacks, queues, trees and graphs are also mentioned. 3) Examples are provided to demonstrate declaring classes, defining member functions, and using constructors and destructors to initialize and free the memory of class objects.

Uploaded by

thumuvsreddy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Syllabus: UNIT-I

Abstract Data Types and the C++ Class: An Introduction to C++ Class, Data Abstraction and
Encapsulation in C++, Declaring Class Objects and Invoking Member Functions, Special Class
Operations (Constructor, Destructor and Operator Overloading), Miscellaneous Topics (Struct,
Union, Static), ADTs and C++ Classes, The Array as an Abstract Data Type, The Polynomial
Abstract Data type: Introduction, Polynomial Representation, Polynomial Addition. Spares
Matrices: Introduction, Sparse Matrix Representation, Transposing a Matrix, Matrix
Multiplication, Representation of Arrays

DATA STRUCTURE:-
A data structure is the way of organizing and storing the data into the computer, for efficient
accessing or retrieval of data.

Primitive Data Structures: The data structures that are not defined by any other data structures,
The basic data types are int, real, char, Boolean.
Non-Primitive Data Structures: The data structures that are defined by any other data structures.
Again it is categorized into 2 types.
1. Linear Data Structures: A data structure is said to be linear if its elements form a sequence or a
linear list.
Examples: Array, Linked List, Stacks, Queues
2. Non-Linear Data: A data structure is said to be Non-linear if its elements form a not sequence or
non linear list.
Examples: Trees, Graphs

1
Operations on Linear and Non Linear Data Structures
 Traversal : Visit every part of the data structure
 Search : Traversal through the data structure for a given element
 Insertion : Adding new elements to the data structure
 Deletion: Removing an element from the data structure.
 Sorting : Rearranging the elements in some type of order(e.g Increasing or Decreasing)
 Merging : Combining two similar data structures into one

Abstract Data Types and the C++ Class:


Introduction to C++ Class:

 Class is a blueprint of data members and member functions. Class is a user defined data type
like structures and unions in C.

 By default class variables are private.


Syntax Example
class class_name class student
{ {
private: public:
//data members and member functions declarations char name[30];
public: int roll_no, age;
//data members and member functions declarations void getData() ;
protected: void display();
//data members and member functions declarations };
};

1) a class name: student

2) Data members: the data that makes up the class (e.g. name. roll_no and age).

3) Member functions: the set of operations that may be applied to the objects of a class (e.g.

getData(), display() ).

4) Levels of program access: these control the level of access to data members and member
functions from program code that is outside the class. There are three levels of access to class
members: public(Access outside of the class), protected(Immediate derived class can access) and
private(can’t access outside of the class).

2
Declaring Class Objects and Invoking Member Functions:-

 The class objects are declared and created in the same way that variables are declared and
created.
 The data members and member functions of class can be accessed using the dot ( . ) or
arrow () operator with the object.
 The public data members are accessed, the private data members are not allowed to be
accessed directly by the object, it can access by public member functions.
 While implementing the member functions outside of the class we use special reference
called scope resolution operator (::).

Example: Implement a program on basic


concepts of C++
#include <iostream.h>
class student
{ int main()
private: {
char name[30]; //declaring object to the class number
int roll_no, age; student S;
public:
void getData() ; S.getData();
void display(); S.display();
};
void student::getData( ) //declaring pointer to the object
{ student *ptrS;
cout<<"Enter Roll number, Age, and Name of ptrS = new student;
student: "; //creating & assigning memory
cin>>roll_no>>age>>name;
} //calling member function with
void student::display( ) pointer
{ ptrS->getData();
cout<<"RollNumber: "<<roll_no<<endl; ptrS->display();
cout<<"Age: "<<age<<endl;
cout<<"Name of student: "<<name; return 0;
} }

3
Data abstraction and Encapsulation:-

 The binding the data and functions into a single unit called class is known as encapsulation.
 The data is not accessible to the outside world, and only those functions which are enclosed
in the class can access it.
 Abstraction is seperating the logical properties from their implementation. It shows only the
essential features of the application and hiding the details.
 In C++, classes can provide methods to the outside world to access & use the data
variables, keeping the variables hidden from direct access. This can be done using access
specifiers(private).
Constructor, Destructor:- These are special member functions of the class.

 Constuctor is a member function, which  Destuctor is a member function, which


initialize the data members of an freeing the memory associated data
object. members of the class
 It call automatically when object of the  It call automatically when the lifetime of
class is created. an object ends
 It will write in public access specifier,  It will write in public access specifier,
name is same as class name and not name is same as class name, not specify
specify any retun type or values. any retun type or values, not pasing any
parameters and preceeded by ~(tield).
 If we not define, memory is allocated to  If we not define, freeing the memory but
the data members but not initialized so it if data members is pointing to some
may contain undefined values. other objects, that pointing is not deleted.
Example: Implement a program on Constructors and destructors using C++
#include<iostream.h> /* Parameterized constructor */
class StudentCon StudentCon(int r, int a)
{ {
private: rollno = r;
int rollno,age; age = a;
public: }
/* Default constructor */ /* Copy constructor */
StudentCon() StudentCon (const StudentCon &s2)
{ {
cout<<"Default Constructor"<<endl; rollno = s2.rollno;
rollno=0;age=0; age = s2.age;
} }
4
/* Destructor */ int main()
~StudentCon() {
{ StudentCon s1; // Default constructor
cout<<"Destructor has called"<<endl; StudentCon s2(545, 28); // Parameterized
StudentCon s3 = s2; // Copy constructor
} cout<<"Parameterized constructor : ";
void display() s2.display();
{ cout<<"Copy constructor : ";
cout<<rollno<<" "<<age<<endl; s3.display();
}
}; return 0;
}

Operator Overloading:
 Operator overloading is a compile-time polymorphism in which the operator is overloaded
to provide the special meaning to the user-defined data type.
 To overload an operator must write a function in public access specifies.
Syntax: returnType operator symbol (arguments)
{ ... .. ... }
This pointer:
 'this' pointer is a constant pointer that holds the memory address of the current object. If
‘this’ pointer is written in member function of a class, it can access data members of that
class for given object.
Friend Function:
 It is non-member function of a class but can access all members of a class (Both public and
private data)
 While defining friend function out of the class, no need to use scope resolution (: :) operator
and class name.
Syntax:
Declaration with in class: friend returnType function_name(parameters);
Calling through main: function_name(parameters);
Definition outside of the class: returntype function_name(parameters) { - - - }

5
Example: Implement a program on operator overloading, this pointer and friend function using C++
#include <iostream.h>
class Test void dosth(Test t)
{ {
private: t.count=t.count+100;
int count; cout<<"total count: "<<t.count;
int a,b; }
public:
void get() {count=5;} int main()
void put() {
{ cout<<"Count: "<<count<<endl; } Test t;
void operator ++() t.get();
{ count = count+1; } t.put();
++t;
Test input(int a,int b) t.put();
{
this->a=a+b;
this->b=a-b; Test t1,t2;
return *this; t2=t1.input(10,5);
} t1.output();
void output() t2.output();
{ cout<<"a,b values are:";
cout<<a<<" "<<b<<endl;} dosth(t);
return 0;
friend void dosth(Test);
}; }

MISCELLANEOUS TOPICS:
Structure:
 Both the structure and classes are almost equivalent.
 Structure is collection of different data items. The default access specifier is public.
 Class is blue print of data members and member functions. The default access specifier is private.
Union:
 Union reserves the storage for one of its largest data member at run time.
 Unions are used in Linked List and Inheritance.
Static:
 Static data member is similar to global variable throughout the class, because it is not similar data
member in the class.
 Each object doesn’t have its own copy; we have only one copy, it shares by all objects of the class.
Examples:
struct student union student
{ {
int rollno, age, marks; int rollno, age, marks;
char name[20]; char name[20];
}S1; // it allocates 26 bytes of memory }S2; // it allocates only 20 bytes of memory
class func void main()
{ public: {
func() { func f1; //11,6
int a=10; func f2; //11,7
static int b=5; func f3; //11,8
a++; b++; func f4; // 11,9
cout<<a<<b; } }; }

6
ADT (Abstract Data Type):-
 Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of
value and a set of operations.
 The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented.
 The process of providing only the essentials and hiding the details is known as abstraction

The model is only focusing on the following.


 The Data, which are affected by the program
 The Operations, which are identified by problem
ADT Notation:
ADT type_data_structure
{
Instances/Objective/Data: Describes the structure of the data used in ADT
Operations: Describe the valid operation for this ADT
}
Example: List ADT
ADT List
{
Instances: A list contains elements of same type arranged in sequential order
Operations:
isEmpty() – Return true if the list is empty, otherwise return false.
isFull() – Return true if the list is full, otherwise return false.
size() – Return the number of elements in the list.
get() – Return an element from the list at any given position.
insert() – Insert an element at any position of the list.
remove() – Remove the first occurrence of any element from a non-empty list.
replace() – Replace an element at any position by another element.
}
ARRAY:
 The array is a basic abstract data type that holds an ordered collection of items accessible
by an integer index. These items can be anything from primitive types such as integers to
more complex types.
 Since it's an ADT, it doesn't specify an implementation
ADT ARRAY
{ Instances:
Set of ordered pair (index, value), no two pairs having same index
Index one dimension / two dimensional / multi dimensional array
Value  primitive data types like int, float..
Operations:
Create(); // create an empty array
Store(index,value); //add or replace the pair into an array
Retrieve(index); //return the pair with index value
}
7
Example: Implementation of an Array ADT using C++
#include <iostream.h> int Array::search(int v)
class Array {
{ for( int i=0; i < size; i++)
int *a; if(a[i] == v)
int size; return i;
public: return (-1);
void create(int size); }
void store(int index, int value); void Array::display( )
int retrive(int index); {
int search(int v); cout<<"Array Elements are: ";
void display( ); for( int i=0; i< size; i++ )
}; cout<< a[i]<<" ";
void Array::create(int s) }
{ int main()
a= new int[s]; {
size= s; Array a1;
} a1.create(10);
void Array::store(int i, int v) a1.store(0,5);
{ a1.store(1,15);
if(i< size) a1.store(2,25);
a[i]= v; a1.store(3,35);
} a1.store(4,45);
int Array::retrive(int i) cout<<"Retrived Element:";
{ a1.retrive(2);
return(a[i]); cout<<"Searched Element:";
} a1.search(75);
a1.display();
return 0;
}
Storage Representation of Array:

One Dimensional Array:


 An array is a collection of items stored at contiguous memory locations.
 This makes it easier to calculate the position of each element i.e., the memory location of the first
element of the array (Base Address).

Address of an element we can find easily


A[index] = Base Address + (Size of data type * index)
Multi Dimensional Arrays:
 A multi-dimensional array is an array of arrays. 2-dimensional arrays are the most commonly
used. They are used to store data in a tabular manner (mXn).
 It can be represented in memory using any of the following two ways
1. Column-Major Order
2. Row-Major Order

8
Column-Major Order:
 In this method the elements are stored column wise, i.e. m elements of first column are
stored in first m locations, m elements of second column are stored in next m locations and
so on
Address of A [ i ][ j ] = BaseAddress + Size of datatype * [ i + (m *j)]
Row-Major Order:
 In this method the elements are stored row wise, i.e. n elements of first row are stored in
first n locations, n elements of second row are stored in next n locations and so on
Address of A [ i ][ j ] = BaseAddress + Size of datatype * [ ( i * n) + j ]
Example:

Row major Order:Address of A[2][3] = 1000+2 *[(2*4)+3]= 1000+22=1022


Column major Order:Address of A[1][2] = 1000+2 *[1+(3*2)]= 1000+14=1014
Three Dimensional Arrays: array is an array of arrays of arrays (rows, columns, depth)

9
Polynomial Abstract Data Type:
e
Polynomial is a result of terms, where each has a form aX , where “X” is a variable, “a” is the coefficient,

“e” is the exponent.


ADT Polynomial
{
Instances:
Set of ordered pair of coefficient and exponent
//P(X) = a0 X e0 + a1 X e1 + ⋯ + an X en
//Where ai is nonzero float coefficient and exponent ei is non negative integer
Operations:
Polynomial(); //construct the polynomial p(x)=0
Polynomial Addpoly(Polynomial A, Polynomial B);
//returns result of two polynomials
Polynomial Subpoly(Polynomial A, Polynomial B);
//returns subtraction of two polynomials
Polynomial Multpoly(Polynomial A, Polynomial B);
//returns multiplication of two polynomials
flaot Evaluate(flaot f);
//Evaluate the polynomial using f and return result
}
Polynomial Representation:
Polynomial may be represented using array (or) linked lists.
Polynomial as Array Representation
It is asresulted that exponent of a expression are arranged from 0 to highest value(degree)
which is represented by subscripts(index) of respective exponents are placed at appropriate
index in the array.
Representation 1:

Advantage: Easy to Store and Represent


Disadvantage: Huge array size is required, waste of space
Representation 2:

10
Code for representations:
class Polynomial class Term
{ friend Polynomial;
{
private:
private: int exp;
float coef;
int degree;
};
float coef[degree+1]; class Polynomial
{ private:
………
Term *termArray;
}; ………
};

Polynomial as Linked Representation:


A Polynomial node has mainly two fields. Exponent and coefficient.

Node of a Polynomial:

In each node the exponent field will store the corresponding exponent and the coefficient field will store
the corresponding coefficient. Link field points to the next item in the polynomial.

Addition of two Polynomials:


Let A and B be the two polynomials represented by the array/linked list.
1. while Both A and B are having terms (not null), repeat step 2.
2. If powers of the two terms are equal
then insert the result of the terms into the result Polynomial
Advance(move to next term) A
Advance(move to next term) B
Else if the power of the first polynomial A> power of second polynomial B
Then insert the term from first polynomial A into result polynomial
Advance(move to next term) A
Else insert the term from second polynomial B into result polynomial
Advance(move to next term) B
3. copy the remaining terms from the non empty polynomial into the
result polynomial.
Ex: Addition of two polynomials using Linked List

11
Ex: Addition of two polynomials using arrays

Sparse Matrix:
 A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m
x n values. If majority of the elements of the matrix have 0 value, then it is called a sparse matrix.
Why to use Sparse Matrix?
 Storage: There are lesser non-zero elements than zeros, lesser memory can be used to store only
those non zero elements.
 Computing time: Computing time can be saved for traversing only non-zero elements..
 Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the
matrix are of no use. So, instead of storing zeroes, we store only non-zero elements. This means
storing non-zero elements with triples- (Row, Column, value).
Representation: Sparse Matrix Representations can be done in following ways

1. Array representation(Triplet Representation)


2. Linked list representation
Method 1: Using Arrays
2D array is used to represent a sparse matrix in which there are three columns named as

 Row: Index of row, where non-zero element is located


 Column: Index of column, where non-zero element is located
 Value: Value of the non zero element located at index – (row,column)
In this representation, the 0throw stores the total number of rows, total number of columns and the total
number of non-zero values in the sparse matrix.

class SparseTerm class SparseMatrix


{
{ friend SparseMatrix;
private:
private: SparseTerm *termArray;
………
int row,col,value;
};
};

12
Method 2: Using Linked Lists
In linked list, each node has five fields. These fields are defined as:
 Row: Index of row, where non-zero element is located
 Column: Index of column, where non-zero element is
located
 Value: Value of the non zero element located at index
 Down: Address of next non-zero in the same Column
 Right: Address of next non-zero in the same row

13
ADT SparseMatrix
{
Instances:
A set of triples, <row, col, value>
//where row and col are integers and form a unique combination.
Operations:
void create(n);//creates a SparseMatrix that can hold n non-zero elements information.
SparseMatrix transpose(SparseMatrix A); //It return the matrix produced by
interchanging the row and column value of every triple.
SparseMatrix add(SparseMatrix A, SparseMatrix B); //if dimensions of A and B are the
same return the matrix else return error.
SparseMatrix multiply(SparseMatrix A, SparseMatrix B); // if number of columns in A
equals number of rows in B return the matrix C produced by multiplying A by B according
to the formula: C[i][j]= Ʃ(A[i][k]*B[k][j]) where C[i][j] is the (i,j) th element else return
error.
}

Sparse Matrix Transpose:


To transpose a matrix we must interchange the rows and columns.

Example: Sparse matrix A, Transpose Sparse Matrix B

row col value row col value


------------------------------------ ------------------------------------
A.t[0] 6 6 8 B.t[0] 6 6 8
[1] 0 0 15 [1] 0 0 15
[2] 0 3 22 [2] 0 4 91
[3] 0 5 -15 [3] 1 1 11
[4] 1 1 11 [4] 2 1 3
[5] 1 2 3 [5] 2 5 28
[6] 2 3 -6 [6] 3 0 22
[7] 4 0 91 [7] 3 2 -6
[8] 5 2 28 [8] 5 0 -15

We move these triples consecutively in to the transpose matrix, as we insert new


triples, we must move elements to maintain the correct order. We should “find all the
elements in column 0 and store them in row 0 of the transpose matrix, find all the
elements in column 1 and store them in row 1 etc.
14
Example:Implement a program for finding Sparse matrix and transpose of sparse matrix
#include<iostream> cout<<"the sparse matrix ";
class matrix for(i=0;i<k;i++)
{ {
int a[20][20],b[20][20],c[20][20],i,j,x,y,m,n; cout<<"\n";
public: for(j=0;j<3;j++)
void input(int,int); cout<<b[i][j];
void sparse(); }
void transpose(); }
}; void matrix::transpose()
void matrix::input(int x,int y) {
{ int i,j,k,n;
m=x; n=y; c[0][0]=b[0][1];
cout<<"enter the matrix: \n"; c[0][1]=b[0][0];
for(i=0;i<m;i++) c[0][2]=b[0][2];
for(j=0;j<n;j++) k=1;
cin>>a[i][j]; for(i=0;i<b[0][1];i++)
cout<<"the matrix is: \n"; for(j=1;j<=b[0][2];j++)
for(i=0;i<m;i++) if(i==b[j][1])
{ {
cout<<"\n"; c[k][0]=b[j][1];
for(j=0;j<n;j++) c[k][1]=b[j][0];
cout<<a[i][j]; c[k][2]=b[j][2];
} k++;
} }
void matrix::sparse() cout<<" Transpose of sparse matrix:”;
{ for(i=0;i<k;i++)
int k=1; {
for(i=0;i<m;i++) cout<<"\n";
{ for(j=0;j<3;j++)
for(j=0;j<n;j++) cout<<c[i][j];
{ }
if(a[i][j]!=0) }
{ int main()
b[k][0]=i; {
b[k][1]=j; int m,n;
b[k][2]=a[i][j]; matrix ob;
k++; cout<<"enter order of matrix: \n";
} cin>>m>>n;
} ob.input(m,n);
} ob.sparse();
b[0][0]=m; ob.transpose();
b[0][1]=n; return 0;
b[0][2]=k-1; }
15
Sparse Matrix Multiplication:

Given A and B where A is m n and B is n p, the product matrix D has dimension m p.


Its <i, j> element is
n1

dij  a b ik kj

k 0

for 0  i < m and 0  j < p.

In general, you multiply a values at row 'i' in matrix A with a column in the matrix B and
store the sum of the row operation as a result in the resultant matrix.

However, since this problem involves sparse matrices, we can ignore the multiplication with
the column in matrix B if the value in matrix A is 0(zero). This small optimization helps us in
avoiding K operations where K is the number of rows in the matrix B or the number of columns in
the matrix A.
iA.rows; jB.cols; kA.cols/B.rows
sum += A[i][k]*B[k][j];
C[i][j] = sum;

16

You might also like