Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

For More Ignou Solved Assignments Please Visit - Connect On Facebook

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

For More Ignou Solved Assignments Please Visit - www.ignousolvedassignments.com Connect on Facebook : http://www.facebook.

com/pages/IgnouSolvedAssignmentscom/346544145433550 Subscribe and Get Solved Assignments Direct to your Inbox : http://feedburner.google.com/fb/a/mailverify?uri=ignousolvedassignments_com Request Any Solved Assignment at : http://ignousolvedassignments.com/request-and-share-solved-assignments/

Course Code : BCS-031 Course Title : C++ Programming Assignment Number : BCA(III)-031/Assignment/2012 Maximum Marks : 100 Last Date of Submission : 15th October, 2012/15th April, 2013 Note: This assignment has five questions of 80 marks (each section of a question carries same marks). Answer all the questions. Rest 20 marks are for viva voce. You may use illustrations and diagrams to enhance explanations. Please go through the guidelines regarding assignments given in the Programme Guide for the format of presentation. Please give precise answers.
Question 1: (a) Compare and contrast Structure programming approach to Object Oriented Programming approach.

Ans:-1(a) Structured programming is a standardization technique used for software development.This approach works by having all programmers uses the same structured design techniques. To develop good software, developers have to carefully think out and design the programs. The structured programming approach to program design is based on the following method:

To solve a large problem, break the problem into several pieces and work on each piece separately;

to solve each piece, treat it as a new problem that can itself be broken down into smaller problems; Repeat the process with each new piece until each can be solved directly, without further decomposition. Structured programming is a programming paradigm aimed on improving the clarity, quality, and development time of a computer program by making extensive use of subroutines, block structures and for and while loops.

Object oriented programming The central concept of object-oriented programming is the object, which is a kind of module containing data and subroutines. An object is a kind of self-sufficient entity that has an internal state and that can respond to messages. This means that a program organised around an object in object oriented programming approach. The OOP approach:

identifying the objects involved in a problem; Identifying the messages that those objects should respond to.

The solution that results is a collection of objects, each with its own data and its own set of responsibilities. The objects interact by sending messages to each other. Modern OO languages provide the programmer with three capabilities that improve and simplify the design of such programs: encapsulation, inheritance, and polymorphism (or generic functionality). Related topics involve objects, classes, and data hiding. An object combines various classical data types into a set that defines a new variable type, or structure. A class unifies the new entity types and supporting data that represents its state with routines (functions and subroutines) that access and/or modify those data. Every object created from a class, by providing the necessary data, is called an instance of the class.

(b) Explain major advantages of ObjectOriented Programming with the help of an example each. Ans : The major advantages of OOP.

Modularity:-OOP provides a clear modular structure for programs which makes it good for defining abstract datatypes where implementation details are hidden and the unit has a clearly defined interface. Modifiability: - OOP provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces.

Maintainable OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones. The principles of good OOP design contribute to an applications maintainability. Reusable:- Because objects contain both data and functions that act on data, objects can be thought of as self-contained boxes (encapsulation). This feature makes it easy to reuse code in new systems. Messages provide a predefined interface to an objects data and functionality. Scalable :-OO applications are more scalable then their structured programming roots. As an objects interface provides a roadmap for reusing the object in new software, it also provides you with all the information you need to replace the object without affecting other code. This makes it easy to replace old and aging code with faster algorithms and newer technology.

(c) Explain the usage of the following C++ operators with the help of an example program. (a) sizeof operator (b) bitwise AND operator (c) ++ as post increment operator Ans 2 (a) Sizeof operator:The sizeof is a keyword, but it is acompile-time operator that determines the size, in bytes, of a variable or datatype. The sizeof operator can be used to get thesize of classes, structures, unions and any other user defined data type. The syntax of using sizeof is as follows: Sizeof (data type);

Where datatype is the desired data type including classes, structures, unions and anyother user defined data type. e.g. #include <iostream> using namespace std; int main() { cout << "Size of char : " << sizeof(char) <<endl; cout << "Size of int : " << sizeof(int) <<endl;

cout << "Size of short int : " << sizeof(shortint) << endl; cout << "Size of long int : " << sizeof(long int)<< endl; cout << "Size of float : " << sizeof(float)<< endl; cout << "Size of double : " << sizeof(double)<< endl; cout << "Size of wchar_t : " << sizeof(wchar_t)<< endl; return 0; } When the above code iscompiled and executed, it produces following result:Size of char : 1 Size of int : 4 Size of short int : 2 Size of long int : 4 Size of float : 4 Size of double : 8 Size of wchar_t : 4 (b) bitwiseAND operator Bitwise operator works on bits and perform bit by bit operation. The truth tables for&, |, and ^ are as follows:

The bitwiseand operate in this wayIf a=7, b=5 Then a& b work in this way:Binary of 5is : 101 Binaryof 7is : 111 then (a & b) = (101)&(111) this gives 101 and compiler thenconvert it into decimal form i.e. output is 5. (c) ++ aspost increment operator Ans:- ++operator increment the origional value by 1. IT is used as postfix and prefix.When we use as a postfix then first of all use the origional contents of variables the increment the value by 1. e.g. #include<iostream.h> Void main()

{ Int a, s; Cout<<enterany two number; Cin>>a>>b; S=a++; Cout<<s; Cout<<a; } Question 2: (a) Define the class Student which has name (char name[20]) ,age(int), sex(char), program(char prg[15]) and address(char add[25]). Define the default constructor, member functions get_data() for taking the name, age, sex, program and address of the Student, print() for displaying the data of Student.

Ans : #include<iostream.h> #include<conio.h> ClassStudent { Charname[20]; Int age; Char sex; Charprogram[15]; Charaddress[25]; Public: Student()

{ } Voidget_data(); { Cout<<Enteryour name; Cin>>name; Cout<<enteryour age; Cin>>age; Cout<<enter your sex; Cin>>sex; Cout<<enteryour address; Cin>>address; Cout<<theprogram enterd is:; Cin>>program; } Voidprint(); { Cout<<theinformation entered by you is as follows; Cout<<endl; Cout<<\nnameis:<<name; Cout<<\nageis:<<age; Cout<<\nprogram is:<<program; Cout<<\nsex is <<sex;

Cout<<\naddressis :<<address; }; Void main() { Student obj; Clescr(); Obj. get_data(); Obj.print(); Getch(); } (b) Explain the following terms in the context of object oriented programming. Also explain how these concepts are implemented in C++ by giving an example program for each.

(a)

Data abstraction refers to, providing only essential information to theoutside word and hiding their background details ie. to represent the neededinformation in program without presenting the details.

Data abstraction is a programming (and design) technique that relies on theseparation of interface and implementation. Benefits of Data Abstraction: Data abstraction provide twoimportant advantages: 1. Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object. 2. The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code Any C++program where you implement a class with public and private members is anexample of data abstraction. e.g.

#include<iostream> usingnamespace std; classAdder{ public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; intmain( ) { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " <<a.getTotal() <<endl; return 0;

} (b)Encapsulation:All C++ programs are composed of following two fundamental elements: 1. Programstatements (code): This is the part of a program that performs actions andthey are called functions.

2. Programdata: The data is the information of the program which affected by theprogram functions. Encapsulation is an Object Oriented Programming concept that binds togetherthe data and functions that manipulate the data, and that keeps both safe fromoutside interference and misuse. Data encapsulation led to the important OOPconcept of data hiding. Data encapsulation is a mechanism of bundling the data, and thefunctions that use them and data abstraction is a mechanism of exposingonly the interfaces and hiding the implementation details from the user. C++ supports the properties of encapsulation and data hiding through thecreation of user-defined types, called classes. e.g. #include<iostream> usingnamespace std; classAdder{ public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; intmain( ) { Adder a; a.addNum(10);

a.addNum(20); a.addNum(30); cout << "Total " <<a.getTotal() <<endl; return 0; }

(c)Function Overloading You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You can not overload function declarations that differ only by return type. In function overloading name of the function must be equal and signature part of the function must be different. #include <iostream> using namespace std; class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } void print(char* c) { cout << "Printing character: " << c << endl; } }; int main(void) { printData pd; // Call print to print integer pd.print(5); // Call print to print float pd.print(500.263);

// Call print to print character pd.print("Hello C++"); return 0; } (c) How is the working of member function different from friend function and a non member function? AnsA friend function is not a member of a class. But it can access the private data members of the class like a member function of the class. It is possible to declare a function as friend in any number of classes. A member function is the one which is defined inside a class and is a member of the class. It may either be a public private or protected function. On other hand we use friend function in the case when we want to one class to communicate with other class. for this we need to declare that friend function in both the classes and define that friend function outside the associated classes. The friend function is always cabable to access all the members of the associated classes. We explicitly use 'friend' keyword to define a friend function. A friendfunction is just like a normal function but it is not a member of a class, so its calling is like a simple function. It is not accessible by the object. Object and class name as parameter of friend function. e.g. #include<iostream.> #include<conio.h> Class one { Int data1; Public Void setdata(int a) {

Data1=a; } Friend intadd_both(one x, two y); }x;

Class two { Int data2; Public: Void setdata(intb) { Data2=b; } Friend intadd_both(one x,two y); }y; Intadd_both(one x, two y) { Returnx.data1+y.data2; } Void main() { x.setdata(12); y.setdata(23);

cout<<sumof one and two <<add_both(x,y); }

Question3: (a)What is a pure virtual function ? Explain use of pure virtual function with anexample. AnsA virtual function with empty body is known as pure virtual function. Syntax:Virtual void get()=0; Or Virtualvoid get() { } In other way we define pure function in this way Pure virtual function :1. Pure virtual function have no function body. 2. Overloading is must in pure virtual funciton. (Must) 3. It is define as : virtual int myfunction() = 0; 4. A class is "abstract class" when it has at least one pure virtual function. 5. You cann't create instance of "abstract class", rather you have to inherit the "abstract class" and overload all pure virtual function. class alpha { public:virtual void show()=0; //pure virtual function }; class beta:public alpha { public:void show() //overriding

{ cout<<"OOP in C++"; } }; void main() { alpha *p; beta b; p=&b; p->show(); } Output: OOP in C++

(b) What are the advantages and disadvantages of inline functions? Explain with an example.

Ans:-When we define a function, normally thecompiler creates just one set of instruction in memory. If we call thefunction, execution of the program jumps to those instruction and when thefunction returns,execution jumps back to the next line in the calling function.If we call the function10 times, our program jump to the same set ofinstruction each time. This means there is only one copy of the function not10. There is some performance overhead in jumping in and out of functions. If a function is declared with the keyword inline, the compiler does not create areal function. It copies the code from the inline function directly into thecalling location , no jump is made and execution of programs is faster. Include<iostream.h> Inline intget(int); Int main() { Int a; Cout<<entera number; Cin>>a; A=get(a); Cout<<a;

Return 0; } Int get(inta) { Return 2*a; }

(c)Explain the meaning of polymorphism. Describe how polymorphism is accomplished in C++ taking a suitable example? Ans:- Theword polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related byinheritance. C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. e.g. #include<iostream> usingnamespace std; classShape { protected: int width, height; public: Shape( int a=0, int b=0) { width = a; height = b; } int area() { cout << "Parent class area:" <<endl; return 0; } }; classRectangle: public Shape{ public:

Rectangle( int a=0, int b=0) { Shape(a, b); } int area () { cout << "Rectangle classarea :" <<endl; return (width * height); } }; classTriangle: public Shape{ public: Triangle( int a=0, int b=0) { Shape(a, b); } int area () { cout << "Rectangle class area:" <<endl; return (width * height / 2); } }; //Main function for the program intmain( ) { Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); // store the address of Rectangle shape = &rec; // call rectangle area. shape->area(); // store the address of Triangle shape = &tri; // call triangle area. shape->area(); return 0; }

Question 4 :

(a)Explain thefollowing functions (with example) for manipulating file pointers, with thehelp of example program: (8 Marks) seekg() seekp() tellg() tellp() Ans:Seekg():SeekgStands for seek get. This function is used to seek and get the position fromwhere the next data of the file is to be read.
The syntax of this function is:

object.seekg(pos);
Where pos represents the position from where thenext data of the file is to be read. To seek the pointer position relative to the beginning of file ,you can write this.

object.seekg(pos , ios::beg);
Similary you can also write this to seek the position of the cursor relatedto your position as.

object.seekg(pos, ios::cur);
And you can also write this to seek the pointer from that point to the endof file.

object.seekg(pos, ios::end);
e.g. void main() { records rec; char op,cc[5]; long int rn=0,t=0;

ifstreamrrr(employee.dat,ios::binary); cout<<enter Code: ; cin>>cc; while(rrr.read((char*)&rec,sizeof(rec))) { if(strcmp(cc,rec.code)==0) { rn=(rn-1)*sizeof(rec); rrr.seekg(rn); cout<<rec.code<<\t<<rec.name<<\t<<rec.address<<endl; rrr.close(); t=1; } rn++; } if(t==0) { cout<<Record not found ; } }

seekp():The Seekp stands forseek put. This function is used to seek


and put the file pointer position fromwhere the data in the file is to be updated.

The syntax is:

Object.seekp(pos);
To put the file pointer position relative to the begining of file you canwrite this.

object.seekp(pos,ios::beg);
To put the file pointer position relative to the cursor of file you canwrite this.

object.seekp(pos,ios::cur);
To put the file pointer position relative to the end of file you can writethis.

object.seekp(pos,ios::end);

tellg():Reports the currentread position in the stream.


Syntax:pos_type tellg( ); include <iostream> #include <fstream> int main() { using namespace std; ifstream file; char c; streamoff i; file.open("basic_istream_tellg.txt"); i = file.tellg(); file >> c; cout << c << " " << i << endl; i = file.tellg(); file >> c; cout << c << " " << i << endl; }

tellp() : Reportposition in output stream.

Syntax:
pos_type ofstream::tellp();

The tellp() function is used with output streams, and returns the currentput position of the pointer in the stream. For example, the following codedisplays the file pointer as it writes to a stream:
string s("In Xanadu did Kubla Khan..."); ofstream fout("output.txt"); for( int i=0; i < s.length(); i++ ) { cout << "File pointer: " << fout.tellp(); fout.put( s[i] ); cout << " " << s[i] << endl; } fout.close();

