Top Banner
Programming in C++: Assignment Week 1 Total Marks : 20 Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology Kharagpur – 721302 [email protected] February 24, 2017 Question 1 Which special symbol allowed in a variable name? Mark 1 a) ! b) | c) * d) _ Answer: d) Explanation: As per the Syntax of the language. Refer Slides Question 2 Which of the following are unary operators in C? Mark 1 a) ?: b) ++ c) *= d) sizeof() Answer: b) d) Explanation: As per the Syntax of the language. Refer Slides Question 3 Which of the following declarations are correct? Mark 1 a) struct mystruct {int a;}; b) struct {int a;} c) struct mystruct {int a;} d) struct mystruct int a; Answer: a) Explanation: As per the Syntax of the language. Refer Slides. 1
91

Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

May 19, 2018

Download

Documents

vominh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming in C++: Assignment Week 1

Total Marks : 20

Partha Pratim DasDepartment of Computer Science and Engineering

Indian Institute of TechnologyKharagpur – 721302

[email protected]

February 24, 2017

Question 1

Which special symbol allowed in a variable name? Mark 1

a) !

b) |

c) *

d) _

Answer: d)Explanation: As per the Syntax of the language. Refer Slides

Question 2

Which of the following are unary operators in C? Mark 1

a) ?:

b) ++

c) *=

d) sizeof()

Answer: b) d)Explanation: As per the Syntax of the language. Refer Slides

Question 3

Which of the following declarations are correct? Mark 1

a) struct mystruct {int a;};

b) struct {int a;}

c) struct mystruct {int a;}

d) struct mystruct int a;

Answer: a)Explanation: As per the Syntax of the language. Refer Slides.

1

Page 2: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 4

What will the function Sum return? Mark 1

void sum(int x, int y) {

x++; y++;

return (y);

}

a) The incremented value of y

b) The incremented value of y; the value of x is incremented but not returned

c) Compilation Error: return value type does not match the function type

d) Does not incremented value of y

Answer: c)Explanation: The return type of the function is void, hence an integer value cannot bereturned.

Question 5

What value will be printed for data.c? Marks 2

#include<stdio.h>

#include <string.h>

int main() {

union Data {

int i;

unsigned char c;

} data;

data.c =’C’;

data.i = 89;

printf( "%c\n", data.c);

return 0;

}

a) C

b) Y: ASCII 89

c) G

d) C89

Answer: b)Explanation: When %c is used for printing an integer value, conversion to the equivalentASCII

2

Page 3: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 6

What is the output of the above program? Marks 2

#include <stdio.h>

void foo( int[] );

int main() {

int myarray[4] = {1, 2, 3, 0};

foo(myarray);

printf("%d ", myarray[0]);

}

void foo(int p[4]){

int k = 34;

p = &k;

printf("%d ", p[0]);

}

a) 1 2

b) 1 3

c) Will always output 1

d) 34 1

Answer: d)Explanation: The base pointer of the array is used to point to an integer 34. In main, thearray is accesssed directly to print the 1st element.

Question 7

What is the output of the following program? Marks 2

#include <stdio.h>

#define func(x, y) x / y + x

int main() {

int i = -6, j = 3;

printf("%d\n",func(i + j, 3));

return 0;

}

a) divide by zero error

b) -4

c) -8

d) 3

Answer: c)Explanation: x/y+x replaced by i + j/3 + i + j i.e (-6 + 3/3 -6 +3) = (-6 + 1 -6 +3) = -8

3

Page 4: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 8

What will be the output of the following program? Marks 2

#include <stdio.h>

int sum(int a, int b, int c) {

return a + b + c / 2;

}

void main() {

int (*function_pointer)(int, int, int);

function_pointer = sum;

printf("%d", function_pointer(2, 3, 4));

}

a) Compilation Error: Error in function call

b) 7

c) 4.5

d) 5.5

Answer: b)Explanation: function pointer is a pointer defined for any function with 3 integer parametersand integer return type. It points to function sum and returns the result of the sum.

Question 9

Fill in the blank to concatenate strings str1 and str2 to form str3? Marks 2

#include <iostream>

#include <string>

using namespace std;

int main(void) {

string str1 = "I ";

string str2 = "Travel";

string str3 = _______________________;

cout << str3;

return 0;

}

Output: I Travel

a) str1+str2

b) strcat(str1,str2);

c) strcat(strcpy(str3,str1),str2);

d) str1.append(str2)

Answer: a) str1+str2 and d) str1.append(str2)Explanation: str1 and str 2 are two string type variables, operations possible for concate-nation are str1+str2 (String is a stl, hence has + operator overloaded) and str1.append(str2)to append strings.

4

Page 5: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 10

What will be the output of the following program? Marks 2

#include <iostream>

#include <algorithm>

using namespace std;

bool srt (int i, int j) {

return (i < j);

}

int main() {

int data[] = {52, 76, 19, 5, 10, 100, 56, 98, 17};

sort (data + 1, data + 4, srt);

for (int i = 0; i < 9; i++)

cout << data[i] << " ";

return 0;

}

a) 52 5 19 76 10 100 56 98 17

b) 52 76 19 10 5 100 56 98 17

c) 76 5 10 19 76 100 56 98 17

d) 76 5 10 19 76

Answer: a)Explanation: The whole array is not passed for sorting, only from index 1 (data + 1, i.e 0+ 1) to index 4 (data + 4, i.e 0 + 4), i. e 3 elements, 76, 19, 5

Question 11

What will be the output of the following program? Marks 2

#include<iostream>

#include<string.h>

#include<stack>

using namespace std;

int main() {

char str[19]= "Programming";

stack<char> s;

for(int i = 0; i < strlen(str); i++)

s.push(str[i]);

for(int i = 0; i < strlen(str) - 1; i++) {

cout << s.top();

s.pop();

}

return 0;

}

a) rogramming

b) ogramming

c) gnimmargor

5

Page 6: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

d) gnigormmar

Answer: c)Explanation: When programming pushed to stack, the element on the top is g (gnimmar-gorp) , which is displayed and then popped. Continues till length of str - 1, hence p not printedat the end.

Question 12

Fill up the blanks for A# and B# below: Marks 2

#include <iostream>

#include <vector>

using namespace std;

int main() {

cout << "Enter the no. of elements: ";

int count, j, sum=0;

cin >> count;

__________________ A# // Declare with Default size

__________________ B# // Change the size to the required amount

for(int i = 0; i < arr.size(); i++) {

arr[i] = i;

sum + = arr[i];

}

cout << "Array Sum: " << sum << endl;

return 0;

}

a) A#: vector <int> arr(count);B#: arr.resize(count);

b) A#: vector <int> arr(count);B#: arr.size(count);

c) A#: vector <int> arr;B#: arr.size(count);

d) A#: vector <int> arr;B#: arr.resize(count);

Answer: d)Explanation: As per syntax, using resize operator

6

Page 7: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming in C++: Assignment Week 2Total Marks : 20

Each question carries one markRight hand side of each question shows its Type (MCQ/MSQ)

March 3, 2017

Question 1

• Look at the code snippet below:

int * const p = &n;

Which of the following statement is true for the variable ’p’? Mark 1

a. const-Pointer to non-const-Pointee

b. non-const-Pointer to const-Pointee

c. const-Pointer to const-Pointee

d. non-const-Pointer to non-const-PointeeAnswer: aExplanation: As per syntax, refer slides

Question 2

• Look at the following code segment and decide which statement(s) is/are correct. Mark1

int main(){

int m = 4;

const int n = 5;

const int * p = &n;

int * const q = &m;

// ...

n = 6; // stmt-1

*p = 7; // stmt-2

p = &m; // stmt-3

*q = 8; // stmt-4

q = &n; // stmt-5

// ...

}

a. stmt-1

b. stmt-2

c. stmt-3

d. stmt-4

1

Page 8: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

e. stmt-5Answer: c, dExplanation: As per syntax, refer slides

Question 3

• Identify the output of the following code. Mark 1 Mark 1

#include<iostream>

using namespace std;

int main() {

typedef struct Complex {

double re;

double im;

} Complex;

const Complex c = {2,4} ;

c.re = 5.9;

cout << c.re;

return 0;

}

a. 5.9

b. Cannot assign an integer value to a double variable

c. 5.90

d. Cannot assign value 5.9 to read only c.reAnswer: dExplanation: c is variable of the structure Complex, but it is defined as const,hence cannot be modified

Question 4

• Identify the correct statement(s). Mark 1

#include <iostream>

#include <cmath>

using namespace std;

#define TWO 2

#define PI 4.0*atan(1.0)

int main() {

int r = 10;

double peri = TWO * PI * r;

cout << "Perimeter = "

<< peri << endl;

return 0;

}

a. TWO and PI are variables

b. Types of TWO and PI may be indeterminate

c. Types of TWO and PI are determinate

2

Page 9: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

d. TWO and PI look like variablesAnswer: b), d)Explanation: TWO and PI are manifest constants, hence types can be indeter-minate and look like variables.

3

Page 10: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 5

• What will be the output of the following code? Mark 1

#include <iostream>

using namespace std;

double Ref_const(const double &param) {

return (param * 3.14);

}

int main() {

double x = 8, y;

y = Ref_const(x);

cout << x << " "<< y;

return 0;

}

a. Cannot return constant parameter

b. Cannot edit constant parameter

c. 8 26

d. 8 25.12Answer: d)Explanation: Const used to pass reference parameter param to prevent frombeing modified. The value of param is used only

Question 6

• What will be the output of the following code? Mark 1

#include <iostream>

using namespace std;

void func(int n1 = 10, int n2) {

cout <<n1 << " "<< n2;

}

int main() {

func(1);

func(3, 4);

return 0;

}

a. 1 10 3 4

b. 10 1 4 3

c. 10 1 3 4

d. Compilation error: Argument missing for parameter 2 of funcAnswer: d)Explanation: Default values needs to specified from the end, hence functionresoultion fails

4

Page 11: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 7

• What will be the output of the following code? Mark 1

#include <iostream>

using namespace std;

int Add(int a, int b) { return (a + b); }

double Add(double c) {

return (c + 1);

}

int main() {

int x = 1, y = 2, z;

z = Add(x, y);

cout << z;

double s = 4.5, u;

u = Add(s);

cout << " " << u << endl;

return 0;

}

a. Add cannot be overloaded with different return types

b. Add cannot be resolved

c. 3 5.5

d. 3 6.5Answer: c)Explanation: Two versions of function Add called as per resolution

Question 8

• Which function prototype will match the function call func(3.6,7)? Mark 1

void func(int, int); // Proto 1

void func(double, double, double = 5.6); // Proto 2

void func(double, double, char = ’c’); // Proto 3

void func(double, char = ’d’, char = ’c’); // Proto 4

a. Proto 1

b. Proto 2

c. Proto 3

d. Proto 4Answer: a), b), c)Explanation: Proto 1 allowed, as 3.6(1st parameter) is downcast to integer.Proto 2 allowed, as default value will be used for third parameter. Proto 3 allowed,default value and type will be used for third parameter. Proto 4 fils for mismatchin 2nd parameter

5

Page 12: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 9

• What will be the output of the following code? Mark 1

#include<iostream>

using namespace std;

int main() {

int *ptr = NULL;

cout << " Output: In Program";

delete ptr;

return 0;

}

a. ptr cannot point to NULL

b. delete ptr (NULL) causes program crash

c. Output: In Program

d. Invalid SyntaxAnswer: c)Explanation: Null assignment to pointer allowed. Normal print provides theoutput

Question 10

• Fill up the blanks to get the desired output according to the test cases. Mark 1

#include <iostream>

#include <cstring>

#include <cstdlib>

using namespace std;

typedef struct _String { char *str; } String;

____________________________________ {

String s;

s.str = (char *) malloc(strlen(s1.str) +

strlen(s2.str) + 1);

strcpy(s.str, s1.str);

strcat(s.str, s2.str);

return s;

}

int main() {

String s1, s2, s3;

s1.str = strdup("I");

s2.str = strdup(" love Travelling ");

s3 = s1 + s2;

cout << s3.str << endl;

return 0;

}

a. String + operator(const String& s1, const String& s2)

6

Page 13: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

b. String +(const String& s1, const String& s2)

c. String operator+(const String& s1, const String& s2)

d. string operator+(const String s1, const String& s2)Answer: c)Explanation: As per syntax, Overloading operator + for String structure. Ref-erence parameters passed as const to prevent modification.

I Programming Assignments

Question 1

• Fill up the blanks by providing appropriate return type and argument type for thefunction Ref func() to get the desired output according to the test cases. Marks 2

#include <iostream>

using namespace std;

_____ Ref_func( _____ param) {

return (++param);

}

int main() {

int x, y, z;

cin >> x ;

cin >> y ;

y = Ref_func(x);

cout << x << " "<< y << endl;

Ref_func(x) = z;

cout << x << " "<< y;

return 0;

}

Input: 8, -9Output: 9 9-9 9Input: 10, 20Output: 11 1120 11Input: -19, -32Output: -18 -18-32 -18

Answer: //int& // int &

7

Page 14: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 2

• Fill up the blanks to get the desired output according to the test cases. Marks 2

#include <stdio.h>

int func(int, int);

#define func(x, y) __ / __ + ___ // Complete the Macro definition

int main() {

int i,j;

scanf("%d", &i);

scanf("%d", &j);

printf("%d ",func(i + j, 3));

______ func // Fill the blank

printf("%d\n",func(i + j, 3));

}

int func(int x, int y) {

return x / y + x;

}

a. Input: -6, 3 Output: -8 -4

b. Input: 11, 15 Output: 42 34

c. Input: -4, -8 Output: -18 -16

Answer: #define func(x, y) x / y + x#undef func

Question 3

• Fill up the blanks with appropriate keyword to get the desired output according to thetest cases. Marks 2

#include <iostream>

using namespace std;

______ int SQUARE(int x) { ______ x * x; }

int main() {

int a , b, c;

cin >> a ;

b = SQUARE(a);

cout << "Square = " << b << ", ";

c = SQUARE(++a);

cout << "++ Square = " << c ;

return 0;

}

a. Input: 4 Output:Square = 16, ++ Square = 25

b. Input: -8 Output: Square = 64, ++ Square = 49

c. Input: -10.5 Output: Square = 100, ++ Square = 81

Answer: inline // return

8

Page 15: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 4

• Fill up the blanks to get the desired output according to the test cases in the perspectiveof dynamic memory allocation and de-allocation. Marks 2

#include <iostream>

using namespace std;

int main(){

int d;

____________________ // use operator new to allocate memory to variable ’p’

cin>> d ;

*p = d ;

cout << ++*p + d++ * (++*p + *p);

__________delete(___); // Fill the blank

return 0;

}

a. Input: -7 Output: 64

b. Input: 11.5 Output: 298

c. Input: 15 Output: 526

Answer: int *p = (int *)operator new(sizeof(int));// operator // p

Question 5

• Overload the function ’Area’, by writing the appropriate definition in place of blank toget the desired output according to the test cases. Marks 2

include<iostream>

using namespace std;

___________________________ // Overload the function ’Area’

___________________________ // Write the definition of ’Area’

int main() {

int x ,y, t;

double z, u, f;

cin >> x >> y ;

cin >> z >> u ;

t = Area(x);

cout << "Area = " << t << " ";

f = Area(z);

cout << "Area = " << f << " ";

f = Area(z,u);

cout << "Area = " << f ;

return 0;

}

a. Input: 8, 7, 9, 10 Output: Area =80 Area =90 Area =90

b. Input: 8, 9, 8.5, 9.5 Output: Area =80 Area =80 Area =80.75

9

Page 16: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

c. Input: 7, 8, 7, 9.6 Output: Area =70 Area =70 Area =67.2

Answer: int Area(int a, int b = 10) { return (a * b); } //double Area(double c, double d) { return (c * d); }

10

Page 17: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming in C++: Assignment Week 3

Total Marks : 20

Partha Pratim DasDepartment of Computer Science and Engineering

Indian Institute of TechnologyKharagpur – 721302

[email protected]

March 17, 2017

Question 1

What is the output of the sizeof operator? (Assume sizeof(int) = 4) Mark 1

#include<iostream>

using namespace std;

class Test {

int x_;

unsigned char str[8];

};

int main() {

Test t;

cout << sizeof(t) << " ";

}

a) 10

b) 12

c) Cannot be determined before memory allocation

d) Default size: 0

Answer: b)Explanation: Sum of memory requirements for all the data members

Question 2

What will be the output of the program? Mark 1

#include<iostream>

using namespace std;

class Test {

int x_;

int y_;

};

int main() {

1

Page 18: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Test.x_ = 1;

cout << Test.x_;

}

a) 1

b) Default value

c) Compilation Error: Cannot modify read only variable

d) 0

Answer: c)Explanation: Object not created, Invalid access of data member x with class name.

Question 3

What is the output of the program? Mark 1

#include<iostream>

using namespace std;

class Test {

int x_;

int y_;

void func() {

x_ = y_ = 1;

cout << x_ << " " << y_;

}

};

int main() {

Test t;

t.func();

}

a) 1 1

b) x = 1 y = 1

c) Compilation error: Cannot access private member

d) None of the above

Answer: c)Explanation: func() is a private member function, hence cannot be accessed outside class

Question 4

Consider Object S of class Sample. What is the type of this pointer? Mark 1

a) S * const this

b) S const * const this

c) S * this

d) const S const * this

Answer: a)Explanation: As per syntax, refer slides

2

Page 19: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 5

Which functions will change the state of the object of class Test? Mark 1

#include<iostream>

using namespace std;

class Test {

int x_;

int y_;

public:

void print() { cout << x_ << " " << y_; }

void setx(int m_) {

x_ = m_;

}

void sety(int n_) {

y_ = n_;

}

int calc1(int n_) {

int t;

t = n_ * x_ * y_;

x_ = n_ * 3;

return t;

}

void calc2(int n_) {

int t;

t = n_ * x_;

cout << t;

}

};

a) Only setx() and sety()

b) Only print()

c) setx(), sety(), calc1(), calc2()

d) setx(), sety(), calc1()

Answer: d)Explanation: The state of a class is the collection of values of all the member variables of aclass at a point. setx(), calc1() and sety() modifies the values of the member variables of theclass. Refer slides

3

Page 20: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 6

Consider the program below. An implementation of class Test is shown along with an appli-cation section using object of Test. Mark 1

PROGRAM 1 // Implementation of class Test

#include<iostream>

using namespace std;

class Test {

int x_;

int y_;

public:

void print() { cout << x_ << " " << y_; }

void setx(int m_) { x_ = m_;}

void sety(int n_) { y_ = n_;}

int calc1(int n_) {

int t;

t = n_ * x_ * y_;

x_ = n_ * 3;

return t;

}

void calc2(int n_) {

int t;

t = n_ * x_;

cout << t;

}

};

int main() { // Application section

Test t;

t.setx(5);

}

Now if we make some changes to the class as given below.

PROGRAM 2 // Updated Implementation of class Test

#include<iostream>

using namespace std;

class Test {

int x_[2];

int y_;

public:

void print() { cout << x_[0] << " " << y_; }

void setx(int m_) { x_[0] = m_; x_[1] = 0; }

void sety(int n_) { y_ = n_; }

int calc1(int n_) {

int t;

t = n_ * x_[0] * y_;

x_[0] = n_ * 3;

return t;

}

void calc2(int n_) {

int t;

4

Page 21: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

t = n_ * x_[0];

cout << t;

}

};

What changes would be required in the application section?

a) Create different objects

b) No change required

c) Pass different parameters to the setx() and sety() function

d) Pass different parameters to the calc1() and calc2() function

Answer: b)Explanation: The implementation of the private members of the class is changed, but itdid not change the interface of the class. The implementation is not visible outside the class.

5

Page 22: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 7

Consider class Test. What are the permissible signatures of a Copy Constructor? Marks 1

a) Test(const Test t), Test(Test t);

b) Test(const Test* t), Test(Test* t);

c) Test(Test& t), Test(Test* t);

d) Test(const Test& t), Test(Test& t);

Answer: d)Explanation: As per syntax, refer slides

Question 8

What will be the output of the following program? Mark 1

#include<iostream>

using namespace std;

class Sample{

int x;

int y;

public:

void setx(int n) { x = n; }

void sety(int m) { y = m; }

int gety() { return y;}

int getx() { return x; }

};

class Experiment {

public:

display(Sample t) { t.setx(8);

cout << t.x;

}

};

int main() {

Sample t;

Experiment e;

e.display(t);

}

a) 8

b) Compilation Error: setx() method of class Sample cannot be accessed in class Experiment

c) 8 8

d) Compilation Error: Variable x is private in Sample, cannot be accessed in class Experiment

Answer: d)Explanation: Private data members of a class cannot be accessed by other classes or globalfunctions.

6

Page 23: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 9

What will be the output of the program? Mark 1

#include <iostream>

#include <string>

using namespace std;

class Sample {

string name;

public:

Sample(string s): name(s) {

cout << name << " Created" << " ";

}

~Sample() {

cout << name << " Destroyed" << " ";

}

};

int main() {

Sample * s1 = new Sample("s1");

Sample * s2 = new Sample("s2");

return 0;

}

a) s1 Created s2 Created s2 Destroyed s1 Destroyed

b) s1 Created s2 Created s1 Destroyed s2 Destroyed

c) s2 Created s1 Created s2 Destroyed s1 Destroyed

d) s1 Created s2 Created

Answer: d)Explanation: s1 and s2 created by new operator, delete operator should be used to call thedestructor, as in this case the destructor is not called implicitly.

7

Page 24: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 10

Identify the correct statement(s). Mark 1

#include <iostream>

#include <string>

using namespace std;

class Employee {

public:

string name, addr;

const int id;

string dob;

Employee(string nm, string ad, string dt, int d):

name(nm), addr(ad), dob(dt), id(d) { }

void print_attr_dob() const {

this->dob = "12-02-1986";

cout << this->dob ;

}

void print_attr_name() {

cout << this->name ;

}

};

static int count = 1;

int main() {

const Employee e1("Ram", "Kolkata", "12-02-02", count++);

e1.print_attr_dob();

e1.print_attr_name();

return 0;

}

a) Compilation Error: print attr dob() cannot assign value to dob

b) Compilation Error: cannot convert ’this’ pointer from ’const Employee’ to ’Employee &’for print attr dob()

c) Compilation Error: cannot convert ’this’ pointer from ’const Employee’ to ’Employee &’for print attr name()

d) B and C

Answer: a), c)Explanation: A constant object cannot invoke a non constant member function. Constantdata member, id cannot be modified in the member function print attr dob

8

Page 25: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

I Programming Assignment

Question 1

Write the required syntax for the constructor and copy constructor to get the output as perthe test cases. Marks 2

#include <iostream>

using namespace std;

class Complex {

public: double *re, *im;

Complex(__________________) {

re = new double(r);

im = new double(m);

}

Complex(________________ ){

re = new double; im = new double;

*re = *t.re; *im= *t.im;

}

~Complex(){

delete re, im;

}

};

int main() {

double x, y, z;

cin >> x >> y >> z;

Complex n1(x,y);

cout << *n1.re << "+" << *n1.im << "i ";

Complex n2 = n1;

cout << *n2.re << "+" << *n2.im << "i ";

*n1.im = z;

cout << *n2.re << "+" << *n2.im << "i ";

cout << *n1.re << "+" << *n1.im << "i ";

return 0;

}

Answer: double r, double m // const Complex &tExplanation: The first parameters are for the constructor, the second arguments are forthe copy constructor which passes a constant Complex object, so that the value of the datamembers are not changed.

a. Input: 4, 5, 6 Output: 4+5i 4+5i 4+5i 4+6i

b. Input: 4, 5, 5 Output: 4+5i 4+5i 4+5i 4+5i

c. Input: 6 7 8 Output: 6+7i 6+7i 6+7i 6+8i

9

Page 26: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 2

Write the required syntax for the constructor to get the output as per the test cases. Marks 2

#include <iostream>

using namespace std;

class Sample {

public:

int data_, graph_;

char data_or_graph_;

Sample(___________________________________): ____________________________{

cout << data_ << " " << data_or_graph_<< " " << graph_ <<" "<<endl;

}

};

int main() {

int x; char y;

cin>>x >> y ;

Sample s1(x, y), s2(--x, ++y), s3;

return 0;

}

Answer: int x = 5, char z = ’B’, int y = 6 // data (x), data or graph (z), graph (y)Explanation: : Evaluation of S3 gives 5, B, 6, hence we get the default values. The rest ofthe syntax is as per slides.

a. Input: 4 D Output: 4 D 6 3 E 6 5 B 6

b. Input: 3 E Output: 3 E 6 2 F 6 5 B 6

Question 3

Write the required constructor and function definitions of the class Stack to get the output asper the test cases. Marks 2

#include <iostream>

#include <vector>

#include<string.h>

using namespace std;

class Stack {

_____________________: // Write the appropriate Access specifier

vector<char> data_; int top_;

public:

int empty() { ________________________; }

void push(char x) { _________________________;}

void pop() { _______________; }

char top() { __________________; }

};

int main() {

Stack s;

10

Page 27: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

char str[20];

cin >> str;

s.data_.resize(100);

s.top_ = -1;

for(int i = 0; i < strlen(str) - 1; ++i)

s.push(str[i]);

while (!s.empty()) {

cout << s.top(); s.pop();

}

return 0;

}

Answer: public // return (top == -1) // data [++top ] = x // –top // return data [top ]Explanation: Access specifier will be public as the data members are accessed outside class.The functions are standard stack functions, refer slides

a. Input: ABCDE ; Output: DCBA

b. Input: MADAM ; Output: ADAM

c. Input: APA ; Output: PA

Question 4

Look into the main() function write the proper constructor by filling the blank to get theoutput as per the test cases. Marks 2

#include <iostream>

#include <cmath>

using namespace std;

class Complex { private: double re_, im_;

public:

Complex(__________________________________): re_(re), im_(im)

{ cout << "Ctor: (" << re_ << ", " << im_ << ")" << endl; }

~Complex()

{ cout << "Dtor: (" << re_ << ", " << im_ << ")" << endl; }

void print() { cout << "|" << re_ << "+j" << im_ << "| " << endl; }

};

Complex c(7.2, 4);

int main() {

cout << "main" << endl;

double x, y;

cin >> x;

cin >> y;

Complex d(x); Complex e;

c.print();

d.print();

return 0;

}

11

Page 28: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Answer: double re = 0.0, double im = 0.0Explanation: The default value of the double parameters of the constructor Complex willbe 0.0,0.0 as it is evaluated so in case of Complex e call

a. Input: 4.5, 5.5 ;

Output:

Ctor: (7.2, 4)

main

Ctor: (4.5, 0)

Ctor: (0, 0)

|7.2+j4|

|4.5+j0|

Dtor: (0, 0)

Dtor: (4.5, 0)

Dtor: (7.2, 4)

b. Input: 5.6, 4;

Output:

Ctor: (7.2, 4)

main

Ctor: (5.6, 0)

Ctor: (0, 0)

|7.2+j4|

|5.6+j0|

Dtor: (0, 0)

Dtor: (5.6, 0)

Dtor: (7.2, 4)

c. Input: 0, 0 ;

Output:

Ctor: (7.2, 4)

main

Ctor: (0, 0)

Ctor: (0, 0)

|7.2+j4|

|0+j0|

Dtor: (0, 0)

Dtor: (0, 0)

Dtor: (7.2, 4)

Question 5

The program indicates the concept of mutability . Fill the blank with appropriate kew wordto satisfy the given test casesMarks 2

#include <iostream>

using namespace std;

class MyClass {

int mem_;

12

Page 29: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

_____________ int x_;

public:

MyClass(int m, int mm) : mem_(m), x_(mm) {}

int getMem() const { return mem_; }

void setMem(int i) { mem_ = i; }

int getxMem() ________ { return x_; }

void setxMem(int i) __________ { x_ = i; }

};

int main() {

int x, y,z;

cin >> x;

cin >> y;

cin >> z;

const MyClass myConstObj(x, y);

myConstObj.setxMem(z);

cout << myConstObj.getxMem() << endl;

return 0;

}

Answer: mutable // const // constExplanation: A mutable data member x only can be accessed and updated in a constmember function.

a. Input: 4, 5, 6 ; Output: 6

b. Input: 1, 1, 0 ; Output: 0

c. Input: 70, 89, 70 ; Output: 70

13

Page 30: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming in C++: Assignment Week 5

Total Marks : 20

Partha Pratim DasDepartment of Computer Science and Engineering

Indian Institute of TechnologyKharagpur – 721302

[email protected]

April 3, 2017

Question 1

Look at the code snippet bellow. Find out the sequence in which the function area() associatedwith Rectangle & Triangle class will be called. Mark 1

class Polygon {

protected:

int width, height;

public:

void set_values (int a, int b)

{ width=a; height=b;}

};

class Rectangle: public Polygon {

public:

int area ()

{ /* Function definition */ } // Area-1

};

class Triangle: public Polygon {

public:

int area ()

{ /* Function definition */ } // Area-2

};

int main () {

Rectangle rect;

Triangle trgl;

rect.set_values (6,5);

trgl.set_values (6,5);

rect.area() ;

trgl.area() ;

return 0;

}

a) Area-2, Area-1

1

Page 31: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

b) Area-1, Area-1

c) Area-1, Area-2

d) Area-2, Area-2

Answer: c)Solution: By the order of calling functions

Question 2

Which of the following function will be invoked by d.func(1)? Mark 1

#include <iostream>

using namespace std;

class Base { public:

int var_;

void func(int){}

};

class Derived: public Base { public:

int varD_;

void func(int){}

};

int main() {

Derived d;

d.func(1);

return 0;

}

a) Base::func(int)

b) Derived::func(int)

c) Compilation Error

d) Base::func(int) then Derived::func(int)

Answer: b) Solution: d is a Derived class object

Question 3

Find out the out put of the following Program.

#include <iostream>

using namespace std;

class Animal {

public:

int legs = 4;

};

2

Page 32: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

class Dog : public Animal {

public:

int tail = 1;

};

int main() {

Dog d;

cout << d.legs;

cout << d.tail;

return 0;

}

a) 1 4

b) Compilation Error: Can’t access Dog::tail

c) Compilation Error: Can’t access Animal::legs

d) 4 1

Answer: d) Solution: legs is inherited from the Animal class

Question 4

Look at the code snippet bellow. Find out, which of the show() function will be called bycalling b->show(). Mark 1

class Base {

public:

void show() { }

};

class Derived :public Base {

public:

void show() { }

};

int main() {

Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

b->show();

return 0;

}

a) show() of Base class only

b) show() of Derived Class only

c) Both but, show() of Derived Class first then Base class

d) Both but, show() of Base class first then Derived Class

Answer: a)Solution: Early Binding Occurs

3

Page 33: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 5

Look at the code snippet bellow. Find out, which of the show() function will be called bycalling b->show() ? Mark 1

class Base {

public:

virtual void show() { cout << "Base class"; }

};

class Derived :public Base {

public:

void show() { cout << "Derived Class"; }

};

int main() {

Base* b; //Base class pointer

Derived d; //Derived class object

b = &d;

b->show();

return 0;

}

a) show() of Base class only

b) show() of Derived Class only

c) Both but, show() of Derived Class first then Base class

d) Both but, show() of Base class first then Derived Class

Answer: b)Solution: Late Binding Occurs as show() is virtual

Question 6

What will be the output of the following Code snippet? Mark 1

class B {

public:

B() { cout << "B "; }

~B() { cout << "~B "; }

};

class C : public B {

public:

C() { cout << "C "; }

~C() { cout << "~C "; }

};

class D : private C {

B data_;

public:

D() { cout << "D " << endl; }

~D() { cout << "~D "; }

};

int main() {

4

Page 34: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

{D d; }

return 0;

}

a) B C B C D ˜D ˜C ˜B ˜C ˜B

b) B C B D ˜D ˜B ˜C ˜B

c) B D B C ˜C ˜B ˜D ˜B

d) B C B C ˜C ˜B ˜C ˜B

Answer: b) Solution: In Inheritance, destructors are executed in reverse order of constructorexecution

Question 7

Identify the correct statements? Mark 1

class base {

public:

int x;

protected:

int y;

private:

int z;

};

class publicDerived: public base

{

//1. x is public

//2. y is protected

//3. z is accessible from publicDerived

};

class protectedDerived: protected base

{

//4. x is public

//5. y is protected

//6. z is not accessible from protectedDerived

};

class privateDerived: private base

{

//7. x is private

//8. y is protected

//9. z is not accessible from privateDerived

}

a) 1, 3 & 5

b) 2, 4 & 6

c) 6, 8 & 9

5

Page 35: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

d) 2, 6 & 7

Answer: d)Solution: By definition of public, private and protected inheritance

Question 8

Which lines of the following program will not compile? Mark 1

#include <iostream> // ---1

using namespace std; // ---2

class Base { protected: // ---3

int var_; // ---4

public: // ---5

Base():var_(0){} // ---6

}; // ---7

class Derived: public Base { public: // ---8

int varD_; // ---9

void print () { cout << var_; } // ---10

}; // ---11

int main() { // ---12

Derived d; // ---13

d.var_ = 1; // ---14

d.varD_ = 1; // ---15

cout << d.var_ <<" " << d.varD_; // ---16

return 0; // ---17

} // ---18

a) 6, 10, 14, 15

b) 6, 15

c) 4, 14, 16

d) 6, 14, 16

Answer: c)Solution: Can’t access protected data member

Question 9

Consider the following code snippet. Which of the following statement is true, when t.getX()

is called ? Mark 1

class Test {

int x;

public:

Test(int a):x(a){}

6

Page 36: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

virtual void show() = 0;

int getX() { /* Function definition */ }

};

int main(void){

Test t(5);

t.getX();

return 0;

}

a) Return an integer value

b) Compiler Error: cannot declare variable ’t’ to be of abstract

c) Compiler Error: cannot access private variable x

d) b & c

Answer: b)Solution: Can’t create object of a abstract class

Question 10

What will be the output of the following program? Marks 1

#include<iostream>

using namespace std;

class Shape {

public:

int x, y;

Shape(int a = 0, int b = 0): x(a), y(b) {}

void draw()

{ cout << x << " " << y << " "; }

};

class Rectangle : public Shape {

public:

int w, h;

Rectangle(int a = 5, int b = 6): w(a), h(b), Shape(7, 8) {}

void draw()

{ Shape::draw(); cout << w << " " << h ; }

};

int main() {

Rectangle *r = new Rectangle(1,2);

r-> draw();

return 0;

}

7

Page 37: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

a) 0 0 1 2

b) 7 8 1 2

c) 7 8 5 6

d) 0 0 5 6

Answer: b)Solution: Shape(7, 8) initialize x and y as 7 and 8. Rectangle(1,2) initialize w and h as 1 and2.

Programming Questions

Question 1

Consider the skeletal code given below and Fill the blank or remove the blank in the headerof the functions to match the output for the given input. Marks 2

#include <iostream>

using namespace std;

class Shape {

protected:

float l;

public:

void getData(){ cin >> l; }

________ float calculateArea(){

return l*l;

}

};

class Circle : public Shape {

public:

_________ float calculateArea(){

return 3.14*l*l;

}

};

int main()

{

Shape * b; //Base class pointer

Circle d; //Derived class object

b = &d;

b->getData();

cout << b->calculateArea();

return 0;

}

8

Page 38: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

a. Input: 5Output: 78.5

b. Input: 28Output: 2461.76

c. Input: 45Output: 6358.5

Answer: virtualSolution: Derived class function is called using a base class pointer. virtual function is resolvedlate, at runtime.

Question 2

Consider the skeletal code given below.Fill up the blank by following the instructions associatedwith each blank and complete the code, So that the output of the test cases would match Marks:3

#include <iostream>

using namespace std;

class Area {

public:

int calc(int l, int b) { return l*b; }

};

class Perimeter {

public:

int calc(int l, int b) { return 2 * (l + b); }

};

/* Rectangle class is derived from classes Area and Perimeter. */

class Rectangle: ________________ { // Inherit the required base classes

private:

int length, breadth;

public:

Rectangle(int l, int b) : length(l), breadth(b) {}

int area_calc() {

/* Calls calc() of class Area and returns it. */

________________

}

int peri_calc() {

/* Calls calc() function of class Perimeter and returns it. */

________________

}

};

int main() {

9

Page 39: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

int l, b;

cin >> l >> b;

Rectangle r(l, b);

cout << r.area_calc() << endl;

cout << r.peri_calc() ;

return 0;

}

10

Page 40: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Public-1

1. Input:

4

6

Output:

24

20

2. Input:

2

3

Output:

6

10

3. Input:

65

34

Output:

2210

198

Answer

public Area, public Perimeter

return Area::calc(length, breadth);

return Perimeter::calc(length, breadth);

Solution: Multiple Inheritance

Question 3

Consider the skeletal code given below. Marks: 3Fill up the blanks by following the instructions associated with it and complete the code, sothat the output of the test cases should match. Do not change any other part of the code.

#include<iostream>

using namespace std;

class Polygon {

protected: int width, height;

public:

Polygon(int a, int b) : width(a), height(b) {}

// Declare the area function here

_________________________________

void printarea() { cout << this->area() << ":"; }

};

class Rectangle : public Polygon {

11

Page 41: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

public:

Rectangle(int a, int b) : Polygon(a, b) {}

int area() { return width*height; }

};

class Triangle : public Polygon {

public:

Triangle(int a, int b) : Polygon(a, b) {}

int area() { return width*height / 2; }

};

int main() {

int h, w;

cin >> h >> w;

// Declare ppoly1 and ppoly2 as "pointer to Polygon" and dynamically allocate

// a Rectangle and a Triangle objects respectively held by these pointers

_________________________________ // Rectangle object of h and w

_________________________________ // Triangle object of h and w

ppoly1->printarea(); // For Rectangle object

ppoly2->printarea(); // For Triangle object

delete ppoly1;

delete ppoly2;

return 0;

}

12

Page 42: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Public 1

Input:

4

5

Output: 20:10:

Public 2

Input:

30

15

Output: 450:225:

Private

Input:

8

6

Output: 48:24:

Answer

virtual int area(void) = 0; or virtual int area(void) { return 0; }

Polygon * ppoly1 = new Rectangle(h, w);

Polygon * ppoly2 = new Triangle(h, w);

Solution: Late binding occurs

Question 4

Fill the blank by defining the proper constructor where name of the parameter should be nc

Marks 2

#include <iostream>

using namespace std;

class Engine {

public:

Engine(int nc) :cylinder(nc){}

void start() {

cout << getCylinder() << " cylinder engine started" ;

};

int getCylinder() {

return cylinder;

}

private:

int cylinder;

};

13

Page 43: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

class Car : private Engine

{ // Car has-a Engine

public:

//Define the constructor to run the code. Name of the parameter should be ’nc’

________________________

void start() {

cout << "car with " << Engine::getCylinder() <<

" cylinder engine started" << endl;

________________________// Call the start function of Engine

}

};

int main()

{

int cylin;

cin >> cylin;

Car c(cylin);

c.start();

return 0;

}

a. Input: 8Output: car with 8 cylinder engine started8 cylinder engine started

b. Input:10Output: car with 10 cylinder engine started10 cylinder engine started

c. Input:4Output: car with 4 cylinder engine started4 cylinder engine started

Answer

Car(int nc) : Engine(nc) { }

Engine::start();

Solution: Use of Private Inheritance

14

Page 44: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming in C++: Assignment Week 6

Total Marks : 20

Partha Pratim DasDepartment of Computer Science and Engineering

Indian Institute of TechnologyKharagpur – 721302

[email protected]

April 6, 2017

Question 1

Look at the code snippet below and find out What will be the correct syntax for up-casting ?Mark 1

class Parent {

public:

void sleep() {}

};

class Child: public Parent {

public:

void gotoSchool(){}

};

int main(){

Parent parent;

Child child;

return 0;

}

a) Child *pChild = (Child *) &parent;

b) Child *pChild = &parent;

c) Parent *pParent = &child;

d) Parent *pParent = (Parent *) &child;

Answer: c)Explanation: By definition of upcasting (Base Class to Derive class)

Question 2

What will be the correct syntax for down-casting in above code (QS No-1)?

a) Child *pChild = (Child *) &parent;

1

Page 45: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

b) Child *pChild = &parent;

c) Parent *pParent = &child;

d) Parent *pParent = (Parent *) &child;

