June 2018

C++ Program To Find Factorial Of Two Numbers Using Recursion Function

#include<iostream>
using namespace std;
long int fact(int);
int main()
{
int n1,n2;
cout<<"Enter number"< cin>>n1>>n2;
cout<<n1<<"! = "<<fact(n1)<<endl;
cout<<n2<<"! = "<<fact(n2)<<endl;
}
long int fact(int n)
{
if(n<=1)
return 1;
else
  return (n*fact(n-1));
}

OUTPUT


Enter number
5
4
5! = 120
4! = 24

Type Conversion

The type conversions are automatic as long as the data types involved are built-in types. If the data types are user-defined, the compiler does not support automatic type conversion and therefore, we must design the conversion routines by ourselves. Three types of situations might arise in the data conversion in this case. 1. Conversion from basic type to class type 2. Conversion from class type to basic type 3. Conversion from one class type to another class type


Conversion from basic type to class type 

        In this case, it is necessary to use the constructor. The constructor, in this, takes a single argument whose type is to be converted. For example,

class distance 
{
private:
int feet;
int inch; public:
distance(int f,int i)
{
feet=f;
inch=i;
}
distance(float m)
{
feet = int(m);
inch = 12 * (m - feet);
}
void display()
{
cout<<"Feet = "<<feet<<endl <<"Inch = "<<inch;
}
};

void main()
{
clrscr();
float f = 2.6;
distance d = f;
d.display();
getch(); }

Output: Feet = 2 Inches = 7

Conversion from class type to basic type

In this case, it is necessary to overload the casting operator. To do this, we use the conversion function. 
Example: 

class distance 
{
private: int feet;
int inch; public:
distance(int f,int i)
{
feet=f;
inch=i;
}
operator float()
{
float a= feet + inches/12.0;
return a; } };

void main()
{
clrscr();
distance d(8, 6);
float x = (float)d; cout<<"x = "<<x;
getch();
}
Output: x = 8.5

Conversion from one class type to another class type

This type of conversion can be carried out either by a constructor or an operator function. It depends upon where we want the routine to be located – in the source class or in the destination class. a. Function in the source class: In this case, it is necessary that the operator function is placed in the source class.
For example,

class distance 
{
int feet;
int inch;
public:
distance(int f, int i)
{
feet = f;
inch = i;
}
void display()
{
cout<<"Feet = "<<feet<<endl<<"Inches = "<<inches;
} };
class dist
{
int meter;
int centimeter;
public:
dist(int m, int c)
{
meter = m;
centimeter = c;
}
operator distance( )
{
distance d;
int f,i;
f= meter*3.3.;
i=centimeter*0.4;
f=f+i/12;
i=i%12;
return distance(f,i);
} };
void main()
{
clrscr();
distance d1;
dist d2(4,50);
d1=d2;
d1.display();
getche(); }

b. Function in the destination class:

In this case, it is necessary that the constructor is placed in the destination class. This constructor is a single argument constructor and serves as an instruction for converting the argument’s type to the class type of which it is a member. 
For example,

class distance
{
int meter;
float centimeter;
public:
distance(int m, int c)
{
meter = m;
centimeter = c;
}
int getmeter()
{
return meter; }
float getcentimeter()
{
return centimeters;
} };
class dist
{
int feet; int inch;
public:
dist(int f, int i)
{
feet = f;
inch = i;
}
dist(distance d)
{
int m,c;
m=d.getmeter();
c=d.getcentimeter();
feet= m*3.3;
inch= c*0.4;
feet=feet+inch/12;
inch= inch%12;
}
void display()
{
cout<<"Feet = "<<feet<<endl<<"Inches = "<<inches;
} };
void main( )
{
clrscr();
distance d1(6,40);
dist d2;
d2=d1;
d2.display();
getche();
}

C++ Program To Multiply Matrices

#include<iostream>
using namespace std;
class Matrix
{
private:
int a[10][10];
public:
void read_matrix(int m, int n);
void display_matrix(int m, int n);
void multiply_matrix(int ,int, int,Matrix x, Matrix y);
};
void Matrix::read_matrix(int m,int n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
}
void Matrix::display_matrix(int m,int n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j] <<"\t";
}
cout<<endl;
}
}
void Matrix::multiply_matrix(int r1,int c1, int c2, Matrix x, Matrix y)
{
 for(int i=0; i<r1; i++)
    {
for(int j=0; j<c2; j++)
        {
        a[i][j]=0;
for(int k=0;k<c1;k++)
        {
        a[i][j]+=x.a[i][k]*y.a[k][j];
}
 }
}
}
int main()
{
int r1,c1,r2,c2;
cout<<"Enter order of first matrix: "; cin>>r1>>c1;
cout<<"Enter order of seond matrix: "; cin>>r2>>c2;
Matrix mat1,mat2,mat3;
if(c1==r2)
{
cout<<"Enter elements of first matrix: \n";
mat1.read_matrix(r1,c1);
cout<<"Enter elements of second matrix: \n";
mat2.read_matrix(r2,c2);
cout<<"First Matrix:\n";
mat1.display_matrix(r1, c1);
cout<<"Second Matrix:\n";
mat2.display_matrix(r2 , c2);
//Multplying matrix
mat3.multiply_matrix(r1,c1,c2,mat1,mat2);
cout<<"Output matrix: \n";
mat3.display_matrix(r1,c2);
}
else
{
cout<<"MATRIX CAN'T BE MULTIPLIED !";
}
//mat3.display_matrix(r1,c2);
}

Output


Enter order of first matrix: 2
3
Enter order of seond matrix: 3
2
Enter elements of first matrix:
2
1
3
4
5
6
Enter elements of second matrix:
2
1
4
5
6
7
First Matrix:
2       1       3
4       5       6
Second Matrix:
2       1
4       5
6       7
Output matrix:
26      28
64      71

C++ Program To Calculate Tax Using Constructor and Destructor 

Calculating the tax using the C++ program is easy if you have the concept of constructor and destructor. There is also another way to calculate Tax using C++ which is simple but the use of constructor is much practical in the programming world. Let us have some knowledge about the class constructor and destructor below.

The Class Constructor

A class constructor is a special member function of a class that is executed whenever we create new objects of that class. A constructor will have the exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.

The Class Destructor

A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.
A destructor will have the exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories, etc.

Question

/*
Define a class taxpayer with following specifications:
Data members:
- Int pan
- Char name[]
- Float income
- Float tax
Member functions:
-Input() to input data
-Disp() to display data
-Calctax() to calculate tax
Tax is calculated according to the following rates
Income                      tax
<=100000                    0%
100000 to 200000            10%
200000 to 500000            15%
>500000                      20%
(Make constructor and destructor too)

*/



#include<iostream>
#include<cstring>
#include<iomanip>
using namespace std;
class Taxpayer
{
private:
int pan;
char name[30];
float income;
float tax;

public:
Taxpayer() //constructor making
{
pan=0;
name[50]=0;
income=0;
tax=0;
}
Taxpayer(int p,char n[],float inc);
void Input();
void Display();
void Calctax();

~Taxpayer()
{
cout<<"\nDestructed..."<<endl;
}
};
void Taxpayer::Input()
{
cout<<"\nEnter pan number : ";
cin>>pan;
cout<<"\nEnter Name : ";
cin>>name;
cout<<"\nEnter income : ";
cin>>income;
}

void Taxpayer::Display()
{
cout<<"Pan No.:- "<<pan<<endl;
cout<<"Name:- "<<setw(4)<<name<<endl;
cout<<"Income :- "<<income<<endl;
}

void Taxpayer::Calctax()
{
if (income<=100000)
{
tax=0;
cout<<"No tax is charged."<<endl;
}
else if (income>100000 && income<=200000)
{
tax=0.1*income;
cout<<"Tax of 10% of total income is charged and the tax amount is : "<<tax<<endl;
}
else if (income>200000 && income<=500000)
{
tax=0.15*income;
cout<<"Tax of 15% of total income is charge and the tax amount is : "<<tax<<endl;
}
else
{
tax=0.2*income;
cout<<"Tax of 20% of total income is charged and the tax amount is : "<<tax<<endl;
}
}

int main()
{
Taxpayer t;
t.Input();
t.Display();
t.Calctax();
return 0;
}

Output


Enter pan number : 25

Enter Name : George

Enter income : 600000

Pan No.:- 25

Name:- George

Income :- 600000

Tax of 20% of total income is charged and the tax amount is : 120000

Destructed...


Rules for overloading operators

  • Only existing operators can be overloaded. New operators cannot be created.
  • The overloaded operator must have at least one operand that is of the user-defined type.
  • We cannot change the meaning of an operator. That is, we cannot redefine the plus (+) operator to subtract one value from others.
  • Overloaded operators follow the syntax rules of the original operators. That cannot be overridden.
  • Friend functions cannot be used to overload certain operators like =, ( ), [ ] and >.
  • Binary operators such as +, -, *, and / must explicitly return a value
  • As described above, all operators cannot be overloaded.
  • Unary operators overloaded by means of a member function take no explicit arguments and return no explicit values. But, those overloaded by means of friend function take one argument.
  • Binary operators overloaded by means of a member function take one explicit argument. But, those overloaded by means of friend function take two arguments.
  • The process of operator overloading generally involves following steps.
  • Declare a class whose objects are to be manipulated using operators.
  • Declare the operator function, in the public part of the class. It can either normal member function or friend function.
  • Define the operator function within the body of a class or outside the body of the class but function prototype must be inside the class body.



Operator Overloading

It is the mechanism of giving special meanings to an operator. By overloading operators, we can give additional meanings to operators like +, *, -, <=, >= etc. which by default are supposed to work only on standard data types like ints, floats.


In general,  a = b + c; works only with basic types like ‘int’ and ‘float’, and attempting to apply it when a, b and c are objects of a user-defined class will cause complaints from the compiler. But, using overloading, we can make this statement legal even when a, b and c are user-defined types (objects).

Even though the semantics of an operator can be expressed, we cannot change its syntax. When an operator overloaded, its original meaning is not lost. The grammar rules defined by C++ that govern its use such as the number of operands, precedence and associatively of the operator remains the same for overloaded operators. 
We can overload (give additional meanings to) all the C++ operators except the following:
  • Class member access operators (. , .*)
  • Scope resolution operator (::)
  • Size of operator (sizeof)
  • Conditional operator (?:)

There are two types of operator overloading
  • Unary operator overloading and
  • Binary operator overloading


Unary operator overloading


Unary operators are those operators that act on a single operand. ++, -- are unary operators. The following program overloads the ++ unary operator for the distance class to increment the data number by one.

class Distance
int feet; 
float inch; 
public: 
Distance (int f, float i);
 void operator++(void); 
void display();
};
Distance :: Distance (int f, float i)
feet = f ; inch = i;
}
void Distance :: display()
cout<<”Distance in feet”< 
cout<<”Distance in inch”<
}
void Distance :: operator ++(void)
feet++;  inch++;
}
void main()
Distance dist(10,10); 
++dist; 
dist.display();
}

In the above example, the ++ unary operator has been overloaded in the function void Distance :: operator ++(void). In this overloaded function, data members feet and inch are increased by one. This function is called at the second line ‘++dist’ in the main.
General syntax for defining operator overloading

return-type   
classname :: operator  operator-to-overload (arg. list)
//func body
}

The keyword ‘operator’ is used to overload an operator. This declaration tells the compiler to call this member function whenever the ++ operator is encountered, provided the operands are of the user-defined type.

//Another Example - overloading unary minus operator


class abc
int x,y,z; 
public: 
void getd/ata(int a,int b,int c) 
{  
x = a;  
y = b;  
z = c; 
void display() 
{  
cout< 
void operator -();
};
 void abc::operator-()
{
 x = -x;
y = -y; 
z = -z;
}

main()
abc a; 
a.getdata(4,-5,6); 
a.display();    
-a; 
a.display(); 
getch(); 
return 0;
}

Overloading Unary operator that return a value:
If we must use overloaded operator function for return a value as:
 Obj2=obj1++;  //returned object of obj++ is assigned to //obj2 

 

 //Example: unary operator overloading  with return type.

class index
int count;
public: 
index() 
{  
count=0; 
void display() 
{  
cout< 
index operator++() 
{  
++count;  
index temp;  
temp.count=count;  
return temp; 
} };
int main()
clrscr(); 
index c,d; 
cout< 
c.display();  ++c; 
cout< 
c.display();  d=++c; 
cout< 
c.display(); 
cout< 
d.display(); 
getch(); 
return 0;
}

Here the operator ++ ( ) function increments the count in its own objects as before, then creates the new temp object and assigns count in the new object the same value as in its own object. Finally it returns the temp object. This has the desired effect. Expression like ++c now return a value, so they can be used in other expressions such as d= ++c;
In this case the value returned from ++c is assigned to d.


