You are on page 1of 19

1 P E

USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

INTERNAL ASSESSMENT TEST 1


Date : 28.2.2018 Marks: 40
Subject & Code : DataStructures Using C++ (15EC661) Sem : VI A,B,C
Name of faculty : Vandana M L Time : 11:30-1:00 PM
Note: Answer FIVE full questions, selecting any ONE full question from each part. Marks
PART 1
1 What are function templates in C++.Write a C++ function template to 8
implement bubble sort

OR
2 Explain reference variables in C++.In the following code explain why does 8
swap method fails to swap the actual parameters. Change the code so that it
swaps the actual parameters
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
}

PART 2
3 a Explain exception handling in C++ with example program. 4

b Explain new and delete operator in C++ 4


OR
4 What is recursive function. Write a recursive function to generate permutations. 8
Trace the code to generate permutations of a,b,c
PART 3
5 a Explain the various ways to represent a matrix. 4
b Write a function to create a 2D matrix using dynamic memory allocation(use 4
array of arrays notation)
OR
6 a Write C++ code to overload operator + to add two matrices 4

b Write a C++ function to multiply two matrices. Use reference variables and 4

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

pointer notation
PART 4
7 a Explain the Abstract Class Linear List. 4

b Write C++ default constructor and copy constructor code for array list class 4
which represents array based implementation for Linear list
OR
8 Write C++ member function for a)inserting an element b) deleting an element 8
from array based linear list
PART 5
9 a Define class for a singly linked chain 4
b Write C++ member function to get data of node with given index position from 4
the linked list
OR
10 a Give structure definition for a node of chain(linked list) with all constructors 4
b Write C++ member function to insert a node at given index position in a single 4
linked list

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

Solution Manual

1. Template Function : Rather than writing new version of the code for
every possible data type of the formal parameters, we can write a
generic code in which the data type is a variable whose value is to be
determined by the compiler. This generic code is written using the
template statement.

template <class T>


T Abc (T a, T b, T c)
{
return a+b+b*c+ (a+b-c) / (a+b) +4;
} Writing Abc( ) as a template function eliminates the need to
know the data type of the formal parameters when we write the code.

2. Reference Variables are used as aliases for other variables within a


function. All operations supposedly performed on the alias (i.e., the
reference) are actually performed on the original variable. An alias is
simply another name for the original variable. Must be initialized at
the time of declaration.

Example

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

int count = 1;
int &cRef = count;
cRef++;

Increments count through alias cRef

The given function code fails to swap the actual parameters as values of
actual parameters are copied to the formal parameters formal
parameters x,y are taken as the local variables and once the function is
executed local variable values are lost and the original values are as it is
we can use reference variables to change the actual parameters

void swap(int &x,int &y)


{
int t;
t=x;
x=y;
y=t;
}

3a. C++ exception handling mechanism is basically built upon three


keywords namely, try, throw and catch.Try block hold a block of
statements which may generate an exception.When an exception is
detected, it is thrown using a throw statement in the try block.

Try block Detects and throws exception


Catch block Catches and handles the exception
A try block can be followed by any number of catch blocks.
The general form of try and catch block is as follows:

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

try

/* try block; throw exception*/

catch (type1 arg)

/* catch block*/

…………………….

catch (type2 arg)

/* catch block*/

#include<iostream.h>

void main()

int x, y;

cout<<”enter two number”<<endl;

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

cin>>x>>y;

try

{if(y!=0)

{z=x/y;

cout<<endl<<z;

else

{throw(y);}

catch(int y)

cout<<”exception occurred: y=”<<y<<endl;

3b. The operator new:

Run-time or dynamic allocation of memory may be done using the


C++ new. This operator returns a pointer to the allocated memory.
For example,

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

dynamically allocate memory for an integer, we must declare a


variable (e.g., y) to be a pointer to an integer using this statement:

int *y;

When the program needs to actually use the integer, memory may
be allocated it using this syntax:

Y = new int;

The operator new allocates enough memory to hold an integer, and


a pointer to this memory is returned and saved in y. The variable y
references the pointer to the integer, and *y references the
integer.

To store an integer value,Ex: 10, in the newly allocated memory,


we can use the following syntax:

*y = 10;

We can combine the three steps-declare y, allocate memory, and


assign a value to *y-into a smaller number of steps.

int *y=new int;

*y=10;

(or)

int *y=new int(10);

(or)

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

int *y;

Y=new int(10);

Many examples of functions that work with one- and two-


dimensional arrays. The dimensions of these arrays may not be
known at compile time. so,memory for these arrays needs to be
allocated dynamically.

To create a one-dimensional floating-point array x at run time, we


must declare x as a pointer to a float and then allocate enough
memory for the array. For example, a floating-point array of size n
may be created as follows:

float *x = new float [n];

The Operator delete :

Dynamically allocated memory should be freed when it is no


longer needed. The freed memory can then be reused to create
new dynamically allocated structures. We can use the C++
operator delete to free space allocated using the operator new.
The statements

delete y;

delete [] x;

free the memory allocated to *y and the one- dimensional array x.

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

When at least one of the dimensions is unknown at compile


time, the array must be created at run time using the ‘new’
operator. A two-dimensional character array for which the
number of columns-for example, 5-is known at compile time
may be allocated using the following syntax:

char (*c) [5] ;

try {

c = new char [n][5];}

4. A recursive function is a function that invokes itself.In direct recursion the code
for function ‘f’ contains a statement that invokes ‘f’,where as an indirect
recursion function ‘f’ invokes a function ‘g’,which invokes a function ‘h’ and soon
until function ‘f’ is again invoked.

Recursive definition of mathematical function:


The factorial function f(n)= { 1 n<=1
{n*f(n-1) n>1
The definition must include a base component in which f(n) is defined directly for
one or more values of n.

#include<iostream.h>
#include<conio.h>
void permute(char a[], int i, int n)
{

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

int j,temp;
if (i == n)
cout << a << endl;
else
{
for (j = i; j <= n; j++)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;

permute(a, i+1, n);


temp=a[i];
a[i]=a[j];
a[j]=temp;
} }
}
int main()
{
char a[] = "ABC";
permute(a, 0, 2);
getch();
return 0;
}

5a. Row Major

Column Major

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

Array of Arrays notation

X[0] ----- [0] [1] [2] [3] [4]


X[1] ----- [0] [1] [2] [3] [4]
X[2] ----- [0] [1] [2] [3] [4]

5b. template <class T>

bool make2dArray(T **&x, int numberOfRows, int numberOfColumns)


{ // Create a two dimensional array,
try {
// create pointers for the rows
x = new T * [numberOfRows];
// get memory for each row
for (int i = 0; i < numberOfRows; i++)
x[i] = new int [numberOfColumns];
return true; }
catch (xalloc) {return false;}
}

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

6a. Class Matrix


{
Public:
Matrix(int rows=0;cols=0);
Matrix operator+(Matrix V);
input();
output();
Private:
int rows;
int cols;
int a[20][20];
}

Matrix Matrix::operator+(Matrix V)
{
if(rows!=V.rows || cols!=V.cols)
throw dimensionmismatch();
Matrix temp(rows,cols);
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
temp. a[i][j]=a[i][j]+V.a[i][j];
return temp;
}
6b.
int** matmul(int** & mat1,int ** &mat2,m1,n1,m2,n2)
{
int **mat3;
if((make2dArray(mat3,mat1.rows,mat2.cols));
for(i=0;i<m1;i++)
for(j=0;j<n2;j++)
{ sum=0;
for(k=0;k<n1;k++)
sum=sum+mat1[i][k]*mat2[k][j];

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

mat3[i][j]=sum;
}
return mat3;
}
}
bool make2dArray(T **&x, int numberOfRows, int numberOfColumns)
{ // Create a two dimensional array,
try {
// create pointers for the rows
x = new T * [numberOfRows];
// get memory for each row
for (int i = 0; i < numberOfRows; i++)
x[i] = new int [numberOfColumns];
return true; }
catch (xalloc) {return false;}
}

7a.
AbstractDataType LinearList
{
instances
ordered finite collections of zero or more elements
operations
empty(): return true iff the list is empty, false otherwise
size(): return the list size (i.e., number of elements in the list)
get(index): return the indexth element of the list
indexOf(x): return the index of the first occurrence of x in
the list, return -1 if x is not in the list
erase(index): remove the indexth element,
elements with higher index have their index reduced by 1
insert(theIndex, x): insert x as the indexth element, elements
with theIndex >= index have their index increased by 1

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

output(): output the list elements from left to right


}

7b.
Default Constructor
template<class T>
arrayList<T>::arrayList(int initialCapacity)
{// Constructor.
if (initialCapacity < 1)
{
throw illegalPrameterValue();
// u can also write a message cout<<“invalid capacity”;
}
else
arrayLength = initialCapacity;
element = new T[arrayLength];
listSize = 0;
}
}
Copy constructor

template<class T>
arrayList<T>::arrayList(const arrayList<T>& theList)
{
// Copy constructor.
arrayLength = theList.arrayLength;
listSize = theList.listSize;
element = new T[arrayLength];
copy(theList.element, theList.element + listSize, element);
}

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

8 a) Inserting an element

template<class T>
void arrayList<T>::insert(int theIndex, const T& theElement)
{ // Insert theElement.
checkIndex(theIndex) ;
// valid index, make sure we have space
if (listSize == arrayLength)
{// no space, double capacity
changeLength1D(element, arrayLength, 2 * arrayLength);
arrayLength *= 2;
}
// shift elements right one position
copy_backward(element + theIndex, element + listSize, element + listSize + 1);
element[theIndex] = theElement;
listSize++;
}

b)Deleting an element

template<class T>

void arrayList<T>::erase(int theIndex)


{
// Delete the element whose index is theIndex.
checkIndex(theIndex);
// valid index, shift elements with higher index
copy(element + theIndex + 1, element + listSize, element + theIndex);

element[--listSize].~T(); // invoke destructor


}

9a. template<class T>

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

class chain : public linearList<T>


{ public:
// constructors and destructor defined here
chain(int initialCapacity = 10)
chain(const chain<T>&)
~chain();
// ADT methods
bool empty() const {return listSize == 0;}
int size() const {return listSize;}
// other ADT methods defined here
get,indexof,erase,insert,output
protected:
void checkIndex(int theIndex) const;
chainNode<T>* firstNode;
int listSize;
};
template <class T>
struct chainNode
{
// data members
T element;
chainNode<T> *next;

// constructors come here


// default and parameterized
};

9b.
template<class T>
T& chain<T>::get(int theIndex) const
{// Return element whose index is theIndex.
checkIndex(theIndex);
// move to desired node

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

chainNode<T>* currentNode = firstNode;


for (int i = 0; i < theIndex; i++)
currentNode = currentNode->next;
//at the end of loop it points to the desired node
return currentNode->element;
}

10. a template <class T>


struct chainNode
{
// data members
T element;
chainNode<T> *next;

// constructors come here


// default and parameterized
};

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

10b.
template<class T>
void chain<T>::insert(int theIndex,
const T& theElement)
{
if (theIndex < 0 || theIndex > listSize)
{// Throw illegalIndex exception
}

if (theIndex == 0)
// insert at front
firstNode = new chainNode<T>

BE VI semester
1 P E
USN

PESIT Bangalore South Campus


Hosur road, 1km before Electronic City, Bengaluru -100
Department of Electronics and Communication

(theElement, firstNode);

BE VI semester

You might also like