Showing posts with label cplusplus. Show all posts
Showing posts with label cplusplus. Show all posts

Implement Adjacency Matrix in C++ using pointers

This program is about implementing an Adjacency Matrix using two dimensional matrix and pointers in C++.


In this program, the following methods are involved :
  • graph() - a default constructor
  • graph(int) - which accepts an integer parameter dim to allocate the matrix using malloc
  • display() - which displays the adjacency matrix
  • add_link(int,int) - which accepts two integer parameters, to check whether a link is needed or whether a link is already present
  • add_node() - it creates a temporary matrix with an additional dimension, original matrix is copied to temporary matrix. Then the original matrix is freed from the memory and again reallocated with an additional dimension and then data in the temporary matrix is again copied into the original matrix and temporary matrix is freed from the memory 
  • path_exist(int,int) - returns 1 if path exists between two vertices and returns 0 if not.
All of the above mentioned methods are mentioned in a custom made header file graph.h
        //graph.h
 #ifndef GRAPH_H_
 #define GRAPH_H_
 class graph
 {
  private :
   int **mat;
   int n;

  public :
   graph();
   graph(int);
   void display();
   int add_link(int,int);
   void add_node();
   int path_exist(int,int);
 };
 #endif 

Now, let us look at the graph.cpp file.

//graph.cpp
#include<iostream>
#include<stdlib.h>
#include "graph.h"
using namespace std;
int n1;
graph::graph()
{
 mat=NULL;
}
graph::graph(int dim)
{
 n=dim;
 n1=n;
 int i,j;
 mat=(int **)malloc(n*sizeof(int));
 for(i=0;i<n;i++)
  mat[i]=(int *)malloc(n*sizeof(int));  
}
void graph::display()
{
 int i,j;
 cout<<"\nYour current matrix is : \n";
 cout<<"**************************\n";
 for(i=0;i<n;i++)
 {
  for(j=0;j<n;j++)
   cout<<*(*(mat+i)+j)<<"   ";
  cout<<"\n";
 }
 cout<<"\n";
}
int graph::add_link(int r,int c)
{
 if(*(*(mat+r)+c)==0)
 {
  *(*(mat+r)+c)=1;
  return 1;
 }
 else return 0;  
}
void graph::add_node()
{
 int i,j,**temp;
 temp=new int *[n+1];
 for(i=0;i<n+1;i++)
  temp[i]=new int[n+1];  
 for(i=0;i<n;i++)
  for(j=0;j<n;j++)    
   *(*(temp+i)+j)=*(*(mat+i)+j);  
 
 delete(mat);  
 n++;   
 n1=n;
 mat=(int **)malloc(n*sizeof(int));   
 for(i=0;i<n;i++)
  mat[i]=(int *)malloc(n*sizeof(int)); 
 for(i=0;i<n;i++) 
  for(j=0;j<n;j++)
   *(*(mat+i)+j)=*(*(temp+i)+j);  
 delete(temp);  
}
int graph::path_exist(int r,int c)
{
 if(*(*(mat+r)+c)==1)  
  return 1;
 else return 0;  
}
main()
{
 int dim,ch,r,c,r1,c1;
 cout<<"\nProgram to implement a matrix in c++ \n";
 cout<<"\nEnter matrix dimension : ";
 cin>>dim;
 graph g(dim);  
 g.display();
 do
 {
 cout<<"[1]Add link"<<" "<<"[2]Add Node"<<" "<<"[3]Path Exist"<<" "<<"[4]Display"<<" "<<"[5]Exit"<<"\n";
 cout<<"\nEnter your choice : ";
 cin>>ch;
 switch(ch)
 {
  case 1:
   cout<<"\nEnter row and column to insert : ";
   cin>>r>>c;
   if(r>n1-1 || c>n1-1)
    cout<<"\nEnter valid row and column...\n";
   else
   { 
    int flag=g.add_link(r,c);
    if(flag==1)
     cout<<"\nInsertion completed....\n";
    else
     cout<<"\nLink already present...\n";
   }
   g.display();
   break;
  case 2:
   g.add_node();
   g.display();
   break;
   case 3:
   cout<<"\nEnter row and column to check : ";
   cin>>r1>>c1;
   if(r1>n1-1 || c1>n1-1)
    cout<<"\nEnter valid row and column...\n\n";
   else
   { 
    int flag1=g.path_exist(r1,c1);
    if(flag1==1)
     cout<<"\nPath exists..\n\n";
    else
     cout<<"\nPath doesn't exist..\n\n";
   }
   break; 
  case 4: 
   g.display();
   break;
  case 5: break;
  default: cout<<"\nEnter correct choice .. \n";
    break;         
 }
 }while(ch!=5); 
}

Minimum Multiplication in Matrix Chain Multiplication in C

In this post, I will show how to write a program in C which will calculate the minimum number of multiplications required in a matrix chain multiplication. There are two algorithms for calculating the minimum no. of multiplication, one is recursive and another is non recursive.

First let us look at the pseudo code.




The recursive programs are always easy to understand but difficult for a programmer to keep it in control. The non recursive programs are longer and difficult to understand but they can be controlled more easily.

Since the theory part can be found in any algorithm book, I am only going to show the programming part.

Let us look at the Non-Recursive Code in C :

#include<stdio.h>
#include<limits.h>
int mat(int p[], int n)
{
 int m[n][n];
 int i, j, k, L, q;
 for (i = 1; i < n; i++)
  m[i][i] = 0;
 for (L=2; L<n; L++)  
 {
       for (i=1; i<=n-L+1; i++)
         {
          j = i+L-1;
          m[i][j] = INT_MAX;
          for (k=i; k<=j-1; k++)
          {
                   q = m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
                    if (q < m[i][j])
                  m[i][j] = q;
          }
         }
 }
 return m[1][n-1];
}
main()
{
 printf("\nProgram to find minimum multiplications:\n");
 int i,n;
 printf("\nEnter number of matrices : ");
 scanf("%d",&n);      
 int a[n];
 printf("\nEnter the dimensions of matrices: ");
 for(i=0;i<=n;i++)
  scanf("%d",&a[i]);      
 printf("\nMinimum multiplications = %d\n\n",mat(a,n+1));
}

Let us look at the Recursive Code in C :

#include<stdio.h>
#include<limits.h>
int mat(int p[], int i, int j)
{
   if(i == j)
         return 0;
     int k,min = INT_MAX,count;
  for (k = i; k <j; k++)
     {
         count=mat(p,i,k)+mat(p,k+1,j)+p[i-1]*p[k]*p[j];
         if (count < min)
          min = count;
     }    
    return min;
}
main()
{
 printf("\nProgram to find the minimum multiplications :\n");
 int i,n;
 printf("\nEnter number of matrices : ");
 scanf("%d",&n);      
 int a[n];
 printf("\nEnter the dimensions of matrices : ");
 for(i=0;i<=n;i++)
  scanf("%d",&a[i]);  
     printf("Minimum multiplications=%d\n\n",mat(a,1,n));    
}

Sorting Algorithms in C++ by using custom made Header file

In C++, you can create your own header file and declare function prototypes in them. An then you can define the functions in .cpp file.
In this post, I will demonstrate how to implement some the most common sorting algorithms in C++ using a custom made header file.

// sort.h
 
#ifndef SORT_H_
#define SORT_H_
#define n 10 
class sort
{
 private:
  int a[n];
   
 public:
  void display();   
  void input();     
  void bubble_sort();
  void selection_sort();
  void insertion_sort();
  void merge_sort(int[],int,int);
  void quick_sort(int[],int,int);
  void shell_sort();
  void radix_sort();
};
#endif   


// sort.cpp
#include<iostream>
#include "sort.h"
#include<malloc.h>
#include<stdlib.h>
using namespace std;
int b[n];  
void sort::input()
{
 int i;  
 for(i=0;i<n;i++)
  a[i]=rand()%100;
}
void recur_input()
{
 int i;  
 for(i=0;i<n;i++)
  b[i]=rand()%100;
}
void sort::display()
{
 int i;
 for(i=0;i<n;i++)
  cout<<a[i]<<"   ";
}
void recur_display()
{
 int i;
 for(i=0;i<n;i++)
  cout<<b[i]<<"   ";
}
void merge(int a[],int l,int mid,int h)
{ 
 int i=l,j=mid+1,k=l,c[50];
 while((i<=mid)&&(j<=h))
 {
  if(a[i]<=a[j])
   c[k++]=a[i++];
  else
   c[k++]=a[j++];       
 }     
 while(i<=mid)   
  c[k++]=a[i++];    
  
 while(j<=h)
  c[k++]=a[j++];    
 
 for(i=l;i<k;i++) 
  a[i]=c[i];     
}
int partition(int *a,int l,int h)
{
 int i,j,pv;
 pv=a[l];
 i=l,j=h+1;
 do
 {
  while(a[i]<=pv) i++;
  while(a[j]>pv) j--;
  if(i<j) 
  {
   int temp=a[i];
   a[i]=a[j];
   a[j]=temp;
  }
  else break;
 }while(i<=j); 
 int temp=a[l];
 a[l]=a[i-1];
 a[i-1]=temp;   
 return i-1;
} 
void sort::bubble_sort()
{
 int i,j;
 for(i=0;i<n-1;i++)
  for(j=0;j<n-1-i;j++)
   if(a[j]>a[j+1])
   {
    int temp=a[j];
    a[j]=a[j+1];
    a[j+1]=temp;
   }
}
void sort::selection_sort()
{
 int i,j,min,pos;   
 for(i=0;i<n;i++)
 {
  min=a[i];
  pos=i;
  for(j=i+1;j<n;j++)
  {
   if(a[j]<min)
   { 
    min=a[j];    
    pos=j;
   }
  }
  if(pos!=i)
  {
   int temp=a[i];
   a[i]=a[pos];
   a[pos]=temp;
  }
  
 }
}
void sort::insertion_sort()
{
 int temp,i,j;
 for(i=1;i<n;i++)
 {
  temp=a[i];
  for(j=i-1;((j>=0)&&(temp<a[j]));j--)
  {
   a[j+1]=a[j];
  }
  a[j+1]=temp;
 }
}
void sort::merge_sort(int a[],int l,int h)
{ 
 int mid;
 if(l<h)
 { mid=(l+h)/2;
  merge_sort(a,l,mid);
  merge_sort(a,mid+1,h);
  merge(a,l,mid,h);
 }
    
}
void sort::quick_sort(int a[],int l,int h)
{
 int x;
 if(l>=h) return;
 x=partition(a,l,h);
 quick_sort(a,l,x-1);
 quick_sort(a,x+1,h);
}
void sort::shell_sort()
{
 int i,j,d=n*4/5;
 while(d>=1)
 {
  for(i=0;i<n-d;i++)
   if(a[i]>a[i+d]) 
   {
    int temp=a[i];
    a[i]=a[i+d];
    a[i+d]=temp;
   }
  if(d==1)
   break;
  d=d*4/5;
 }
}
void sort::radix_sort()
{
 int i,j,k=1,l,temp,b[10][n],cnt;
 int max=a[0],c=0;
 for(i=0;i<n;i++)
  if(a[i]>max)
   max=a[i];
 while(max%10)
 {
  c++;
  max/=10;
 } 
 for(i=0;i<10;i++)
  for(j=0;j<n;j++)
   b[i][j]=-999; 
 for(l=0;l<c;l++)
 {
  for(j=0;j<n;j++)
  {
   temp=(a[j]/k)%10;
   b[temp][j]=a[j];
  }
  k=k*10; cnt=0;
  for(i=0;i<10;i++)
   for(j=0;j<n;j++)
    if(b[i][j]!=-999)
     a[cnt++]=b[i][j];
  for(i=0;i<10;i++)
   for(j=0;j<n;j++)
    b[i][j]=-999;
 }
}
main()
{
int ch,i;
cout<<"\nProgram of sorting algorithms :\n";
sort s;  
do
{
  cout<<"\n\n[1] Bubble   [2] Selection  [3] Insertion  ";
  cout<<"\n[4] Merge      [5] Quick   [6] Shell Sort ";
  cout<<"\n[7] Radix      [8] Exit ";
  cout<<"\nEnter your choice : ";
  cin>>ch;
  switch(ch)
  {
 case 1: 
  s.input();    
  cout<<"\nArray before sorting : \n";
  s.display();
  s.bubble_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 2: 
  s.input();    
  cout<<"\nArray before sorting : \n";
  s.display();
  s.selection_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 3: 
  s.input();    
  cout<<"\nArray before sorting : \n";
  s.display();
  s.insertion_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 4: 
  recur_input();
  cout<<"\nArray before sorting : \n";
  recur_display();     
  s.merge_sort(b,0,n-1);
  cout<<"\nArray after sorting : \n";
  recur_display();
  break;
 case 5: 
  recur_input();
  cout<<"\nArray before sorting : \n";
  recur_display();    
  s.quick_sort(b,0,n-1);
  cout<<"\nArray after sorting : \n";
  recur_display();
  break;
 case 6: 
  s.input();    
  cout<<"\nArray before sorting : \n";
  s.display();
  s.shell_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 7:
  s.input();     
  cout<<"\nArray before sorting : \n";
  s.display();
  s.radix_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 8:
  break;
 default: cout<<"\nEnter correct choice .... \n";
  break;     
 }
 }while(ch!=8);  
  
 } 

Program to print number sequence in C++ (3)

/* Program to print sequence

                   1
                  121
                 12321
                1234321
                 12321
                  121
                   1
*/

#include<stdio.h>
#include<iostream>
main()
    {
        int i,j,k,p=4;
        for(i=1;i<=4;i++)
        {
            for(k=1;k<=p;k++)
                std::cout<<" ";
            p--;
            for(j=1;j<=i;j++)
                std::cout<<j;
            for(j=i-1;j>=1;j--)
                std::cout<<j;
            std::cout<<"\n";
        }
        p=2;
        for(i=3;i>=1;i--)
        {
            for(k=1;k<=p;k++)
                std::cout<<" ";
            p++;    
            for(j=1;j<=i;j++)
                std::cout<<j;
            for(j=i-1;j>=1;j--)
                std::cout<<j;
            std::cout<<"\n";
        }
    }    

Program to print number sequence in C++ (2)

 /*  Program to print sequence

                                 1
                                101
                               10101
                              1010101
                               10101
                                101
                                 1
     */

#include<stdio.h>
#include<iostream>
main()
    {
        int i,p=4,a=1,k,j;
        for(i=1;i<=4;i++)
        {
            a=1;
            for(k=1;k<=p;k++)
                std::cout<<" ";
            p--;
            for(j=1;j<=i;j++)
            {
                std::cout<<a;
                if(a==0)
                    a=1;
                else
                    a=0;
            }
            for(j=i-1;j>=1;j--)
            {
                std::cout<<a;
                if(a==0)
                    a=1;
                else
                    a=0;
            }
            std::cout<<"\n";
        }
        p=2;
        for(i=3;i>=1;i--)
        {
            a=1;
            for(k=1;k<=p;k++)
                std::cout<<" ";
            p++;
            for(j=1;j<=i;j++)
            {
                std::cout<<a;
                if(a==0)
                    a=1;
                else
                    a=0;
            }
            for(j=i-1;j>=1;j--)
            {
                std::cout<<a;
                if(a==0)
                    a=1;
                else
                    a=0;
            }
            std::cout<<"\n";
        }
    }        

Printing String Sequence in C++ (1)

/* Program to print string sequence in C++

        C O M P U T E R
          C O M P U T E
            C O M P U T
              C O M P U
                C O M P
                  C O M
                    C O
                      C        */

#include<iostream>
#include<stdio.h>
#include<string.h>
main()
    {
        int l,i,j,p=1,s=1,k;
        char a[]="COMPUTER";
        l=strlen(a);
        for(i=l;i>0;i--)
        {
            for(k=1;k<=s;k++)
                std::cout<<" ";
            s=s+2;
            for(j=0;j<i;j++)
            {
                std::cout<<" ";
                p++;
                std::cout<<a[j];
            }
            std::cout<<"\n";
        }
    }

Program to print number sequence in C++ (1)

/*  Program to print number sequence in C++


               1
              212
             32123
            4321234
           543212345               */


#include<iostream>
#include<stdio.h>
main()
{
        int i,s=5,j,k;
        for(i=1;i<=5;i++)
        {
            for(k=1;k<=s;k++)
                std::cout<<" ";
            s--;
            for(j=i;j>=1;j--)
                std::cout<<j;
            for(j=2;j<=i;j++)
                std::cout<<j;
            std::cout<<"\n";
        }
 }

Implement Circular queue in C++

#include<iostream.h> 
#include<stdio.h> 
int display_menu(); 
class circularqueue 
{ 
  int arr[10]; 
  int front,rear; 
  int size; 
  public: 
     circularqueue() 
     { 
      front=0; 
      rear=0; 
      size=10; 
     } 
     void display(); 
     void enqueue(); 
     void delete_element(); 
}; 
void circularqueue :: display() 
{ 
 cout<<endl; 
 if(front!=0 && rear!=0) 
 { 
        int i=front; 
        cout<<"arr["<<i<<"] :"<<arr[i]<<endl; 
        while(i!=rear) 
        { 
         i=(i % size)+1; 
         cout<<"arr["<<i<<"] :"<<arr[i]<<endl; 
        } 
 } 
 else 
 { 
    cout<<"Queue is empty"<<endl; 
 } 
 getch(); 
} 
void circularqueue :: enqueue() 
{ 
 cout<<endl; 
 if(front==0 && rear==0) 
 { 
  cout<<"Enter Number to enqueue at Position arr["<<rear+1<<"] :"; 
  cin>>arr[1]; 
  rear=1; 
  front=1; 
 } 
 else 
 { 
  int next=(rear % size)+1; 
  if(next==front) 
  { 
   cout<<"Queue is Full ..."; 
   getch(); 
  } 
  else 
  { 
   cout<<"Enter Number to enqueue at Position arr["<<next<<"] :"; 
   cin>>arr[next]; 
   rear=next; 
  } 
 } 
} 
void  circularqueue :: delete_element() 
{ 
 cout<<endl; 
 if(rear==0 && front==0) 
 { 
   cout<<"Queue is empty ..."; 
   getch(); 
   return; 
 } 
 if(rear==front) 
 { 
  rear=0; 
  front=0; 
 } 
 else 
 { 
  front=(front % size)+1; 
 } 
} 
void main() 
{ 
 circularqueue cq1; 
 while(1) 
 { 
  switch(display_menu()) 
  { 
    case 1: cq1.enqueue(); 
        break; 
    case 2: cq1.delete_element(); 
        break; 
    case 3: cq1.display(); 
        break; 
    case 4: exit(1); 
  } 
 } 
} 
int display_menu() 
{ 
 int c; 
 clrscr(); 
 cout<<endl; 
 cout<<"| 1 | : Enqueue element"<<endl; 
 cout<<"| 2 | : Delete element"<<endl; 
 cout<<"| 3 | : Display"<<endl; 
 cout<<"| 4 | : Exit"<<endl; 
 cout<<"Enter your Choice :"; 
 cin>>c; 
 return c; 
}/*Code for Program to create a circular queue in C++ Programming*/ 
#include<iostream.h> 
#include<stdio.h> 
int display_menu(); 
class circularqueue 
{ 
  int arr[10]; 
  int front,rear; 
  int size; 
  public: 
     circularqueue() 
     { 
      front=0; 
      rear=0; 
      size=10; 
     } 
     void display(); 
     void enqueue(); 
     void delete_element(); 
}; 
void circularqueue :: display() 
{ 
 cout<<endl; 
 if(front!=0 && rear!=0) 
 { 
        int i=front; 
        cout<<"arr["<<i<<"] :"<<arr[i]<<endl; 
        while(i!=rear) 
        { 
         i=(i % size)+1; 
         cout<<"arr["<<i<<"] :"<<arr[i]<<endl; 
        } 
 } 
 else 
 { 
    cout<<"Queue is empty"<<endl; 
 } 
 getch(); 
} 
void circularqueue :: enqueue() 
{ 
 cout<<endl; 
 if(front==0 && rear==0) 
 { 
  cout<<"Enter Number to enqueue at Position arr["<<rear+1<<"] :"; 
  cin>>arr[1]; 
  rear=1; 
  front=1; 
 } 
 else 
 { 
  int next=(rear % size)+1; 
  if(next==front) 
  { 
   cout<<"Queue is Full ..."; 
   getch(); 
  } 
  else 
  { 
   cout<<"Enter Number to enqueue at Position arr["<<next<<"] :"; 
   cin>>arr[next]; 
   rear=next; 
  } 
 } 
} 
void  circularqueue :: delete_element() 
{ 
 cout<<endl; 
 if(rear==0 && front==0) 
 { 
   cout<<"Queue is empty ..."; 
   getch(); 
   return; 
 } 
 if(rear==front) 
 { 
  rear=0; 
  front=0; 
 } 
 else 
 { 
  front=(front % size)+1; 
 } 
} 
void main() 
{ 
 circularqueue cq1; 
 while(1) 
 { 
  switch(display_menu()) 
  { 
    case 1: cq1.enqueue(); 
        break; 
    case 2: cq1.delete_element(); 
        break; 
    case 3: cq1.display(); 
        break; 
    case 4: exit(1); 
  } 
 } 
} 
int display_menu() 
{ 
 int c; 
 clrscr(); 
 cout<<endl; 
 cout<<"| 1 | : Enqueue element"<<endl; 
 cout<<"| 2 | : Delete element"<<endl; 
 cout<<"| 3 | : Display"<<endl; 
 cout<<"| 4 | : Exit"<<endl; 
 cout<<"Enter your Choice :"; 
 cin>>c; 
 return c; 
}

File Handling in C++

/*  Program to print ASCII Values using put()  */

    #include<fstream.h>
    #include<conio.h>
    void main()
    {
            ofstream fout;
            fout.open("ASCIIChars",ios::app);
            if(!fout)
            {
                cout<<"The file cannot be opened ...\n";
                return;
            }
            char ch;
            int line=0;
            for(int i=33;i<128;i++)
                fout.put((char)i);
            fout.close();
            ifstream fin;
            fin.open("ASCIIChars",ios::in);
            fin.seekg(0);
            for(i=33;i<128;i++)
            {
                fin.get(ch);
                cout<<" "<<i<<" = ";
                cout.put((char)i);
                if(!(i%8))
                    cout<<endl<<line++;
                if(line>22)
                {
                    getch();
                    line=0;
                }
            }
    }

Bubble Sort in C++


    #include<iostream>
    #include<stdio.h>
    void swap(int *a,int x,int y)
        {
            int temp=*(a+x);
            *(a+x)=*(a+y);
            *(a+y)=temp;
        }
    void bubble_sort(int a[],int n)
    {
        int i,j;
        for(i=0;i<n-1;i++)
            for(j=0;j<n-1-i;j++)
                if(a[j]>a[j+1])
                    swap(a,j,j+1);

    }

    main()
        {    int i,n;
            std::cout<<"Program to sort using bubblesort :"<<"\n";
            std::cout<<"Enter array capacity :" ;
            std::cin>>n;
            int a[n];
            std::cout<<"Enter the numbers : "<<"\n";
            for(i=0;i<n;i++)
                std::cin>>a[i];
            printf("\nGIVEN ARRAY :  ");
            for(i=0;i<n;i++)
                std::cout<<a[i]<<"  ";
            printf("\n\nSORTED ARRAY : ");
            bubble_sort(a,n);
            for(i=0;i<n;i++)
                std::cout<<a[i]<<"  ";
            std::cout<<"\n\n";
        }
                   

Top