Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* PREPROCESSOR DIRECTIVES */
- #include <stdio.h>
- /* FUNCTION PROTOTYPES */
- int add(int, int, int);
- /* MAIN ENTRY POINT */
- int main(void)
- {
- int num1, num2;
- printf("Enter two positive integers: ");
- scanf("%d %d", &num1, &num2);
- printf("Sum = %d\n", add(num1, num2, 1));
- return 0;
- }
- /* FUNCTION DEFINITIONS */
- /*
- * <summary> Recursively performs addition on 2 integers </summary>
- * <params>
- * "n1", "n2" = The two integers to perform addition on
- * "carry" = The weight of the last digit of both numbers
- * </params>
- * <return> Computed addition of "n1" and "n2" </return>
- * <precond> Both "n1" and "n2" should contain the same number of digits and do not have leading zeroes </precond>
- */
- int add(int n1, int n2, int carry)
- {
- int sum;
- //Both are equal in length, so if n1 <=0, n2 as well
- if (n1 > 0)
- {
- //Add last digits and multiply with their weight
- sum = (n1%10 + n2%10) * carry;
- //Recursion - Remove last digit and increase weight by a factor of 10
- return sum + add(n1/10, n2/10, carry*10);
- }
- else
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement