assignment-1 (tcs 305) 5/9/16 (solutions) … · (solutions) by:dilip kumar gangwar ... 1.do not...

39
ASSIGNMENT-1 (TCS 305) 5/9/16 SECTION C (SOLUTIONS) BY:DILIP KUMAR GANGWAR Faculty,CS/IT Deptt.,GEHU,Dehradun ([email protected]) Instructions: 1. Do not copy from others assignment 2. If student A copied from student B and B has done the assignment himself/herself, and during checking ,I first checked the assignment of A ,then B’s assignment ,then B will be treated as defaulter and will be deducted marks.So donot give your assignment to others. 3. You can use net,books and can discuss the question with your clas mate,but the answers should be according to your understanding.If you are not able to find the answer and just copied.It will lead to deduction of marks. 4. Programming questions should be first executed on compiler,then you should write them. 5. Assume necessary header files are present in program code. 6. Submission date: 16/9/2016 7. No Assignment will be submitted after due date. Q1. Engineers often measure the ratio of two power measurements in decibels, or dB. The equation for decibels is W h e r e : Ndb is the ratio of the two power expressed in decibels P2 is the power level being measured and P1 is some reference power level. a. Write the definition of a function named decibel to calculate the decibel level using this equation. The function should have two power levels corresponding toP1 and P2 as parameters and should return the decibel level. Use function log10 to calculate the logarithm. //N can be negative as well as 0 #include <iostream>

Upload: dinhdat

Post on 29-May-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

ASSIGNMENT-1 (TCS 305) 5/9/16 SECTION C

(SOLUTIONS) BY:DILIP KUMAR GANGWAR

Faculty,CS/IT Deptt.,GEHU,Dehradun([email protected])

Instructions:1. Do not copy from others assignment2. If student A copied from student B and B has done the assignment

himself/herself, and during checking ,I first checked the assignment of A,then B’s assignment ,then B will be treated as defaulter and will bededucted marks.So donot give your assignment to others.

3. You can use net,books and can discuss the question with your clasmate,but the answers should be according to your understanding.If you arenot able to find the answer and just copied.It will lead to deduction ofmarks.

4. Programming questions should be first executed on compiler,then youshould write them.

5. Assume necessary header files are present in program code.6. Submission date: 16/9/20167. No Assignment will be submitted after due date.

Q1.Engineers often measure the ratio of two power measurements in decibels, or dB. Theequation for decibels is

W h e r e : Ndb is the ratio of the two power expressed in decibels

P2 is the power level being measured and P1 is some reference power level.

a. Write the definition of a function named decibel to calculate the decibel levelusing this equation. The function should have two power levels correspondingtoP1 and P2 as parameters and should return the decibel level. Use functionlog10 to calculate the logarithm.

//N can be negative as well as 0

#include <iostream>

Page 2: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

#include <cmath>

using namespace std;

float decible(float p1,float p2)

{

if(p1>0)

return log10(p2/p1);

}

int main ()

{

float p1,p2,N;

cout<<"enter p1,p2";

cin>>p1>>p2;

N=decible(p1,p2);

cout<<"ratio="<<N;

return 0;

}2)Write a function called changeLetter that can directly alter the value of a charactervariable. It takes one argument: a reference to a character. It returns nothing. If functionis passed the character and it is alphabetic ('a' to 'z' or 'A' to 'Z'), then make thecharacter become the next higher ASCII value ('a' becomes 'b' etc.).If it is Z or z makeit ‘A’ or ‘a’ respectively . If the passed in character is not a letter, don't alter it.

Ans: #include<iostream>

using namespace std;

void changeLetter(char &);

int main()

{

Page 3: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

char ch;

cout<<"Enter a character\n";

cin>>ch;

if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))

{

changeLetter(ch);

cout<<"Changed letter="<<ch;

}

else

cout<<"You should enter the letter\n";

}

void changeLetter(char &ch)

{

{

if((ch=='Z'||ch=='z'))

ch=ch-25;

else

ch++;

}

}

Page 4: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

3)Give 3 differences between C++ References and Pointers.

Ans:Done in Practice questions sheet

4) Differentiate between constructor and destructor in tabular form on the basis offollowing points :

Purpose,when they are called,Memorymanagement,arguments,overloading,name,syntax.

Ans:

Purpose Constructor is used to initialize theinstance of a class.

Destructor destroys the objects when they areno longer needed.

When Called Constructor is Called when new instanceof a class is created.

Destructor is called when instance of aclass(object) is deleted or released.

MemoryManagement

Constructor allocates the memory. Destructor releases the memory.

Arguments Constructors can have arguments. Destructor can not have any arguments.

Overloading Overloading of constructor is possible. Overloading of Destructor is not possible.

Name Constructor has the same name as classname.

Destructor also has the same name as class namebut with (~) tiled operator.

Syntax ClassName(Arguments){//Body of Constructor}

~ ClassName(){}

5)a)When is it better to make a function inline?

Ans: it is only useful and better to make the function inline if the time spent during a function call is more

compared to the function body execution time.

b)Where do we write inline keyword ?

i)if both delaration and definition of a function is present?

Page 5: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

Anywhere in Definition or declaration

ii)if only function definition is present?

Definition

More description:Inline function is one of the important feature of C++. So, let’s first understand why inline functions areused and what is the purpose of inline function?When the program executes the function call instruction the CPU stores the memory address of theinstruction following the function call, copies the arguments of the function on the stack and finallytransfers control to the specified function. The CPU then executes the function code, stores the functionreturn value in a predefined memory location/register and returns control to the calling function. This canbecome overhead if the execution time of function is less than the switching time from the caller functionto called function (callee). For functions that are large and/or perform complex tasks, the overhead of thefunction call is usually insignificant compared to the amount of time the function takes to run. However, forsmall, commonly-used functions, the time needed to make the function call is often a lot more than thetime needed to actually execute the function’s code. This overhead occurs for small functions becauseexecution time of small function is less than the switching time.C++ provides an inline functions to reduce the function call overhead. Inline function is a function that isexpanded in line when it is called. When the inline function is called whole code of the inline function getsinserted or substituted at the point of inline function call. This substitution is performed by the C++compiler at compile time. Inline function may increase efficiency if it is small.The syntax for defining the function inline is:

inline return-type function-name(parameters)

{

// function code

}

Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the request forinlining. Compiler may not perform inlining in such circumstances like:1)If a function contains a loop. (for, while, do-while)

2) If a function contains static variables.

3) If a function is recursive.

4) If a function return type is other than void, and the return statement doesn’t exist in function body.

5) If a function contains switch or goto statement.Inline functions provide following advantages:1) Function call overhead doesn’t occur.2) It also saves the overhead of push/pop variables on the stack when function is called.3) It also saves overhead of a return call from a function.The following program demonstrates the use of use of inline function.

Page 6: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

#include <iostream>using namespace std;int cube(int);int main(){ cout << "The cube of 3 is: " << cube(3) << "\n"; return 0;} //Output: The cube of 3 is: 27inline int cube(int s){ return s*s*s;}

Inline function and classes:

It is also possible to define the inline function inside the class. In fact, all the functions defined inside theclass are implicitly inline. Thus, all the restrictions of inline functions are also applied here. If you need toexplicitly declare inline function in the class then just declare the function inside the class and define itoutside the class using inline keyword.For example:class S{public: inline int square(int s) // redundant use of inline { // this function is automatically inline // function body }};The above style is considered as a bad programming style. The best programming style is to just write theprototype of function inside the class and specify it as an inline in the function definition.For example:

class S{public: int square(int s); // declare the function};

inline int S::square(int s) // use inline prefix{

}The following program demonstrates this concept:

#include <iostream>using namespace std;class operation{ int a,b,add,sub,mul;

Page 7: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

float div;public: void get(); void sum(); void difference(); void product(); void division();};inline void operation :: get(){ cout << "Enter first value:"; cin >> a; cout << "Enter second value:"; cin >> b;}

inline void operation :: sum(){ add = a+b; cout << "Addition of two numbers: " << a+b << "\n";}

inline void operation :: difference(){ sub = a-b; cout << "Difference of two numbers: " << a-b << "\n";}

inline void operation :: product(){ mul = a*b; cout << "Product of two numbers: " << a*b << "\n";}

inline void operation ::division(){ div=a/b; cout<<"Division of two numbers: "<<a/b<<"\n" ;}

int main(){ cout << "Program using inline function\n"; operation s; s.get();

Page 8: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

s.sum(); s.difference(); s.product(); s.division(); return 0;}Output:

Enter first value: 45

Enter second value: 15

Addition of two numbers: 60

Difference of two numbers: 30

Product of two numbers: 675

Division of two numbers: 3

6)a)Find the output or error if any in the following code:

#include<iostream>

#include<iomanip>

using namespace std;

class overload

{

public:

overload(int a ) //1

{

cout<<a<<endl;

}

overload(int a,int b) //2

{

Page 9: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

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

}

overload(int a,int b,int c) //3

{

cout<<a<<" "<<b<<" "<<c<<endl;

}

};

main()

{

overload e1(2,3); //line 1

overload e2(3,7.3); //line 2

overload e3(3,5,8); //line 3

}

Output:

2 3

3 7

3 5 8

b) Find the output or error if any in the following code.What is the meaning of line 4?

#include<iostream>

#include<iomanip>

using namespace std;

Page 10: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

class overload

{

public:

overload(int a,int b=8) //1

{

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

}

};

main()

{

overload e1(2,3); //line 1

overload e2(3,7.3); //line 2

overload e3(67); //line 3

overload e4(); //line 4

}

O/P

2 3

3 7

67 8

Line 4 means e4() is a function which takes no argument and return an object of typeoverload.ex() is not a call to constructor.

c) Will this code run? Which functions out of 1,2,3 should be removed to make thiscode run.(do not change main() )

Page 11: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

#include<iostream>

#include<iomanip>

using namespace std;

class overload

{

public:

overload(int a ) //1

{

cout<<a<<endl;

}

overload(int a,int b=78) //2

{

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

}

overload(int a,int b=45,int c=90) //3

{

cout<<a<<" "<<b<<" "<<c<<endl;

}

};

main()

{

overload e1(2,3); //line 1

overload e2(3,7,89); //line 2

overload e4(3); //line 3

Page 12: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

}

Ans:.No.

Remove 1 and 2 both

Then output:

2 3 90

3 7 89

3 45 90

7)Find output or error:

Array starts from address 200(assume)

#include<iostream>

#include<iomanip>

using namespace std;

int main()

{

int a[]={2,3,4,6};

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

cout<<a[i]<<" "<<i[a]<<" "<<(i+a)<<" "<<*(i+a)<<" "<<(a+i)<<endl;

}

Ans:

2 2 200 200

3 3 204 204

4 4 208 208

6 6 212 212

Page 13: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

8)Find output.If errors are present ,then tell the reasons of error and make the coderunnable.

#include<iostream>

#include<iomanip>

using namespace std;

int main()

{

char k='m';

char t=10;

char a[]="hello";

char *p="fine";

cout<<a<<" "<<p<<" "<<a[0]<<" "<<p[0]<<" "<<a[1]<<" "<<p[1]<<endl;

//a++;

p++;

cout<<a<<" "<<p<<" "<<a[1]<<" "<<p[1]<<" "<<a[0]<<" "<<p[0]<<endl;

a[2]='k';

//p[2]='t';

cout<<a[2]<<" "<<p[2]<<endl;

p=&k;

cout<<p<<" "<<*p;

//a=&t;

cout<<a<<" "<<*a;

}

After commenting green lines the output is:

hello fine h f e i

hello ine e n h i

k e

Page 14: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

m▼■" mheklo h

1)

In char *p=”fine”

fine is string constant so no character in it can be changed as it is stored in read onlyarea part of program.But p can be changed to store some other address.

In char a[] =”hello”

Any character in hello can be changed as it is like

H e l l o \0

a[0] a[1] ………………………………………………………. a[5]

Name of array is constant pointer so it cannot be changed ,so a++ is wrong

2)

Here m▼■" is the answer given by cout<<p after p=&k. But why ?? shouldn’t itgive only m

For this,

ed

First, you need to understand how "strings" work in C.

"Strings" are stored as an array of characters in memory. Since there is no way ofdetermining how long the string is, a NUL character, '\0', is appended after the string sothat we know where it ends.So for example if you have a string "foo", it may look like this in memory:

--------------------------------------------| 'f' | 'o' | 'o' | '\0' | 'k' | 'b' | 'x' | ...--------------------------------------------The things after '\0' are just stuff that happens to be placed after the string, which mayor may not be initialised.When you assign a "string" to a variable of type char *, what happens is that the variablewill point to the beginning of the string, so in the above example it will point to 'f'. (Inother words, if you have a string str, then str == &str[0] is always true.) When youassign a string to a variable of type char *, you are actually assigning the addressof the zeroth character of the string to the variable.

When you pass this variable to printf(), it starts at the pointed address, then goes

Page 15: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

through each char one by one until it sees '\0' and stops. For example if we have:

char *str = "foo";and you pass it to printf(), it will do the following:1. Dereference str (which gives 'f')2. Dereference (str+1) (which gives 'o')3. Dereference (str+2) (which gives another 'o')4. Dereference (str+3) (which gives '\0' so the process stops).

char k='m';char *p=”fine”;…………p=&k; //or p=’m’;cout<<k;

so p has the starting address i.e address of m.Cout will print the characters from here tillit finds ‘\0’ so may be we get m or mgarbage (as we are getting here)

cout<<*p; //dereference just the zeroth address so we get m

9)Fill in the blanks:

I. A programmer can allocate memory space at run time using __new_ operator.

II. When there are multiple constructor,then ___default___constructor is __ notprovided (provided/not provided) by compiler. We have to provided the _default_ constructor explicitly.

III. cin and cout are operators (operators/functions) of class istream and ostreamrespectively.

IV. Symbolic conastant can be made by const keyword or define directive.

Page 16: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

V. cin.getline (p,10) (where p is a char * p) means getline can read max 9characters and store in the memory area pointed by pointer p.

10)Give 2 uses of scope resolution operator by example?Is it unary or binary operator.

Ans:1)Used to access global variable

#include<iostream>

using namespace std;

int a=20;

main()

{

int a=90;

cout<<a<<" "<<::a;

}

o/p: 90 20

2)to associate a function with its class.

class ex

{

………..

public:

void fun();

};

class qw

{

……..

public:

void fun();

};

Page 17: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

void ex::fun()

{

}

void qw::fun()

{

}

main()

{

……

………

}

It is unary operator.

11)Here is a code:

#include<iostream>

int main()

{

int a;

cin>>a;

cout<<a;

}

Will this code run?Make this code run without writing using namespace std in programand tell the output,If user enters value of a=78;

Ans:

#include<iostream>

Page 18: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

int main()

{

int a;

std::cin>>a;

std::cout<<a;

}

If a=78 o/p is 78.

12)Answer the following questions:

I. Name 3 object based and 3 object oriented languages.

Ans: 3 object based: Javascript,visual basic,Fortran 90

object oriented languages: c++,java,simula,python,perl,swift,smalltalk,c#,VB .NET

II. Name any 1 pure object oriented language.

Ans: smalltalk

III. Name 10 keywords present in C++ not in C.

Ans:new,delete,friend,virtual,operator,inline,private,public,protected,class,using,nullptr(since c++ 11)

IV. Briefly Explain the dataypes in C ++.

Refer Book:

V. What is the use of const keyword with a pointer variable,function?When shouldbe make a function as const?Can we pass constant arguments to afunction?Explain with example.

Ans: with pointer variable:

1) int * const p;declares a constant pointer to a integer.

2) char * const myPtr

declares a constant pointer to a character. The location stored in the pointer cannot change. You cannot change

where this pointer points:

Page 19: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

1. char char_A = 'A';

2. char char_B = 'B';

3. char * const myPtr = &char_A;

4. myPtr = &char_B; // error - can't change address of myPtr

The third declares a pointer to a character where both the pointer value and the value being pointed at will not

change.

3)when we know that a function should not change the values of some data then makethat function as const

void display () const

{

}

4)Yes,we Can we pass constant arguments to a function.

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

return a + b;}

VI. We can make programs in C.Why then object oriented programming like C++was developed?

Ans:Explain the reasons:unrestricted access of global data,no reusability,no datahiding.

Main reaon to develop C++:It is used to make large software in an organized way.

VII. With respect to scope,what is the difference between static data memberand global data member?

Ans:The static data member is visible in the file in which they are defined.They canootbe used in other file or program

Page 20: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

The global data member is visible in the file in which they are defined. And are visiblein other file or program also.So they can be used in other file also using externkeyword.

VIII. Is it possible to call constructor and destructor explicitly?

Ans: Yes, it is possible to call special member functions explicitly by programmer.Following program calls constructor and destructor explicitly.

#include <iostream>using namespace std;

class Test{public: Test() { cout << "Constructor is executed\n"; } ~Test() { cout << "Destructor is executed\n"; }};

int main(){ Test(); // Explicit call to constructor Test t; // local object t.~Test(); // Explicit call to destructor return 0;}Output:

Constructor is executed

Destructor is executed

Constructor is executed

Destructor is executed

Destructor is executed

When the constructor is called explicitly the compiler creates a nameless temporaryobject and it is immediately destroyed. That’s why 2nd line in the output is call todestructor.

IX.Why can typecasting be dangerous?

Ans:we might lose some part of data like truncating a part of float while converting toint

Page 21: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

13) A student X want to print the following output :

LOCATION POPULATIONPortcity 2425785Hightown 47Lowville 9761

He writes the following code,but it is not printing the desired output.Modify this codeusing manipulators to get above output (do not use tabs\spaces):

int main(){long pop1=2425785, pop2=47, pop3=9761;cout << “LOCATION “ << “POPULATION” << endl<< “Portcity “ << pop1 << endl<< “Hightown “ << pop2 << endl<< “Lowville “ << pop3 << endl;return 0;}

Ans:

#include <iostream>

#include <iomanip> // for setw

using namespace std;

int main()

{

long pop1=2425785, pop2=47, pop3=9761;

cout << setw(8) <<"LOCATION" << setw(12)

<< "POPULATION" << endl

<< setw(8) << "Portcity" << setw(12) << pop1 << endl

<< setw(8) << "Hightown" << setw(12) << pop2 << endl

<< setw(8) << "Lowville" << setw(12) << pop3 << endl;

return 0;

}

Page 22: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

14)Give 6 benefits/applications of C++.

Ans:Applications:

Adobe Systems

All major applications of adobe systems are developed in C++ programming language. These applicationsinclude Photoshop & ImageReady, Illustrator and Adobe Premier.

Google

Some of the Google applications are also written in C++, including Google file system and GoogleChromium.

Mozilla

Internet browser Firefox and email client Thunderbird are written in C++ programming language and theyare also open source projects.

MySQL

MySQL is the world’s most popular open source database software, with over 100 million copies of itssoftware downloaded or distributed throughout its history. Many of the world’s largest and fastest-growingorganizations use MySQL to save time and money powering their high-volume Web sites, critical businesssystems, and packaged software — including industry leaders such as Yahoo!, Alcatel-Lucent, Google,Nokia, YouTube, Wikipedia, and Booking.com.

Alias System – Autodesk Maya

Maya 3D software was originally developed by Alias System Corporation and was later carried over byAutodesk. Maya 3D software, now a days is widely used in computers, video games, television. It is apowerful, integrated 3D modelling, animation, visual effects, and rendering solution.

Winamp Media Player

Winamp is the ultimate media player, allows you to manage audio and video files, rip and burn CDs, enjoyfree music, access and share your music and videos remotely, and sync your music to your iPod ,

Page 23: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

Creative, and Microsoft Plays for Sure devices . Winamp features album art support, streams audio andvideo content, and provides access to thousands of internet radio stations and podcasts.

12D Solutions

12D Solutions Pty Ltd is an Australian software developer specialising in civil engineering and surveyingapplications. Computer Aided Design system for surveying, civil engineering, and more. 12D Solutionsclients include civil and water engineering consultants, environmental consultants, surveyors, local, stateand national government departments and authorities, research institutes, construction companies andmining consultants.

Bloomberg

Providing real-time financial information to investors.

callas Software

callas software develops pdf creation, optmisation, updation and pdf form creation tools and plugins.

Image Systems

These are the world leading motion analysys programs and film scanner systems.

Some /(some part of )Operating systems are also written in C++programming language.

Apple – OS X

Few parts of apple OS X are written in C++ programming language. Also few application for iPod arewritten in C++.

Microsoft

Literally most of the software are developed using various flavors of Visual C++ or simply C++. Most of thebig applications like Windows 95, 98, Me, 200 and XP are also written in C++. Also Microsoft Office,Internet Explorer and Visual Studio are written in Visual C++.

Page 24: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

Symbian OS

Symbian OS is also developed using C++. This is one of the most widespread OS’s for cellular phones.

Benefits of C++ C++ is a highly portable language and is often the language of choice for multi-device,

multi-platform app development. C++ is an object-oriented programming language and includes classes, inheritance,

polymorphism, data abstraction and encapsulation. C++ has a rich function library. C++ allows exception handling, and function overloading which are not possible in C. C++ is a powerful, efficient and fast language. It finds a wide range of applications – from

GUI applications to 3D graphics for games to real-time mathematical simulations.

In broad form ,it has data hiding concept,large software can be made in organizedform.

15)Student X of B.Tech CS C has made the following code and in this code, functionfun() ( a non member function ) is trying to access the private and public member of class .It has error.Change the code inside the fun(ex e) so that at least k or m is printed.You cannot change anything else. (If you have to remove some line,you can remove)

#include<iostream>#include<iomanip>using namespace std;class ex{

int a;public:

int b;void sample(){

Page 25: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

a=10;b=78;cout<<a<<" "<<b<<endl;

}};

void fun(ex e){

int k=e.b+2;int m=e.a+4;cout<<k<<" "<<m;

}int main(){

ex e;e.sample();fun(e);

}

Ans:If you do not know the concept of friend function,then change here only:void fun(ex e){

int k=e.b+2;//int m=e.a+4; //as a non member function can only access public data. //cout<<k<<" "<<m;

cout<<k;}

O/p:10 7880 --------------------------------.If you do know the concept of friend function,then make fun () friend of the class ex.#include<iostream>using namespace std;class ex{

int a;public:

int b;void sample(){

a=10;b=78;cout<<a<<" "<<b<<endl;

Page 26: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

}friend void fun(ex e);

};

void fun(ex e){

int k=e.b+2;int m=e.a+4;cout<<k<<" "<<m;

}int main(){

ex e;e.sample();fun(e);

}

O/P:10 7880 14

Q16) Create a class complex having the following: 2 data members:1)one float data member will store the real part of a complex no. 2) other float data member will store the imaginary part of a complex no.

Complex numbers are numbers of form x+iy (x is real part and y is imaginary part)

When program will run,You have to enter 2 complex numbers on screen and have toshow the addition of them.Members functions are:1)one default constructor which should initialize the real and imaginary part of bothcomplex no as 0.2)a function enter() to input the 2 complex no.3) a function addcomplex( ) to input the 2 complex no.It should take only one object asargument.Function should add 2 complex numbers and return the object to main()having final answer4)Function display() should print the final answer.

Ans://overlaoding unary minus#include<iostream>using namespace std;

class complex

Page 27: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

{float real,img;public:

complex(){

real=img=0;}

void enter() {

cin>>real>>img; } void display() {

cout<<"("<<real<<" + "<<img<<"i"<<")"<<endl; } complex addcomplex(complex c2) {

complex t;t.real=real+c2.real;t.img=img+c2.img;return t;

}

};

main(){

complex c1,c2,c3;cout<<"Enter 1st complex no\n";c1.enter();cout<<"The number is=";c1.display();cout<<"Enter 2nd complex no\n";c2.enter();cout<<"The number is=";c2.display();c3=c1.addcomplex(c2);cout<<"\nAddition(c3)=";c3.display();

}

17)Find the error in this code with reason and what possible modification can run thiscode.

Page 28: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

#include<iostream>using namespace std;char foo(char a){

return a+2;}char foo(char b){

return b+4;}int main(){ char k=foo('d'); char m=foo('r'); cout<<k<<" "<<m;}

Ans:Return type does not distinguish overloaded function as during fn call return type isnot known.

Modification :Change no of arguments,or their type.#include<iostream>using namespace std;char foo(int a){

return a+2;}char foo(char b){

return b+4;}int main(){ char k=foo(67); char m=foo('r'); cout<<k<<" "<<m;}

O/p: E v

18) Write a program that compiles and runs both in C and C++, but produces differentresults when compiled by C and C++ compilers.

Ans: There can be many such programs, following are some of them.

Page 29: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

1) Character literals are treated differently in C and C++. In C character literals like ‘a’,‘b’, ..etc are treated as integers, while as characters in C++. For example, the following program produces sizeof(int) as output in C, but sizeof(char)in C++.

#include<stdio.h> //some new compiler write as cstdioint main(){ printf("%d", sizeof('a')); return 0;

}O/p in c++: 1O/p in c: 4

2)Types of boolean results are different in C and C++.

// output = 4 in C (which is size of int)printf("%d", sizeof(1==1));

// output = 1 in c++ (which is the size of boolean datatype)cout << sizeof(1==1);

19) When is it better to pass arguments by reference or pointer?Ans:

1) To modify local variables of the caller function: A reference (or pointer) allows called function tomodify a local variable of the caller function. For example, consider the following example programwhere fun() is able to modify local variable x of main().void fun(int &x) { x = 20;}

int main() { int x = 10; fun(x); cout<<"New value of x is "<<x; return 0;}O u t p u t :New value of x is 20

2) For passing large sized arguments: If an argument is large, passing by reference (or pointer) is moreefficient because only an address is really passed, not the entire object. For example, let us consider thefollowing Employee class and a function printEmpDetails() that prints Employee details.class Employee {

Page 30: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

private: string name; string desig;

// More attributes and operations};

void printEmpDetails(Employee emp) { cout<<emp.getName(); cout<<emp.getDesig();

// Print more attributes}

The problem with above code is: every time printEmpDetails() is called, a new Employee abject isconstructed that involves creating a copy of all data members. So a better implementation would be topass Employee as a reference.void printEmpDetails(const Employee &emp) { cout<<emp.getName(); cout<<emp.getDesig();

// Print more attributes }This point is valid only for struct and class variables as we don’t get any efficiency advantage for basictypes like int, char.. etc.

20)a)When does compiler create default and copy constructors in C++?Ans: In C++, compiler creates a default constructor if we don’t define our own constructor Compilercreated default constructor has empty body, i.e., it doesn’t assign default values to data members (Injava,default constructor assign default valuesCompiler also creates a copy constructor if we don’t write our own copy constructor. Unlike defaultconstructor, body of compiler created copy constructor is not empty, it copies all data members of passedobject to the object which is being created.

b) What happens when we write only a copy constructor – does compiler create defaultconstructor?Ans:Compiler doesn’t create a default constructor if we write any constructor even if it is copy constructor.For example, the following program doesn’t compile.#include <iostream>using namespace std;

class Point{ int x, y;

Page 31: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

public: Point(const Point &p) { x = p.x; y = p.y; }};

int main(){ Point p1; // COMPILER ERROR Point p2 = p1; return 0;}

Output:

COMPILER ERROR: no matching function for call to 'Point::Point()

c) What about reverse – what happens when we write a normal constructor and don’twrite a copy constructor?Ans: Reverse is not true. Compiler creates a copy constructor if we don’t write our own. Compiler createsit even if we have written other constructors in class. For example, the below program works fine.

#include <iostream>using namespace std;

class Point{ int x, y;public: Point(int i, int j) { x = 10; y = 20; } int getX() { return x; } int getY() { return y; }};

int main(){ Point p1(10, 20); Point p2 = p1; // This compiles fine cout << "x = " << p2.getX() << " y = " << p2.getY(); return 0;}Output:

x = 10 y = 20

21) Can we use function on left side of an expression in C and C++?

Page 32: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

Ans: In C, it might not be possible to have function names on left side of an expression, but it’s possiblein C++.#include<iostream>

using namespace std;

/* such a function will not be safe if x is non static variable of it */int &fun(){ static int x; //static is made as it is not correct to return a reference of

//a local variable return x;}

int main(){ fun() = 10;

/* this line prints 10 on screen */ printf(" %d ", fun());

return 0;}

22) Why is the size of an empty class not zero in C++?Ans:

#include<iostream>using namespace std;

class Empty {};

int main(){ cout << sizeof(Empty); return 0;}Output:

1

Size of an empty class is not zero. It is 1 byte generally. It is nonzero to ensure that the two differentobjects will have different addresses. See the following example.

#include<iostream>using namespace std;

class Empty { };

Page 33: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

int main(){ Empty a, b;

if (&a == &b) cout << "impossible " << endl; else cout << "Fine " << endl;

return 0;}Output:

Fine

23) a)Find the ouput and tell how many times destructor is called and constructor iscalled and at what positions these are called?

#include<iostream>

using namespace std;

class test

{ int i;

public:

test(int a)

{

cout<<"Object is created\n";

i=a;

}

~test()

{

cout<<"Good Bye"<<i<<endl;

}

Page 34: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

};

int main()

{

test t1(3);

test t2(5);

{

test t3(4);

}

test t4(90);

}

Ans:

O/P:

Object is created

Object is created

Object is created

Good Bye4

Object is created

Good Bye90

Good Bye5

Good Bye3

4 time destructor, 4 time constructor is called at following positions.

int main()

{

test t1(3); //constructor called

Page 35: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

test t2(5); //constructor called

{

test t3(4); //constructor called

} //destructor called

test t4(90); //constructor called

} //destructor called

b) If line test t3(4); is replaced by test *t3=new test(56); then tell how many timesdestructor is called and constructor is called and at what positions these are called?

O/p:

Object is created

Object is created

Object is created

Object is created

Good Bye90

Good Bye5

Good Bye3

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

3 time destructor, 4 time constructor is called at following positions.

int main()

{

test t1(3); //constructor called

test t2(5); //constructor called

{

test *t3=new test(56); //constructor called

Page 36: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

} //No destructor called

test t4(90); //constructor called

} //destructor called

25)What is the difference between delete and destructor in C++?

Ans:delete calls constructor

