Articles by "Cpp Programming"
Showing posts with label Cpp Programming. Show all posts

C++ Program To Calculate Square And Cube Of Given Number Using Nested Macro Substitution

This Program is to find the square and cube of given number using nested macro substitution which is on of the easier way to find because it is declared at the #define header which helps us further in the program to use it directly to get the output. 

Before writing a program let us know what is macro substitution? and How it works?

Macro substitution

Macro substitution has a name and replacement text, defined with #define directive. The preprocessor simply replaces the name of a macro with replacement text from the place where the macro is defined in the source code.

Source Code

#include<iostream>
using namespace std;
#include<iomanip>
#define square(x)(x*x) //defining the square
#define cube(x)(square(x)*x) //defining the cube
int main()
{
int x;
cout<<"Enter the value for x :\n";
cin>>x;
cout<<"Square is "<<square(x)<<endl<<"cube is "<<cube(x)<<endl;    // Using the defined function to calculate square and cube
return 0;
}

OUTPUT


Enter the value for x :
5
Square is 25
cube is 125

C++ Program for modular search and linear search using recursion function


Before starting with the program to find binary search and linear search using recursion function let us know about recursion function and Modular Search.


Recursion Function

Recursion is a process by which a function call itself repeatedly until some specified condition has been satisfied.
                
The process is used for repetitive computation in which action is stated in terms of previous result.
                
In order to solve a problem recursively two condition must be satisfied.
  • The problem must be written in a recursive form.
  • The problem statement must include a problem stopping condition.


Modular Search

It is the type of search in which we use mod recursively to find the item which is searched in the program.


C++ Program for linear search using recursion function


#include<iostream>
using namespace std;

int recursiveLinearSearch(int array[],int key,int size)
{
size=size-1;
if(size <0)
{
return -1;
}
else if(array[size]==key){
return 1;
}
else{
return recursiveLinearSearch(array,key,size);
}
}


int main()
{

cout<<"Enter The Size Of Array: ";
int size;
cin>>size;
int array[size], key,i;

// Taking Input In Array
for(int j=0;j<size;j++)
{
cout<<"Enter "<<j<<" Element : ";
cin>>array[j];
}
//Your Entered Array Is
for(int a=0;a<size;a++)
{
cout<<"array[ "<<a<<" ] = ";
cout<<array[a]<<endl;
}
cout<<"Enter Key To Search in Array";
cin>>key;
int result;
result=recursiveLinearSearch(array,key,size--);
if(result==1)
{
cout<<"Key Found in Array ";
}
else{
cout<<"Key NOT Found in Array ";
}
return 0;
}


C++ Program for modular search and using recursion function

#include <iostream>
using namespace std;
int mod (int x, int y, int a)
{
if (x == 0)
return 0;
if (y == 0)
return 1;
// If y is even
long temp;
if (y % 2 == 0) {
temp = mod(x, y / 2, a);
temp = (temp * temp) % a;
}
// If y is odd
else {
temp = x % a;
temp = (temp * mod(x, y - 1, a) % a) % a;
}
return (int)((temp + a) % a);
}
int main()
{
int x,y,a;
cout<<"x^y (mod a)"<<endl;
cout<<"Enter Base Value: ";
cin>>x;
cout<<"Enter Exponent: ";
cin>>y;
cout<<"Enter Modular Value: ";
cin>>a;
long temp;
temp= mod(x,y,a);
cout<<x <<" ^ "<<y <<" (mod "<<a<<")"<<" = "<<temp;
}

C++ Program To Represent The Graph Using Adjacency Matrix 

#include<iostream>

#include<iomanip>

using namespace std;

// A function to print the adjacency matrix.

void PrintMat(int mat[][20], int n)

{

    int i, j;

     cout<<"\n\n"<<setw(4)<<"";

     for(i = 0; i < n; i++)

      cout<<setw(3)<<"("<<i+1<<")";

     cout<<"\n\n";

// Print 1 if the corresponding vertexes are connected otherwise 0.

    for(i = 0; i < n; i++)

     {

          cout<<setw(3)<<"("<<i+1<<")";

          for(j = 0; j < n; j++)

          {

               cout<<setw(4)<<mat[i][j];

          }

          cout<<"\n\n";

     }

}

int main()

{

    int i, j, v;

     cout<<"Enter the number of vertexes: ";

     cin>>v;

     int  mat[20][20];

     cout<<"\n";

// Take input of the adjacency of each pair of vertexes.

    for(i = 0; i < v; i++)

     {

          for(j = i; j < v; j++)

          {

               if(i != j)

               {

                cout<<"Enter 1 if the vertex "<<i+1<<" is adjacent to "<<j+1<<", otherwise 0: ";

                cin>>mat[i][j];

                 mat[j][i] = mat[i][j];

               }

               else

                mat[i][j] = 0;

          }

     }

     PrintMat(mat, v);

     return 0;

}

OUTPUT

C++ Program To Represent The Graph Using Adjacency Matrix


Difference Between Procedure Oriented Programming (POP) & Object-Oriented Programming (OOP) | C++ Programming


