Restoring Division

#include<stdio.h>

int no_dig;

void dectobin(int a,int aa[])
{
    int i=0;
    no_dig=0;
    while(a!=0)
    {
        aa[i]=a%2;
        i++;
        no_dig++;
        a=a/2;
    }
}

void comp_2(int aa[],int m[])
{
    int i,flag=0;
    for(i=0;i<=no_dig;i++)
    {
        if(flag==1)
        {
            if(aa[i]==0)
            m[i]=1;
            else
            m[i]=0;
        }
        else if(flag==0&&aa[i]==1)
        {
            flag=1;
            m[i]=aa[i];
        }
        else
        {
            m[i]=0;
        }
    }
}


void add(int acc[],int m[])
{
    int carry=0,i;
    for(i=0;i<=no_dig;i++)
    {
        acc[i]=acc[i]+m[i]+carry;
        carry=0;
        if(acc[i]==2)
        {
            acc[i]=0;
            carry=1;
        }
        if(acc[i]==3)
        {
            acc[i]=1;
            carry=1;
        }
    }
}

void shift_left(int acc[],int q[])
{
    int i;
    for(i=no_dig-1;i>=0;i--)
    {
        acc[i+1]=acc[i];
    }
    acc[0]=q[no_dig-1];
    for(i=no_dig-2;i>=0;i--)
    {
        q[i+1]=q[i];
    }
}

void main()
{
    int a,b,acc[10],aa[10],bb[10],m1[10],m2[10],q[10],i,j;
    for(i=0;i<10;i++)
    {
        aa[i]=0;
        acc[i]=0;
        bb[i]=0;
        m1[i]=0;
        m2[i]=0;
        q[i]=0;
    }
    printf("Enter 2 numbers ");
    scanf("%d%d",&a,&b);
    dectobin(b,bb);
    dectobin(a,aa);
    comp_2(bb,m2);
    for(i=0;i<=no_dig;i++)
    {
        m1[i]=bb[i];
    }
    for(i=0;i<no_dig;i++)
    {
        q[i]=aa[i];
    }
    printf("\nRestoring Division :");
    for(i=0;i<no_dig;i++)
    {
        shift_left(acc,q);
        add(acc,m2);
        if(acc[no_dig]==1)
        {
            q[0]=0;
            add(acc,m1);
        }
        else
        {
            q[0]=1;
        }
        printf("\n");
        for(j=no_dig;j>=0;j--)
        {
            printf("%d",acc[j]);
        }
        printf(" ");
        for(j=no_dig-1;j>=0;j--)
        {
            printf("%d",q[j]);
        }
    }
    printf("\n\nQuotient ");
    for(i=no_dig-1;i>=0;i--)
    {
        printf("%d",q[i]);
    }
    printf("\nRemainder ");
    for(i=no_dig-1;i>=0;i--)
    {
        printf("%d",acc[i]);
    }
}

/*Output
Enter 2 numbers 29 3

Restoring Division :
000001 11010
000000 10101
000001 01010
000010 10100
000010 01001

Quotient 01001
Remainder 00010
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s