(b) What is an exception? Explain how exceptions are handled in C++, with the help of an example program. Ans : An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions providea way to transfer control from one part of a program to another. C++ exceptionhandling is built upon three keywords: try, catch, and throw. 1. throw: A program throws anexception when a problem shows up. This is done using a throw keyword. 2. catch: A program catches anexception with an exception handler at the place in a program where you want tohandle the problem. The catch keyword indicates the catching of anexception. 3. try: A try blockidentifies a block of code for which particular exceptions will be activated.It's followed by one or more catch blocks. #include<iostream> usingnamespace std; doubledivision(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; }

return (a/b); } intmain () { int x = 50; int y = 0; double z = 0; try { z = division(x, y); cout << z << endl; }catch (const char* msg) { cerr << msg << endl; } return 0; } Question5: (a ) Write appropriatestatements to create a template class for Queue data structure in C++. Ans: #include<iostream.h> #include<stdio.h> #defineTRUE true #defineFALSE false #defineNULL 0 template<class Type> class Node { public: Type type;

Node(const Type& type,Node<Type>*previous,Node<Type>* next)

{ this->type=type; this->previous=previous; this->next=next; } Node<Type>*previous; 028.Node<Type>*next; };

// theclass with the template. template<class Type> class Queue { public: Queue(); Type&font(); const Type&front() const; void push(const Type&);//add element to back of Queue void pop(); //remove element from head of queue. boolempty() const; // true if no elements in the Queue. private: Node<Type>* first; Node<Type>* last; }; // endclass Queue.

//implements the methods in the class Queue template<class Type> Queue<Type>::Queue() { first=NULL; last=NULL; }

template<class Type> const Type&Queue<Type>::front() const { // we arenot going to check for the //exceptional conditions that can be arise in this code. return last->type; }

template<class Type> void Queue<Type>::push(const Type&type) { if(first==NULL) { // create anew node

Node<Type>* new_node =new Node<Type>(type,NULL,NULL); first=new_node; last=new_node; return; } else{ Node<Type>*new_node=new Node<Type>(type,NULL,first); first->previous=new_node; first=new_node; return; } }

template<class Type> void Queue<Type>::pop() { if(last==NULL) return ; else { Node<Type>* tmp_node=last; last=last->previous; delete tmp_node;

} }

template<class Type> boolQueue<Type>::empty() const { if(last==NULL) return TRUE; else return FALSE; }

// mainmethod int main(int argc,char**argv) { Queue<int>integer_queue; for(int i=0;i<100;i++) integer_queue.push(i);

// nowprint the array; for(int i=0;i<100;i++) { int front=integer_queue.front();

std::cout<<front; integer_queue.pop(); } return 0; }

(b) Explain any three features in C++ that can be used to display the outputs in a specified manner (formatted output). Ans:- The format of the output is controlled in two ways. The first is by adding directives to the output statement; these can control such things as the number of places of decimals printed for a floating-point value or the width of the field in which a value is displayed. The other technique involves setting various flags which control the ways in which values are displayed; this can be used, for example, to determine whether a decimal point is always displayed in a floating-point value and where within the field a value is justified.

If a program is displaying a set of floating-point values it is usual to ensure that all the values are displayed with the same number of decimal places. To set the precision (number of decimal places) used to output a floating-point number the directive setprecision is used:

const float PI = 3.1415; cout << setprecision (2) << PI << endl;

This will output:

3.14

If a floating-point number has fewer than two significant places of decimals these are not printed by default, so:

float number = 1.0; cout << setprecision (2) << number << endl; would display: 1

If these extra places are required, a flag can be set:

float one = 1.0; cout << setiosflags (ios::fixed) << setprecision (2) << one << endl; which will output: 1.00 rather than the default: 1

The width of the field in which a value is printed can be set using the setw directive. This can be useful for creating tables of data with columns neatly lined up.

string flossy = "Flossy"; cout << flossy << endl; // prints "Flossy" cout << setw (20) // sets field width to 20 << flossy << endl; // prints with trailing spaces

The values are normally aligned in the left of the field with spaces added to the end to make up the required column width. In some tables numeric values are required to be aligned to the right of the field, and this is in fact the default. This default can be changed by setting another flag. This statement will display the value right-justified in a field 10 characters wide:

const int Hundred = 100; cout << setw (10) << Hundred << endl;

To change to left justification a flag must be set:

cout << setiosflags (ios::left) << setw (10) << Hundred << endl;

and to change back to right justification the flag is unset:

cout << resetiosflags (ios::left) << setw (10) << Hundred << endl;

---------------------------------- THE END ----------------------------------------

You might also like