0% found this document useful (0 votes)
17 views45 pages

BCS031

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

BCS031

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

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
aim 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.

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. A
prototype abject serves as a base from which another object may derive its features and actions.
Thus, you may use multiple prototype abject 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 eritical information inside an object
and only revealing a subset of it to the outside world. For example, code inside the class template
defines attributes and behaviors. The data and methods are then enclosed in the object when it is
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 interaction with just a subset of an object's
characteristics and operations. To access a complicated item, abstraction uses simpler, high-level
technigues.

4. Polymorphism: Polymorphism refers to the creation of items that have similar behavior, For
example, objects 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 is a 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 a variety of objects of
various sorts, Each kind of object 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 is a construct that is used to describe 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 of members, especially methods, allow the behavior of class instances.
Simply classes consequently

define the type of their instances. A class usually represents a person, place or thing, or something.

(b) Briefly explain different operators of C++.

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. Logical Operators: Logical Operators are used to combine two or more conditions/constraints or to
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. Otherwise it returns false. Therefore, a &8& b returns true when
both a and b are true (i.e. non-

zero).

4. Bitwise Operators: The Bitwise operators is used to perform bit-leve| 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 both 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:


(a) sizeof operator: sizeof is a much used in the C/C++ programming language. ltisa compile time
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 Expressionl ? Expression2 : Expression3
. Here, Expression is the

condition to be evaluated. If the condition(Expressionl) is True then we will execute and return the
result of Expression2

otherwise if the condition(Expressionl) is false then we will EE and return the result of Expression3.
We may replace the

use of if..else statements by conditional operators.

(c) Explain use of followings in C++ programming, with EY program for each.

(a) ::

(b) for loop

(c) 2:

Ans. (a) :: The scope resolution operator is the highest precedence operator in the C++ language. The
scope resolution operator

mainly identifies and specifies the context to which an identifier refers.

Example:

// C++ program to show that we can access a global variable

// using scope resolution operator i: when there is a local


// variable with same name

#include<iostream>

using namespace std;

int x; // Global x

int main()

intx=10; // Local x

cout << "Value of global x is " << x;

cout << "\nValue of local x is " << x;

return 0;

Output:

Value of global xis 0

Value of local x is 10

(b) for loop: This is a repetition control structure that helps us iterate over a section of C++ code for a
fixed number of times. A

for loop runs provided the test expression is true. The loop terminates execution immediately the
test expression becomes false.

This means before the execution of the loop body in each iteration, the condition has to be
evaluated. If the evaluation returns a
true, the loop body is executed. If the evaluation returns a false, execution of the loop body is
terminated.

Syntax of for loop

for(initialization; condition ; increment/decrement)

C++ statement(s);

Example:

#include <iostream>

using namespace std;

int main()}{

for(int i=1; i<=6; i++)

/* This statement would be executed

* repeatedly until the condition

* j<=6 returns false.

cout<<"Value of variable i is: "<<i<<end|;

}
return 0;

Output:

Value of variable i is: 1

Value of variable i is: 2

Value of variable i is: 3

Value of variable i is: 4

Value of variable i is: 5

Value of variable i is: 6

(c) ?: The conditional operator evaluates an expression, returning one value if that expression
evaluates to true, and a different

one if the expression evaluates as false.

Example:

// conditional operator

#include <iostream>

using namespace std;

int main ()

int a,b,c;

a=2; roy
c=(a>b)?a:b;

cout << c << '\n';

Q2. (a) Write a C++ program to add two matrices.

Ans.

// C++ program to find add of two matrices

#include <iostream>

using namespace std;

int main(}{

int rows, cols, i, |;

int one[50][50], two[50][50], sum[50][50];

cout <<"Enter Rows and Columns of Matrix\n";

cin >> rows >> cols;

cout <<"Enter first Matrix of size "<<rows<<" X "<<cols;

// Input first matrix*/

for(i = 0; i < rows; i++)}{

for{j= 0; j < cols; j++}

cin >> oneli](j];

// Input second matrix

cout <<"\nEnter second Matrix of size "<<rows<<" X "<<cols;

for(i = 0; i < rows; i++}

for(j=0; j < cols; j++){

cin >> two[i][j];

}
[* adding corresponding elements of both matrices

sum(i][j] = one[i] [i] + twoli][il */

for(i = 0; i < rows; i++){

for(j=0;j < cols; j++){

sum(i][j] = ene[i][j] + twalil [i];

cout <<"Sum Matrix\n";

for(i = 0; i < rows; i++){

for(j= 0; j < cols; j++}{

cout << sum(i][j] <<

ii fir

cout << "\n";

return 0;

Output:

Enter Rows and Columns of Matrix =1}

33

Enter first Matrix of size 3X 3

123

456

789

Enter second Matrix of size 3 X 3


987

654

321

Sum Matrix Erouait®

10 10 10

10 10 10

10 10 10

(b) Explain the following in detail, in context of C++ programming.

i. Abstract class

ii. Order of constructer calling in inheritance

Ans. i. Abstract class: An abstract class in C++ is a class that has at least one pure virtual function (i.e.,
a function that has no

definition). The classes inheriting the abstract class must provide a definition for the pure virtual
function; otherwise, the

subclass would become an abstract class itself.

Abstract classes are essential to providing an abstraction to the code to make it reusable and
extendable.

Example:

#include <iostream>

using namespace std;

class Shape {

public:

virtual int Area() = 0; // Pure virtual function is declared as follows.

// Function to set width.


void setWidth{int w) {

width = w;

// Function to set height.

void setHeight(int h) {

height = h;

protected:

int width;

int height;

// A rectangle is a shape; it inherits shape. fs

class Rectangle: public Shape {

public:

// The implementation for Area is specific to a rectangle.

int Area() {

return {width * height); Es

b “oo

// A triangle is a 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 Area) {

return (width * height)/2;

int main() {

Rectangle R;

Triangle T;

R.setWidth(5);

R.setHeight(10);

T.setWidth(20});

T.setHeight(8);

cout << "The area of the rectangle is: " << R.Area() << endl;

cout << "The area of the triangle is: " << T.Area() << endl;

Output:

The area of the rectangle is: 50

The area of the triangle is: 80

ii. Order of constructer calling in inheritance: When we derive a class from the base class then all the
data members of the base

class will become a member of the derived class. We use the constructor to initialize the data
members and here the obvious

case is when the data is inherited into the derived class who will be responsible to initialize them? To
initialize the inherited data
membres constructor is necessary and that's why the constructor of the base class is called first. In
the program given below, we

can see the sequence of execution of constructors in inheritance is given below:

example:

#include <iostream>

using namespace std;

class Base

int x;

// default constructor

Base()

cout << "Base default constructor\n";

1 STUDY

class Derived : public Base

inty;

public:

// default constructor
Derived()

cout << "Derived default constructor\n";

// parameterized constructar

Derived(int i)

cout << "Derived parameterized constructor\n";

int main()

Base b;

Derived di;

Derived d2(10};

Output:

Base default constructor

Base default constructor

Derived default constructor

Base default constructor


Derived parameterized constructor

(c) Write a C++ program to explain how an object can be passed as a parameter to a function.

Ans

#include <iostream>

using namespace std;

class A {

public:

int age = 20;

char ch = 'A'

// function that has objects as parameters

void display(A &a) {

cout << "Age =" << a.age << endl;

cout << "Character =" << a.ch << endl;

} fe =

int main() { J 2d

A obj;

obj.display(obj);

return 0;

Output

Age =20

Character = A
Q3. (a) What are containers? Explain any two container classes of C++.

Ans. A container is a holder object that stores a collection of other objects (its elements). They are
implemented as class

templates, which allows a great flexibility in the types supported as elements.

The container manages the storage space for its elements and provides member functions to access
them, either directly or

through iterators (reference objects with similar properties to pointers).

List any two container class:

s Sequence containers (array, vector, list)

* Associative containers (set, map, multimap)

Sequence containers: In C++, sequential containers allow us to store elements that can be accessed
in sequential order.

Internally, sequential containers are implemented as arrays or linked lists data structures.

Example:

#include <iostream>

ffinclude <vector>

using namespace std;

int main() {

// initialize a vector of int type

vector<int> numbers = {1, 100, 10, 70, 100};

/{ print the vector £, ib \


cout << "Numbers are: ";

for{auto &num: numbers) { i

cout << num <<","

return 0;

Output:

Numbers are: 1, 100, 10, 70, 100,

Associative containers: In C++, associative containers allow us to store elements in sorted order. The
order doesn’t depend upon

when the element is inserted. Internally, they are implemented as binary tree data structures.

Example:

#include <iostream>

#Hinclude <set>

using namespace std;

int main() {

// initialize a set of int type

set<int> numbers = {1, 100, 10, 70, 100};

// print the set

cout << "Numbers are: ";


for(auto &num: numbers) {

nom,

cout << num <<

return 0;

Output:

Numbers are: 1, 10, 70, 100,

(b) What is inheritance? What are different types of inheritance supported by C++? Explain
advantage of inheritance with the

help of a program.

Ans. Inheritance :- One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code functionality
and fast implementation time. When creating a class, instead of writing completely new data
members and member functions, the programmer can designate that the new class should inherit
the members of an existing class. This existing class is called the base class, and the new class is
referred to as the derived class.

Different types of inheritance:

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one
sub class is inherited by one base class only.

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more
than one classes. i.e one sub class is inherited from more than one base classes.
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived
class.

4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a
single base class. i.e. more than one derived class is created from a single base class.
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type
of inheritance. For

example: Combining Hierarchical inheritance and Multiple Inheritance.

Below image shows the combination of hierarchical and multiple inheritance:

Advantages of inheritance:

* [nheritance promotes reusability. When a class inherits or derives another class, it can access all
the functionality of

inherited class.

s Reusability enhanced reliability. The base class code will be already tested and debugged.

* As the existing code is reused, it leads to less development and maintenance costs.

* Inheritance makes the sub classes follow a standard interface.

* [nheritance helps to reduce code redundancy and supports code extensibility.

* Inheritance facilitates creation of class libraries.


Example program:

// C++ program to show the order of constructor call

// in single inheritance

#include <iostream>

using namespace std;

// base class

class Parent

public:

// base class constructor

Parent()

cout << "Inside base class" << endl;

// sub class

class Child : public Parent

= =a

public:

as)

//sub class constructor


Child()

cout << "Inside sub class" << endl;

J/ main function

int main() {

// 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 ‘+ in a 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:

#include<jostream>
using namespace std; £, ChE \

=K

class Complex {

private:

int real, imag;

public:

Complex{intr=0, inti=0) {real =r; imag =i;}

// This is automatically called when '+' is used with

// between two Complex objects

Complex operator + (Complex const &obj) {

Complex res;

res.real = real + obj.real;

res.imag = imag + obj.imag;

return res;

void print() { cout << real <<" +i" << imag << '\n"; }

kb

int main()

Complex c1(10, 5), c2(2, 4);

Complex c3 =cl + c2;

c3.print{);

Output:

12 + i9

Q4. (a) Explain the following in detail with the help of examples, in context of C++ programming

i. Object and Class oe


ii. Virtual Function

iii. Friend function

iv. Constructors ged

Ans. i. Object and Class: An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is

instantiated (i.e. an object is created) memory is allocated.

Class: A class in C++ is the building block that leads to Object-Oriented programming. It is a user-
defined data type, which holds

its own data members and member functions, which can be accessed and used by creating an
instance of that class. A C++ class

is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different names and brand but
all of them will share some

commaon properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car
is the class and wheels,

speed limits, mileage are their properties.

* A (Classis a user defined data-type which has data members and member functions.

* Data members are the data variables and member functions are the functions used to manipulate
these variables and

together these data members and member functions defines the properties and behavior of the
objects in a Class.

* Inthe above example of class Car, the data member will be speed limit, mileage etc and member
functions can be apply

brakes, increase speed etc.

Example:

// C++ program to demonstrate

// accessing of data members


#include <bits/stdc++.h> wtuoy

using namespace std;

class

// Access specifier

public:

// Data Members

string ignoustudyhelpername;

// Member Functions()

void printname()

cout << "ignoustudyhelpername is: " << ignoustudyhelpername;

int main() {

// Declare an object of class ignoustudyhelper

ignoustudyhelper objl;

// accessing data member

objl. ignoustudyhelpername = "Sunil":


/{ accessing member function

objl.printname();

return 0;

Output;

ignoustudyhelpername is: Sunil

ii. Virtual Function

* A C++ virtual function is a member function in the base class that you redefine in a derived class. It
is declared using the

virtual keyword.

* It is used to tell the compiler to perform dynamic linkage or late binding on the function.

* There is a necessity 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.

Example:

#include <iostream>

using namespace std;

class A
{

int x=5;

public:

void display()

std::cout << "Value of x is : " << x<<std::endl;

class B: public A

inty = 10;

public:

void display()

std::cout << "Value of y is ; " <<y<< stdi:endl;

ki

int main()

A *a;

Bb;

a=8&b;

a->displayl();

return 0;

Output:

Value of xis: 5 Wm
iii. Friend function: If a function is defined as a friend function in C++, then the protected and private
data of a 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 class
starting with the keyword

friend.

Example:

#include <iostream>

using namespace std;

class Box

private:

int length;

public:

Box(): length{0) { }

friend int printLength(Box); //friend function

int printLength(Box b)

b.length += 10;

return b.length;

int main()

Box b; Am pal 4

cout<<"Length of box: "<< printLength(b)<<endl;


return 0;

Output:

Length of box : 0

iv. Constructors: Constructor in C++ is a special method that is invoked automatically at the time of
object creation. It is used to

initialize the data members of new objects generally. The constructor in C++ has the same name as
the class or

structure, Constructor is invoked at the time of object creation. It constructs the values i.e, provides
data for the object which is

why it is known as constructors.

Constructor does not have a return value, hence they do not have a return type.

Example:

// defining the constructor within the class

#include <iostream>

using namespace std;

class student {

int rno;

char name[10];

double fee;

public:
student()

cout << "Enter the RollNo:";

cin >> rno;

cout << "Enter the Name:";

cin >> name;

cout << "Enter the Fee:";

cin >> fee:

void display()

cout << endl << ro << "\t" << name << "\t" << fee;

int main()

student s; // constructor gets called automatically when

// we create the object of the class

s.display();

return 0;

Output:

Enter the RollNo:Enter the Name:Enter the Fee:

0 6.95303e-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 different 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 a parameter. ++ 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:

#include <iostream>

#include <cstdlib>

using namespace std;

// define default capacity of the queue

#define SIZE 10

// Class for queue

template <class X>

class queue

X *arr; // array 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

int count; // current size of the queue

public:

queue(int size = SIZE); //constructor


void dequeue();

void enqueue(X x);

X peek();

int size();

bool isEmpty};

bool isFull();

// Constructor to initialize queue

template <class X>

queue<X>::queue(int size)

arr = new X[size];

capacity = size;

front =0;

rear =-1;

count =0;

// Utility function to remove front element from the queue

template <class X>

void queue<X>::dequeue()

/f check for queue underflow

if (isEmpty(})

{
cout << "UnderFlow\nProgram Terminated\n";

exit(EXIT_FAILURE);

cout << "Removing " << arr[front] << '\n";

front = (front + 1) % capacity;

count--;

// Utility function to add an item to the queue

template <class X>

void queue<X>:enqueue(X item)

// check for queue overflow

if (isFull())

cout << "OverFlow\nProgram Terminated\n";

exit(EXIT_FAILURE);

cout << "Inserting " << item << '\n';

rear = (rear + 1) % capacity; £ a

arr[rear] = item;

count++; Wome fl

// Utility function to return front element in the queue


template <class X>

X queue<X>::peek()

if (isEmpty())

cout << "UnderFlow\nProgram Terminated\n";

exit(EXIT_FAILURE);

return arr{front];

// Utility function to return the size of the queue

template <class X>

int queue<X>:size()

return count;

// Utility function to check if the queue is empty or not

template <class X>

bool queue<X>::isEmpty()

return (size() == 0);

// Utility function to check if the queue is full or not

template <class X>

bool queue<X>::isFull()

{
return (size() == capacity);

int main()

// create a queue of capacity 4

queue<string> qi4);

g.enqueue("a");

q.enqueue("b");

g.enqueue("c");

cout << "Front element is: " << g.peek() << endl;

g.dequeue();

q.enqueue("d"); (=)

nf

cout << "Queue size is " << q.size() << endl;

g.dequeue();

g.dequeue();

g.dequeue();

if (g.isEmptyl))

cout << "Queue Is Empty\n";

else

cout << "Queue Is Not Empty\n";

return 0;

}
Output:

Inserting a

Inserting b

Inserting c

Front element is: a

Removing a

Inserting d

Queue size is 3

Removing b

Remaving c

Removing d

Queue Is Empty

Q5. (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 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 provide a way to transfer control from one part of a program to another. C++ exception
handling is built upon three keyword: try, catch, and throw.

* throw - rogram 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 a program where
you want to handle

the problem. The catch keyword indicates the catching of an exception.


* try - A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more

catch blocks.

Program:

#include <iostream>

using namespace std;

int main()

int x=-1;

// Some code

cout << "Before try \n";

try {

cout << "Inside try \n";

if (x <0)

throw x;

cout << "After throw (Never executed) \n";

catch (int x) {

cout << "Exception Caught \n";

cout << "After catch (Will be executed) \n";

return 0;
}

Output:

Before try

Inside try

Exception Caught

After catch (Will be executed)

(b) What is function overriding? Write a C++ program to explain concept of function overriding.

Ans.Function overloading is a feature of object oriented programming where two or more


functions can have the same name

but different parameters.

When a function name is overloaded with different jobs it is 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:

#include <iostream>

using namespace std;

void print(int i) {

cout <<" Here is int " << j << endl;

void print{double f){


cout <<" Here is float " << f << endl;

void print(char const *c) {

cout <<" Here is char* " << c << endl;

int main() { ts) y3

print(10); ee

print{10.10);

print{"ten");

return 0;

Output:

Here is int 10

Here is float 10.1

Here is char* ten

(c) Explain how I/O formatting is done in C++ with the help of a program.

Ans.C++ helps you to format the I/O operations like determining the number of digits to be displayed
after the decimal point,

specifying number base etc.

Program:

#include <iostream>

#finclude <fstream>

using namespace std;


int main()

cout << "Example for formatted 10" << end];

cout << "Default: " << endl;

cout << 123 << endl;

cout << "width(5): " << endl;

cout.width(5);

cout << 123 << endl;

cout << "width(5) and fill{"*'): " << endl;

cout.width(5);

cout. fill{('*');

cout << 123 << endl;

cout.precision(5);

cout << "precision(5) -—>" << 123.4567890 << end;

cout << "precision(5) -—>" << 9.876543210 << endl;

cout << "setf(showpos): " << endl;

cout.setf(ios::showpos);

cout << 123 << endl;

cout << "unsetf(showpos): " << endl;

cout.unsetf{ios::showpos);

cout << 123 << endl;


return 0;

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy