Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Tuesday, December 8, 2015

Read very large strings of UNKNOWN length

char buffer[10];
    char *s = 0;
    size_t cur_len = 0;
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        size_t buf_len = strlen(buffer);
        char *extra = realloc(s, buf_len + cur_len + 1);
        if (extra == 0)
            break;
        s = extra;
        strcpy(s + cur_len, buffer);
        cur_len += buf_len;
    }

Friday, November 6, 2015

Graph implementation using adjacency list

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int key;
    struct node * next;
}node;
typedef struct list
{
    struct node * head;
}list;
typedef struct GRAPH
{
    int V;
    struct list * array;
}GRAPH;
node * newnode(int k)
{
    node *n=(node *)malloc(1*sizeof(node));
    n->key=k;
    return n;
}
GRAPH *newgraph(GRAPH * g,int v)
{   g=(GRAPH *)malloc(sizeof(GRAPH));
    g->V=v;int i;
    g->array=(list *)malloc(v*sizeof(g->array));
    for(i=0;i<v;i++)
         g->array[i].head=NULL;
    return g;
}
void add_edge(GRAPH * g,int s , int t)
{
    node *n=newnode(t);
    n->next=g->array[s].head;
    g->array[s].head=n;
    node *n2=newnode(s);
    n2->next=g->array[t].head;
    g->array[t].head=n2;
}

void delete_edge(GRAPH * g,int s , int t)
{
     if(g->array[s].head==NULL){printf("There is no edge between %d and %d \n", s , t);return;}
    node * ptr1=g->array[s].head;
    if(ptr1->next==NULL)
        {if(ptr1->key==t){free(ptr1);ptr1=NULL;}return;}
    if(ptr1->key==t)
    {  g->array[s].head=ptr1->next;free(ptr1);return;}

    node * ptr2=g->array[s].head->next;

    while(ptr2!=NULL)
    {
        if(ptr2->key!=t)
          {
            ptr1=ptr2;
            ptr2=ptr2->next;
           }
          else break;

    }
   if(ptr2!=NULL)
    {
      if(ptr2->key==t)
        {ptr1->next=ptr2->next;
        free(ptr2);
        }
      else printf("There is no edge between %d and %d \n", s , t);
    }
    else
         printf("There is no edge between %d and %d \n", s , t);

}
void printgraph(GRAPH *g)
{
    int v,i;
    v=g->V;
    for(i=0;i<v;i++)
        {   node * ptr=g->array[i].head;            printf("%d->",i);

            while(ptr!=NULL)
            {
                printf("%d->",ptr->key);
                ptr=ptr->next;
            }
            printf("\n");
        }
}
void remove_edge(GRAPH *graph ,int a , int b)
{   printf("deleting edge %d-%d \n",a,b);
    delete_edge(graph,a,b);delete_edge(graph,b,a);

}
int main()
{   int size=5;
    GRAPH *graph=newgraph(graph,size);
    add_edge(graph,0,1);add_edge(graph,0,2);add_edge(graph,0,4);
    add_edge(graph,1,4);add_edge(graph,1,2);add_edge(graph,1,3);
    add_edge(graph,2,3);add_edge(graph,2,4);
    add_edge(graph,3,4);
    printgraph(graph);
    remove_edge(graph,2,3);
    remove_edge(graph,1,4);
    remove_edge(graph,1,3);


           printgraph(graph);
    printf("success\n");
return 0;
}



Tuesday, October 13, 2015

program to find the linearly dependent columns in multidimensional array

#include<stdio.h>
#include<stdlib.h>
int main()
{

int i,j,k,m,n,len,col,a[9][9]={{2,3,6,5,1,2,3,6,9},{2,3,6,5,4,2,3,6,2},{2,3,6,5,4,2,3,1,9},{2,3,6,5,4,2,3,6,9},{2,3,6,5,4,2,3,6,9},
       {2,3,6,5,4,2,3,6,9},{2,3,6,5,4,3,3,6,9},{2,3,6,5,4,2,4,6,9},{2,3,6,5,8,2,3,6,9}
        };

for(i=0;i<8;i++)
    for(j=i+1;j<9;j++)
{ printf("here");
     if(a[0][i]%a[0][j]==0)
     {  printf("here1");
           len=1;
         col=i;
         for(k=1;k<9;k++)
         {
             if(a[k][i]%a[k][j]!=0)
                 len=0;
         }
       printf("here2");
     }
     else if(a[0][j]%a[0][i]==0)
     {   len=1;printf("here3");
         col=j;
         for(k=1;k<9;k++)
         {   len=1;printf("in55");
             if(a[k][j]%a[k][i]!=0)
                 len=0;
                 printf("in56");
         }
         printf("here4");
     }
     if(len==1)printf("\ncolumn : %d is linearly dependent",col);
}
return 0;
}

Saturday, October 10, 2015

Implementation of longest common sub-sequence in c

#include<stdio.h>
#include<stdlib.h>
int max(int a,int b){return (a>b)?a:b;}
char *x, *y;
int lcs(int i,int j)
 {
  if(i==0||j==0)return 0;
  else if(i>0&&j>0&&x[i]==y[j]) return lcs(i-1,j-1)+1;
  else if(i>0&&j>0&&x[i]!=y[j]) return max(lcs(i-1,j),lcs(i,j-1));
}
int main()
{int n=10,m=5;

 x=(char *)malloc(n*sizeof(char ));
 y=(char *)malloc(m*sizeof(char ));
 gets(x);
 gets(y);
 //sizeof longest common subsequence among first n letters of x and first m letters of y
 printf("%d",lcs(n,m));
return 0;
}

Thursday, October 8, 2015

Represent graph with adjacency list : C program

#include <stdio.h>
#include <stdlib.h>
typedef struct node{int key;struct node * next;}node;
node * init_node(node * n,int b){n=(node *)malloc(sizeof(node));n->key=b;n->next=NULL;return n;}
node **list,*front=NULL,*rear=NULL;
void enqueue(node * n)
{ if(rear==NULL)front=rear=n;
  else{ rear->next=n;rear=n; } }

void add_edge(int a,int b)
{  node * ptr=NULL,*n=NULL;
   n=init_node(n,b);
    if(list[a]->next==NULL){list[a]->next=n;}
  else{  ptr=list[a]; while(ptr->next!=NULL)ptr=ptr->next;ptr->next=n;}
}
int main()
{int n=4,i,j;node * ptr=NULL;
 list=(node **)malloc(n*(sizeof(node *)));

for(i=0;i<n;i++)
{  list[i]=(node *)malloc(n*(sizeof(node *)));list[i]->next=NULL;list[i]->key=i;}

add_edge(0,3);add_edge(0,1);add_edge(1,3);
add_edge(2,0);add_edge(3,2);add_edge(2,1);
for(j=0;j<n;j++)
    if(list[j]->next!=NULL)
         { printf("[ %d ]",j);ptr=list[j]->next;
           while(ptr!=NULL){printf("--> %d ",ptr->key);ptr=ptr->next;}
          printf("\n");
         }

printf("IN THE END......");
return 0;
}

Saturday, October 3, 2015

Program for String Matching with Finite Automata in C

#include <stdio.h>
#include <stdlib.h>
char * prefix(char * c,int start, int end,int size)
{   int i;
    char *temp=(char *)malloc(size*sizeof(char));
    for(i=0;i<size;i++)
       temp[i]=c[start++];
    return temp;
}
char * suffix(char * c,int start, int end,int size)
{   int i,j;
    char *temp=(char *)malloc(size*sizeof(char));
    for(j=0,i=end-size+1;i<=end;i++,j++)
       temp[j]=c[i];
    return temp;
}
int match(char * a, char *b)
{  int i=0;
    while(a[i]!='\0')
     {
if(a[i]!=b[i])
 return 0;
i++;
     }
    return 1;
}
int sigma(char * t , char * p ,int i)
{
  int j,v=0;
  for(j=0;p[j]!='\0';j++)
     if(match(suffix(t,0,i,j+1),prefix(p,0,j,j+1)))
v=j+1;
  return v;
}
int main()
{  char a[]="dfhghjgfjschhscgchgfbgfsgfjh";
   char b[]="jhgfj";
   printf("%d\n",sigma(a,b,8));
   
 
}

Friday, October 2, 2015

Implmentation of Rabin-Karp Algorithm in c

#include <stdio.h>
#include<stdlib.h>
int hash (char * a,int s,int t)
{ int h=0;
    for(;s<=t;s++)
        h+=a[s];
       return h;
}
int match(char * a,int a1,int a2,char * b, int b1,int b2)
{  
    for(;a1<=a2,b1<=b2;a1++,b1++)
       { if(a[a1]!=b[b1])
           return 0;
       }
       return 1;
}   
   

void rk(char*a,char *b,int as,int bs)

   int ph=hash(b,0,bs-1),i;
   for(i=0;i<(as-bs+1);i++)
    { if(hash(a,i,i+bs-1)==ph)
        if(match(a,i,i+bs-1,b,0,bs-1))
      { printf("  match for < %s > found at position : %d ",b,i+1);}
    }
        
    
}
void main()
{  
 char t[]="abcdefghijklmnopqrstuvwxyz";
 char p[]="klmnop";
    int st=sizeof(t)-1;
    int  sp=sizeof(p)-1;
    rk(t,p,st,sp);
    
    
}

Tuesday, September 29, 2015

Simple string matching algorithm to find position of a pattern in a given string without using any string function in C

#include<stdio.h>
#include<stdlib.h>
void main()
{ int i=0,j,count;
  char string[]={"kfhisdcodesoecodeupzz"};
  char pattern[]={"code"};
 
 
  for(i=0;i<sizeof(string)-1;i++)
     {
     
       if(string[i]==pattern[0])
         { count =1;

           for(j=1;j<sizeof(pattern)-1;j++)
              {
                if(pattern[j]==string[i+j])
                   count++;
                else break;
              }

         if(count==(sizeof(pattern)-1))
         printf("\none match at position : %d ",i);
           
         }
     
     }
printf("\n");
}

Saturday, September 26, 2015

Implementation of Breadth First search in C using dynamic adjacency list

#include <stdio.h>
#include <stdlib.h>
typedef struct node{int key;struct node * next;}node;
node * init_node(node * n,int b){n=(node *)malloc(sizeof(node));n->key=b;n->next=NULL;return n;}
node **list,*front=NULL,*rear=NULL;
void enqueue(node * n)
{ if(rear==NULL)front=rear=n;
  else{ rear->next=n;rear=n; } }
node * dequeue()
{
if(front==NULL&&rear==NULL){return NULL;}
if(front==rear){ node *temp=front;front=rear=NULL;return temp;}
node * temp=front;front=front->next;return temp;
}
void add_edge(int a,int b)
{  node * ptr=NULL,*n=NULL,*p;
   n=init_node(n,b);
    if(list[a]==NULL){p=init_node(p,a);list[a]=p;}
    ptr=list[a]; while(ptr->next!=NULL)ptr=ptr->next;ptr->next=n;

    ptr=NULL;n=NULL;
   n=init_node(n,a);
    if(list[b]==NULL){p=init_node(p,b);list[b]=p;}
    ptr=list[b]; while(ptr->next!=NULL)ptr=ptr->next;ptr->next=n;
}
void dfs(int s,int n)
{   node * ptr;int visited[n],i,d=6,parent[n],distance[n],parenti;
      for(i=0;i<n;i++){visited[i]=0;parent[i]=0;distance[i]=-1;}
    if(list[s]==NULL)return;
  enqueue(list[s]);
  parenti=s;
  distance[s]=0;
  visited[s]=1;
printf("\nDFS Distance from %d  :\n",s);
  while(front!=NULL)
  {
     ptr=dequeue();
     parenti=ptr->key;
     ptr=list[ptr->key]->next;

    while(ptr!=NULL)
     {   if(!visited[ptr->key])
         {enqueue(ptr);if(parent[ptr->key]==0)parent[ptr->key]=parenti;visited[ptr->key]=1;
          distance[ptr->key] =distance[parent[ptr->key]]+6;
          printf(" node-%d:parent-:%d:distance:%d\n ",ptr->key,parent[ptr->key],distance[ptr->key]);}
         ptr=ptr->next;
     }


  }
}
int main()
{int n=10,i,j;node *ptr=NULL;
 list=(node **)malloc(n*(sizeof(node *)));

for(i=0;i<n;i++)
{  list[i]=(node *)malloc(n*(sizeof(node *)));list[i]=NULL;}

add_edge(2,1);
add_edge(0,1);add_edge(2,0);
add_edge(2,3);
add_edge(9,6);add_edge(9,0);add_edge(9,5);add_edge(9,4);add_edge(9,7);add_edge(9,8);add_edge(9,3);
add_edge(8,7);add_edge(8,6);
add_edge(7,2);add_edge(7,2);
add_edge(6,0);add_edge(6,1);
add_edge(5,4);add_edge(5,2);add_edge(5,3);
add_edge(4,2);
add_edge(3,0);add_edge(3,1);
add_edge(1,0);

for(j=0;j<n;j++)
    if(list[j]!=NULL)
         { ptr=list[j];
           while(ptr!=NULL){printf("%d --> ",ptr->key);ptr=ptr->next;}
          printf("\n");
         }
dfs(3,10);

return 0;
}

Implementation of Binary Search Tree in C using dynamic linked list

//Binary Search Tree
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
  int key;
  struct node *left;
  struct node* right;
}node;

void printIO(node * n)
{ if(!n)return;
  if(n->left)
    printIO(n->left);
  printf("%d.",n->key);
  if(n->right)
    printIO(n->right);
}

node * create(node * n,int k)
{ n=(node *)malloc(sizeof(node));
  n->key=k;
  n->left=NULL;
  n->right=NULL;  
 return n;
 }

node * insert(node * n,int k)
{  
   node * root=n;
   if(n==NULL)
     {n= create(n,k);printf("%d.",k);}
   else if(k>n->key){n->right= insert(n->right,k);}
   else if(k<=n->key){n->left= insert(n->left,k);} 
   return n;
}

int main()
{
node * root=NULL;
printf("\n Inserting Sequence\n");
root=insert(root,202);root=insert(root,125);root=insert(root,255);root=insert(root,313);
root=insert(root,116);root=insert(root,222);root=insert(root,150);

printf("\n In Order of Created Binary Search tree\n");
printIO(root);
printf("\n");
return 0;
}

Friday, September 25, 2015

Implementation of AVL tree in C

#include<stdio.h>
#include<stdlib.h>
int kk;
typedef struct node{
int key;
int height;
struct node * left;
struct node * right;
}node;

node * create(node * n,int k)
{ n=(node *)malloc(sizeof(node));
  kk=k;
  n->key=k;
  n->height=1;
  n->left=NULL;
  n->right=NULL;
  return n;
}

int max(int a,int b){return (a<b)?b:a;}

node *updateheight(node *n )
{
  if(n->left!=NULL&&n->right!=NULL)
  {n->height=max(n->left->height,n->right->height)+1;printf("height updated\n");}
  else if(n->left!=NULL)
  {n->height=n->left->height;printf("height updated\n");}
  else if(n->right!=NULL)
  {n->height=n->right->height;printf("height updated\n");}
  else
  n->height=1;

  return n;
}
node * rotateR(node * r)
{
 
  node *n=r->left;
  node *temp;
  if(r->left->right!=NULL)
    temp=r->left->right;
  else temp=NULL;
  n->right=r;
  r->left=temp;
  if(n->right!=NULL)
  n->right=updateheight(n->right);
  n=updateheight(n);
  printf(".R.");
 return n;
 
}
node * rotateL(node * r)
{ node *n=r->right;
  node *temp;
  if(r->right->left!=NULL)
  temp=r->right->left;
  else temp =NULL;
  n->left=r;
  r->right=temp;
  updateheight(n->left);
  updateheight(n);
  printf(".L.");
  return n;

}

node * balance(node *n,int k)
{ int balance,l=0,r=0;
   if(n->left)
     l=n->left->height;
   if(n->right)
     r=n->right->height;
   balance=l-r;
     if(balance>1&&k<=n->left->key)
        {n=rotateR(n);printf("LL..");}
     else if(balance>1&&k>n->left->key)
       {printf("LR..");n=rotateL(n);n=rotateR(n);}
     else if(balance<-1&&k>n->right->key)
       {n=rotateL(n);printf("RR..");}
     else if(balance<-1&&k<=n->left->key)
       {n=rotateR(n);n=rotateL(n);printf("RL..");}

  return n;

}

node * insert(node * r,int k)
{
   if(r==NULL){node *n=create(n,k);r=n;}
   else if(k<=r->key){r->left=insert(r->left,k);r->height=r->left->height+1;r=balance(r,kk);}
   else if(k>r->key){r->right=insert(r->right,k);r->height=r->right->height+1;r=balance(r,kk);}
   return r;
}
void printAVLIO(node *r)
{
    if(!r)return;
    if(r->left)printAVLIO(r->left);
    printf("\n%d..",r->key);
    printf(".height.%d..\n",r->height);
    if(r->right)printAVLIO(r->right);
}

int main()
{
  node *root=NULL;
  int i,a[]={50,25,75,70,60},k=sizeof(a)/sizeof(int);
  printf("Inseting sequence into the AVL tree\n");
  for(i=0;i<k;i++)
     printf("%d..",a[i]);printf("\n");
  i=0;
  while(i<k)
     {root=insert(root,a[i]);i++;}
  printAVLIO(root);
return 0;
}

Sunday, September 6, 2015

Program to Build binary MaxHeap using ANSI C

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>

int c,i,j;

int left(int j){return j*2+1;}
int right(int j){return j*2+2;}
int parent(int j) {return (j-1)/2;}

typedef struct node
{  int data;}node;

typedef struct heap
{  int capacity;
  int heapSize;
  node *element;
}heap;

void swap(node *x,node *y)
{ node *temp; temp=x; y=x; x=temp; }

initHeap(heap *h,int cap){h->capacity=cap;}

printHeap(heap *h){
for (i=0;i<h->capacity;i++)
    printf("\n %d",h->element[i].data);
}


insertKey(heap *h,int k)
{
   if(!(h->capacity))
     h->element=malloc(sizeof(node));
  else
     h->element=realloc(h->element,(h->capacity+1)*sizeof(node));
  node n;
  n.data=k;
  int i=(h->heapSize)++;
  while(i&&h->element[i].data>h->element[parent(i)].data)
       h->element[i]=h->element[parent(i)];
  h->element[i]=n;
}

void heapify(heap *h,int i)
{
   int max=i;
   if(h->element[left(i)].data>h->element[i].data)
     max=left(i);
  if(h->element[right(i)].data>h->element[i].data)
     max=right(i);
  if(i!=max)
    swap(&(h->element[max]),&(h->element[i]));
  heapify(h,max);
}

int extractMax(heap *h)
{
  int max=h->element[0].data;
   h->element[0]=h->element[(h->heapSize)--];
   h->element=realloc(h->element,h->heapSize*sizeof(node));
 
  return max;

}

deleteKey(heap *h,int k)
   {  if(h->heapSize)
      {  h->element[k].data=INT_MAX;
         heapify(h,k);
         int d=extractMax(h);
      }
      else printf("\n MaxHeap Is Empty");

   }

void main()
{
 int capacity=0;
 heap maxHeap;
 initHeap(&maxHeap,capacity);
char c='c';
int key;
  while (c=='c')
 { printf("\ni...insert");
  printf("\np...print");
  printf("\nm...get max");
  printf("\ne...exit");
  printf("\n\n........ENTER CHOICE::");
  c=getchar();
  switch (c)
        {
          case 'i' :
          printf("\nEnter the number to be inserted : ");
          scanf("%d",&key);
          insertKey(&maxHeap,key);
          printf("\n");
          printHeap(&maxHeap);
          break;
          case 'p':
          printf("\n");
          printHeap(&maxHeap);
          break;
          case 'm':
          printf("%d",extractMax(&maxHeap));
          default : break;
        }

 printf("\nPress....c...To Continue");
 printf("\nPress....any other key...EXIT");
 c=getchar();
printf("\n");
}
 

}

Monday, August 24, 2015

Program for Gauss-Jordan Elimination without frills

#include <iostream>
#include <cmath>
using namespace std;
                
int main ()
{

        int a,z,i,j;
        cout << "Enter the number of equations \n";
        cin >> a;
        float ar [a][a+1];
        
        cout << "Entering the elements of the array \n";
        for (i=0;i<a;i++)
        {        
        for (j=0; j<(a); j++)
        {
        if (i==j)
        {
         ar[i][j] = 2;
        }
        else if(i!=j)
        {
        ar[i][j] = -1;
        }
        }
        }

        for (i=0;i<a;i++)
        {
        ar[i][a] = -97;
        }

        

        
        cout << " \n\n GAUSS JORDAN ELIMINATION \n";
        float temp,max;        
        int k,l;
        
        for (i=0;i <a; i++)
        {
        max = ar[i][i]; 
        k=i;
        for (j=i;j <a; j++)
        {
        
        
        if (abs(ar[j][i]) > abs(max))        
        {
        
        
        max = ar[j][i];
        
        k=j;
        
        }
        }
        
        for (l=0;l<a+1;l++)
        {
        
        temp = ar[i][l];
        ar[i][l] = ar[k][l];
        ar[k][l] = temp;
        
        }
        
        
        

        
        int x,y;
        float z, rat;
        z = ar[i][i]; 
        
        if (z != 0)
        {
        for (x=i+1; x <a; x++)
        {
        
        rat = (ar[x][i]) / (ar[i][i]);        
        
        for (y=0;y<a+1;y++)
        {
        ar[x][y] = ar[x][y] - (rat*ar[i][y]);
        }
        }
        }

        
        }
        
        int ab;
        float x[a];
        for (ab=(a-1);ab>-1;ab--)
        {
         x[ab]=ar[ab][a];
        
        for (i=ab+1;i<a;i++)
        {
        x[ab]=x[ab]-(ar[ab][i]*x[i]);
        }
        x[ab] = (x[ab]/ar[ab][ab]);
        
        }
        

        for (i=0;i<a;i++)
        {
        cout << "x["<<i<<"] \t= " << x[i] <<endl;
        }
        
return 0;
        }

Wednesday, April 2, 2014

Errors in programs of computer graphics related to GRAPHICS.H

Some of the Errors Startup and New Programmers face while writing Graphics programs in C or C++  :

  • Messages like  " Cannot open include file < graphics.h > " .
  • Linker errors relating to < graphics.h > .
  • Messages like : Graphics not initialized .
To overcome the above errors and many others, try the following steps
  1. Copy the file [ egavga.bgi ] from the folder BGI to BIN folder 
  2. GoTo OPTIONS >   LINKER > LIBRARIES and mark the Graphics option
  3. Use int gdriver , gmode = DETECT;  initgraph( &gdriver, &gmode, "" ) ;                       before writing any graphics code ;
                                       

Monday, February 10, 2014

Program to implement Extended Euclidean algorithm

This version is for RSA public-key encryption method.
e*d mod z =1

it takes the value of e or d and returns the value of  d or e respectively.

#include <stdio.h>
#include <string.h>
int z,ed;
int ee_algo(int x1,int x2,int x3,int y1,int y2,int y3)
{ int q=x3/y3;
     int tx1=y1;
     int tx2=y2;
     int tx3=y3;
     y1=x1-q*y1;
     y2=x2-q*y2;
     y3=x3-q*y3;
   
    if(y3==1)
    { if(y2>0)
       return y2;
       else return y2+z;

    }
  else
  {   x1=tx1;
     x2=tx2;
     x3=tx3;
       
      return ee_algo(x1,x2,x3,y1,y2,y3);
  }

}
main()
{
    z=2400;

  ed=29;
   printf("%d",ee_algo(1,0,z,0,1,ed));
}

Thursday, June 16, 2011

Algorithm and Program for Strassen's matrix multiplication


Algorithm

If the sizes of A and B are less than the threshold
Compute C = AB using the traditional matrix multiplication algorithm.
Else use Strassen's algorithm
Split matrices A and B
For each of

Mi i = 1 to 7
Create a new thread to compute

Mi = A'i B'i
If the sizes of the matrices are less than the threshold
Compute C using the traditional matrix multiplication algorithm.
Else use Strassen's algorithm
Split matrices A'

i and B'i
For each of M

ij j = 1 to 7

If i=7 and j=7 go to step 1 with A = A'77

and
B = B'77
Get a thread from the thread pool to compute

M= A'ij B'ij
Execute the recursive version of Strassen's algorithm in this thread
Wait for the Mij
threads to complete execution
Compute MiWait for the Mi

threads to complete execution
Compute C

Program

#include<iostream.h>
#include<conio.h>
void main()
{
int a[2][2],b[2][2],c[2][2],i,j;
int p1,p2,p3,p4,p5,p6,p7;
clrscr();
cout<<"enter the first matrix";
for(i=1;i<=2;i++)
for(j=1;j<=2;j++)
cin>>a[i][j];
cout<<"enter the second matrix";
for(i=1;i<=2;i++)
for(j=1;j<=2;j++)
cin>>b[i][j];
p1=a[1][1]*(b[1][2]-b[2][2]);
p2=(a[1][1]+a[1][2])*b[2][2];
p3=(a[2][1]+a[2][2])*b[1][1];
p4=a[2][2]*(b[2][1]-b[1][1]);
p5=(a[1][1]+a[2][2])*(b[1][1]+b[2][2]) ;
p6=(a[1][2]-a[2][2])*(b[2][1]+b[2][2]) ;
p7=(a[1][1]-a[2][1])*(b[1][1]+b[1][2]) ;
c[1][1]=p5+p4-p2+p6;
c[1][2]=p1+p2;
c[2][1]=p3+p4;
c[2][2]=p5+p1-p3-p7;
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
cout<<c[i][j]<<" ";
}
cout<<"\n" ;
}
getch();
}

Algorithm and Program for Depth First Search(DFS)

Algorithm
procedure DFS(G,v):
2      label v as explored
3      for all edges e in G.incidentEdges(v) do
4          if edge e is unexplored then
5              w ← G.opposite(v,e)
6              if vertex w is unexplored then
7                  label e as a discovery edge
8                  recursively call DFS(G,w)
9          else
10             label e as a back edge
Program
#include<stdio.h>
#include<conio.h>
#define MAX 5
int dfs(int adj[][MAX],int visited[],int start)
{
    int stack[MAX];
    int top=-1,i;
   
    printf("%c-",start+65);
    visited[start]=1;
    stack[++top]=start;
    while(top!=-1)
    {
    start=stack[top];
    for(i=0;i<MAX;i++)
    {  if(adj[start][i]&&visited[i]==0)
    {stack[++top]=i;
      printf("%c-",i+65);
        visited[i]=1;
        break;                                                            
        }}
      if(i==MAX)
      top--;
    }
    return 0;
}
int main()
{
    int adj[MAX][MAX]={{0,0,1,1,0},{0,0,0,0,0},{0,1,0,1,1},{0,0,0,0,1},{0,0,0,1,0}};
    int visited[MAX]={0};
     printf("DFS Traversal : ");
    dfs(adj,visited,0);
 printf("\n");
    getch();
    return 0;
}

Algorithm and Program for Merge Short

Algorithm

function merge(left,right)
    var list result
    while length(left) > 0 or length(right) > 0
        if length(left) > 0 and length(right) > 0
            if first(left) ≤ first(right)
                append first(left) to result
                left = rest(left)
            else
                append first(right) to result
                right = rest(right)
        else if length(left) > 0
            append first(left) to result
            left = rest(left)
        else if length(right) > 0
            append first(right) to result
            right = rest(right)
    end while
    return result

Program

#include <stdio.h>
#include<conio.h>
int a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{ int mid;
  if(low<high)
 {mid=(low+high)/2;
  merge_sort(low,mid);
  merge_sort(mid+1,high);
  merge(low,mid,high);
 }
}
void merge(int low,int mid,int high)
{
 int h,i,j,b[50],k;
 h=low;
 i=low;
 j=mid+1;
 while((h<=mid)&&(j<=high))
 {if(a[h]<=a[j])
  {b[i]=a[h];
   h++;
  }
  else
  {b[i]=a[j];
   j++;
  }
  i++;
 }
 if(h>mid)
 {
  for(k=j;k<=high;k++)
  {b[i]=a[k];
   i++;
  }
 }
 else
 {  for(k=h;k<=mid;k++)
       {b[i]=a[k];
        i++;
       }
 }
 for(k=low;k<=high;k++) a[k]=b[k];
}
int main()
{int num,i;
 printf("Please Enter THE NUMBER OF ELEMENTS you want to sort :\n");
 scanf("%d",&num);
 printf("\n");
 printf("Now, Please Enter the ( %d ) numbers :\n",num);
 for(i=1;i<=num;i++)
 {  scanf("%d",&a[i]); }
 merge_sort(1,num);
 printf("\n");
 printf("So, the sorted list (using MERGE SORT) will be :\n");
 printf("\n\n");
 for(i=1;i<=num;i++)
 printf("%d  ",a[i]);
 printf("\n\n\n\n");
getch();
return 0;
}

Algorithm and Program for Quick Short

Algorithm

// left is the index of the leftmost element of the array
  // right is the index of the rightmost element of the array (inclusive)
  // number of elements in subarray: right-left+1
  function partition(array, left, right, pivotIndex)
     pivotValue := array[pivotIndex]
     swap array[pivotIndex] and array[right]  // Move pivot to end
     storeIndex := left
     for i from left to right - 1 // left ≤ i < right
         if array[i] < pivotValue
             swap array[i] and array[storeIndex]
             storeIndex := storeIndex + 1
     swap array[storeIndex] and array[right]  // Move pivot to its final place
     return storeIndex

Program
#include<conio.h>
#include<stdio.h>
void quickshort(int ,int,int);
int partition(int arr[], int left, int right)
{  int i = left, j = right;
   int tmp;
   int pivot = arr[i];
   while (i <= j)
         { while (arr[i] < pivot)
                  i++;
            while (arr[j] > pivot)
                   j--;
            if (i <= j)
               { tmp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = tmp;
                  i++;
                  j--;
               }
         };
   return i;
}
void quickSort(int arr[], int left, int right)
{  int index = partition(arr, left, right);
      if (left < index - 1)
      quickSort(arr, left, index - 1);
      if (index < right)
            quickSort(arr, index, right);
}
int main()
{printf("enter the no of elements in the list\n");
int n,i;
scanf("%d",&n);
int arr[n];
printf("now enter the %d elements of the list ",n);
for(i=0;i<n;i++)
    scanf("%d",&arr[i]);
quickSort(arr,0,7);
printf("\n The shorted list is ");
for(i=0;i<n;i++)
printf("  %d  ",arr[i]);
getch();
    return 0;}

Algorithm and Program for Binary Search


implementation of the algorithm

limitations :
entered list must be pre shorted;
there must be only one element in the list which is to be searched;

#include<stdio.h>
#include<conio.h>
int mid;
int BinarySearch(int A[], int key, int low,int high)
{
       if (high < low)
        return -1;
      mid =low + (high - low)/2;
       if (A[mid] > key)
          return BinarySearch(A,key, low, mid-1);
       else if (A[mid] < key)
          return BinarySearch(A, key, mid+1, high);
       else
           return mid ;
   };
  
   int main()
   {
     
      int j,low=0,high=9,key,k=0;
      int A[9];
       printf("enter the 12 elements of array");
      for(j=0;j<9;j++)
      scanf("%d",&A[j]);
       printf("\n enter the element to be searched for");
      scanf("%d",&key);
      j=BinarySearch(A,key,low,high);
      if (j>=0)
      printf("\element %d is found at position %d",key,j+1); 
      else
      printf("\n element not found");
      getch();
      return 0;
   }
BinarySearch(A[0..N-1], value, low, high) {
       if (high < low)
           return -1 // not found
       mid = low + (high - low) / 2
       if (A[mid] > value)
           return BinarySearch(A, value, low, mid-1)
       else if (A[mid] < value)
           return BinarySearch(A, value, mid+1, high)
       else
           return mid // found
   }