Advertisement
Razali

Table Addition

Nov 13th, 2014
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. /* PREPROCESSOR DIRECTIVES */
  2. #include <stdio.h>
  3.  
  4. /* FUNCTION PROTOTYPES */
  5. int add(int, int, int);
  6.  
  7. /* MAIN ENTRY POINT */
  8. int main(void)
  9. {
  10.      int num1, num2;
  11.  
  12.       printf("Enter two positive integers: ");
  13.       scanf("%d %d", &num1, &num2);
  14.       printf("Sum = %d\n", add(num1, num2, 1));
  15.  
  16.       return 0;
  17. }
  18.  
  19. /* FUNCTION DEFINITIONS */
  20.  
  21. /*
  22. * <summary> Recursively performs addition on 2 integers </summary>
  23. * <params>
  24. *   "n1", "n2" = The two integers to perform addition on
  25. *   "carry" = The weight of the last digit of both numbers
  26. * </params>
  27. * <return> Computed addition of "n1" and "n2" </return>
  28. * <precond> Both "n1" and "n2" should contain the same number of digits and do not have leading zeroes </precond>
  29. */
  30. int add(int n1, int n2, int carry)
  31. {
  32.      int sum;
  33.      
  34.      //Both are equal in length, so if n1 <=0, n2 as well
  35.       if (n1 > 0)
  36.      {
  37.           //Add last digits and multiply with their weight
  38.          sum = (n1%10 + n2%10) * carry;
  39.    
  40.     //Recursion - Remove last digit and increase weight by a factor of 10
  41.          return sum + add(n1/10, n2/10, carry*10);
  42.       }
  43.       else
  44.            return 0;
  45.  
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement