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

C Answers

Data hiding in C++ is achieved using access specifiers like private and protected to restrict access to class members. Private makes data hidden to all code outside the class, while protected also hides it from code outside the class and derived classes. This encapsulation protects object integrity and reduces complexity. Polymorphism allows one message to have multiple forms and is achieved through compile-time techniques like function overloading and operator overloading, as well as runtime technique like function overriding. Inline functions can improve efficiency for small, commonly used functions by expanding their code at the call site to avoid overhead, but have limitations like not inlining functions with loops, gotos etc.
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)
178 views

C Answers

Data hiding in C++ is achieved using access specifiers like private and protected to restrict access to class members. Private makes data hidden to all code outside the class, while protected also hides it from code outside the class and derived classes. This encapsulation protects object integrity and reduces complexity. Polymorphism allows one message to have multiple forms and is achieved through compile-time techniques like function overloading and operator overloading, as well as runtime technique like function overriding. Inline functions can improve efficiency for small, commonly used functions by expanding their code at the call site to avoid overhead, but have limitations like not inlining functions with loops, gotos etc.
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/ 27

Q1. What is meant by data hiding? How is it achieved in c++?

Ans. Data hiding is a software development technique specifically used in object-oriented


programming (OOP) to hide internal object details (data members). Data hiding ensures
exclusive data access to class members and protects object integrity by preventing unintended or
intended changes.

Data hiding also reduces system complexity for increased robustness by limiting
interdependencies between software components.

Data hiding is also known as data encapsulation or information hiding.

How is it achieved in c++?

By using access specifiers.

private - makes the data members hidden to all code outside the class scope.

protected - makes the data members hidden to all code outside the class scope and scope of the
derived classes.

Data shouldn’t be accessed by using getDataMember() ( if it returns by reference), or set using


setDataMember (no point of making data hidden in the first place if you do this). We should
simply call the public functions of the class, which represent it’s functionality.

You can further hide to restrict visibility of variables to it’s current file, using static.

Q2. Define Polymorphism. What are the techniques used in C++ to achieve this?

Ans. Polymorphism in C++

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at the same time can have different characteristic.
Like a man at the same time is a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
 Compile time Polymorphism
 Runtime Polymorphism
Compile time polymorphism: This type of polymorphism is achieved by function overloading
or operator overloading.

1.
 Function Overloading: When there are multiple functions with same name but
different parameters then these functions are said to be overloaded. Functions can be
overloaded by change in number of arguments or/and change in type of
arguments.
Rules of Function Overloading
filter_none
edit
play_arrow
brightness_4
// C++ program for function overloading
#include <bits/stdc++.h>

using namespace std;


class Geeks
{
public:

// function with 1 int parameter


void func(int x)
{
cout << "value of x is " << x << endl;
}

// function with same name but 1 double parameter


void func(double x)
{
cout << "value of x is " << x << endl;
}

// function with same name and 2 int parameters


void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};

int main() {

Geeks obj1;

// Which function is called will depend on the parameters passed


// The first 'func' is called
obj1.func(7);

// The second 'func' is called


obj1.func(9.132);

// The third 'func' is called


obj1.func(85,64);
return 0;
}
Output:
value of x is 7
value of x is 9.132
value of x and y is 85, 64
In the above example, a single function named func acts differently in three different
situations which is the property of polymorphism.
 Operator Overloading: C++ also provide option to overload operators. For example,
we can make the operator (‘+’) for string class to concatenate two strings. We know
that this is the addition operator whose task is to add two operands. So a single
operator ‘+’ when placed between integer operands , adds them and when placed
between string operands, concatenates them.
Example:
filter_none
edit
play_arrow
brightness_4
// CPP program to illustrate
// Operator Overloading
#include<iostream>
using namespace std;

class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =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 << endl; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Output:
12 + i9
In the above example the operator ‘+’ is overloaded. The operator ‘+’ is an addition
operator and can add two numbers(integers or floating point) but here the operator is
made to perform addition of two imaginary or complex numbers. To learn operator
overloading in details visit this link.
2. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.
 Function overriding on the other hand occurs when a derived class has a definition
for one of the member functions of the base class. That base function is said to
be overridden.
filter_none
edit
play_arrow
brightness_4
// C++ program for function overriding

#include <bits/stdc++.h>
using namespace std;

class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }

void show ()
{ cout<< "show base class" <<endl; }
};

class derived:public base


{
public:
void print () //print () is already virtual function in derived class, we could also declared as virtual v
{ cout<< "print derived class" <<endl; }

void show ()
{ cout<< "show derived class" <<endl; }
};

//main function
int main()
{
base *bptr;
derived d;
bptr = &d;

//virtual function, binded at runtime (Runtime polymorphism)


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}
Output:
print derived class
show base class

Q3. How are inline functions implemented in C++. What are its merits and limitations?

Ans. Inline Functions in C++

Inline function is one of the important feature of C++. So, let’s first understand why inline
functions are used and what is the purpose of inline function?
When the program executes the function call instruction the CPU stores the memory address of
the instruction following the function call, copies the arguments of the function on the stack and
finally transfers control to the specified function. The CPU then executes the function code,
stores the function return value in a predefined memory location/register and returns control to
the calling function. This can become overhead if the execution time of function is less than the
switching time from the caller function to called function (callee). For functions that are large
and/or perform complex tasks, the overhead of the function call is usually insignificant compared
to the amount of time the function takes to run. However, for small, commonly-used functions,
the time needed to make the function call is often a lot more than the time needed to actually
execute the function’s code. This overhead occurs for small functions because execution 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 is expanded in line when it is called. When the inline function is called whole code
of the inline function gets inserted 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 for inlining. 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.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal function
calls. Other optimizations can be obtained by considering the flows of calling context and the
called context.
5) Inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function call preamble and return.
Inline function disadvantages:
1) The added variables from the inlined function consumes additional registers, After in-lining
function if variables number which are going to use register increases than they may create
overhead on register variable resource utilization. This means that when inline function body is
substituted at the point of function call, total number of variables used by the function also gets
inserted. So the number of register going to be used for the variables will also get increased. So if
after function inlining variable numbers increase drastically then it would surely cause an
overhead on register utilization.
2) If you use too many inline functions then the size of the binary executable file will be large,
because of the duplication of same code.
3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of
instruction fetch from that of cache memory to that of primary memory.
4) Inline function may increase compile time overhead if someone changes the code inside the
inline function then all the calling location has to be recompiled because compiler would require
to replace all the code once again to reflect the changes, otherwise it will continue with old
functionality.
5) Inline functions may not be useful for many embedded systems. Because in embedded
systems code size is more important than speed.
6) Inline functions might cause thrashing because inlining might increase size of the binary
executable file. Thrashing in memory causes performance of computer to degrade.
Q4. How is polymorphism achieved at run time. Explain with the help of a program?
Ans.

Runtime Polymorphism

Function overriding is an example of Runtime polymorphism.


Function Overriding: When child class declares a method, which is already present in the
parent class then this is called function overriding, here child class overrides the parent class.

In case of function overriding we have two definitions of the same function, one is parent class
and one in child class. The call to the function is determined at runtime to decide which
definition of the function is to be called, thats the reason it is called runtime polymorphism.

Example of Runtime Polymorphism

#include <iostream>
using namespace std;
class A {
public:
void disp(){
cout<<"Super Class Function"<<endl;
}
};
class B: public A{
public:
void disp(){
cout<<"Sub Class Function";
}
};
int main() {
//Parent class object
A obj;
obj.disp();
//Child class object
B obj2;
obj2.disp();
return 0;
}
Output:

Super Class Function


Sub Class Function

Q5. What is run time memory management in C++.What support is provided by c++ for
this and how does it differ from C’s memory management?
Ans.

new and delete operators in C++ for dynamic memory

Dynamic memory allocation in C/C++ refers to performing memory allocation manually by


programmer. Dynamically allocated memory is allocated on Heap and non-static and local
variables get memory allocated on Stack What are applications?
 One use of dynamically allocated memory is to allocate memory of variable size which is
not possible with compiler allocated memory except variable length arrays.
 The most important use is flexibility provided to programmers. We are free to allocate and
deallocate memory whenever we need and whenever we don’t need any more. There are
many cases where this flexibility helps. Examples of such cases are Linked List, Tree, etc.
How is it different from memory allocated to normal variables?
For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and
deallocated. For dynamically allocated memory like “int *p = new int[10]”, it is programmers
responsibility to deallocate memory when no longer needed. If programmer doesn’t deallocate
memory, it causes memory leak (memory is not deallocated until program terminates).
How is memory allocated/deallocated in C++?
C uses malloc() and calloc() function to allocate memory dynamically at run time and uses free()
function to free dynamically allocated memory. C++ supports these functions and also has two
operators new and delete that perform the task of allocating and freeing the memory in a better
and easier way.

new operator
The new operator denotes a request for memory allocation on the Heap. If sufficient memory is
available, new operator initializes the memory and returns the address of the newly allocated and
initialized memory to the pointer variable.
 Syntax to use new operator: To allocate memory of any data type, the syntax is:
 pointer-variable = new data-type;
Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data
type including array or any user defined data types including structure and class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;

OR

// Combine declaration of pointer


// and their assignment
int *p = new int;
 Initialize memory: We can also initialize the memory using new operator:
 pointer-variable = new data-type(value);
 Example:
 int *p = new int(25);
 float *q = new float(75.25);
 Allocate block of memory: new operator is also used to allocate a block(an array) of
memory of type data-type.
 pointer-variable = new data-type[size];
where size(a variable) specifies the number of elements in an array.
Example:
int *p = new int[10]
Dynamically allocates memory for 10 integers continuously of type int and returns pointer
to the first element of the sequence, which is assigned to p(a pointer). p[0] refers to first
element, p[1] refers to second element and so on.
delete operator
Since it is programmer’s responsibility to deallocate dynamically allocated memory,
programmers are provided delete operator by C++ language.
Syntax:
// Release memory pointed by pointer-variable
delete pointer-variable;
Here, pointer-variable is the pointer that points to the data object created by new.
Examples:
delete p;
delete q;
To free the dynamically allocated array pointed by pointer-variable, use following form
of delete:
// Release block of memory
// pointed by pointer-variable
delete[] pointer-variable;

Example:
// It will free the entire array
// pointed by p.
delete[] p;
// C++ program to illustrate dynamic allocation
// and deallocation of memory using new and delete
#include <iostream>
using namespace std;

int main ()
{
// Pointer initialization to null
int* p = NULL;

// Request memory for the variable


// using new operator
p = new(nothrow) int;
if (!p)
cout << "allocation of memory failed\n";
else
{
// Store value at allocated address
*p = 29;
cout << "Value of p: " << *p << endl;
}

// Request block of memory


// using new operator
float *r = new float(75.25);

cout << "Value of r: " << *r << endl;

// Request block of memory of size n


int n = 5;
int *q = new(nothrow) int[n];

if (!q)
cout << "allocation of memory failed\n";
else
{
for (int i = 0; i < n; i++)
q[i] = i+1;

cout << "Value store in block of memory: ";


for (int i = 0; i < n; i++)
cout << q[i] << " ";
}

// freed the allocated memory


delete p;
delete r;

// freed the block of allocated memory


delete[] q;

return 0;
}
Output:
Value of p: 29
Value of r: 75.25
Value store in block of memory: 1 2 3 4 5

Q6. What is operator overloading ?What are the methods of overloading the operators in
C++? Explain one method of operator overloading in C++ with example.?

Ans. In C++, it's possible to change the way operator works (for user-defined types). In this
article, you will learn to implement operator overloading feature.

The meaning of an operator is always same for variable of basic types like: int, float, double etc.
For example: To add two integers, + operator is used.

However, for user-defined types (like: objects), you can redefine the way operator works. For
example:

If there are two objects of a class that contains string as its data members. You can redefine the
meaning of + operator and use it to concatenate those strings.

This feature in C++ programming that allows programmer to redefine the meaning of an operator
(when they operate on class objects) is known as operator overloading.

Why is operator overloading used?


You can write any C++ program without the knowledge of operator overloading. However,
operator operating are profoundly used by programmers to make program intuitive. For example,

You can replace the code like:

calculation = add(multiply(a, b),divide(a, b));

to

calculation = (a*b)+(a/b);
How to overload operators in C++ programming?

To overload an operator, a special operator function is defined inside the class as:

class className
{
... .. ...
public
returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};

 Here, returnType is the return type of the function.


 The returnType of the function is followed by operator keyword.
 Symbol is the operator symbol you want to overload. Like: +, <, -, ++
 You can pass arguments to the operator function in similar way as functions.

Example: Operator overloading in C++ Programming


#include <iostream>
using namespace std;

class Test
{
private:
int count;

public:
Test(): count(5){}

void operator ++()


{
count = count+1;
}
void Display() { cout<<"Count: "<<count; }
};

int main()
{
Test t;
// this calls "function void operator ++()" function
++t;
t.Display();
return 0;
}

Q7. Write a program which implements the concept of virtual base class?

Ans. #include<iostream.h>
#include<conio.h>

class student {
int rno;
public:

void getnumber() {
cout << "Enter Roll No:";
cin>>rno;
}
void putnumber() {
cout << "\n\n\tRoll No:" << rno << "\n";
}
};

class test : virtual public student {


public:
int part1, part2;

void getmarks() {
cout << "Enter Marks\n";
cout << "Part1:";
cin>>part1;
cout << "Part2:";
cin>>part2;
}

void putmarks() {
cout << "\tMarks Obtained\n";
cout << "\n\tPart1:" << part1;
cout << "\n\tPart2:" << part2;
}
};

class sports : public virtual student {


public:
int score;

void getscore() {
cout << "Enter Sports Score:";
cin>>score;
}

void putscore() {
cout << "\n\tSports Score is:" << score;
}
};

class result : public test, public sports {


int total;
public:

void display() {
total = part1 + part2 + score;
putnumber();
putmarks();
putscore();
cout << "\n\tTotal Score:" << total;
}
};

void main() {
result obj;
clrscr();
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
}

Sample Output

Enter Roll No: 200

Enter Marks

Part1: 90
Part2: 80
Enter Sports Score: 80

Roll No: 200


Marks Obtained
Part1: 90
Part2: 80
Sports Score is: 80
Total Score is: 250

Q8.What is the role of file() function? When do we use this function?

Ans. Files are a means to store data in a storage device. C++ file handling provides a mechanism
to store output of a program in a file and read from a file on the disk. So far, we have been
using <iostream> header file which provide functions cin and coutto take input from console
and write output to a console respectively. Now, we introduce one more header
file <fstream>which provides data types or classes ( ifstream , ofstream , fstream ) to read
from a file and write to a file.

File Opening Modes


A file can be opened in different modes to perform read and write operations. Function to open a
file i.e open( ) takes two arguments : char *filename and ios :: mode. C++ supports the
following file open modes :

Mode Explanation

ios :: in Open a file for reading

ios :: out Open a file for writing

ios :: app Appends data to the end of the file

ios :: ate File pointer moves to the end of the file but allows to writes data
in any location in the file

ios :: binary Binary File

ios :: trunc Deletes the contents of the file before opening

If a file is opened in ios :: out mode, then by default it is opened in ios :: trunc mode also i.e the
contents of the opened file is overwritten. If we open a file using ifstream class, then by default
it is opened in ios :: in mode and if we open a file using ofstream class, then by default it is
opened in ios :: out mode. The fstream class doesn’t provide any default mode.

Q9.What are input and output streams. Describe various classes available for file
operations?

Ans. C++ comes with libraries which provides us many ways for performing input and output. In
C++ input and output is performed in the form of sequence of bytes or more commonly known
as streams.
Input Stream: If the direction of flow of bytes is from device(for example: Keyboard) to the
main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device(
display screen ) then this process is called output.
Header files available in C++ for Input – Output operation are:
 iostream: iostream stands for standard input output stream. This header file contains
definitions to objects like cin, cout, cerr etc.
 iomanip: iomanip stands for input output manipulators. The methods declared in this files
are used for manipulating streams. This file contains definitions of setw, setprecision etc.
 fstream: This header file mainly describes the file stream. This header file is used to
handle the data being read from a file as input or data being written into the file as output.
In C++ articles, these two keywords cout and cin are used very often for taking inputs and
printing outputs. These two are the most basic methods of taking input and output in C++. For
using cin and cout we must include the header file iostream in our program.
Standard output stream (cout): Usually the standard output device is the display
screen. cout is the instance of the ostream class. cout is used to produce output on the standard
output device which is usually the display screen. The data needed to be displayed on the screen
is inserted in the standard output stream (cout) using the insertion operator (<<).
standard input stream (cin): Usually the input device is the keyboard. cin is the instance of the
class istream and is used to read input from the standard input device which is usually keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.

Q10.What are friend functions and Friend classes.

Ans. Friend Class A friend class can access private and protected members of other class in
which it is declared as friend. It is sometimes useful to allow a particular class to access private
members of other class. For example a LinkedList class may be allowed to access private
members of Node.

class Node

private:

int key;

Node *next;

/* Other members of Node Class */

friend class LinkedList; // Now class LinkedList can

// access private members of Node

};
Friend Function Like friend class, a friend function can be given special grant to access private
and protected members. A friend function can be:
a) A method of another class
b) A global function
class Node

private:

int key;

Node *next;

/* Other members of Node Class */

friend int LinkedList::search(); // Only search() of linkedList

// can access internal members

};

Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. too many functions or external classes are
declared as friends of a class with protected or private data, it lessens the value of encapsulation
of separate classes in object-oriented programming.
2) Friendship is not mutual. If a class A is friend of B, then B doesn’t become friend of A
automatically.
3) Friendship is not inherited (See this for more details)
4) The concept of friends is not there in Java.

Q11.What are the main advantages of passing arguments by reference. Explain with the help of
an example?

Ans.

Here are some advantages of passing by reference:

1. No new copy of variable is made, so overhead of copying is saved. This Makes program
execute faster specially when passing object of large structs or classes.
2. Array or Object can be pass
3. Sometimes function need to change the original value(eg. Sorting an array, swapping) and
sometimes changing value inside function is useful.
4. Can return multiple values from a function.

PROGRAM:-

#include <iostream>

using namespace std;

// function declaration

void swap(int &x, int &y);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

cout << "Before swap, value of a :" << a << endl;

cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/

swap(a, b);

cout << "After swap, value of a :" << a << endl;

cout << "After swap, value of b :" << b << endl;

return 0;
}

Q12. Write a program in C++ to sort an array of integers using insertion sort?

Ans.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int size, arr[50], i, j, temp;
cout<<"Enter Array Size : ";
cin>>size;
cout<<"Enter Array Elements : ";
for(i=0; i<size; i++)
{
cin>>arr[i];
}
cout<<"Sorting array using selection sort ... \n";
for(i=1; i<size; i++)
{
temp=arr[i];
j=i-1;
while((temp<arr[j]) && (j>=0))
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=temp;
}
cout<<"Array after sorting : \n";
for(i=0; i<size; i++)
{
cout<<arr[i]<<" ";
}
getch();
}

Q13. Write a program in c++ to calculate the sum of odd & even numbers in an array

Ans.

#include <iostream>

using namespace std;


void EvenOddSum(int arr[], int n)
{
int even = 0;
int odd = 0;
for (int i = 0; i < n; i++) {
// Loop to find even, odd sum
if (i % 2 == 0)
even += arr[i];
else
odd += arr[i];
}

cout << "Even index positions sum " << even;


cout << "nOdd index positions sum " << odd;
}

// Driver function
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);

EvenOddSum(arr, n);

return 0;
}

Q14. write a program in c++ to print the sorted array?

Ans.

#include <iostream>

using namespace std;

1.
2. int main()
3. {
4. int arr[100];
5. int size, i, j, temp;
6.
7. // Reading the size of the array
8. cout<<"Enter size of array: ";
9. cin>>size;
10.
11. //Reading elements of array
12. cout<<"Enter elements in array: ";
13. for(i=0; i<size; i++)
14. {
15. cin>>arr[i];
16. }
17. //Sorting an array in ascending order
18. for(i=0; i<size; i++)
19. {
20. for(j=i+1; j<size; j++)
21. {
22. //If there is a smaller element found on right of the array then swap it.
23. if(arr[j] < arr[i])
24. {
25. temp = arr[i];
26. arr[i] = arr[j];
27. arr[j] = temp;
28. }
29. }
30. }

//Printing the sorted array in ascending order

31. cout<<"Elements of array in sorted ascending order:"<<endl;


32. for(i=0; i<size; i++)
33. {
34. cout<<arr[i]<<endl;
35. }
36.
37. return 0;

Q15. Write a program to print highest and second highest element of an array?

Ans.

#include<iostream>
#include<conio.h>

using namespace std;

void main()
{
int a[10], i, largest = 0, second_largest = 0, pos1, pos2;
int n;
cout << "Enter Number of elements :";
cin>>n;
for (i = 0; i<n; ++i)
{
cout << "n Enter " << (i + 1) << "th Element :";
cin >> a[i];
}
//Finding Largest
for (i = 0; i<10; ++i)
{
if (a[i]>largest)
{
largest = a[i];
pos1 = i;
}
}
//finding second largset
for (i = 0; i<10; ++i)
{
if (a[i]>second_largest)
{
if (a[i] == largest)
continue; //Ignoring largest in order to get second largest
second_largest = a[i];
pos2 = i;
}
}
cout << "nn Largest Number :" << largest << " at position " << (pos1 + 1);
cout << "nn Second Largest Number :"<< second_largest << " at position " << (pos2 + 1);

getch();
return;
}

Q16. Write a program in C++ to find area of a circle , rectangle and triangle by
overloading the function area()?

Ans.

#include<iostream.h>
#include<conio.h>
class over
{
float l,b,r,area;
public:
void volume(float,float);
void volume(float);
};
void over::volume(float l, float b)
{
cout<<"Area of rectangle = "<<l*b;
void over::volume(float r)
{
cout<<"Area of circle = "<<3.14*r*r;
}
void main()
{
over o;
clrscre():
float r,l,b;
cout<<"\nEnter radius: ";
cin>>r;
o.volume(r);
cout<<"\n\nEnter lenght and breadth: ";
cin>>l>>b;
o.volume(l,b);
getch();
}

Q17. Explain the various file manipulation functions available in c++?

Ans.

Manipulation of file pointers


The read operation from a file involves get pointer. It points to a specific location in the file and
reading starts from that location. Then, the get pointer keeps moving forward which lets us read
the entire file. Similarly, we can start writing to a location where put pointer is currently
pointing. The get and put are known as file position pointers and these pointers can be
manipulated or repositioned to allow random access of the file. The functions which manipulate
file pointers are as follows :

Function Description

seekg( ) Moves the get pointer to a specific location in the file


seekp( ) Moves the put pointer to a specific location in the file

tellg( ) Returns the position of get pointer

tellp( ) Returns the position of put pointer

The function seekg( n, ref_pos ) takes two arguments :


n denotes the number of bytes to move and ref_pos denotes the reference position relative to
which the pointer moves. ref_pos can take one of the three constants : ios :: beg moves
the get pointer n bytes from the beginning of the file, ios :: end moves the get pointer n bytes
from the end of the file and ios :: cur moves the get pointer n bytes from the current position. If
we don’t specify the second argument, then ios :: beg is the default reference position.
The behaviour of seekp( n, ref_pos ) is same as that of seekg( ). Following program illustrates
random access of file using file pointer manipulation functions :

#include<iostream>
#include<fstream>
using namespace std;

int main() {
fstream fp;
char buf[100];
int pos;

// open a file in write mode with 'ate' flag


fp.open("random.txt", ios :: out | ios :: ate);
cout << "\nWriting to a file ... " << endl;
fp << "This is a line" << endl; // write a line to a file
fp << "This is a another line" << endl; // write another file
pos = fp.tellp();
cout << "Current position of put pointer : " << pos << endl;
// move the pointer 10 bytes backward from current position
fp.seekp(-10, ios :: cur);
fp << endl << "Writing at a random location ";
// move the pointer 7 bytes forward from beginning of the file
fp.seekp(7, ios :: beg);
fp << " Hello World ";
fp.close(); // file write complete
cout << "Writing Complete ... " << endl;

// open a file in read mode with 'ate' flag


fp.open("random.txt", ios :: in | ios :: ate);
cout << "\nReading from the file ... " << endl;
fp.seekg(0); // move the get pointer to the beginning of the file
// read all contents till the end of file
while (!fp.eof()) {
fp.getline(buf, 100);
cout << buf << endl;
}
pos = fp.tellg();
cout << "\nCurrent Position of get pointer : " << pos << endl;
return 0;
}

You might also like