Answer: a)Explanation: By definition of downcasting (Derive class to Base Class)

Question 3

Look at the following code snippet and Find out the static bindingfrom the option below Mark 1

class Base {

public:

void first() {}

virtual void second() {}

};

class Derived : public Base {

public:

void f() {}

virtual void g() {}

};

int main() {

Base b;

Derived d;

Base *pb = &b;

Base *pd = &d;

Base &rb = b;

Base &rd = d;

pb->first(); // 1

pd->first(); // 2

rb.first(); // 3

rd.first(); // 4

pb->second(); // 5

pd->second(); // 6

rb.second(); // 7

rd.second(); // 8

}

a) 1 2 5 6

b) 3 4 7 8

c) 1 2 3 4

d) 5 6 7 8

Answer: c)Explanation:Direct function calls can be resolved using a process known as early binding orstatic binding.

2

Page 46: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 4

Consider the code of question 3 and find out the dynamic binding from the option below

a) 1 2 5 6

b) 3 4 7 8

c) 1 2 3 4

d) 5 6 7 8

Answer: d)Explanation: Virtual functions get resolve at run time.

Question 5

Consider the following code snippet. Find out the correct sequence of function calling. Marks:1

class X {

public:

virtual void f() { } //1

void g() { } //2

};

class Y : public X {

public:

void f() { } //3

virtual void g() { }//4

};

int main() {

X x; Y y;

X& rx = y;

x.f();

x.g();

rx.f();

rx.g();

return 0;

}

a) 1 2 3 2

b) 1 2 3 4

c) 3 2 1 2

d) 3 2 1 4

Answer: a)Explanation: rx.f() call Y::f as f is virtual in the base class.

3

Page 47: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 6

What will be the output/Error of the bellow code snippet?

class Base {

public:

virtual void show() = 0;

};

class Derived : public Base{

public:

void show(){ cout << "Virtual Function";}

};

int main()

{

Base obj;

Base *b;

Derived d;

b = &d;

b->show();

}

a) Compile Time Error: cannot create object

b) Compile Time Error: cannot inherit Base class

c) Compile Time Error: cannot overload show

d) Virtual Function

Answer: a)Explanation: Can’t create of object of a abstract base class

Question 7

What will be the output of the following program? Marks: 1

#include<iostream>

using namespace std;

class base {

public:

base() { cout << "c"; }

virtual ~base() { cout << "~c"; }

};

class derived : public base {

public:

derived() { cout << "d"; }

~derived() { cout << "~d"; }

};

int main(void)

4

Page 48: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

{

{

derived *d = new derived();

base *b = d;

delete b;

}

return 0;

}

a) d c ∼c ∼d

b) d c ∼d ∼c

c) c d ∼c ∼d

d) c d ∼d ∼c

Answer: d)Explanation: Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined

Question 8

Find the abstract classes from the bellow code?

class Instrument {

public:

virtual void play() = 0

{ cout << "Instrument: Init Brush" << endl; }

};

class Wind : public Instrument {

void play() { cout << "Polygon: play" << endl; }

};

class Percussion : public Instrument {

};

class Woodwind : public Wind {

public:

void play() { cout << "Woodwind: play" << endl; }

};

class Brass : public Wind {

public:

void play() { cout << "Brass: play" << endl; }

};

class Drum : public Percussion {

public:

void play() { cout << "Drum: play" << endl; }

};

class Tambourine : public Percussion {

public:

void play() { cout << "Tambourine: play" << endl; }

};

a) Woodwind, Brass

5

Page 49: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

b) Instrument, Percussion

c) Instrument, Tambourine

d) Percussion, Drum

Answer: b)Explanation: pure virtual function play() is there in Instrument and Percussion class

Question 9

What will be the output of the following Code Snippet ? Marks: 1

class Instrument {

public:

virtual void play()

{ cout << "1 "; }

};

class Wind : public Instrument {

void draw() { Instrument::play(); cout << "2 "; }

};

class Percussion : public Instrument {

};

class Woodwind : public Wind {

public:

void play() { Instrument::play(); cout << "3 "; }

};

class Brass : public Wind {

public:

void play() { Instrument::play(); cout << "4 "; }

};

class Drum : public Percussion {

public:

void play() { Instrument::play(); cout << "5 "; }

};

class Tambourine : public Percussion {

public:

void play() { Instrument::play(); cout << "6 "; }

};

int main() {

Instrument *arr[] = { new Woodwind, new Brass, new Drum, new Tambourine };

for (int i = 0; i < sizeof(arr) / sizeof(Instrument *); ++i) arr[i]->play();

return 0;

}

a) 3 4 5 6

b) 1 3 1 4 1 5 1 6

c) 1 3 4 5 6

d) Compile Time Error: Virtual function can’t have body

Answer: b)Explanation:: Virtual function may have body

6

Page 50: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 10

What will be the output of the following code snippet? Marks: 1

class A { public: int i; };

class B { public: double d; };

A a;

B b;

a.i = 8;

b.d = 9.7;

A *p = &a;

B *q = &b;

p = (A*)&b;

q = (B*)&a;

cout << p->i << endl;

cout << q->d << endl;

a) 9.7 8

b) 8 9.7

c) GARBAGE

d) Compile Time Error: casting is not possible

Answer: c)

Explanation: Force casting between unrelated classes

Programming Questions

Question 1

Problem Statement: Marks: 2Consider the following code. Modify the code in editable section to match the public test cases.

#include <iostream>

using namespace std;

class B {

public:

B() { cout << "98 "; } // don’t modify the "cout"

~B() { cout << "56 "; } // Don’t Edit/Modify the "cout"

};

class D : public B {

7

Page 51: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

int n;

public:

D(int p):n(p) { cout << n << " "; }

~D() { cout << n*2 << " "; }

};

int main() {

int n ; cin >> n ;

B *basePtr = new D(n);

delete basePtr;

return 0;

}

//---------------------------------------------------------------------

Public-1

Input:

2

Output:

98 2 4 56

Public-2

Input:

8

Output:

98 8 16 56

Private

Input:

3

Output:

98 3 6 56

Answer: virtual

Question 2

Consider the skeletal code below. When the program is executed, the member functions(excluding the constructors and destructors) are called in the order: A::g B::g B::f A::g

B::g C::g C::f. Fill up the blanks to match the test cases. Marks: 2

#include <iostream>

using namespace std;

class A { protected: int ai;

public:

A(int i) : ai(i) {}

_______ void f() = 0; // Fill the blank or Remove blank

_______ void g() // Fill the blank or Remove blank

{ ++ai; }

8

Page 52: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

};

class B : public A { protected: int bi;

public:

B(int i) : A(i), bi(i) {}

_______ void f() // Fill the blank or Remove blank

{ cout << ai << bi; } // DO NOT EDIT THIS LINE

_______ void g() // Fill the blank or Remove blank

{ A::g(); }

};

class C : public B { int ci;

public:

C(int i) : B(i), ci(i) {}

_______ void f() //Fill the blank or Remove blank

{ cout << ai << bi << ci; } // DO NOT EDIT THIS LINE

_______ void g() //Fill the blank or Remove blank

{ B::g(); }

};

int main() {

int x = 3 ;

int y;

cin >> y;

A *p[] = { new B(x), new C(y) };

for(int i = 0; i < sizeof(p) / sizeof(A*); ++i)

{ p[i]->g(); p[i]->f(); }

return 0;

}

Further, the input / output test case is as follows:

Public 1

Input: 2

Output: 43322

Public 2

Input: 23

Output: 43242323

Private

Input: 4

Output: 43544

Answer: virtual // virtual // virtual or blank // virtual or blank // virtual or blank// virtual or blank

Question 3

Consider the following code. write the proper definition of ”getArea()” in the editable sectionso that the test cases would pass . Marks: 2

9

Page 53: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

#include <iostream>

using namespace std;

class Shape {

protected:

int width, height;

public:

// Write the getArea() function here

void setWidth(int w) { width = w; }

void setHeight(int h) { height = h; }

};

class Rectangle : public Shape {

public:

int getArea() { return (width * height); }

};

class Triangle : public Shape {

public:

int getArea() { return (width * height) / 2; }

};

int main(void) {

int x, y;

cin >> y >> x;

Rectangle Rect;

Triangle Tri;

Rect.setWidth(x);

Rect.setHeight(y);

Tri.setWidth(x);

Tri.setHeight(y);

Shape *shape[] = { &Rect, &Tri, 0 };

Shape **pShape = &shape[0];

while (*pShape)

cout << (*pShape++)->getArea() << " ";

return 0;

}

10

Page 54: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Public-1

Input:

3

7

Output:

21 10

Public-2

Input:

35

23

Output:

805 402

Private

Input:

6

9

Output:

54 27

Answer:

virtual int getArea() = 0;

Question 4

Consider the following code. Fill up the code in editable section to congratulate the Managerand the Clerk, so that outputs will be matched as given in the test cases. Marks: 2

#include <iostream>

#include <string>

using namespace std;

class Employee {

public:

string Name;

double salary;

Employee(string fName, double sal) : Name(fName), salary(sal) {}

void show() {

cout << Name << " " << salary;

}

void addBonus(double bonus) {

salary += bonus;

}

};

class Manager :public Employee {

public:

Manager(string fName, double sal) : Employee(fName, sal) {}

};

11

Page 55: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

class Clerk :public Employee {

public:

Clerk(string fName, double sal) : Employee(fName, sal) {}

};

void congratulate(Employee* emp) {

emp->addBonus(200);

emp->show();

cout << " ";

};

int main() {

Employee* emp;

int sal_m, sal_c;

cin >> sal_c >> sal_m;

Manager m1("Steve", sal_m);

Clerk c1("Kevin", sal_c);

// Call the proper function to congratulate the Manager and the Clerk

return 0;

}

Public-1

Input:

2000

1000

Output:

Kevin 2200 Steve 1200

Public-2

Input:

4000

1000

Output:

Kevin 4200 Steve 1200

Private

Input:

6200

2500

Output:

Kevin 6400 Steve 2700

Answer:

congratulate(&c1);

congratulate(&m1);

12

Page 56: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 5

#include <iostream>

using namespace std;

class Shape {

protected:

int width, height;

public:

Shape(int a = 0, int b = 0) {

width = a;

height = b;

}

// Fill the blank to run the code

__________ void area() {

cout << "Parent class area :" << endl;

}

};

class Rectangle : public Shape {

public:

Rectangle(int a = 0, int b = 0) :Shape(a, b) { }

void area() {

cout << (width * height) << " ";

}

};

class Triangle : public Shape{

public:

Triangle(int a = 0, int b = 0) :Shape(a, b) { }

void area() {

cout << (width * height / 2);

}

};

// Main function for the program

int main() {

int a, b;

cin >> a;

cin >> b;

Shape *shape;

Rectangle rec(a, b);

Triangle tri(a, b);

// Write the code to call rectangle area.

_____________________________

shape->area();

// Write the code to call triangle area.

_____________________________

13

Page 57: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

shape->area();

return 0;

}

Public-1

Input:

10 5

Output:

50 25

Public-2

Input:

10 25

Output:

250 125

Private

Input:

60 30

Output:

1800 900

Answer:

virtual

shape = &rec;

shape = &tri;

14

Page 58: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming in C++: Assignment Week 7

Total Marks : 20

Partha Pratim DasDepartment of Computer Science and Engineering

Indian Institute of TechnologyKharagpur – 721302

[email protected]

April 5, 2017

Question 1

Find out the output of the following program? Marks: 1

#include <iostream>

using namespace std;

int fun(int* ptr){

return (*ptr + 10);

}

void fun(int& ptr){

ptr = 100;

}

int main(void){

const int val = 10;

const int *ptr = &val;

int *ptr1 = const_cast <int *>(ptr);

*ptr1 = fun(ptr1);

fun(*ptr1);

cout << *ptr;

return 0;

}

a) 10

b) 100

c) 20

d) Compilation error

Answer: b)Solution: Function fun() expects a pointer to an int, not a const int. The statement

int *ptr1 = const_cast <int *>(ptr)}

returns a pointer ptr1 that refers to a without the const qualification of val.

1

Page 59: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 2

What will be the output of the following program? Marks: 1

#include<iostream>

using namespace std;

class Person {

public:

Person(int x) { cout << 2 * x << " "; }

Person() { cout << 3 << " "; }

};

class Faculty : virtual public Person {

public:

Faculty(int x) :Person(x) {

cout << 3 * x << " ";

}

};

class Student : virtual public Person {

public:

Student(int x) :Person(x) {

cout << 3 * x << " ";

}

};

class TA : public Faculty, public Student {

public:

TA(int x) : Student(x), Faculty(x) {

cout << 5 * x << " ";

}

};

int main() {

TA ta1(30);

}

a) 90 90 150

b) 150 90 90

c) 3 90 90 150

d) 60 90 90 150

Answer: c)Solution: constructor and Destructor of Person will also be called two times when object ta1is constructed and destructed. So object ta1 has two copies of all members of Person, thiscauses ambiguities. The solution to this problem is virtual keyword. We make the classesFaculty and Student as virtual base classes to avoid two copies of Person in TA class.

Question 3

How many virtual table will be set up by the compiler for the following code ? Marks: 1

2

Page 60: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

class Base {

public:

virtual void function1() {};

virtual void function2() {};

};

class D1: public Base

{

public:

virtual void function1() {};

};

class D2: public Base

{

public:

virtual void function2() {};

};

a) 0

b) 1

c) 2

d) 3

Answer: d)Solution: Because there are 3 classes here, the compiler will set up 3 virtual tables: one for

Base, one for D1, and one for D2.

Question 4

For the above code (Question 3) what will be the virtual function table entry for function1 &function2 in class D2? Marks: 1

a) Base::function1() & D2::function2()

b) Base::function1() & D1::function2()

c) D1::function1()only

d) D1::function1() & D2::function2()

Answer: a)Solution: VFT for Class base– Base::fucntion1() & Base::function2()

VFT for Class D1– D1::fucntion1() & Base::function2()VFT for Class D2– Base::fucntion1() & D2::function2()

Question 5

In the above code(Ref:Question 3), in which classes the compiler automatically add a hiddenpointer to the virtual function table?

a) Base, D1, D2

3

Page 61: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

b) Base only

c) D1, D2

d) Base, D1

Answer: a)Solution: Whenever a class defines a virtual function a hidden member variable is added tothe class which points to an array of pointers to (virtual) functions called the Virtual FunctionTable (VFT)

Question 6

Look at the code given below. Identify the statements where correct use of staic cast operatorhas been done. MCQ, Mark 1

#include <iostream>

using namespace std;

int main(){

float f = 12.3;

float* pf = &f;

int n = static_cast<int>(f); // stmt-1

int* pn = static_cast<int*>(pf); // stmt-2

void* pv = static_cast<void*>(pf); // stmt-3

return 0;

}

a) stmt-1, stmt-2

b) stmt-2, stmt-3

c) stmt-1, stmt-3

d) stmt-1, stmt-2, stmt-3

Answer: c)Solution: In stmt-2, types pointed to are unrelated.

Question 7

Fill the blank by an appropriate cast operator given that the output of the program is:FailureSA, Marks: 1

#include <iostream>

using namespace std;

class Base { public: virtual ~Base() {} };

class Derived : public Base { };

int main() {

4

Page 62: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

// Fill the blank by appropriate caste operator

Derived *pd = ___________ <Derived*>(new Base);

cout << (pd ? "Success": "Failure");

return 0;

}

Answer: dynamic cast

Solution: dynamic cast is used to cast a base pointer into a derived pointer. If the basepointer doesn’t point to an object of the type of the derived, it returns NULL pointer.

Question 8

Look at the following code snippet. If typeid(*ap).name() and typeid(ar).name() will be called,then it will refer to which structure/s. Marks: 1

#include <iostream>

#include <typeinfo>

using namespace std;

struct A { virtual ~A() { } };

struct B : A { };

int main() {

B obj;

A* ap = &obj;

A& ar = obj;

return 0;

}

a) struct A struct B

b) struct A struct A

c) struct B struct B

d) struct B struct A

Answer: c)Solution: If the expression points to a base class type, yet the object is actually of a typederived from that base class, a type info reference for the derived class is the result.

Question 9

Consider the following code snippet. What will be output of the code below? Marks: 1

class Base {

protected:

int marker;

public:

Base(int m = 4) : marker(m) {}

5

Page 63: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

virtual ~Base() {};

virtual void Action() { ++marker; }

};

class Derived : public Base {

public:

void Action() {

static_cast<Base>(*this).Action();

marker *= 2;

cout << marker << endl;

}

};

int main() {

Base *p = new Derived;

p->Action();

return 0;

}

a) 8

b) 10

c) 4

d) 32

Answer: a)Solution: static cast<Base>(*this).Action() explicitly call a single-argument construc-tor. Hence, value of marker is becoming 4 again after thestatic cast<Base>(*this).Action() call.

Question 10

static cast can be used for

1. Downcast

2. Upcast

3. Implicit conversions

4. User-defined conversions

Find out the correct statements. Marks: 1

a) 1 2 3

b) 1 3 4

c) 3 4 2

d) 1 2 3 4

Answer: d)Solution: By the definition of static cast

6

Page 64: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming Questions

Question 1

Fill the bank with appropriate casting Marks: 3

#include <iostream>

using namespace std;

class Base {

public:

virtual void DoIt() = 0; // pure virtual

virtual ~Base() {};

};

class Foo : public Base {

public:

virtual void DoIt() { cout << "12,"; };

void FooIt() { cout << "13,"; }

};

class Bar : public Base {

public:

virtual void DoIt() { cout << "14,"; }

void BarIt() { cout << "15:"; }

};

Base* CreateRandom(int x) {

if ((x % 2) == 0)

return new Foo;

else

return new Bar;

}

int main() {

int lim = 0;

cin >> lim;

for (int n = 0; n < lim; ++n) {

Base* base = CreateRandom(n);

base->DoIt();

Bar* bar = __________________(base);

Foo* foo = __________________(base);

if (bar)

bar->BarIt();

if (foo)

foo->FooIt();

}

return 0;

}

7

Page 65: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Public 1

Input: 1

Output: 12,13,

Public 2

Input: 2

Output: 12,13,14,15:

Public 3

Input: 3

Output: 12,13,14,15:12,13,

Private

Input: 4

Output: 12,13,14,15:12,13,14,15:

Answer:

Bar* bar = dynamic_cast<Bar*>(base);

Foo* foo = dynamic_cast<Foo*>(base);

Solution: The casts execute at runtime, and work by querying the object (no need to worryabout how for now), asking it if it the type we’re looking for. If it is, dynamic cast<Type*>

returns a pointer; otherwise it returns NULL.

Question 2

Problem statement: Consider the following program. Fill the blank With proper constructor/ conversion operator for the given casting to match the outputs of test cases. Marks: 2

#include <iostream>

using namespace std;

class A {

int i;

public:

A(int ai) : i(ai) {}

int get() const { return i; }

void update() { ++i; }

};

class B {

int i;

public:

B(int ai) : i(ai) {}

int get() const { return i; }

//------------------------- Template Code (Editable) --------------------

_____________________________

8

Page 66: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

_____________________________

//-------------------------- Suffix Fixed Code --------------------------

void update() { ++i; }

};

int main() {

int i;

cin >> i;

A a(i++);

B b(i);

B &r = static_cast<B>(a);

a.update();

cout << a.get() << ":";

cout << r.get() << ":";

A &s = static_cast<A>(b);

b.update();

cout << b.get() << ":";

cout << s.get() << ":";

return 0;

}

//------------------------------------------------------------------

Public 1

Input:

1

Output: 2:1:3:2:

Public 2

Input:

15

Output: 16:15:17:16:

Private

Input:

5

Output: 6:5:7:6:

Answer:

B(A& a) : i(a.get()) {}

operator A() { return A(i); }

Question 3

Problem Statement: Write the appropriate constructor / operator function in the followingprogram to cast a class A object to a char * object. Marks: 2

9

Page 67: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

//------------------------- Prefixed Fixed Code --------------------------

#include <iostream>

#include <cstring>

using namespace std;

class A {

public: char *str;

A(char *s) : str(s) { }

//-------------------------- Template Code (Editable) ---------------------

// Write the appropriate constructor or conversion operator function

____________________________________

//----------------------- Suffixed Fixed Code -----------------------------

};

int main() {

char input[20];

cin >> input;

A a(input);

// A ==> char *

char *s = static_cast<char*>(a);

strcat(s, "-success");

cout << s;

return 0;

}

//--------------------------------------------------------------------

Public 1

Input: string

Output: string-success

Public 2

Input: what

Output: what-success

Private

Input: My

Output: My-success

Answer:

operator char *()

{ return (str); }

10

Page 68: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 4

Consider the following code snippet and fill the bank with appropriate code. Marks: 3

#include <iostream>

using namespace std;

class student {

private:

int roll;

public:

student(int r) :roll(r) {}

void fun() const {

(_______________(this))->roll = 5;

}

int getRoll() { return roll; }

};

int main(void) {

int old_roll_no = 0;

cin >> old_roll_no;

student s(old_roll_no);

cout << s.getRoll() << " ";

s.fun();

cout << s.getRoll() ;

return 0;

}

Public 1

Input: 3

Output: 3 5

Public 2

Input: 12

Output: 12 5

Private

Input: 1

Output: 1 5

Answer:

(const_cast <student*>(this))->roll = 5;

Solution: const cast can be used to change non-const class members inside a const memberfunction.

11

Page 69: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming in C++: Assignment Week 8

Total Marks : 20

Partha Pratim DasDepartment of Computer Science and Engineering

Indian Institute of TechnologyKharagpur – 721302

[email protected]

April 12, 2017

Question 1

What will be the output of the following program? Marks: 1

int main()

{

try {

throw ’a’;

}

catch (int x) {

cout << "Caught 1 " << x;

}

catch (double x) {

cout << "Caught 2 " << x;

}

catch (string x) {

cout << "Caught 3 " << x;

}

catch (...) {

cout << "Default Exception";

}

return 0;

}

a) Caught 1 a

b) Caught 2 a

c) Caught 3 a

d) Default Exception

Answer: d)Solution: No catch argument type matches the type of the thrown object. If the ellipsis(...) is used as the parameter of catch, then that handler can catch any exception no matterwhat the type of the exception thrown. This can be used as a default handler that catches allexceptions not caught by other handlers.

1

Page 70: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 2

Consider the following code snippet and find appropriate option to fill the blank. Marks: 2

_________________ {

T result;

result = (a>b)? a : b;

return (result);

}

int main () {

int i = 5, j = 6, k;

long l = 10, m = 5, n;

k = GetMax<int>(i,j);

n = GetMax<long>(l,m);

cout << k << endl;

cout << n << endl;

return 0;

}

a) int GetMax (int a, int b)

b) template <class T>T GetMax (T a, T b)

c) template <class T >class GetMax

d) class GetMax

Answer: b)Solution: By the definition of template

Question 3

What will be the output of the following code snippet? Marks: 1

void myFunction(int test) {

try{

if (test)

throw test;

else

throw "Value is zero";

}

catch (int i) {

cout << "CaughtOne " ;

}

catch (const char *str) {

cout << "CaughtString ";

}

}

int main() {

2

Page 71: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

myFunction(1);

myFunction(2);

myFunction(0);

myFunction(3);

return 0;

}

a) CaughtOne CaughtOne CaughtString CaughtString

b) CaughtOne CaughtString CaughtString CaughtOne

c) CaughtOne CaughtOne CaughtOne CaughtOne

d) CaughtOne CaughtOne CaughtString CaughtOne

Answer: d)Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a differentparameter type. Only the handler whose argument type matches the type of the exceptionspecified in the throw statement is executed.

Question 4

What will be the output of the following code snippet? Marks: 1

#include<iostream>

using namespace std;

struct MyException : public exception {

const char * what () const throw () {

return "C++ Exception";

}

};

int main() {

try {

throw MyException();

}catch(MyException& e) {

std::cout << "MyException caught" << std::endl;

std::cout << e.what() << std::endl;

} catch(std::exception& e) {

std::cout << "Exception caught" << std::endl;

std::cout << e.what() << std::endl;

}

}

a) MyException caughtC++ Exception

b) C++ ExceptionMyException caught

c) Exception caughtC++ Exception

3

Page 72: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

d) C++ ExceptionMyException caughtException caught

Answer: a)Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a differentparameter type. Only the handler whose argument type matches the type of the exceptionspecified in the throw statement is executed.

Question 5

What will the the output of the following code? Marks: 1

#include <iostream>

using namespace std;

class X {

public:

class Trouble {};

class Small : public Trouble {};

class Big : public Trouble {};

void f() { throw Big(); }

};

int main() {

X x;

try {

x.f();

}

catch (X::Trouble&) {

cout << "caught Trouble" << endl;

}

catch (X::Small&) {

cout << "caught Small Trouble" << endl;

}

catch (X::Big&) {

cout << "caught Big Trouble" << endl;

}

catch (...) {

cout << "default" << endl;

}

return 0;

}

a) caught Trouble

b) caught Small Trouble

c) caught Big Trouble

d) default

Answer: a)

4

Page 73: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a differentparameter type. Only the handler whose argument type matches the type of the exceptionspecified in the throw statement is executed.

Question 6

What will be the output of the following program? MCQ, Marks 2

#include <iostream>

using namespace std;

class Test {

public:

Test() { cout << "In Constructor" << endl; }

~Test() { cout << "In Destructor " << endl; }

};

int main() {

try {

Test t1;

throw 10.00;

}

catch(int i) {

cout << "Caught Integer " << i << endl;

}

catch(...) {

cout << "Caught Default" << endl;

}

return 0;

}

a) In Constructor

In destructor

Caught Integer 10

Caught Default

b) In Constructor

Caught Integer 10

c) In Constructor

In Destructor

Caught Default

d) In Constructor

Caught Default

Answer: c)Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a differentparameter type. Only the handler whose argument type matches the type of the exceptionspecified in the throw statement is executed.

5

Page 74: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 7

Fill in the blank in the following code to get the desired output. MCQ, Marks 2

#include <iostream>

using namespace std;

----------------------- // Fill in the blank

int arrMin(T arr[], int n) {

int m = max;

for (int i = 0; i < n; i++)

if (arr[i] < m)

m = arr[i];

return m;

}

int main() {

int arr1[] = {10, 20, 15, 12};

int n1 = sizeof(arr1)/sizeof(arr1[0]);

char arr2[] = {1, 2, 3};

int n2 = sizeof(arr2)/sizeof(arr2[0]);

cout << arrMin<int, 10000>(arr1, n1) << endl;

cout << arrMin<char, 256>(arr2, n2);

return 0;

}

------------

Output:

10

1

a) template <T, int max>

b) template <T>, int max

c) template <class T>, int max

d) template <class T, int max>

Answer: d)Solution: By the definition of template

6

Page 75: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming Questions

Question 1

Consider the following code. Modify the code in editable section to match the public test cases.Marks: 3

#include<iostream>

#include<string>

using namespace std;

// Define Swap() function here

int main() {

int a, b;

double s, t;

string mr, ms;

cin >> a >> b >> s >> t ;

cin >> mr >> ms ;

Swap(a, b);

Swap(s, t);

swap(mr, ms);

cout << a << " " << b << " ";

cout << s << " " << t << " ";

cout << mr << " " << ms ;

return 0;

}

Public 1

I/P: 20 30 2.3 5.6 ppd tm

O/P: 30 20 5.6 2.3 tm ppd

Public 2

I/P: 45 34 7.9 5.6 kolkata delhi

O/P: 34 45 5.6 7.9 delhi kolkata

Private

I/P: 15 78 4.76 2.45 sm ppm

O/P: 78 15 2.45 4.76 ppm sm

Answer

template<typename T>

void Swap(T& x, T& y)

{

T tmp = x;

x = y;

y = tmp;

}

7

Page 76: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 2

Consider the following code.Define the proper function in editable section. Marks: 2

#include <iostream>

#include <exception>

using namespace std;

class myexception : public exception

{

// Define the Proper function which will return a string "DivideByZero"

} myex;

class DivideByZero {

public:

int numerator, denominator;

DivideByZero(int a = 0, int b = 0) : numerator(a), denominator(b){}

int divide(int numerator, int denominator){

if (denominator == 0) {

throw myex;

}

return numerator / denominator;

}

};

int main() {

DivideByZero d;

int a, b;

cin >> a >> b;

try

{

d.divide(a, b);

}

catch (exception& e)

{

cout << e.what() << ’\n’;

}

return 0;

}

Public-1

Input: 10 0

Output: DivideByZero

Public-2

Input: 12 0

Output: DivideByZero

8

Page 77: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Private

Input: 8 0

Output: DivideByZero

9

Page 78: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Answer

virtual const char* what() const throw()

{

return "DivideByZero";

}

Question 3

Consider the following code. Fill the blank with proper class header Marks: 2

#include<iostream>

using namespace std;

// Write the class header here

_______________________

class A {

public:

T x;

U y;

A() { cout << "called" << endl; }

A(T x, U y){ cout << x << ’ ’ << y << endl; };

};

int main() {

int num1 = 0;

double num2 = 0;

char c;

cin >> num1;

cin >> num2;

cin >> c;

A<char> a;

A<char, int> (c, num1);

A<int, double> (num1, num2);

return 0;

}

Public-1

Input:

2

3.4

n

Output:

called

n 2

2 3.4

Public-2

Input:

5

5.4

i

10

Page 79: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Output:

called

i 5

5 5.4

Private

Input:

3

3.4

p

Output:

called

p 3

3 3.4

Answer

template<class T, class U = int >

class A {

public:

T x;

U y;

A() { cout << "called" << endl; }

A(T x, U y){ cout << x << ’ ’ << y << endl; };

};

Question 4

Consider the following code. Modify the code in editable section to match the public test cases.Marks: 3

#include <iostream>

#include <vector>

using namespace std;

class Test {

static int count;

int id;

public:

Test(int id) {

count++;

cout << count << ’ ’;

if (count == id)

throw id;

}

~Test() {}

};

int Test::count = 0;

int main() {

int n, m = 0;

cin >> n >> m;

11

Page 80: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

_______________________ // Declare testArray here

try {

for (int i = 0; i < n; ++i) {

testArray.push_back(Test(m));

}

}

_______________________// Write the catch here

{

cout << "Caught " << i << endl;

}

return 0;

}

Public-1

Input:

6

5

Output:

1 2 3 4 5 Caught 5

Public-2

Input:

8

6

Output:

1 2 3 4 5 6 Caught 6

Private

Input:

3

3

Output:

1 2 3 Caught 3

Answer

catch (int i)

vector<Test> testArray;

12

Page 81: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Programming in C++: Assignment Week 4

Total Marks : 20

March 22, 2017

Question 1

Using friend operator function, which set of operators can be overloaded? Mark 1

a. � , � , <, >, ==, <=,>=

b. + , - , / , *

c. = , ( ) , [ ] , ->

d. && , = , * , ->Answer: aExplanation: As per language syntax, check slides

Question 2

While overloading I/O stream how many number of parameters are required in operator func-tion ? Mark 1

a. 0

b. 1

c. 2

d. 3Answer: cExplanation: Check slides

Question 3

What is the output of the following code? Mark 1

#include <iostream>

using namespace std;

struct emp {

int a;

emp ( int b): a(b){}

~emp(){ cout << " Destroyed " ;}

void disp(){ cout << " In Display " ; }

};

int main(){

1

Page 82: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

emp e(20);

cout << e.a ;

e.disp();

}

Output of the Code is

a. Compilation error

b. 20 In Display

c. 20 In Display Destroyed

d. 0 In DisplayAnswer: cExplanation: As per execution semantics of classes and objects, check slides

Question 4

What is the output of the following code? Mark 1

#include <iostream>

using namespace std ;

namespace Ex { int x = 10; }

namespace Ex { int y = 10; }

int main(){

using namespace Ex ;

x = y = 50;

cout << x << " " << y;

}

Output of the Code is

a. 10 10

b. 50 50

c. Error: Cannot Link the namespaces

d. Compilation error: Invalid Namespace ResolutionAnswer: bExplanation: Using namespace EX to access x and y

Question 5

Fill in the blank. Mark 1

#include<iostream>

using namespace std;

class Test { static int x;

public:

void get() { x = 15; }

void print() {

x = x + 20;

cout << "x =" << x << endl;

2

Page 83: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

}

};

____________; // Define static variable ’x’

int main() {

Test o1, o2;

o1.get(); o2.get();

o1.print(); o2.print();

return 0;

}

a) int Test t.x = 0;

b) Test t; t.x = 0;

c) int Test::x = 0;

d) Test t; t::x = 0;

Answer: c)Explanation: Static variables are declared and initialised with class name, check slides

Question 6

What will be the output of the following program? Mark 1

#include<iostream>

using namespace std;

class Test { int x;

public:

Test(int i) : x(i) {}

friend void print(const Test& a);

};

void print(const Test& a) {

cout << "x = " << a.x;

}

int main(){

Test t(10);

print(t);

return 0;

}

a) x = 10

b) Compilation Error: print cannot access x as it is private

c) Compilation Error: illegal parameter passing in print

d) Compilation Error: Const parameter cannot be passed in friend function

Answer: a)Explanation: X can be accessed as print is a friend function

3

Page 84: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

Question 7

What will be the output of the following program? Mark 1

#include <iostream>

using namespace std;

class sample {

public:

int x, y;

sample() {};

sample(int, int);

sample operator + (sample);

};

sample::sample (int a, int b) {

x = a;

y = b;

}

sample sample::operator+ (sample param) {

sample temp;

temp.x = x + param.x;

temp.y = y + param.y;

return (temp);

}

int main () {

sample a (4,1);

sample b (3,2);

sample c;

c = a + b;

cout << c.x << " " << c.y;

return 0;

}

a) 5 5

b) 7 3

c) 3 7

d) 4 6

Answer: b)Explanation: using operator overloading of + with class Sample objects

Question 8

What will be the output of the following program? Mark 1

#include <iostream>

using namespace std;

class Test {

4

Page 85: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

int i;

public:

Test(int ii) : i(ii) {}

const Test operator+(const Test& rv) const {

cout << "Executes +" << endl;

return Test(i + rv.i);

}

Test& operator+=(const Test& rv) {

cout << "Executes +=" << endl;

i += rv.i;

return *this;

}

};

int main() {

int i = 1, j = 2, k = 3;

k += i + j;

Test ii(1), jj(2), kk(3);

kk += ii + jj;

}

a) Executes +Executes +=

b) Executes +Executes +

c) Executes +=Executes +

d) Compilation Error: Ambiguous declaration

Answer: a)Explanation: As per precedence

Question 9

Fill in the blanks Mark 1

#include <iostream>

using namespace std;

class Complex { double re, im; public:

explicit Complex(double r = 0, double i = 0) : re(r), im(i) { }

void disp() { cout << re << " +j " << im << endl; }

friend Complex operator+ (const Complex &a, const Complex &b) {

return Complex(a.re + b.re, a.im + b.im);

}

friend Complex operator+ (const Complex &a, double d) {

Complex b(d); return a + b;

}

__________________________________________________ {

Complex a(d); return a + b;

5

Page 86: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

}

};

int main(){

Complex d1(2.5, 3.2), d2(1.6, 3.3), d3;

d3 = d1 + d2; d3.disp();

d3 = d1 + 6.2; d3.disp();

d3 = 4.2 + d2; d3.disp();

return 0;

}

a) friend Complex operator+ (double d, const Complex &a)

b) friend Complex operator+ (const Complex &b, double d)

c) friend Complex operator+ (const Complex &a, double d)

d) friend Complex operator+ (double d, const Complex &b)

Answer: d)Explanation: As Complex a(d) is created in the body, hence option d

Question 10

Identify the Incorrect statement(s) about static data member of a class. Mark 1

a) It needs to be defined to avoid linker error.

b) Static data member must be initialized in a source file.

c) It is Associated with object not with class.

d) It can be accessed as a member of any object of the class

Answer: c)Explanation: As per definition of static data members

Programming Assignment

Question 1

Write down the required keywords in the first blank. Fill the rest of the blank by callingthe user defined function abs() or library function abs(), So that the given test cases will besatisfied Marks 2

#include <iostream>

#include <cstdlib>

____________ NS { // Fill the blank with proper keyword

int abs(int n) {

if (n < -128) return 0;

if (n > 127) return 0;

if (n < 0) return -n;

return n;

}

}

int main() {

6

Page 87: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

double x, y, z;

std::cin >> x >> y >> z ;

std::cout << _______(x) << " "

<< _______(y) << " "

<< _______(z) << std::endl;

std::cout <<_______(x) << " "

<< _______(y) << " "

<< _______(z) << std::endl;

return 0;

}

Answer: namespace // NS::abs//NS::abs//NS::abs // abs//abs//absExplanation: As per syntax of namespaces, refer slides

a. Input: -203, -69, 9

Output: 0 69 9

203 69 9

b. Input: 178, 45, 0

Output: 0 45 0

178 45 0

c. Input: -114, 20, 2

Output: 114 20 2

114 20 2

Question 2

Here S and R Represent two geometric class, Square and Rectangle respectively. Our objectiveis to convert /Interpret the Square object as Rectangle and calculating the area of rectangle.Marks 2

#include <iostream>

using namespace std;

class S;

class R {

int width, height;

public:

int area () // Area of rectangle

{return (width * height);}

void convert (S a);

};

class S {

7

Page 88: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

_____________________; // Fill the blank

private:

int side;

public:

S (int a) : side(a) {}

};

void ____________________ (S a) {

width = a.side;

height = a.side; // Interpreting Square as an rectangle

}

int main () {

int x;

cin >> x;

R rect;

S sqr (x);

rect.convert(sqr);

cout << rect.area();

return 0;

}

Answer: friend class R// R::convertExplanation: If a class needs to access the private members(width and height) of a differentclass, it should be a declared as a friend class.

a. Input: 4

Output: 16

b. Input: -6

Output: 36

c. Input: -2.5

Output: 4

Question 3

This Program is all about the implementation of Pre/Post Incrementer. Fill the blank Bykeeping this in mind so that the given test cases will satisfy. Marks 2

#include <iostream>

using namespace std;

8

Page 89: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

class MyClass { int data;

public:

_____________________{ } // Define Constructor

MyClass& operator++() {

++data;

return ___________;

}

_____________________________ {

MyClass t(data);

++data;

return ______________;

}

void disp() { cout << " " << data ; }

};

int main() {

int x;

cin >> x;

MyClass obj1(x);

obj1.disp();

MyClass obj2 = obj1++;

obj2.disp();

obj2 = ++obj1;

obj2.disp();

return 0;

}

Answer: MyClass(int d): data(d) // *this // MyClass operator++(int) // t //Explanation: As per operational semantics of the post and pre increment operators, checkslides.

a. Input: 4

Output: 4 4 6

b. Input: -9

Output: -9 -9 -7

c. Input: 0

Output: 0 0 2

Question 4

Here display() is a non member function which should display the data member of Myclass.Apply the proper concept to fill the blank so that the given test cases will pass. Marks 2

9

Page 90: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

#include<iostream>

using namespace std;

class MyClass { int x_;

public:

MyClass(int i) : x_(i) {}

________________________; // Declare the display function.

};

void display(__________________) {

cout << " " << a.x_;

}

int main(){

int x;

cin >> x;

MyClass obj(x);

display(obj);

return 0;

}

Answer: friend void display(const MyClass &a); // const MyClass &aExplanation: To access the private member of a class, a non member function(in this casedisplay) should be a declared as a friend function. Check the slides

a. Input: 4

Output: 4

b. Input: 8.7

Output: 8

c. Input: 0

Output: 0

Question 5

Fill the blank by keeping in mind that, the program tests the conceptual knowledge aboutstaticMarks 2

#include<iostream>

using namespace std;

class MyClass { static int x;

public:

10

Page 91: Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include

void get() { x++; }

_______ ________ print(int y) { //Fill the blank with proper key words

x = x - y;

cout << " " << x ;

}

};

______________________; // Define static data member

int main() {

int x;

cin >> x;

MyClass:: print(x);

MyClass o1;

o1.get();

o1.print(x);

return 0;

}

Answer: static void // int MyClass::x = 1Explanation: Static variables can be initialised outside the scope of the main withoutconstructing objects. It remains live outside main.

a. Input: 5

Output: -4 -8

b. Input: 0

Output: 1 2

c. Input: -7

Output: 8 16

11