Showing posts with label DSTC using C Language. Show all posts
Showing posts with label DSTC using C Language. Show all posts

Wednesday, January 31, 2024

ADJACENCY LIST - Representation of Graph through Adjacency LIST - DSTC using C Language (Source Code Implemented)

ADJACENCY LIST
(Representation of Graph through Adjacency LIST 
)
Implemented using C Language 
 

 


ADJLIST.H

/*  Name     : Adjlist.h
Purpose  : This files defines node structure and all basic Graph opearations
Operations :
Graph * GetGraph(void);
void InsNode(Graph *g, int v);
NodeEdge * FindNode(Graph *g, int v);
void InsEdge(Graph *g, int v, int x);
void print(Graph *s);
void DelEdge(Graph *g, int v, int x);
void DelNode(Graph *g, int v);
void PrintEdge(Graph *g, int v);
void BreadthFirst(Graph *g,int v,int w);
void DepthFirst(Graph *g,char v);           */

#include "stack.h"
#include <string.h>
typedef union nodeedge {
    struct node {
        char info;      //Node name or number
        int status;     //Status of node, status will be 1-Ready State,
        //2-Waiting State and 3-Processed State
        union nodeedge * nextnode;
        union nodeedge * edgeptr;
    }Node;

struct edge {
        union nodeedge * nextedge;
        union nodeedge * nodeptr;
    }Edge;
}NodeEdge;

typedef struct {
    union nodeedge * start;
}Graph;

Graph * GetGraph(void)
{
    Graph *s;
    s=(Graph *)malloc(sizeof(Graph));
    s->start=NULL;
    return s;
}

// operations on Graph
//Inserting a new node in the Graph
void InsNode(Graph *g, char v)
{
    NodeEdge *new1;
    new1=(NodeEdge *)malloc(sizeof(NodeEdge));
    new1->Node.info=v;
    new1->Node.nextnode=g->start;
    new1->Node.edgeptr=NULL;
    new1->Node.status=1;    //Initially status of all the nodes
    //will be 1
    g->start=new1;
}

//Finding a node in the graph
NodeEdge * FindNode(Graph *g, char v)
{
    NodeEdge *temp;
    temp=g->start;
    // printf("Testing(Inside find node): %c\n",v);
    // printf("\nTesting(Inside find node): %c %c\n",v,temp->Node.info);
    while(temp)
    {
        if(temp->Node.info==v)
            break;
        else
            temp=temp->Node.nextnode;
    }
    return temp;
}

//Adding an edge in the graph
void InsEdge(Graph *g, char v, char x)
{
    NodeEdge *newedge, *start, *end;
    newedge=(NodeEdge *)malloc(sizeof(NodeEdge));
    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Starting Node %c does not exist\n",v);
        exit(1);
    }
    end=FindNode(g,x);
    if(end==NULL)
    {
        printf("Ending Node %c does not exist\n",x);
        exit(1);
    }

    newedge->Edge.nextedge=start->Node.edgeptr;
    start->Node.edgeptr=newedge;
    newedge->Edge.nodeptr=end;
}

//Deleting an edge from the graph
void DelEdge(Graph *g, char v, char x)
{
    NodeEdge *start, *end, *q, *q1;
    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Starting Node %c does not exist\n",v);
        exit(1);
    }
    if(start->Node.edgeptr)
    {
        printf("This node does not have any edge\n");
        exit(1);
    }
end=FindNode(g,x);
    if(end==NULL)
    {
        printf("Ending Node %c does not exist\n",x);
        exit(1);
    }

    q=start->Node.edgeptr;
    while(q)
    {
        if(q->Edge.nodeptr==end)
            break;
        else
        {
            q1=q;
            q=q->Edge.nextedge;
        }
    }
if(q==start->Node.edgeptr && q->Edge.nodeptr==end)
    {
        start->Node.edgeptr=q->Edge.nextedge;
        free(q);
    }
    else
    {
        if(q)  //if edge exist only then
        {
            q1->Edge.nextedge=q->Edge.nextedge;
            free(q);
        }
    }
}

//Deleting a node
void DelNode(Graph *g, char v)
{
    NodeEdge *start, *del, *q;
    del=g->start;
    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Node %c does not exist\n",v);
        exit(1);
    }
    while(del) //deleting all the edges pointing to this node if any
    {
        DelEdge(g,del->Node.info, v);
        del=del->Node.nextnode;
    }

    del=g->start;
    while(del)
    {
        if(del->Node.nextnode==start)
        {
            del->Node.nextnode=start->Node.nextnode;
            free(start);
            break;
        }
        del=del->Node.nextnode;
    }
}

//printing all the edges of the node
void PrintEdge(Graph *g, char v)
{
    NodeEdge *q,*q1,*q2;
    q=FindNode(g,v);
    if(q==NULL)
    {
        printf("Node %c does not exist\n",v);
        exit(1);
    }
    printf("----All the edges starting from %c are--->\n",v);
    if(q->Node.edgeptr==NULL)
    {
        printf("This Node does not have any edge\n");
        return;
    }
    else
    {
        q1=q->Node.edgeptr;
        while(q1)
        {
            q2=q1->Edge.nodeptr;
            printf("To Node: %c\n", q2->Node.info);
            q1=q1->Edge.nextedge;
        }
    }
}

//printing the graph
void print(Graph *g)
{
    NodeEdge *t;
    t=g->start;
    while(t)
    {
        PrintEdge(g,t->Node.info);  //printing all the edges of current node
        t=t->Node.nextnode;
        fflush(stdin);
        getchar();
    }
}

//Breadth first algorithm---------------
void BreadthFirst(Graph *g,char v,char w)
{
    NodeEdge *start,*end,*q,*p;
    char c;
    int front,rear;
    int flag=0;
    char *queue,*orig;
    //char *path;
    void detpath(char *a,char *b,int c,char d);

    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Starting Node %c does not exist\n",v);
        exit(1);
    }
    end=FindNode(g,w);
    if(end==NULL)
    {
        printf("Ending Node %c does not exist\n",w);
        exit(1);
    }

    //put starting node in Queue and Change its Status to 2
    front=0;   //initially queue is empty
    queue[front]=start->Node.info;
    orig[front]=' ';
    start->Node.status=2;
    rear=1;

while(front<=rear)
    {
        //remove top node of queue and change its status to 3
        c=queue[front];
        q=FindNode(g,c);
        q->Node.status=3;
        //add to queue all the neighbors of current node whose status is 1
        p=q->Node.edgeptr;
        while(p)
        {
            if(p->Edge.nodeptr->Node.status==1)
            {
                queue[rear]=p->Edge.nodeptr->Node.info;
                orig[rear]=q->Node.info;
                p->Edge.nodeptr->Node.status=2;
                if(queue[rear]==w)  //if target node is found then quit
                {
                    queue[rear+1]='\0';
                    orig[rear+1]='\0';
                    flag=1;
                    break;
                }
                rear++;
            }
            p=p->Edge.nextedge;
        }
        //-------------------------------------------------------------

        if(flag)
        {
            printf("Queue is   : %s\n",queue);
            printf("Originating: %s\n",orig);
            break;
        }
        front++;
    }

    //determining path
    detpath(queue,orig,rear,v);
}

//Finding the position of a info
int find(char *arr,char c)
{
    int i;
for(i=0;i<strlen(arr);i++)
    {
        if(arr[i]==c)
            return i;
    }
    return -1;
}

//determining the path-------------------------
void detpath(char *q,char *o,int r,char st)
{
    char *path;
    int f;
    char c;

    f=0;
    c=o[r];
    path[f++]=q[r];

    //   printf("test: %x %x %x\n",q,o,path);
    while(r>=0 && c!=st)
{
        path[f++]=c;
        r=find(q,c);
        /*       printf("here1:%s %s\n",q,o);
        printf("here2:%d %c %c %c\n",r,c,o[r],o[3]);*/
        c=o[r];
    }
    path[f]=c;
    //displaying path
    while(f>=0)
    {
        printf(" -> %c",path[f]);
        f--;
    }
    fflush(stdin);
    getchar();
}


//Depth first algorithm---------------
void DepthFirst(Graph *g,char v)
{
    NodeEdge *start,*q,*p;
    char c;
    Stack *s;
s=GetStack();
    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Node %c does not exist\n",v);
        exit(1);
    }

    //push starting node in Stack and Change its Status to 2
    //initially stack is empty
    start->Node.status=2;
    push(s, start->Node.info);
    while(!empty(s))
    {
        //pop top node of stack and change its status to 3
        c=pop(s);
q=FindNode(g,c);
        printf("%c ",q->Node.info);
        q->Node.status=3;
        //push to stack all the neighbors of current node whose status is 1
        p=q->Node.edgeptr;
        while(p)
        {
            if(p->Edge.nodeptr->Node.status==1)
            {
                push(s, p->Edge.nodeptr->Node.info);
                p->Edge.nodeptr->Node.status=2;
            }
            p=p->Edge.nextedge;
        }
        //-------------------------------------------------------------
    }
    fflush(stdin);
    getchar();
}

 


ADJLIST.CPP

/* Name : AdjList.cpp
Purpose: Linked representation of a Graph */
#include <conio.h>
#include "adjlist.h"
void main()
{
    int menu(void);
    Graph *g;
    char c,start,end,info;
    /* char tNode[]="KJGFEDCBA";
    char sNode[]="ABCDEFGJK";
    char eNode[9][4]={"BCF","CG","F","C","JCD","D","EC","KD","GE"};
    int i,j; */
    clrscr();
    g=GetGraph();

   while(1)
    {
        c=menu();
        if(c==8)
            break;
        switch(c) {
case 1:
    printf("Enter Node Number: ");
    fflush(stdin);
    scanf("%c", &info);
    //for(i=0;i<9;i++)
    //InsNode(g,tNode[i]);
    InsNode(g,info);
    break;
case 2:
    printf("Enter Node Number: ");
    fflush(stdin);
    scanf("%c", &info);
    DelNode(g,info);
    break;
case 3:
    printf("Enter starting Node: ");
    fflush(stdin);
    scanf("%c", &start);

    printf("Enter ending Node: ");
    fflush(stdin);
    scanf("%c", &end);

    InsEdge(g,start,end);
    //        }
    //  }
    break;
case 4:
    printf("Enter starting Node: ");
    fflush(stdin);
    scanf("%c", &start);

    printf("Enter ending Node: ");
    fflush(stdin);
    scanf("%c", &end);
    DelEdge(g,start,end);
    break;
case 5:
    print(g);
    break;
case 6:
    printf("Enter starting Node: ");
    fflush(stdin);
    scanf("%c", &start);
printf("Enter ending Node: ");
    fflush(stdin);
    scanf("%c", &end);
    BreadthFirst(g,start,end);
    break;
case 7:
    printf("Enter Node: ");
    fflush(stdin);
    scanf("%c", &start);
    DepthFirst(g,start);
    break;
        }
    }

}

int menu(void)
{
    int ch;
    while(1)
    {
        printf("1. Inserting a Node\n");
        printf("2. Deleting a Node\n");
        printf("3. Inserting an Edge\n");
        printf("4. Deleting an Edge\n");
        printf("5. Printing the Graph\n");
        printf("6. Breadth First Search\n");
        printf("7. Depth First Search\n");
        printf("8. Quit\n");
printf("Enter the choice: ");
        scanf("%d", &ch);
        if(ch<1 || ch > 8)
            printf("Invalid choice\n");
        else
            return ch;
    }
}

 

Tuesday, January 30, 2024

Arrays - 2D Array/Matrix - DSTC using C Language (Source Code Implemented)

Arrays - 2D Array/Matrix
Implemented using C Language


Two-dimensional arrays are a little more complicated to use than one-dimensional ones. Here data is stored in the form of ROWS and COLUMNS which are accessed with the help of SUBSCRIPT number.
For e.g int arr[5][4] ;

  • Conventionally, the 1st subscript is used for rows and the 2nd for columns.
  • The 2d array can hold up to (rows * columns) values.
  • As is usual in C, subscripts start with zero, so the subscripts range from 0 to 4 for the rows and 0 to 3 for the columns.
  • If the system uses 2 bytes for an int, this array would use 40 bytes of RAM. All of the bytes are in consecutive memory locations, the first row occupying the first 8 bytes, the second the next 8, and so on.

The following table illustrates how the subscripts are specified for this array, which has five (5) rows and four (4) columns.

   
0123
0[0][0][0][1][0][2][0][3]
1[1][0][1][1][1][2][1][3]
2[2][0][2][1][2][2][2][3]
3[3][0][3][1][3][2][3][3]
4[4][0][4][1][4][2][4][3]

 

C Language Code:

        MULTIARR.H      

// DSTC ------- MULTIARR.H
// This program is creating MATRIX Dynamically
// MATRIX.. add, mulitpication, subtration, creation,

#include "assert.h"

typedef struct MultiDimentionArray
{
int maxr;
int maxc;
int **bfr;
}matrix;

matrix *makemat(int nr,int nc)
{
matrix *m;
int i,j;
m = (matrix *) malloc(sizeof(matrix));
m->maxr= nr;
m->maxc= nc;
m->bfr = (int **) malloc(sizeof(int*)*nr);
for(i=0;i<nr;i++)
{
m->bfr[i]=(int *)malloc(sizeof(int)*nc);
}
// m->bfr = (int *) malloc(sizeof(int **)*nc);
return (m);
}

void inputmat(matrix *m,int val, int r, int c)
{
m->bfr[r][c] = val ;
}

int inputmat(matrix *m, int r, int c)
{
return(m->bfr[r][c]);
}

void printmat(matrix *m)
{
int i,j ;
printf("\n");
for(i=0;i < m->maxr;i++)
{
printf("\n |");


Get Paid by Reading Ads on your Mobiles

for(j=0;j < m->maxc ; j++)
{
printf("\t%d",m->bfr[i][j]);
}
printf(" |");
}
} void add2mat(matrix *m1,matrix *m2,matrix *res)
{
int i,j;
assert((m1->maxr == m2->maxr) && (m1->maxc == m2->maxc)) ;
for(i=0;i<m1->maxr;i++)
{
for(j=0;j < m1->maxc ; j++)
{
res->bfr[i][j] = m1->bfr[i][j] + m2->bfr[i][j] ;
}
}
}

void subtract2mat(matrix *m1,matrix *m2,matrix *res)
{
int i,j;
assert((m1->maxr == m2->maxr) && (m1->maxc == m2->maxc)) ;
for(i=0;i<m1->maxr;i++)
{
for(j=0;j < m1->maxc ; j++)
{
res->bfr[i][j] = m1->bfr[i][j] - m2->bfr[i][j] ;
}
}
}

// precondion for matrix Multiplication is
// cols of first matrix = rows of second matrix
// and new matrix will be if
// m1(m*n) * m2(n*p) == res(m*p)

matrix *multiplymat(matrix *m1, matrix *m2)
{
assert(m1->maxc == m2->maxr) ;
matrix *r;
int i,j,m,n,s ;
i = m1->maxr ;
j = m2->maxc ;
r = makemat(i,j);

for(i=0;i < r->maxr;i++)
{
for(j=0;j < r->maxc;j++)
{
printf("\n");
s=0;
for(m=0,n=0;m< m1->maxc;m++,n++)
{
s = s + (m1->bfr[i][m] * m2->bfr[m][j]);
r->bfr[i][j] = s;
printf("m1[%d][%d] * m2[%d][%d]\t",i,m,m,j);
}
}
}
return (r) ;
}

          MULTIARR.CPP        

// DSTC ------- MULTIARR.CPP (including MULTIARR.H header file)
// this program is creating Dynamically
//

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "multiarr.h"

main()
{
clrscr();

int i,j,v ,r,c;
matrix *m,*m1,*res;

printf("\n Enter the 1 Matrix's Dimentions r,c");
scanf("%d,%d", &r,&c);

m = makemat(r,c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\nEnter m[%d][%d]:",i,j);
scanf("%d",&v);
inputmat(m,v,i,j);
}
}

printf("\n Enter the 2 Matrix's Dimentions r,c");
scanf("%d,%d", &r,&c);
m1 = makemat(r,c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\nEnter m1[%d][%d]:",i,j);
scanf("%d",&v);
inputmat(m1,v,i,j);
}
}

Get Paid by Reading Ads on your Mobiles

res = makemat(r,c) ;
printmat(m);
printf("\n + ");
printmat(m1);
//add2mat(m,m1,res);

printf(" = \n" );
//printmat(res);
//subtract2mat(m,m1,res);
//printf(" - \n" );
//printmat(res);
res = multiplymat(m,m1) ;
printf("\nMatrix Multiplication:");
printmat(res);
}

Arrays - One Dimensional - DSTC using C Language (Source Code Implemented)

Arrays - One Dimensional 
Implemented using C Language

 

Arrays have 2 basic operations i.e. extraction and storing values.

  • Extraction operation is a function that accepts an array (arr) and an index or subscript number ( i ) , and returns a values stored at index nuber. It is denoted as arr[i].

  • Storing operation accepts an array (arr), and index or subscript ( i ), and a value to be stored ( X ). It is denoted as arr[i] = X. Before a value has been assigned to an element of the array, its value is undefined and a reference to it in an expression is illegal.

C Language Code:

       ARRAY1D.H      

#include "assert.h"
typedef struct integer_array
{
int *bfr ;
int size;
}intarr ;

intarr *makearray(int n)
{
intarr *a1;
a1 = (intarr *) malloc(sizeof(intarr)) ;
a1->size = n ;
a1->bfr = (int *) malloc(sizeof(int)*n);
return (a1);
}

void input(intarr *a1,int val, int pos)
{
assert(pos>=0 && pos<a1->size);
assert(val != 0) ;
a1->bfr[pos] = val;
// or *(a1->bfr+pos) = v ;
}

int get(intarr *a1,int pos)
{
assert(pos>=0 && pos<a1->size);
return(a1->bfr[pos]);
// or return(*(a->bfr+pos));
}

void printarray(intarr *a1,int posupto)
{
// if posupto is zero(0) then it will all array elements otherwise
// only the speicified no. of elements.
int i=0,k ;
if (posupto==0)
i=a1->size ;
else
i = posupto ;

//DISPLAYS THE ARRAY BEFORE SORTING
printf("\n");
for(k=0;k<i;k++)
printf("a[%d]\t",k);

printf("\n");
for(k=0;k<i;k++)
printf("%d\t",a1->bfr[k]);
}

void sortarray(intarr *a1)
{
int i=0,j=0,t ;

for(i=0;i<a1->size-1;+i++)
{
for(j=i+1;j<a1->size;j++)
{
if ( a1->bfr[i] > a1->bfr[j] )
{
t = a1->bfr[i];
a1->bfr[i] = a1->bfr[j] ;
a1->bfr[j] = t ;
}
}
}

}

             ARRAY1D.CPP         

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <assert.h>
#include "array1d.h"

void main()
{
intarr *a1;
int i,val,n ;
printf("\n Enter the no.of elements in the array: ");
scanf("%d",&n);
printf("\nvalue entered wwas %d",n);
a1 = makearray(n);
printf("\nsize of array %d",a1->size);
for(i=0;i<n;i++)
{
printf("\n Enter values of a[%d]=",i);
scanf("%d",&val);
// a1->bfr[i] = val ;
input(a1,val,i);
}
printarray(a1,0) ;

sortarray(a1) ;
printarray(a1,0);
}


Rational Numbers (Abstract Data Type) - DSTC using C Language

Rational Numbers (Abstract Data Type) 
Implemented using C Language

 

Consider the ADT Rational, which is a Mathematical concept of a rational number. A rational number is a number that can be expressed as the quotient of two integers.

Operations to be performed for implemented Rational numbers are:

  • Creation of a rational number from two integers (rat *makerat(int a,int b))
  • Addition
  • Multiplication
  • Testing for Equality

C Language Code:

RATIONAL.H

typedef struct rational
{
int n;
int d;
}rat ;

rat *makerat(int a,int b)
{
rat *r ;
if (b==0)
{
printf("\n Den Not allowed as Zero ") ;
exit(1);
}
r = (rat *)malloc(sizeof(rat)) ;
r->n = a ;
r->d = b ;
return (r) ;
}

rat *sumrat(rat *x, rat *y)
{
rat *r ;
r = (rat *)malloc(sizeof(rat)) ;
r->n = (x->n * y->d) + (x->d * y->n) ;
r->d = x->d * y->d ;
return(r) ;
}

void killrat(rat *n)
{
free(n);
}

void printrat(rat *n)
{
printf("%d/%d",n->n,n->d);
}

rat *reducerat(rat *r)
{
rat *t ;
t = (rat *)malloc(sizeof(rat));
t = r ;
int i ;
if (t->n > t->d)
i = t->d;
else
i = t->n;

for(;i>1;i--)
{
if((t->n%i==0) && (t->d%i==0))
{
t->n = t->n/i ;
t->d = t->d/i ;
}
}

return(t);
}

 

rat *subtractrat(rat *x, rat *y)
{
rat *r ;
r = (rat *)malloc(sizeof(rat)) ;
r->n = (x->n * y->d) - (x->d * y->n);
r->d = x->d * y->d ;
return(r);
}

Get Paid by Reading Ads on your Mobiles

rat *multiplyrat(rat *x, rat *y)
{
rat *r ;
r = (rat *)malloc(sizeof(rat)) ;
r->n = x->n * y->n ;
r->d = x->d * y->d ;
return(r);
}

rat *dividerat(rat *x, rat *y)
{
rat *r ;
r = (rat *)malloc(sizeof(rat)) ;
r->n = (x->n * y->d) / (x->d * y->n);
r->d = 0 ;
return(r);
}

void ratequal(rat *x, rat *y)
{
if((x->n * y->d)== (x->d * y->n) )
printf("\n\t\tNumbers are Equal") ;
else
printf("\n\t\tNumbers are NOT Equal") ;

}

RATIONAL.CPP

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <rational.h>

void main()
{
rat *m, *n, *p, *l, *q, *t ;
int i,j,k ;
clrscr();
printf("\n Enter 1st num and denomentor(n/d):");
scanf("%d/%d",&i,&j);
m = makerat(i,j);

printf("\n Enter 2st num and denomentor(n/d):");
scanf("%d/%d",&i,&j);
n = makerat(i,j);

// SUM OF Rational nos.
p = sumrat(m,n);

printf("\n Display Two Rational No.s sum ");
printrat(m) ;
printf(" + ");
printrat(n) ;
printf(" = ");
printrat(p) ;
t = reducerat(p) ;
printf(" = ");
printrat(t);

//********* SUBSTRATION OF 2 RATIONAL NOS.

q = subtractrat(m,n);

printf("\n Display Two Rational No.s Subtraction ");
printrat(m) ;
printf(" - ");
printrat(n) ;
printf(" = ");

printrat(q) ;
t = reducerat(q) ;
printf(" = ");
printrat(t);

killrat(m) ;
killrat(n) ;
killrat(p) ;
killrat(l) ;
killrat(q) ;
killrat(t) ;

}