0% found this document useful (0 votes)
96 views

BCS-031 (2022-23) Solved Assignment

BCS-031 (2022-23) Solved Assignment

Uploaded by

Jone Deo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
96 views

BCS-031 (2022-23) Solved Assignment

BCS-031 (2022-23) Solved Assignment

Uploaded by

Jone Deo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 24
55's Tou STUDY HELPER mee Ey inl ane Course Title : Programming in c++ ‘Assignment Number : BCA(3)031/Assignment/2022-23 Maximum Marks : 100 Weightage : 25% wwnw-ignousite.com Last Date of Submission : 31st October, 2022 (for July 2022 sessioafen = o 215th April, 2023 (for January 2023 sessionf™™" ‘Question 1: (a) What is Object Oriented Programming (OOP) approach? Explain features of OOP. Ans, Object-oriented programming As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main ait of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function Polymorphism | Inheritance OOPs Avmacton | OOPS, | ncapeulaion (cass [object P fet oe Features of OOP: 1. Inheritance: In layman's terms, the attributes that you inherit from your parents are a simple illustration of inheritance, Classes may inherit characteristics from other classes thanks to inheritance. Parent classes, in other words, extend properties and behaviors to child classes. Reusability is aided via inheritance. Prototyping is another name for inheritance in JavaScript. & prototype object serves as a base from which another object may derive its features and actions, Thus, you may use multiple prototype object templates to form a prototype chain, Inheritance is passed down from one generation to the next. parent 2. Encapsulation: Encapsulation is the process of enclosing all critical information inside an object and only revealing a subset of {to the outside worid, For example, code inside the class template detines attributes and benaviors. The data and methods are then enclosed in the object when itis created from the class. Inside a class, encapsulation conceals the underlying software code implementation and the internal data of the objects. Encapsulation necessitates designating certain fields as private while others are made public. 3. Abstraction: Abstraction refers to the user's ‘teraction with just a subset of an object's characteristics and operations. To access a complicated item, abstraction uses simpler, high-level techniques. Ignou Study Helper-Sunil Poonia Page 1 4: Tend Stun HELPER www ignousite.com Bt Sumit Poomls 4 Polymorphism: Polymorphism refers to the cretion of tems that have similar behavior. FoF @xample, objets may override common parent behaviors with particular child behaviors through inheritance. Method overriding and method overloading are ‘two ways that polymorphism enables the same method to perform various actions, 5, Objects: An object isa self-contained segment with the attributes and processes needed to make data usable in programming, terms. From an object-oriented perspective, objects are the main building pieces of programs. In each application you create, you may employ 2 variety of objects of various sorts, Each kind of abject is derived from a specific class of that type. Consider an object to be a sculpt of the real-world perceptions, processes, or objects that are important to the application you're designing, 6, Classes: In the oops concept, a class isa construct that is used to deseribe an individual type. The class is instantiated into instances of itself-referred to as class instances or simply objects. A class defines ingredient members that allow its instances to have position and behavior. Member variables or instance variables facilitate a class instance to maintain its position. On the other hand, other kinds off members, especially methods, allow the behavior of class instances. Simply classes consequently define the type oftheir instances. A class usually represents a person, place or thing, or something 0 (b) Briefly explain different operators of C++. A 3 ‘Ans. C++ has many built-in operator types and they are classified as follows: 1. Arithmetic Operators: These are the operators used to perform arithmetic/mathematical operations on operands Examples: (+, >, *, /,%/++.-). Arithmetic operator are of two types: ‘+ Unary Operators: Operators that operates or works with a single operand are unary operators. For example: (++ '* Binary Operators: Operators that operates or works with two operands are binary operators. For example: (+, ~,*, /) 2. Relational Operators: These are Used for comparison of the values of two operands. For example, checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not etc. Some of the relational operators are ¢ ) 3. Lugital Operators: Lugital Operators ore used to Combine two Ur more cunulitions/iuristiaiits OF tu Complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a boolean value either true or false. For example, the logical AND represented as '&&’ operator in C or C++ returns true when both the conditions under consideration are satisfied, Othetwise it returns false. Therefore, a && b returns true when both a and b are true (i. non- zero). 4, Bitwise Operators: The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. The mathematical operations such as addition, subtraction, multiplication etc. can be performed at bit-level for faster processing. For example, the bitwise AND represented ‘as & operator in C or C++ takes two numbers as operands and does AND on every bit of two numbers, The result of AND is 1 only if hoth bits are 1 5, Assignment Operators: Assignment operators are used to assign value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of variable on the left side otherwise the compiler will raise an error. 6. Other Operators: Apart from the above operators there are some other operators available in C or C++ used to perform some specific task. Some of them are discussed here: Ignou Study Helper-Sunil Poonia Page 2 itis fay) Tonav Stuy HELPER www.ignousite.com =F SUNIL POONIA (2) sizeot operator: sizeof a much used in the C/C++ programming language. itis a compile tte unary operator which can be used to compute the size of its operand, The result of sizeof is of unsigned integral type which is usually denoted by size_t, Basically, sizeof operator is used to compute the size of the variable. (b) Comma Operator: The comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest. precedence of any C operator. Comma acts as both operator and separator. {c) Conditional Operator: Conditional operator is of the form Expression ? Expression? : Expression3 . Here, Expression1 is the condition to be evaluated. If the condition(Expression’) is True then we will execute and return the result of Expression? otherwise ifthe condition(Expressiont) is false then we will execute and return the result of Expression3. We may replace the use of felse statements by conditional operators, yey ey (€) Explain use of followings in C+ programming, with an example program for each. fa) (b) for loop @ ‘Ans, (a) :: The scope resolution operator is the highest precedence operator in the C++ language. The scope resolution operator mainly identifies and opceifics the context to which on identifier refcrs. Example: 1] C+ program to show that we can access a global variable // using scope resolution operator :: when there'is aocal Ji variable with same name Hincludeciostream> using namespace sta; int x; // Global x int main() { int x= 10; // Local x cout << "Value of global x is" <<:2x; cout using namespace std; int main forlint it; ico6; i+) /* This statement would be executed * repeatedly until the condition “ is=6 returns false. “a coutce*Value of variable iis: "cciccendl; } return 0; ) Output: Value of variable jis: 1 Value of variable tis: 2 Value of variable is: 3 Value of variable ii: 4 Value of variable i is: S Value of variable i is: 6 Sum Pooma (c)?: The conditional operator evaluates an expression, returning one value if that expression evaluates to true, and a different une if the expression evaluates as false. Example: // conditional operator include using namespace std; int main () c= (arb) ?a:b; cout <<¢<< \n'; } Ignou Study Helper-Sunil Poonia Page 4 www.ignousite.com Q2, (a) Write a C++ program to add two matrices. Ans, // C+ program to find add of two matrices #include using namespace std; int main() int rows, cols, i,j int one[50)[50], two[50][50}, sum[50][50]; cout <<"'Enter Rows and Columns of Matrix\n"; Se Touov Stvoy HeLPee Sum Pooma ins rou cil cout > twoli]lil; } t {* adding corresponding elements of both matrices, sum{i){j] = one(i}{j] + twofi)fi] */ forli = 0; i< rows; itt furl 0, j eos, Feri sumfil{j] = onefi]fj] + twolilfi]; } } cout <<" um Matrie\n"; Forli = 0; 1< rows; i++) for()~0; j using namespace std; class Shape { public: virtual int Area() = 0; // Pure virtual function is declared as follows. // Function to set width, void setwidthint w) { width = wi } // Function to set height. void setHeight{int h) { height } protected int width; int height; 8 /nrectangle isa shape; itnherts shape. fy eit class Rectangle: public Shape { Kerns public: —_ Ignou Study Helper-Sunil Poonia Page 6 www.ignousite.com eS Sum Pooma 1/ The implementation for Area Is specific to a rectangle. int Areal) { return (width * height}; } k 1/ Attiangle isa shape too; it inherits shape. class Triangle: public Shape ( public: // Triangle uses the same Area function but implements it to // return the area of a triangle. int Areal) { return (width * height)/2; } int main() { Rectangle R; Triangle Ts Rsetwidth(S); RsetHeight(10); T.setwidth(20}; T.setHeight(8); cout << "The area of the rectangle is: " << R.Areal) << endl; cout << "The area of the triangle is: "<< T.Area() < using namespace std; class Base { int x3 public: // default constructor Ignou Study Helper-Sunil Poonia Page 7 www.ignousite.com eS Sum Pooma Base() { cout << "Base default constructor\n"; : ‘eh ey class Derived : public Base { inty; public: // default constructor Derived() { cout << "Derived default constructor\a"; } // parameterized constructor Derivedtint i) { cout << "Derived parameterized constructor\n"; } i int main() { Base b; Derived di; Derived u2(10), } Output: Base default constructor Base default constructor Derived default constructor Base default constructor Derived parameterized constructor (©) Write a C++ program to explain how an object can be passed as a parameter to a function. Ans. aruoy. veces, {EE class A( Send Ignou Study Helper-Sunil Poonia Page 8 www.ignousite.com eS Sum Pooma char ch ='A'; {/ function that has objects as parameters void display(A &a) { cout << "Age =" << a.age < numbers = (1, 100, 10, 70, 100}; H print the set ‘cout << "Numbers are: *; for{auto &num: numbers) { cout using namespace std; // base class class Parent { public: // ase class constructor Parent() ( Ignou Study Helper-Sunil Poonia Page 12 www.ignousite.com cout << "inside base class” << endl; fet Touov Stvoy HeLPee Sum Pooma % H/ sub class, class Child : public Parent ‘ ‘et publi 2 one Afsub class constructor Child) { cout << "Inside sub class" << endl; 1 main function int main() { If creating object of sub class Child obj; return 0; Output: Inside base class Inside sub class (c) What is operator overloading in C++? Explain use of operator overloading with the help of a program to add two real numbers. ‘Ans. Operator overloading: In C++, we can make operators work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator ‘ina class like String so that we can concatenate two strings by just using +. Other example classes where arithmetic operators may be overloaded are Complex Numbers, Fractional Numbers, Big Integer, etc Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C+ without changing its original meaning Example of add two real numbers: Hincludeciostream> using namespace std; fe as class Complex { Soe private: Ignou Study Helper-Sunil Poonia Page 13 www. ignousite.com eS Sum Pooma int real, imag; public: Complentint r= 0, int i= 0) real =r: imag = ik //Thisis cutomaticaly called when "sis used with 1/ between two Complex objects Complex operator + (Complex const obj) { Complex res; resreal= real + obj-real; res.imag = imag + obj imag; return res; } void print) {cout sr00y comment get class ignoustudyhelper “Serre { oe I/ Access specifier public: 1/ Data Members string ignoustudyhelpername; 1/ Member Functions|} void printname() { cout << *ignoustudyhelpemame is: " << ignoustudyhelpername; } ‘ int main() { 1/ Declare an object of class ignoustudyhelper ignoustudyhelper obj1; I accessing data member obj1. ignoustudyhelpername = "Sunil" I accessing member function obj1.printnamel); return 0; + Output: ignoustudyhelpername is: Sunil Ui, Virtual Function © ACt+ virtual function is a member function in the base class that you redefine in @ derived class. itis declared using the Virtual keyword, + [tis used to tell the compiler to perform dynar © There isanece: linkage or late binding on the function. to use the single pointer to refer to all the objects of the different classes. So, we create the pointer to the base class that refers to all the derived objects. But, when base class pointer contains the address of the derived class object, always executes the base class function, This issue can only be resolved by using the ‘virtual’ function. ‘© A'Virtual’is a keyword preceding the normal declaration of a function. ‘* When the function is made virtual, C++ determines which function is to be invoked at the runtime based on the type of the object pointed by the base class pointer. Ignou Study Helper-Sunil Poonia Page 15 www. ignousite.com eS Sum Pooma Example: #include using namespace s class A { int x5; 099, e, uo fey void display’) “femme i of ste } i class B: public A { out << "Value of xis :" << xdisplavll: return 0; } soy output fgets Value of xis:5 “femson ~/ jend function: If a function is defined as a friend function in C++, then the protected and private data of class can be accessed using the function. By Using the keyword friend compiler knows the given function is a friend function. For accessing the data, the declaration of a friend function should be done inside the body of a ¢lass starting with the keyword friend. Example: finelude Using namespace sta; class Box { private int length; publ Ignou Study Helper-Sunil Poonia Page 16 Touau Styoy HELPER www.ignousite.com Sum Pooma Box(): length(0) {} friend int printLength(Box); //friend function b int printLength(Box b) { bilength += 10; return b.length; } sv *, int main() fe { a? Box b; Nae cout<"Length of box: “<< printlength(b)< using namespace std: class student { int mor char name(10]; double fee; public: student() ( cout << "Enter the RoliNo:"; cin >> mo} cout << "Enter the Name:"; cin >> name; cout <<"Enter the Fee: cin >> fee; void dispiay() Ignou Study Helper-Sunil Poonia Page 17 www.ignousite.com { fet Touov Stvoy HeLPee Sum Pooma cout <« endl << mo <<"\t" << name <<"\t" << fee; k int main() { student s; // constructor gets called automatically when // we create the object of the class spat return 0; sruoy, ; fe ‘ey ou: = Enter the RollNo:Enter the NamezEnter the Fee: © 6.953036 310 (b) What is template? Write appropriate statements to create a template class for Queue data Structure in C++. ‘Ans. A template is a simple and yet very powerful tool in C+. The simple idea is to pass data type as a parameter so that we don't need to write the same code for differenit data types. For example, a software company may need sort) for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as @ parameter. CH adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’. Create a template class for Queue data structure: Hinelude #include using namespace std; Ii define default capacity of the queue define SIZE 10 // Class for queue template class queue t Xan: /farray to store queue elements int capacity; // maximum capacity of the queue int front; /{ front points to front element in the queue (if any] int rear; // rear points to last element in the queue _, ser int count; /{ current size of the queue ‘et Sort f/ constructor Ignou Study Helper-Sunil Poonia Page 18 www. ignousite.com eS Sum Pooma Void dequeue(); Void enqueue (x x); Xpeekt); int size(); bool isEmpty(); bool isFull(); // Constructor to initialize queue template quevesX>:;queue{int size) { arr = new X[size]; capacity = size; front =| rear=-4; count =0; ) // Utility function to remove front element from the queue template void queue::dequeue() { 1 check for queue underflow if (smpty()) : out SS "UnnderFlaw\nProgiain Tes eit(EXIT_FAILURE); roteu\n", cout << "Removing " void queue::enqueue(X item) { Jf check for queue overflow: if (sFUlIQ) { cout <<" OverFlow\nProgram Terminated\n"; cexit(EXIT_FAILURE); Ignou Study Helper-Sunil Poonia Page 19 www. ignousite.com eS Sum Pooma } cout <<" Inserting " << item <<"\ sur fo rear = (rear+1) % capacity; arrlrear] = item; count++; // Utility function to return front element in the queue template X queuesX>::peek() { if isEmpty()) { cout <<"UnderFlow\nProgram Terminated\n" cenit(EXIT_FAILURE); } return artffront]; } // Utility function to return the size of the queue template int queue::size() { return count; // Utility function to check if the queue is empty or nat template bool queve:isEmpty() { return (size() // Utility function to check if the queue is full or not template baal quieueeX>~isFull) { return (size() == capacity); } int main() { I/create a queue of capacity 4 queue a(4): Ignou Study Helper-Sunil Poonia Page 20 www. ignousite.com eS Sum Pooma q.enquevet"s"); q.enqueve("b"); g.enqueue("c"); cout << "Front element is:" << q.peek|) << endl; qdequeve(); cena, (EY cout << "Queue size is" << q,size() << endl; gdequevel); gdequevel); qdequeue(); if (isEmpty) cout << "Queue Is Empty\n"; else cout << "Queue Is Not Empty\n"; return 0; } Output: Inserting a Inserting b Inserting € Front eleneritis. Removing a Inserting d Queue size is3 Removing Removing c Removing d feh Queue semery Fe 5. (a) What is exception? What is need of exceptions handling in C++? Write program to handle arithmetic as exception in C+. Make necessary assumptions ‘Ans. An exception isa problem that arises during the execution of a program. A C++ exception is a response to an exceptional circurnstance that arises while a program is runing, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw. ‘© throw ~ A program throws an exception when a problem shows up. This is done using a throw keyword. ‘© catch ~ A program catches an exception with an exception handler at the place in @ program where you want to handle the problem. The catch keyword indicates the catching of an exception. Ignou Study Helper-Sunil Poonia Page 21 13 TOHu STvoY HeLPee www. ignousite.com Sumit Pooma ‘© try-Atry block identifies a block af code for which particular exceptions will be activated. It's followed by one or more catch blocks. Program: finclude using namespace sta; int main), #0 { my 1/ Some code cout << "Before try \n"; try cout <<" inside try \n"; if <0} { throw x: cout << “After throw (Never executed) \n*; t } catch (int) { cout <« "Exception Caught \o"; cout <"After catch (Will be executed) \n"; return 0; a Output: Before try Inside try Exception Caught After catch (Will be executed) (b) What is function overriding? Write @ C+ program to explain concept of function overriding. ‘Ans. Function overloading is a feature of object oriented programming where two 6r moré functions can have the same name but different parameters. When a function name is overloaded with different jobs itis called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading can be considered as an example of polymorphism feature in C++ Program: Using namespace s Ne Ignou Study Helper-Sunil Poonia Page 22 www. ignousite.com eS Sum Pooma void print{int i) { cout <<" Here is int" < using namespace st int main() { cout << "Example for formatted 10" << endl; cout << "Default: " << endl; rout << 123 << endl cout << "width(5):" << endl; cout.width(5); cout << 123 << endl; cout << "width(S) and fill cout.width(5); cout.fill’*'); Ignou Study Helper-Sunil Poonia Page 23 fey Tonou Sy HeLPee www.ignousite.com Nat Sumie Rooms cout << 123 <« endl; cout.precision(5); cout <<" precision(5) >" << 123,4567890 << endl; cout << "precision(5) >" << 9.876543210 << endl; cout << "setf(showpos): " << endl; cout.setflios:-showpos); cout << 123 << endl; cout <<"unsetf(showpos): " << endl; cout.unsetflios:'showpos); cout << 123 << endl; return 0; mill (ee Ignou Study Helper-Sunil Poonia Page 24

You might also like