Program’s output would look like this: 
C=0 
C=1 
C=2 
D=2  
In our program we created a temporary object called temp. Its purpose was to provide a return value for the ++ operator. We could have achieved the same effect using the nameless temporary object.

 
Rules for overloading operators

  • Only existing operators can be overloaded. New operators cannot be created.
  • The overloaded operator must have at least one operand that is of user-defined type.
  • We cannot change the meaning of an operator. That is, we cannot redefine the plus (+) operator to subtract one value from others.
  • Overloaded operators follow the syntax rules of the original operators. That cannot be overridden.
  • Friend functions cannot be used to overload certain operators like =, ( ), [ ] and >.
  • Binary operators such as +, -, *, and / must explicitly return a value
  • As described above, all operators cannot be overloaded.
  • Unary operators overloaded by means of a member function take no explicit arguments and return no explicit values. But, those overloaded by means of friend function take one argument.
  • Binary operators overloaded by means of a member function take one explicit argument. But, those overloaded by means of friend function take two arguments.
  • The process of operator overloading generally involves following steps.
  • Declare a class whose objects are to be manipulated using operators.
  • Declare the operator function, in public part of class. It can either normal member function or friend function.
  • Define operator function within the body of a class or outside the body of the class but function prototype must be inside the class body.


    C program to find Cartesian Product of two sets

     Cartesian product is a mathematical operation that returns a set (or product set or simply product) from multiple sets. That is, for sets A and B, the Cartesian product A × B is the set of all ordered pairs (ab) where a ∈ A and b ∈ B. Products can be specified using set-builder notation, e.g.



    Let us take an example of 3✕3 Cartesian product: -


    Let A = {a, b, c} and B = {d, e, f}
    The Cartesian product of two sets is
    A x B = {a, d}, {a, e}, {a, f}, {b, d}, {b, e}, {b, f}, {c, d}, {c, e}, {c, f}}



    Concept For the Code:-

    In this program we declare 3 array a, b and c of length 50, now we declare variable i, s1, s2, j, and k. Now we ask all the variables value from the user to compute the Cartesian product. The use of For Loop is to take out the Cartesian product until the user inputted condition is met.


    CODES

    #include <stdio.h>
    #include <conio.h>
    int main()
    {
        int a[50], b[50], c[50], i, s1, s2, j, k;
        printf("Enter how many elements in set 1\n");
        scanf("%d", &s1);
        printf("Enter how many elements in set 2\n");
        scanf("%d", &s2);
        printf("Enter elements of set 1\n");
        for (i = 0; i < s1; i++)
        {
            scanf("%d", &a[i]);
        }
        printf("Enter elements of set 2\n");
        for (i = 0; i < s2; i++)
        {
            scanf("%d", &b[i]);
        }
        printf("cartessian product=");
        printf("{");
        for (i = 0; i < s1; i++)
        {
            for (j = 0; j < s2; j++)
            {
                printf("(%d,%d)", a[i], b[j]);
                printf(",");
            }
        }
        printf("}");
    }

    This Program helps to calculate intersection of two sets, union of two sets, differences of two sets and symmetric difference of two sets using one simple program in which different variables are declared so that it can be useful to find intersection of two sets, union of two sets, differences of two sets and symmetric difference of two sets

    Codes

    #include <stdio.h>
    int a[10], b[10], c[10], d[10], i, j, k = 0, n, m, flag = 0;
    void unio()
    {
        for (i = 0; i < n; i++)
        {
            c[k] = a[i];
            k++;
        }
        for (i = 0; i < m; i++)
        {
            flag = 0;
            for (j = 0; j < n; j++)
            {
                if (b[i] == a[j])
                {
                    flag = 1;
                    break;
                }
            }
            if (flag == 0)
            {
                c[k] = b[i];
                k++;
            }
        }
        printf("\n Union \n");
        for (i = 0; i < k; i++)
        {
            printf("%d ", c[i]);
        }
    }
    void intersection()
    {
        printf("\nIntersections\n");
        for (i = 0; i < n; i++)
        {
            for (j = 0; j < m; j++)
            {
                if (a[i] == b[j])
                    printf("%d ", a[i]);
            }
        }
    }
    void difference()
    {
        printf("\nA-B\n");
        for (i = 0; i < n; i++)
        {
            flag = 0;
            for (j = 0; j < m; j++)
            {
                if (a[i] == b[j])
                {
                    flag = 1;
                    break;
                }
            }
            if (flag == 0)
                printf("%d ", a[i]);
        }
        printf("\n\nB-A\n");
        for (i = 0; i < m; i++)
        {
            flag = 0;
            for (j = 0; j < n; j++)
            {
                if (b[i] == a[j])
                {
                    flag = 1;
                    break;
                }
            }
            if (flag == 0)
                printf("%d ", b[i]);
        }
    }
    void symmetric_diff()
    {
        k = 0;
        for (i = 0; i < n; i++)
        {
            flag = 0;
            for (j = 0; j < m; j++)
            {
                if (a[i] == b[j])
                {
                    flag = 1;
                    break;
                }
            }
            if (flag == 0)
            {
                d[k] = a[i];
                k++;
            }
        }
        for (i = 0; i < m; i++)
        {
            flag = 0;
            for (j = 0; j < n; j++)
            {
                if (b[i] == a[j])
                {
                    flag = 1;
                    break;
                }
            }
            if (flag == 0)
            {
                d[k] = b[i];
                k++;
            }
        }

        printf("\n(A-B)U(B-A)\n");
        for (i = 0; i < k; i++)
        {
            printf("%d ", d[i]);
        }
    }
    int main()
    {
        printf("Enter the size of array A\n");
        scanf("%d", &n);
        printf("Enter the element of First array A\n");
        for (i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
        }
        printf("Enter the size of array B\n");
        scanf("%d", &m);
        printf("Enter the elements of array B\n");
        for (j = 0; j < m; j++)
        {
            scanf("%d", &b[j]);
        }
        unio();
        printf("\n");
        intersection();
        printf("\n");
        printf("difference of set\n");
        difference();
        printf("\n");
        symmetric_diff();
        printf("\n");
        return 0;
    }