pesit bangalore south campuspesitsouth.pes.edu/pdf/2018/ec/15ec661_t1.pdf · ... datastructures...

19
USN 1 P E PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication BE VI semester 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 implement bubble sort 8 OR 2 Explain reference variables in C++.In the following code explain why does 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; } 8 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. Trace the code to generate permutations of a,b,c 8 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 array of arrays notation) 4 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

Upload: dinhcong

Post on 25-Jun-2018

233 views

Category:

Documents


0 download

TRANSCRIPT

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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

implement bubble sort

8

OR

2 Explain reference variables in C++.In the following code explain why does

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;

}

8

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.

Trace the code to generate permutations of a,b,c

8

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

array of arrays notation)

4

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

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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

which represents array based implementation for Linear list

4

OR

8 Write C++ member function for a)inserting an element b) deleting an element

from array based linear list

8

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

the linked list

4

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

linked list

4

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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:

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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;

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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,

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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)

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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.

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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) {

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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;} }

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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];

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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); }

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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>

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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 };

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

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>

USN

1 P E

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100

Department of Electronics and Communication

BE VI semester

(theElement, firstNode);