CPP Program
CPP Program
Solution:
#include <iostream.h>
void main ()
{
int x;
cout << "Please enter an integer value: ";
cin >>x;
cout <<endl<< "Value you entered is " <<x;
cout << " and its double is " <<x*2 << ".\n";
}
Output:
Please enter an integer value:
5
Value you entered is 5 and its double is 10.
Solution:
#include <iostream.h>
void main ()
{
int a, b, p, q, r, s;
a = 10;
b=4;
p= a/b;
q= a*b;
r= a%b;
s= b%a;
cout<<p<<q<<r<<s;
}
Output:
2 40 2 4
Solution:
#include <iostream.h>
void main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout<<c;
}
Output: 7
Program 1.4 WAP to check whether a person is old or young. A person will be said old if his
age is above 35 and young if his age is below 35.
Solution:
#include<iostream.h>
void main()
{
int age;
cout<<”Enter Age”;
cin>>age;
if(age>=35)
cout<<"Old";
else
cout<<”Young”;
}
Output:
Enter age 39
Old
Program 1.5 Write a program to calculate division obtained by a student with his percentage
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 2
C++, Mentor Computer classes 2017
mark given.
Solution:
#include<iostream.h>
void main()
{
int mark;
cout<<”Enter mark”;
cin>>mark;
if(mark>=60)
cout<<”1st Division”;
else
cout<<”Fail”;
}
Output:
Enter mark 87
1st Division
Program 1.6 Write a program to illustrate the use of switch case statements.
Solution:
#include<iostream.h>
void main()
{
int i
for(int i=0; i<6; i++)
switch(i)
{
case 0:
cout<<”i is zero.”;
break;
case 1:
cout<<”i is one.”;
break;
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 3
C++, Mentor Computer classes 2017
case 2:
cout<<”i is two.”;
break;
case 3:
cout<<”i is three.”;
break;
default:
cout<<”i is greater than 3.”;
}
}
Output:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Program 1.7 Write a program to print the message “C++ is good” 10 times using while loop.
Solution:
#include<iostream.h>
void main()
{
int n = 0;
while (n <10)
{
cout<<”C++ is good”;
n++;
}
}
Program 1.8 Write a program to print the message “C++ is good” 10 times using do while loop.
Solution:
#include<iostream.h>
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 4
C++, Mentor Computer classes 2017
void main()
{
int n = 0;
do
{
cout<<”C++ is good”;
n++;
} while(n<9);
}
Program 1.9 Write a program to print the message “C++is good” 10 times using for loop.
Solution:
#include<iostream.h>
void main()
{
int n ;
for(n=0; n<10; n++)
{
cout<<”C++ is good”;
}
}
Program 1.11 The marks obtained by a student in 5 different subjects are input through the
keyboard. The student gets a division as per the following rules:
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 5
C++, Mentor Computer classes 2017
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 – Fail. Write a program to calculate the division obtained by the student.
Solution:
#include<iostream.h>
void main( )
{
int m1, m2, m3, m4, m5, per ;
cout<< "Enter marks in five subjects " ;
cin>>m1>>m2>>m3>>m4>>m5 ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
{
cout<< "First division" ;
}
else if ( ( per >= 50 ) && ( per < 60 ) )
{
cout<< "Second division" ;
}
else if ( ( per >= 40 ) && ( per < 50 ) )
{
cout<<"Third division" ;
}
else
{
cout<< "Fail" ;
}
}
Output:
Enter marks in 5 subjects 65 65 65 60 70
First division
Program 1.12 Write a program to find the roots of a quadratic equation ax 2+bx+c=0, where the
values of coefficient a, b and c are given from the keyboard.
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 6
C++, Mentor Computer classes 2017
Solution:
#include<iostream.h>
#include<math.h>
void main()
{
int a, b, c, d;
float r1, r2, x, y;
cout<<“Enter the coefficients”;
cin>>a>>b>>c;
d=(b*b) - (4*a*c);
if(d>0)
{
r1=(-b+pow(d,0.5))/2*a;
r2=(-b- pow(d,0.5))/2*a;
cout<<”Roots are real and the roots are ”<<r1<<” and ”<<r2;
}
else if(d==0)
{
r1=-b/2*a;
cout<< “Roots are equal and the root is “<<r1;
}
else
{
x=-b/2*a;
y =pow(-d,0.5)/2*a;
cout<<”Roots are imaginary and the roots are”<<endl;
cout<<x<<“+i ”<<y<<endl;
cout<<x<<“-i ”<< y;
}
}
Output:
Enter the coefficients 1 -4 4
Roots are equal and the root is 2
Program 1.13 If the three sides of a triangle are entered through the keyboard, write a
program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.
Solution:
#include<iostream.h>
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 7
C++, Mentor Computer classes 2017
void main()
{
int a, b, c;
cout<<“Enter 3 sides”;
cin>>a>>b>>c;
if(a+b>c && b+c>a && c+a>b)
{
if((a*a+b*b)==c*c || (b*b+c*c)==a*a || (c*c+a*a)==b*b)
{
cout<<“Right Angled”;
}
else if( (a==b &&b!=c) || (b==c&&c!=a) || (c==a&&a!=b))
{
cout<<“Isosceles”;
}
else if(a==b && b==c)
{
cout<<“Equilateral”;
}
else
{
cout<<“Any Valid Triangle”;
}
}
else
{
cout<<“Cannot form a valid triangle”;
}
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 8
C++, Mentor Computer classes 2017
Program 1.14 to print all the even integers from 1 to 100.
Write a program
#include<iostream.h
> void main()
{
int i;
for(i=0; i<100 ; i+=2)
{
cout<< i<<“\n”;
}
}
PrograWmA1P. Compute 1+2+3+4+………………….+n for a given value of n.
1 t 5o
#include<iostream.h>
void main()
{
int i, n, s=0;
cout<<“Enter the value of n”;
cin>>n;
for(i=1; i<=n; i++)
{
s=s+i;
}
cout<< s;
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 9
C++, Mentor Computer classes 2017
Program 1.17 Write a program to find sum of digits of a number.
Solution:
#include<iostream.h>
void main()
{
int a, n, s=0;
cout<<“Enter a number”;
cin>>n;
while(n!=0)
{ a=n
%10;
s=s+a;
n=n/10;
}
cout<<s;
}
Solution:
#include<iostream.h>
void main()
{
int a, n, rn=0;
cout<<“Enter a number”;
cin>>n;
while(n!=0)
{ a=n
%10;
rn=rn*10+a;
n=n/10;
}
cout<<rn;
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 10
C++, Mentor Computer classes 2017
Example 1.19 Write a program to check whether a no is palindrome number or not. (A number
is said to be palindrome number if it is equal its reverse
#include<iostream.h>
void main()
{
int a, n, rn=0, b;
cout<<“Enter a number”;
cin>>n;
b=n;
while(n!=0)
{ a=n
%10;
rn=rn*10+a;
n=n/10;
}
if(b==rn)
{
cout<<“palindrome”;
}
else
{
cout<<“not palindrome”;
}
}
Example 1.20 Write a program to check whether a no is Armstrong number or not. (A number
is said to be Armstrong number if sum of cube of its digit is equal to that number).
#include<iostream.h>
void main()
{
int a, n,s=0, b;
cout<<“Enter a number”;
cin>>n;
b=n;
while(n!=0)
{ a=n
%10;
s=s+a*a*a;
n=n/10;
}
if(b==s)
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 11
C++, Mentor Computer classes 2017
cout<<“Armstrong”;
}
else
{
cout<<“Not Armstrong”;
}
}
Example 1.21 Write a program to print all the prime numbers from 1 to 500.
#include<iostream.h>
void main( )
{
int n, i ;
for(n=2; n<=500; n++)
{
for(i=2; i<=n-1; i++)
{
if ( n% i == 0 )
{
break ;
}
}
if ( i == n )
{
cout<<n<< "\t" ;
}
}
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 12
C++, Mentor Computer classes 2017
Program 1.22 Write a program to swap two integers using call by value and call by ref.
Output: Output:
57 75
75 75
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 13
C++, Mentor Computer classes 2017
Assignment-1
1. Why structure is used instead of union? Write the difference between structure and union.
2. What is the difference between procedure oriented programming and object oriented
programming?
3. Describe the basic concepts of object oriented programming briefly.
4. Describe different types of operators in c++.
5. What is pointer? Differentiate between call by value and call by reference.
6. Explain function prototype, function calling and function definition with suitable examples.
7. Write a program to find factorial of a number.
8. Write a program to find largest among a list of integers stored in an array.
9. Using structure, write a program to find addition of two complex number.
10. Write a program to check whether a number is Armstrong or not?
11. Write a program to reverse a number using function recursion.
12. Write both recursive and non recursive function to find gcd of two integers.
13. Write a program to print fibonacii sequence up to 50 terms. (Assume, first two terms of fibonacii
sequence are 0 and 1 respectively.)
14. Write a program to print all integers from 1 to n using recursion, where the value of n is supplied
by the user.
15. Write a program to convert a 2×2 matrix into 3×3 matrix, where a new row element is obtained
by adding all elements in that row, a new column element is obtained by adding all elements in
that column and the diagonal element is obtained by summing all diagonal elements of given
2×2 matrix.
Chapter 2
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 14
C++, Mentor Computer classes 2017
Program 2.1 Write a program to find sum of two integers using class and object.
Solution:
#include<iostream.h>
class Add
{
int x, y, z;
public:
void getdata()
{
cout<<”Enter two numbers”;
cin>>x>>y;
}
void calculate(void);
void display(void);
};
void main()
{
Add a;
a.getdata();
a.calculate();
a.display();
}
Output:
Enter two numbers 5 6
11
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 15
C++, Mentor Computer classes 2017
Program 2.2 Write a program to add two time objects (in the form hh:mm).
Solution:
#include<iostream.h>
class time
{
int hours, minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void sum(time, time);
void display(void);
};
void time :: sum (time t1, time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
void time :: display()
{
cout<<hours<<” : ”<<minutes<<endl;
}
void main()
{
time T1, T2, T3;
T1.gettime(2,45);
T2.gettime(3,30);
T3.sum(T1, T2);
T1.display();
T2.display();
cout<<"Addition of above two time is ";
T3.display();
}
Output:
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 16
C++, Mentor Computer classes 2017
2 : 45
3 : 15
Addition of above two time is 6:15
Array of object
Solution:
#include<iostream.h>
class Employee
{
char name[30];
int age;
public:
void getdata(void);
void putdata(void);
};
void main()
{
Employee e[5];
int i;
for(i=0; i<5; i++)
{
e[i].getdata();
}
for(i=0; i<5; i++)
{
e[i].putdata();
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 17
C++, Mentor Computer classes 2017
}
}
Output:
Enter Name and Age: Rajib 25
Enter Name and Age: Sunil 27
Enter Name and Age: Ram 23
Enter Name and Age: Bibhuti 26
Enter Name and Age: Ramani 32
Rajib 25
Sunil 27
Ram 23
Bibhuti 26
Ramani 32
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 18
C++, Mentor Computer classes 2017
Program 2.4 Demonstration of default Constructor.
Solution:
#include<iostream.h>
class Add
{
int x, y, z;
public:
Add(); // Default Constructor
void calculate(void);
void display(void);
};
Add::Add()
{
x=6;
y=5;
}
void Add :: calculate()
{
z=x+y;
}
void Add :: display()
{
cout<<z;
}
void main()
{
Add a;
a.calculate();
a.display();
}
Output:
11
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 19
C++, Mentor Computer classes 2017
Parameterized constructor
Solution:
#include<iostream.h>
class Add
{
int x, y, z;
public:
Add(int, int);
void calculate(void);
void display(void);
};
Add :: Add(int a, int b)
{
x=a;
y=b;
}
void Add :: calculate()
{
z=x+y;
}
void Add :: display()
{
cout<<z;
}
void main()
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 20
C++, Mentor Computer classes 2017
Copy Constructor
The constructor which takes reference to its own class as argument is known as copy constructor.
Solution:
#include<iostream.h>
class Add
{
int x, y, z;
public:
Add()
{
}
Add(int a, int b)
{
x=a;
y=b;
}
Add(Add &);
void calculate(void);
void display(void);
};
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 21
C++, Mentor Computer classes 2017
Add b(a);
b.calculate();
b.display();
}
Output:
Value of x and y for new object are 5 and 6
11
Note: Here in the above program when the statement Add a(5, 6); will execute (i.e. object creation), the
parameterized constructor Add (int, int) will be called automatically and value of x and y will be set to 5
and 6respectively. Now when the statement Add b(a) ; will execute, the copy constructor Add(Add& )
will be called and the content of object a will be copied into object b.
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 22
C++, Mentor Computer classes 2017
Destructor
Solution:
#include<iostream.h>
class XYZ
{
int x;
public:
XYZ( );
~XYZ( );
void display(void);
};
XYZ::XYZ( )
{
x=9;
}
XYZ:: ~XYZ( )
{
cout<<”Object is destroyed”<<endl;
}
void XYZ::display()
{
cout<<x;
}
void main()
{
XYZ xyz;
xyz.display();
}
Output:
9
Object is destroyed.
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 23
C++, Mentor Computer classes 2017
Inline function
Program 2.8
Write a program to find area of a circle using inline function.
Solution:
#include<iostream.h>
inline float area(int);
void main()
{
int r;
cout<<“ Enter the Value of r: ”;
cin>>r;
cout<<” Area is: “ << area(r);
}
inline float area (int a)
{
return(3.14*a*a);
}
Output:
Enter the Value of r:
7
153.86
Friend Function
Program 2.9
Demonstration of Friend Function.
Solution:
#include<iostream.h>
class Add
{
int x, y, z;
public:
Add(int, int);
friend int calculate(Add p);
};
Output:
11
Note: Here the function calculate () is called directly like normal function as it is declared as friend.
Friend Classes
It is possible for one class to be a friend of another class. When this is the case, the friend class and all of
its member functions have access to the private members defined within the other class.
#include <iostream.h>
class TwoValues
{
int a;
int b;
public:
TwoValues(int i, int j)
{
a = i;
b = j;
}
friend class Min;
};
class Min
{
public:
int min(TwoValues x);
};
int Min::min(TwoValues x)
{
return x.a < x.b ? x.a : x.b;
}
int main()
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 25
C++, Mentor Computer classes 2017
TwoValues ob(10, 20);
Min m;
cout << m.min(ob);
return 0;
}
Output:
10
Note: In this example, class Min has access to the private variables a and b declared within the
TwoValues class.
Solution:
#include<iostream.h>
class A
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 26
C++, Mentor Computer classes 2017
i d
n )
t ;
p v
; o
} i
; s d
A: t
: a d
A() t i
{ i s
c p
} l
i a
y
n
(
t
v
o
q
i
;
d
)
p
;
u
b
l
i
p=5;
c
:
A();
v
o
i
d
i
n
c
r
(
v
o
i
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 27
C++, Mentor Computer classes 2017
int A:: q=10;
void A:: incr()
{
p++;
q++;
}
void A:: display()
{
cout<<p<<”\t”<<q<<endl;
}
void main()
{
A a1, a2, a3;
a1.incr();
a1.display();
a2.incr();
a2.display();
a3.incr();
a3.display();
}
Output:
6 11
6 12
6 13
Note: Here p is a normal variable, whose value is 5 for all 3 objects a1, a2 and a3 (For each object,
separate copy of p exists). But q is static variable or member, whose initial value is 10 and a single copy
of q exists for all the objects.
Solution:
#include<iostream.h>
class ABC
{
public:
static int add(int, int);
};
int ABC:: add(int a, int b)
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 28
C++, Mentor Computer classes 2017
{
return(a+b);
}
void main()
{
ABC abc;
int res;
res=ABC :: add(30, 40);
cout<<res;
}
Output:
70
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 30
C++, Mentor Computer classes 2017
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 31
C++, Mentor Computer classes 2017
Chapter 3 Inheritance
Program 4.1 Example of single inheritance with base class access control as public.
Solution:
#include <iostream.h>
class A
{
int i, j;
public:
void set(int a, int b)
{
i=a; j=b;
}
void show()
{
cout << i << " " << j << "\n";
}
};
class B : public A
{
int k;
public:
B(int x)
{
k=x;
}
void showk()
{
cout << k << "\n";
}
};
void main()
{
B b(3);
b.set(1, 2);
b.show();
b.showk();
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 32
C++, Mentor Computer classes 2017
Output:
12
3
Note: Here all public and protected members of the base class become private members of the derived
class. So object of derived class cannot directly access the member function and data members of the
base class.
Program 4.2 Example of single inheritance with base class access control as private.
Solution:
#include <iostream.h>
class A
{
int i, j;
public:
void set(int a, int b)
{
i=a; j=b;
}
void show()
{
cout << i << " " << j << "\n";
}
};
class B : private A
{
int k;
public:
B(int x)
{
k=x;
}
void showk()
{
cout << k << "\n";
}
};
void main()
{
B b(3);
b.set(1, 2);
b.show(); //******Error******
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 33
C++, Mentor Computer classes 2017
How to access the private data member of base class in derived class?
Private data members of base class can be accessed by derived class by using public member
function/methods of the base class.
Multiple Inheritance
In multiple inheritance derived class is derived from more than one base class.
A B C
(Multiple Inheritance)
Multilevel Inheritance
In multilevel inheritance class B is derived from a class A and a class C is derived from the class B.
Syntax:
class base-class-name1
{
Data members
Member
functions
};
class derived-class-name : visibility mode base-class-name
{
Data members
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 34
C++, Mentor Computer classes 2017
};
(Multilevel inheritance)
Hierarchical Inheritance
In hierarchical inheritance several classes can be derived from a single base class
Syntax:
class base-class-name
{
Data members
Member functions
};
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 35
C++, Mentor Computer classes 2017
B C D
(Hierarchical inheritance)
Hybrid inheritance
B C
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 36
C++, Mentor Computer classes 2017
Program 4.4 Constructor and Destructor execution in single inheritance.
Solution:
#include <iostream.h>
class base
{
public:
base()
{
cout << "Constructing base\n";
}
~base()
{
cout << "Destructing base\n";
}
};
class derived: public base
{
public:
derived()
{
cout << "Constructing derived\n";
}
~derived()
{
cout << "Destructing derived\n";
}
};
void main()
{
derived ob;
}
Output:
Constructing base
Constructing derived
Destructing derived
Destructing base
Note: In the above program, first base's constructor is executed followed by derived's. Next (because ob
is immediately destroyed in this program), derived's destructor is called, followed by base's.
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 37
C++, Mentor Computer classes 2017
Program 4.5 Constructor and Destructor execution in multilevel linheritance.
Solution:
#include <iostream.h>
class base
{
public:
base()
{
cout << "Constructing base\n";
}
~base()
{
cout << "Destructing base\n";
}
};
class derived1 : public base
{
public:
derived1()
{
cout << "Constructing derived1\n";
}
~derived1()
{
cout << "Destructing derived1\n";
}
};
class derived2: public derived1
{
public:
derived2()
{
cout << "Constructing derived2\n";
}
~derived2()
{
cout << "Destructing derived2\n";
}
};
void main()
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 38
C++, Mentor Computer classes 2017
derived2 ob;
}
Output:
Constructing base
Constructing derived1
Constructing derived2
Destructing derived2
Destructing derived1
Destructing base
Solution:
#include <iostream.h>
class base1
{
public:
base1()
{
cout << "Constructing base1\n";
}
~base1()
{
cout << "Destructing base1\n";
}
};
class base2
{
public:
base2()
{
cout << "Constructing base2\n";
}
~base2()
{
cout << "Destructing base2\n";
}
};
class derived: public base1, public base2
{
public:
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 39
C++, Mentor Computer classes 2017
derived()
{
cout << "Constructing derived\n";
}
~derived()
{
cout << "Destructing derived\n";
}
};
void main()
{
derived ob;
}
Output:
Constructing base1
Constructing base2
Constructing derived
Destructing derived
Destructing base2
Destructing base1
Note: In the above program, constructors are called in order of derivation, left to right, as specified in
derived's inheritance list. Destructors are called in reverse order, right to left.
Here, base1 through baseN are the names of the base classes inherited by the derived class. Notice that
a colon separates the derived class' constructor declaration from the base-class specifications, and that
the base-class specifications are separated from each other by commas, in the case of multiple base
classes.
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 40
C++, Mentor Computer classes 2017
Program 4.7 Passing Parameters to Base Class Constructors in Single Inheritance.
Solution:
#include <iostream.h>
class base
{
protected:
int i;
public:
base(int x)
{
i=x; cout << "Constructing base\n";
}
~base()
{
cout << "Destructing base\n";
}
};
class derived: public base
{
int j;
public:
derived(int x, int y): base(y)
{
j=x; cout << "Constructing derived\n";
}
~derived()
{
cout << "Destructing derived\n";
}
void show()
{
cout << i << " " << j << "\n";
}
};
void main()
{
derived ob(3, 4);
ob.show();
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 41
C++, Mentor Computer classes 2017
Solution:
// This program contains an error and will not compile.
#include <iostream.h>
class base
{
public:
int i;
};
class derived1 : public base
{
public:
int j;
};
class derived2 : public base
{
public:
int k;
};
class derived3 : public derived1, public derived2
{
public:
int sum;
};
void main()
{
derived3 ob;
ob.i = 10; // this is ambiguous, which i???
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k; // i ambiguous here, too
cout << ob.i << " "; // also ambiguous, which i?
cout << ob.j << " " << ob.k << " ";
cout << ob.sum;
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 42
C++, Mentor Computer classes 2017
Solution:
#include <iostream.h>
class base
{
public:
int i;
};
class derived1 : virtual public base
{
public:
int j;
};
class derived2 : virtual public base
{
public:
int k;
};
class derived3 : public derived1, public derived2
{
public:
int sum;
};
void main()
{
derived3 ob;
ob.i = 10; // now unambiguous
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k; // unambiguous
cout << ob.i << " "; // unambiguous
cout << ob.j << " " << ob.k << " ";
cout << ob.sum;
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 43
C++, Mentor Computer classes 2017
Assignment 3
1. Define Inheritance.
2. Write any two advantages of inheritance.
3. List various types of inheritances.
4. Define virtual base class.
5. How do the properties of the following two derived classes differ?
class X: private Y { //….};
class A: proctected B { //….};
6. Private attributes can’t be inherited. State a remedy for this problem so that attributes of a
class behave like private attributes but can be inherited. Explain with an example.
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 44
C++, Mentor Computer classes 2017
Chapter 4
Program 4.1 Write a program to overload function area () to calculate area of circle and
area of a rectangle.
Solution:
#include <iostream.h>
float area(int);
int area(int, int);
void main( )
{
int r, l, b;
cout << “Enter the Value of r, l & b: ”;
cin>>r>>l>>b;
cout<< “Area of circle is ”<<area(r)<<endl;
cout<< “Area of rectangle is ”<<area(l,b);
}
float area(int a)
{
return (3.14*a*a);
}
int area(int a, int b)
{
return (a*b);
}
Output:
Enter the Value of r, l & b:
786
Area of circle is 153.86
Area of circle is 48
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 45
C++, Mentor Computer classes 2017
Program 4.2 Demonstration of function overriding.
Solution:
#include<iostream.h>
class B
{
public:
void show()
{
cout<<"I am in base show"<<endl;
}
};
class D:public B
{
public:
void show()
{
cout<<"I am in derived show"<<endl;
}
};
void main()
{
B b, *bp;
D d;
bp=&b;
bp->show();
bp=&d;
bp->show();
}
Output:
I am in base show
I am in base show
Note: Here the base version of function show () will work as it overrides the derived version of show ().
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 46
C++, Mentor Computer classes 2017
Program 4.3 Write a program to demonstrate virtual function.
#include<iostream.h>
class B
{
public:
virtual void show()
{
cout<<"I am in base show"<<endl;
}
};
class D:public B
{
public:
void show()
{
cout<<"I am in derived show"<<endl;
}
};
void main()
{
B b, *bp;
D d;
bp=&b;
bp->show();
bp=&d;
bp->show();
}
Output:
I am in base show
I am in derived show
Important Tips!
A base pointer can be made to point to any number of derived objects, it cannot access the members
defined by a derived class. It can access only the members which are common to the base class. If a
same function is present in both base and derived class, always base version of the function is called
when we access the function using base pointer (no matters whether it points to base class or derived
class). Derived version of the function can be called by making the function (having same name) as
virtual. This is also called function overriding because function in the base class is overridden by the
function in the derived class.
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 47
C++, Mentor Computer classes 2017
Remember!
When a virtual function is inherited, its virtual nature is also inherited. This means that when a derived
class that has inherited a virtual function is itself used as a base class for another derived class, the
virtual function can still be overridden.
Program 4.4 Create an abstract class called Shape which contains a pure virtual function called
find_vol() and a protected attribute named as volume. Create two new derived classes from the
above class named as Cube and Sphere having double type attribute named as side and radius
respectively. Implement dynamic polymorphism to find out volume of a cube and a sphere. Also
display the result.
Solution:
#include<iostream.h>
class Shape
{
protected:
double volume;
public:
virtual void find_vol()=0;
};
class Cube: public Shape
{
protected:
double side;
public:
Cube();
void find_vol();
};
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 48
C++, Mentor Computer classes 2017
Cube::Cube()
{
cout<<”Enter side of the Cube:”<<endl;
cin>>side;
}
Sphere::Sphere ()
{
cout<<”Enter radius of the sphere:”<<endl;
cin>>radius;
}
void main()
{
Shape *ptr;
Cube cube;
Sphere sphere;
ptr=&cube;
ptr->find_vol();
ptr=&sphere;
ptr->find_vol();
}
Output:
Enter side of the Cube:
3
Enter radius of the sphere:
4
Volume of Cube is: 27
Volume of sphere is: 200.96
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 49
C++, Mentor Computer classes 2017
Assignment 4
Chapter 5
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 50
C++, Mentor Computer classes 2017
Operator Overloading
this Pointer
Every object in C++ has access to its own address through an important pointer called this pointer. The
this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this
may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class. Only non static
member functions have a this pointer.
public:
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return (length * breadth * height);
}
int compare(Box box)
{
return (this->Volume() > box.Volume());
}
};
void main(void)
{
Box Box1(3.3, 1.2, 1.5);
Box Box2(8.5, 6.0, 2.0);
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 51
C++, Mentor Computer classes 2017
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
}
Output:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
Overloading Operators
Program 5.2 Write a program to overload unary operator ++ using member function.
Solution:
#include<iostream.h>
class A
{
int n;
public:
void getdata( );
void operator ++( );
void display( );
};
void A::getdata( )
{
cout<<”Enter a number”;
cin>>n;
}
void A::operator ++( )
{
n=n+1;
}
void A::display( )
{
cout<<n;
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 52
C++, Mentor Computer classes 2017
void main()
{
A a;
a.getdata();
a++;
a.display();
}
Output:
Enter a number
5
6
Program 5.3 Write a program to overload unary operator ++ using friend function.
Solution:
#include<iostream.h>
class A
{
int n;
public:
void getdata( );
friend void operator ++( A &);
void display( );
};
void A::getdata( )
{
cout<<”Enter a number”;
cin>>n;
}
void operator ++(A x)
{
x.n=x.n+1;
}
void A::display( )
{
cout<<n;
}
void main()
{
A a;
a.getdata();
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 53
C++, Mentor Computer classes 2017
a++;
a.display();
}
Output:
Enter a number
5
6
Program 5.4Write a program to overload binary operator + to find sum of two complex
numbers using member function.
Solution:
#include<iostream.h>
class Complex
{
float real, img;
public:
Complex(float, float );
Complex operator + ( Complex);
void display( );
};
Complex::Complex(float x, float y )
{
real=x;
img=y
}
Complex Complex::operator +(Comlex c)
{
Complex temp;
temp.real=real+c.real;
temp.img=img+c.img;
return(temp);
}
void A::display( )
{
cout<<real<<” +j”<<img<<”\n”;
}
void main( )
{
Complex c1(2.5, 3.4), c2(4.2, 6.5), c3;
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 54
C++, Mentor Computer classes 2017
c3=c1+c2;
c1.display( );
c2.display( );
c3.display( );
}
Output:
2.5+ j3.4
4.2+ j6.5
6.7+ j9.9
Note: As you can see, operator+ () has only one parameter even though it overloads the binary +
operator. (You might expect two parameters corresponding to the two operands of a binary operator.)
The reason that operator+ () takes only one parameter is that the operand on the left side of the + is
passed implicitly to the function through the this pointer. The operand on the right is passed in the
parameter c. The fact that the left operand is passed using this also implies one important point: When
binary operators are overloaded, it is the object on the left that generates the call to the operator
function.
The statement c3=c1+c2; is same as c1.operator+(c2).
Program 5.5 Write a program to overload binary operator + to find sum of two complex
numbers using friend function.
Solution:
#include<iostream.h>
class Complex
{
float real, img;
public:
Complex(float, float );
friend Complex operator + ( Complex, Complex);
void display( );
};
Complex::Complex(float x, float y )
{
real=x;
img=y
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 55
C++, Mentor Computer classes 2017
temp.x=a.real+b.real;
temp.y=a.img+b.img;
return(temp);
}
void A::display( )
{
cout<<real<<” +j”<<img<<”\n”;
}
void main()
{
Complex c1(2.5, 3.4), c2(4.2, 6.5), c3;
c3=c1+c2;
c1.display();
c2.display();
c3.display();
}
Output:
2.5+ j3.4
4.2+ j6.5
6.7+ j9.9
Program 5.5 Suppose there is a class called X with two double type attributes. Write a C++
program to create two objects named ob 1 and ob 2 of the above class and overload the binary ==
operator to perform the following operation within main():
if(ob 1== ob 2)
cout<<”Objects are same”<<endl;
else
cout<<”Objects are different”<<endl; [BPUT 2010]
Solution:
#include<iostream.h>
class X
{
double d1, d2;
public:
X(double, double);
int operator==(X);
void display( );
};
X::X(double x, double y )
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 56
C++, Mentor Computer classes 2017
d1=x;
d2=y;
}
int X:: operator==(X p)
{
if(d1==p.d1 &&d2==p.d2)
return 1;
else
return 0;
}
void main()
{
X ob1(2.5, 3.4), ob2(2.5, 3.0);
if(ob 1== ob 2)
cout<<”Objects are same”<<endl;
else
cout<<”Objects are different”<<endl;
Assignment 5
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 57
C++, Mentor Computer classes 2017
Short Type Questions
1. Create a class complex with real and imaginary parts as member variables, member function
get () and disp () to input and display a complex number respectively. Write a program using the
above class to overload + and – operators to perform addition and subtraction of two complex
numbers.
2. Write a program in C++ to overload subscript [] operator.
3. Define a class called Increment; the class contains one integer data member. Overload the
object of the class for both pre-increment and post-increment operator.
4. Write a program to compare two strings by overloading == operator.
5. Write a program to add two string using + operator overloading.
6. Write a program to overload new and delete operator.
7. Write an appropriate C++ code showing ambiguity resolving mechanism where a class attribute
has same name as that of a local parameter of a member by using this pointer.
8. Write a program to overload == operator to check whether two circles are equal or not. (Two
circles are said to be equal if their radius is same and center has same coordinate)
9. Write a program to overload new and delete operator in C++.
10. Write a program to overload == operator to check whether two strings are equal or not.
Chapter 6
Exception Handling
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 58
C++, Mentor Computer classes 2017
Program 7.1 Write a program to find x/y, where x and y are given from the keyboard and
both are integers.
Solution:
#include<iostream.h>
void main()
{
int x, y;
cout<<”enter two number”<<endl;
cin>>x>>y;
try
{
if(y!=0)
{
z=x/y;
cout<<endl<<z;
}
else
{
throw(y);
}
}
catch(int y)
{
cout<<”exception occurred: y=”<<y<<endl;
}
}
Output:
Enter two number
60
exception occurred:y=0
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 59
C++, Mentor Computer classes 2017
A try block can be localized to a function. When this is the case, each time the function is entered, the
exception handling relative to that function is reset. For example, examine this program.
Program 7.2
#include <iostream.h>
void Xhandler(int test)
{
try
{
if(test) throw test;
}
catch(int i)
{
cout << "Caught Exception #: " << i << '\n';
}
}
void main()
{
cout << "Start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
}
Output:
Start
Caught Exception #: 1
Caught Exception #: 2
Caught Exception #: 3
End
As you can see, three exceptions are thrown. After each exception, the function returns. When the
function is called again, the exception handling is reset.
It is important to understand that the code associated with a catch statement will be executed only if it
catches an exception. Otherwise, execution simply bypasses the catch altogether. (That is, execution
never flows into a catch statement.) For example, in the following program, no exception is thrown, so
the catch statement does not execute.
#include <iostream.h>
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 60
C++, Mentor Computer classes 2017
void main()
{
cout << "Start\n";
try
{
cout << "Inside try block\n";
cout << "Still inside try block\n";
}
catch (int i)
{
cout << "Caught an exception -- value is: ";
cout << i << "\n";
}
cout << "End";
}
Output:
Start
Inside try block
Still inside try block
End
Program 7.3
#include <iostream.h>
void Xhandler(int test)
{
try
{
if(test) throw test;
else throw "Value is zero";
}
catch(int i)
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 61
C++, Mentor Computer classes 2017
cout << "Caught Exception #: " << i << '\n';
}
catch(const char *str)
{ cout << "Caught a string:
"; cout << str << '\n';
}
}
void main()
{
cout << "Start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
}
Output:
Start
Caught Exception #: 1
Caught Exception #: 2
Caught a string: Value is zero
Caught Exception #: 3
End
As you can see, each catch statement responds only to its own type.
Program 7.4
#include <iostream.h>
void Xhandler(int test)
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 62
C++, Mentor Computer classes 2017
try
{
if(test==0) throw test; // throw int
if(test==1) throw 'a'; // throw char
if(test==2) throw 123.23; // throw double
}
catch(...)
{
cout << "Caught One!\n";
}
}
void main()
{
cout << "Start\n";
Xhandler(0);
Xhandler(1);
Xhandler(2);
cout << "End";
}
Output:
Start Caught
One! Caught
One! Caught
One! End
Rethrowing an Exception
Program 7.5
#include <iostream.h>
void Xhandler()
{
try
{
throw "hello"; // throw a char *
}
catch(const char *)
{
cout << "Caught char * inside Xhandler\n";
throw ; // rethrow char * out of function
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 63
C++, Mentor Computer classes 2017
}
}
void main()
{
cout << "Start\n";
try
{
Xhandler();
}
catch(const char *)
{
cout << "Caught char * inside main\n";
}
cout << "End";
}
Output:
Start
Caught char * inside Xhandler
Caught char * inside main
end
Assignment 6
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Page 64
C++, Mentor Computer classes 2017
Chapter 7 Templates
Program 7.1 Write a generic function swap to interchange any two variables
(integer, character, and float).
#include
<iostream.h>
template
<class T> void
swap(T p, T q)
{
T temp; temp = p; p = q;
q = temp; cout<<p<<”\t”<<q;
}
void main()
{
int i=10, j=20;
float x=10.1, y=23.3; char a='x', b='z';
swap (i, j); /*swaps
integers*/ swap (x,
y); /* swaps floats*/
swap (a, b); /*swaps
chars*/
}
Output:
20 10
23.2 10.1
z x
Solution:
#include
<iostream.h>
template <class T1,
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
class T2> void
myfunc (T1 x, T2 y)
{
cout << x << “\t” << y << “\n”;
}
void main()
{
myfunc (10, "I
like C++");
myfunc (98.6,
19);
}
Output:
10 I like C++
98.6 19
Solution:
#include <iostream.h>
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
return 0;
}
Here, the template for f() is overloaded to accept either one or two parameters
Solution:
#include <iostream.h>
template <class T> void sort(X *a, int n)
{
int i,j; T t;
for(i=1; i<n;i++)
for(j=n-1; j>=i; j--)
if(a[j-1] > a[j])
{
t = a[j-1]; a[j-1] = a[j];
a[j] = t;
}
}
void main()
{
int iarray[7] = {7, 5, 4, 3, 9, 8, 6};
double farray[5] = {2.6, -3.0,
1.2,9.6,8.9}; int i;
sort(iarray, 7);
sort(farray, 5);
cout << "Sorted INTEGER
array is: "; for(i=0; i<7; i++)
cout << iarray[i] << “\t”;
cout << "\nSorted CHARACTER
array is: "; for(i=0; i<5; i++)
cout << farray[i] << “\t”;
}
Output:
Sorted INTEGER array is: 3 4 5 6 7 8 9
Sorted CHARACTER array is:-3.0 1.2 2.6 8.9 9.6
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
Solution:
#include <iostream.h>
template <class T>
class Add
{
T
a
,
b
;
p
u
b
l
i
c
:
void getdata(); void
display();
};
cout<<”sum=”<<a+b;
}
void main()
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
Add <int> ob1; Add
<float> ob2;
ob1.getdata( );
ob1.display( );
ob2.getdata( );
ob2.display( );
}
Output:
Eneter 2 nos 4 5
Sum=9
Eneter 2 nos 4.8 5.1
Sum=9.9
Solution:
#include <iostream.h>
template <class Type1, class
Type2> class myclass
{
T
y
p
e
1
i
;
T
y
p
e
2
j
;
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
p
u
b
l
i
c
:
myclass(Type1 a, Type2 b)
{
i = a; j = b;
}
void show()
{
cout << i << ' ' << j << '\n';
}
};
void main()
{
myclass<int, double> ob1(10, 0.23);
myclass<char, char *> ob2('X', "Templates add
power."); ob1.show(); // show int, double
ob2.show(); // show char, char *
}
Assignment 7
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "This is line 1." << endl;
cout << "This is line 2." << endl;
cout << "This is line 3." << endl;
cout << "Word1" << endl << "Word2" << endl << "Word3" << endl;
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char pName[3][30]={"Dove Soap","Colgate","Vim"};
int qty[3] ={5,10,15};
int i;
cout << setw(30) << "Product Name" << setw(20) << "Quantity" << endl;
for(i=0; i< 3; i++){
cout << setw(30) << pName[i] << setw(20) << qty[i] << endl;
}
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
char pName[3][30]={"Dove Soap","Colgate","Vim"};
int qty[3] ={5,10,15};
int i;
cout << setw(30) << "Product Name" << setw(20) << "Quantity" << endl;
for(i=0; i< 3; i++){
cout << setw(30) << setfill('-') << pName[i] << setw(20) << setfill('#') << qty[i] << endl;
}
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float val=123.456f;
cout << "Value of val with different setprecision parameters:" << endl;
cout << setprecision( 3) << val << endl;
cout << setprecision( 4) << val << endl;
cout << setprecision( 5) << val << endl;
cout << setprecision( 6) << val << endl;
cout << setprecision( 7) << val << endl;
cout << setprecision( 8) << val << endl;
return 0;
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
#include <iostream>
#include <iomanip>
using namespace std;
/*This program will show you to print decimal values in other format*/
int main()
{
int x=12349;
cout << "Octal value is: " << setbase( 8) << x << endl;
cout << "Decimal value is: " << setbase(10) << x << endl;
cout << "Hexadecimal value is: " << setbase(16) << x << endl;
return 0;
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
Chapter 9: Working with Files
//C++ program to create a file.
#include <iostream>
#include <fstream>
int main()
{
fstream file; //object of fstream class
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
return 0;
}
int main()
{
char ch;
const char *fileName="test.txt";
//declare object
ifstream file;
//open file
file.open(fileName,ios::in);
if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return -1; //return from main
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
return 0;
}
Output
int main()
{
fstream file; //object of fstream class
if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}
if(!file)
{
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}
return 0;
}
Output
/C++ program to write and read values using variables in/from file.
#include <iostream>
#include <fstream>
int main()
{
char name[30];
int age;
fstream file;
file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
file.close();
cout<<"\nFile saved and closed succesfully."<<endl;
cout<<"Name: "<<name<<",Age:"<<age<<endl;
return 0;
}
Enter age: 21
Name: Mike,Age:21
//C++ program to write and read object using read and write function.
#include <iostream>
#include <fstream>
void showData(void)
{
cout<<"Name:"<<name<<",Age:"<<age<<endl;
}
};
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
int main()
{
student s;
ofstream file;
return 0;
}
Output
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
int main()
{
fstream file;
//open file sample.txt in and Write mode
file.open("sample.txt",ios::out);
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
//write A to Z
file<<"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//print the position
cout<<"Current position is: "<<file.tellp()<<endl;
file.close();
Output
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
At position : 1 Character "B"
At position : 2 Character "C"
At position : 3 Character "D"
At position : 4 Character "E"
At position : 5 Character "F"
At position : 6 Character "G"
At position : 7 Character "H"
At position : 8 Character "I"
At position : 9 Character "J"
At position : 10 Character "K"
At position : 11 Character "L"
At position : 12 Character "M"
At position : 13 Character "N"
At position : 14 Character "O"
At position : 15 Character "P"
At position : 16 Character "Q"
At position : 17 Character "R"
At position : 18 Character "S"
At position : 19 Character "T"
At position : 20 Character "U"
At position : 21 Character "V"
At position : 22 Character "W"
At position : 23 Character "X"
At position : 24 Character "Y"
At position : 25 Character "Z"
char str[10];
fstream file;
file.open(FILE_NAME, ios::out|ios::binary);
if(!file){
cout<<"Error in creating file!!!"<<endl;
return;
}
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
char str[10];
int inH,inM,inS;
fstream finC;
finC.open(FILE_NAME,ios::in|ios::binary);
if(!finC){
cout<<"Error in file opening..."<<endl;
return;
}
if(finC.read((char*)str,sizeof(str))){
//extract time values from the file
sscanf(str,"%02d:%02d:%02d",&inH,&inM,&inS);
//assign time into variables, which are passing in function
*h=inH;
*m=inM;
*s=inS;
}
finC.close();
}
int main(){
int m,h,s;
cout<<"Enter time:\n";
cout<<"Enter hour: "; cin>>h;
cout<<"Enter minute: "; cin>>m;
cout<<"Enter second: "; cin>>s;
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
return 0;
}
Output
Enter time:
Enter hour: 10
Enter minute: 15
Enter second: 5
Time 10:15:05 has been written into file.
The time is 10:15:05
Program to write and read an object in, from binary file using write() and read() in C++
In the following program there are following details to be read through Employee class
Employee ID
Employee Name
Designation
Date of joining
Date of birth
#include <iostream>
#include <fstream>
#define FILE_NAME "emp.dat"
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
int main(){
file.write((char*)&emp,sizeof(emp));
file.close();
cout<<"Date saved into file the file.\n";
if(file.read((char*)&emp,sizeof(emp))){
cout<<endl<<endl;
cout<<"Data extracted from file..\n";
//print the object
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag
C++, Mentor Computer classes 2017
emp.displayEmployee();
}
else{
cout<<"Error in reading data from file...\n";
return -1;
}
file.close();
return 0;
}
Output
EMPLOYEE DETAILS
ENTER EMPLOYEE ID : 1001
ENTERNAME OF THE EMPLOYEE : Priya Kaushal
ENTER DESIGNATION : Student
ENTER DATE OF JOIN:
DATE : 21
MONTH: 11
YEAR : 2016
ENTER DATE OF BIRTH:
DATE : 15
MONTH: 09
YEAR : 1999
Date saved into file the file.
Add: Besides Sharad Bank, Revenue Colony, Shirur, Tal-Shirur, Dist: Pune Pag