/************* Comprehensive Examination(II Sem 1999-2000) ****************/
/*****************    Computer Programming - I   **************************/
/***********************   5th May 2000      ******************************/

/*

Question:

Write a function subtract that takes 2 positive integers, say num1 and num2, subtracts the smallest integer from the larger and returns the result.

The function should perfromt the subtraction, as we do manually i.e., on a digit-by-digit basis.  You must perform the subtraction by extracting individual digits of the 2 integers.

Assume that the two integers can have a maximum of 9 digits each.

Hint: It is a common practice to use arrays for such problems!
*/


#include <stdio.h>
#define SIZE    10      //9+1

char *subtract(char*,char*);
main()
{
        char num1[SIZE],num2[SIZE],*result;
        read_input(num1,num2);
        greater_first(num1,num2);
        result=subtract(num1,num2);
        printf("%10s\n%10s\n%10s\n",num1,num2,result);
}

int read_input(char *str1,char *str2)
{
        printf("Give the first number:");
        scanf("%s",str1);
        printf("Give the second number:");
        scanf("%s",str2);
        return 1;
}

int greater_first(char *str1,char *str2)
{
        char temp_string[SIZE];
        if(strcmp(str1,str2)<=0)
                return 0;
        strcpy( temp_string, str1 );
        strcpy( str1, str2 );
        strcpy( str2, temp_string );
        return 1;
}

char* subtract(char *num1,char *num2)
{
        int len1=0,len2=0;
        int i,carry=0;
        
        char str1[SIZE],str2[SIZE];
        char *result;
        
        strcpy(str1,num1);
        strcpy(str2,num2);

        result=(char*) malloc(SIZE);    
        for(i=0;i<SIZE-1;i++)
                result[i]=' ';
        
        len1=strlen(str1);
        len2=strlen(str2);
        result[len1]='\0';
        for(i=1;i<=len2;i++)
        {
                if(str1[len1-i]<str2[len2-i])
                {
                        str1[len1-i-1]--;
                        str1[len1-i]+=10;
                }
                result[len1-i]=str1[len1-i]-str2[len2-i]+'0';
                //printf("%c %c %c\n",str1[len1-i],str2[len2-i],result[len1-i]);
        }
        while(len1-i>=0)
        {
                if(str1[len1-i]<'0')
                {
                        str1[len1-i-1]--;
                        str1[len1-i]+=10;
                }
                result[len1-i]=str1[len1-i];
                i++;
        }
        return result;
}