Procedure Oriented ProgrammingObject-Oriented Programming
Divided IntoIn POP, the program is divided into small parts called functions.In OOP, the program is divided into parts called objects.
ImportanceIn POP, Importance is not given to data but to functions as well as the sequence of actions to be done.In OOP, Importance is given to the data rather than procedures or functions because it works as a real world.
ApproachPOP follows Top-Down approach.OOP follows Bottom-Up approach.
Access SpecifiersPOP does not have any access specifier.OOP has access specifiers named Public, Private, Protected, etc.
Data MovingIn POP, Data can move freely from function to function in the system.In OOP, objects can move and communicate with each other through member functions.
ExpansionTo add new data and function in POP is not so easy.OOP provides an easy way to add new data and functions.
Data AccessIn POP, the Most function uses Global data for sharing that can be accessed freely from function to function in the system.In OOP, data can not move easily from function to function,it can be kept public or private so we can control the access of data.
Data HidingPOP does not have any proper way for hiding data so it is less secure.OOP provides Data Hiding so it provides more security.
OverloadingIn POP, Overloading is not possible.In OOP, overloading is possible in the form of Function Overloading and Operator Overloading.
ExamplesExample of POP are : C, VB, FORTRAN, Pascal.Example of OOP are : C++, JAVA, VB.NET, C#.NET.

C++ Program For Banking System Using Class

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

class bank
{
char name[20];
int acno;
char actype[20];
int bal;
public :
void opbal(void);
void deposit(void);
void withdraw(void);
void display(void);
};

void bank :: opbal(void)
{
cout<<endl<<endl;
cout<<"Enter Name :-";
cin>>name;
cout<<"Enter A/c no. :-";
cin>>acno;
cout<<"Enter A/c Type :-";
cin>>actype;
cout<<"Enter Opening Balance:-";
cin>>bal;
}

void bank :: deposit(void)
{
cout<<"Enter Deposit amount :-";
int deposit=0;
cin>>deposit;
deposit=deposit+bal;
cout<<"\nDeposit Balance = "<bal=deposit;
}

void bank :: withdraw(void)
{
int withdraw;
cout<<"\nBalance Amount = "<<bal;
cout<<"\nEnter Withdraw Amount :-";
cin>>withdraw;
bal=bal-withdraw;
cout<<"After Withdraw Balance is "<<bal;
}

void bank :: display(void)
{
cout<<endl<<endl<<endl;
cout<<setw(50)<<"DETAILS"<<endl;
cout<<setw(50)<<"name "<<name<<endl;
cout<<setw(50)<<"A/c. No. "<<acno<<endl;
cout<<setw(50)<<"A/c Type "<<actype<<endl;
cout<<setw(50)<<"Balance "<<bal<<endl;
}

int main()
{
bank o1;
int choice;
do
{
cout<<"\n\nChoice List\n\n";
cout<<"1) To assign Initial Value\n";
cout<<"2) To Deposit\n";
cout<<"3) To Withdraw\n";
cout<<"4) To Display All Details\n";
cout<<"5) EXIT\n";
cout<<"Enter your choice :-";
cin>>choice;
switch(choice)
{
case 1: o1.opbal();
break;
case 2: o1.deposit();
break;
case 3: o1.withdraw();
break;
case 4: o1.display();
break;
case 5: goto end;
}
}while(1);
end:
return 0;
}

Output



Choice List

1)  Create a New Account
2)  To Deposit
3)  To Withdraw
4)  To Display All Details
5)  EXIT
Enter your choice :-1


Enter Name :-John
Enter A/c no. :-0012003322
Enter Opening Balance:-5000


Choice List

1)  Create a New Account
2)  To Deposit
3)  To Withdraw
4)  To Display All Details
5)  EXIT
Enter your choice :-2
Enter Deposit amount :-6000

Deposit Balance = 11000

Choice List

1)  Create a New Account
2)  To Deposit
3)  To Withdraw
4)  To Display All Details
5)  EXIT
Enter your choice :-3

Balance Amount = 11000
Enter Withdraw Amount :-4000
After Withdraw Balance is 7000

Choice List

1)  Create a New Account
2)  To Deposit
3)  To Withdraw
4)  To Display All Details
5)  EXIT
Enter your choice :-4



                                           DETAILS
                                        name      John
                                     A/c. No.     12003322
                                      Balance     7000


Choice List

1)  Create a New Account
2)  To Deposit
3)  To Withdraw
4)  To Display All Details
5)  EXIT
Enter your choice :-5

Constructor Overloading

When more than one constructor function is defined in a class, then it is called constructor overloading or the use of multiple constructors in a class. It is used to increase the flexibility of a class by having a greater number of constructors for a single class. Overloading constructors in C++ programming gives us more than one way to initialize objects in a class.

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.
Following example explains the concept of constructor −

#include 
using namespace std; 
class Line { public: 
void setLength( double len ); 
double getLength( void ); 
Line(); // This is the constructor 
private: 
double length;}; // Member functions definitions including constructorLine::Line(void) 
{ 
 cout << "Object is being created" << 
endl;
}
void Line::setLength( double len ) 
{ 
 length = len;}double Line::getLength( void ) 
{ 
return length;
}// Main function for the program
int main() 
{ 
Line line; // set line length 
line.setLength(6.0); 
cout << "Length of line : " << 
line.getLength() <<
endl; 
return 0;
}
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6

Parameterized Constructor

A default constructor does not have any parameter, but if you need, a constructor can have parameters. This helps you to assign an initial value to an object at the time of its creation as shown in the following example −

#include 
using namespace std;
class Line 
{ 
public: 
void setLength( double len ); 
double getLength( void ); 
Line(double len); // This is the constructor 
private: 
double length;}; // Member functions definitions including constructorLine::Line( double len) 
{ 
 cout << "Object is being created, length = " << 
len << 
endl;
length = len;
}
void Line::setLength( double len ) 
{ 
 length = len;
}
double Line::getLength( void ) 
{ 
return length;
} 
// Main function for the program
int main() 
{ 
Line line(10.0); // get initially set length. 
 cout << "Length of line : " << 
line.getLength() <<endl; // set line length again line.setLength(6.0); 
cout << "Length of line : " << 
line.getLength() <<
endl; 
return 0;
}
When the above code is compiled and executed, it produces the following result −

Object is being created, length = 10
Length of line : 10
Length of line : 6


C++ Program for Constructor Overloading

#include<iostream>
using namespace std;
class item
{
int code,price;
public:
item()
{
code=0; price=0;
}
item(int c, int p)// Over Loading Constructor
{
code=c; price=p;
}
ite5m(item &x)
{
code=x.code; price=x.price;
}
void display()
{
cout<<"\ncode:"<<code<<"\nPrice:"< }
};
int main()
{
item i1;
item i2(102,300);//Passing Value
item i3(i2);
i1.display();
i2.display();
i3.display();

}

C++ Program To Find Negation Of A Number

#include<iostream>
using namespace std;
class point{
int x,y;
public:
void getdata()
{
cout<<"Enter x and y coordinate:";
cin>>x>>y;
}
void display()
{
cout<<"("<<x<<","<<y<<")";
}
point operator -()
{
point t;
t.x=-x;
t.y=-y;
return t;
}
};
int main()
{
point p,q;
p.getdata();
q=-p;
cout<<"q=";
q.display();
}

OUTPUT


Enter x and y coordinate:
5
4
q=(-5,-4)

Access Modifiers in C++

Access modifiers are constructs that define the scope and visibility of members of a class. There are three access modifiers:


Private

Private members are accessible only inside the class and not from any other location outside of the class.

Protected

Protected members are accessible from the class as well as from the child class but not from any other location outside of the class.

Public

Public members are accessible from any location of the program.
class Test

{ 
private:   int x;  public: int y;
void getdata()
{ 
cout<<”Enter x and y”<<endl; 
cin>>x>>y;
}
void display()
{ 
cout<<”x=”<<x<<”y=”<<y<<endl;
} }

void main()
{ 
clrscr(); 
Test p;
p.getdata(); 
cout<<”Enter  value of x”<<endl; 
cin>>p.x;
cout<<”Enter value of y”<<endl; 
cin>
>
p.y; 
getch();
}


Here the statement “cin>>p.x;” generates error because x is private data member because, x is private data member and is not accessible from outside of the class. But the statement “cin>>p.y;” does not generates error because y is public data member and is accessible from everywhere. Thus we can say that use of private access specifier is used to achieve data hiding in class.

Types of Inheritance


A class can inherit properties from one or more classes and from one or more levels.

On the basis of this concept, there are five types of inheritance.

  1. Single Inheritance
  2. Multiple Inheritance
  3. Hierarchical Inheritance
  4. Multilevel Inheritance
  5. Hybrid Inheritance

Single Inheritance

In single inheritance, a class is derived from only one base class. The example and figure below show this inheritance.
Example

class A
{
 members of A
};
class B  :  public A
{
 members of B
};

Multiple Inheritance

In this inheritance, a class is derived from more than one base class. The example and figure below show this inheritance.
Implementation Skeleton:

class A
{
members of A
}; class B
{  members of B
};
class C  :
public A,
public B 
{
members of C
};

Hierarchical Inheritance

In this type, two or more classes inherit the properties of one base class. The example and figure below show this inheritance.
Implementation Skeleton:
class A
{
members of A
};
class B
{
members of B
};
class C  : 
public A,
public B 
{
members of C
};

Multilevel Inheritance

The mechanism of deriving a class from another derived class is known as multilevel inheritance. The process can be extended to an arbitrary number of levels. The example and figure below show this inheritance.
Implementation Skeleton:
class A
{
members of A
};
class B :
public A
{
members of B
};
class C  :
public B 
{
members of C
};

Hybrid Inheritance

This type of inheritance includes more than one type of inheritance mentioned previously. The example and figure below show this inheritance.
Example
class A
{
 members of A
};
class B :
public A
{
 members of B
};
class C  :
public A 
{
 members of C
};
class D :
public B, public C
{
 members of D
};

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();
}