26)A student X comes to class on Monday and teacher say to him you can see anystudent and he started seeing a student s1.

A student Y comes to class on Monday and teacher ask him to not to see anyone.

A student Z comes to class on Monday and teacher say to him to see the student s2.

After sometime,Z wants to talk to s2 but he is not able to do it as there is some otherperson in place of s2.

A student K comes to class on Monday and teacher say to him to see the student s3who have worn RED colour DRESS .After sometime teacher say to K to see student s4who has worn blue colour dress(type of sudent is distinguished on the basis ofdress).Teacher has the flexibility that he can say K to see anyone.

Tell which student(out of X,Y,Z,K) is which type of pointer(out of WILDPOINTER,NULL POINTER,DANGLING POINTER,VOID POINTER)

Ans:

X:WILD POINTER

Y:NULL POINTER

Z:DANGLING POINTER

K:VOID POINTER

27)Some person told that data hiding means a customer is not able to see your sourcecode,then it is data hiding.Is it true?If not then what is data hiding in C++?

Ans:Data hiding in normal form means that when a programmer is making the programshould not accidently access any data.For Some data we want that it should be notaccessible directly by a function like main().So we make that data as private(controlledaccess).You know we can access that private data yet also.But not directly in

Page 37: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

main().We can access it through a function only.If user accidently accessed privatedata from main() ,he gets error,in that sense data hiding concept come into picture.

28) Some person told that C++ follow bottom up approach and it is said because wewrite main() at the end and all code is wriiten at the start of program.So main(), thestarting part of program is at end so in that sense C++ follow bottom up approach.Is ittrue?In not , then what do you mean by bottom up approach ?

Ans:

Top down and bottom up are actually the approaches that a programmer takes todesign his program,how he thinks about the solution of his program.Generally,C is asidthat it follow top down approach

In Top-Down development you start out with your main function, and then think of the mainsteps you need to take, then you break up each of those steps into their subparts, and soon.

In Bottom-Up programming you think of the basic functionality and the parts you're going toneed and build them up. You develop the actors and their methods, and then you tie themtogether to make a coherent whole.

OOP naturally tends toward Bottom-Up as you develop your objects, while proceduralprogramming tends toward Top-Down as you start out with one function and slowly add to it.

In OOPs we thinks first our problem in terms of objects that what can be the differentobjects to solve our problem ,then we think of operations that can be done on them.Thenwe make or think of various classes.Thnen we create several classes each giving somefunctionality in our solution of problem.The me combine everything through main () bycreating objects of them .So we start from small parts like objects,then cobine everythingvia main().So bottom up approach.

In general a programmaer can follow any approach.

(We can write main() in upper portion of program and define functions at last after main() )

29) Run this code and tell what each line is doing .Also tell why this code gettingcrashed at execution time.

#include <iostream>

int main(){ int *ptr = new int;

Page 38: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

*ptr = 7; delete ptr; std::cout << *ptr; delete ptr; return 0;}

Ans: #include <iostream>

int main(){ int *ptr = new int; // dynamically allocate an integer *ptr = 7; // put a value in that memory location

delete ptr; // return the memory to the operating system. ptr is now a danglingpointer.

std::cout << *ptr; // Dereferencing a dangling pointer will cause undefined behavior delete ptr; // trying to deallocate the memory again will also lead to undefinedbehavior.

30)Find output and tell what each line is doing inside main()

#include <iostream>

using namespace std;

class Test{public: Test() { cout << "Constructor is executed\n"; } ~Test() { cout << "Destructor is executed\n"; }};

int main(){ Test(); Test t; t.~Test(); return 0; }

Ans:int main(){

Page 39: ASSIGNMENT-1 (TCS 305) 5/9/16 (SOLUTIONS) … · (SOLUTIONS) BY:DILIP KUMAR GANGWAR ... 1.Do not copy from others assignment 2.If student A copied from student B and B has done the

Test(); // Explicit call to constructor Test t; // local object t.~Test(); // Explicit call to destructor return 0;}

o/p:

Constructor is executed

Destructor is executed

Constructor is executed

Destructor is executed

Destructor is executed

Side notes:When the constructor is called explicitly the compiler creates a namelesstemporary object and it is immediately destroyed. That’s why 2nd line in the output iscall to destructor.

In general, special member functions like constructor and destructor shouldn’t becalled explicitly.

Destructor should not be called explicitly when the object is dynamically allocatedbecause delete operator automatically calls destructor which can do more work thandestructor: