Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C89 Programming - CANNOT use pointers, or addition. Has to use recursion and inc

ID: 669382 • Letter: C

Question

C89 Programming - CANNOT use pointers, or addition. Has to use recursion and incrementors/decrementors

The program will use incrementors and decrementors in an add() function to substitute for the addition fuction. It will also need to use recursion to add the two numbers. The program will need to work with both positive and negative values. Here's what I have so far, which doesn't work properly:

#include <stdio.h>

int add (int n, int m);

int main(void){
   int n, m, sum;
  
   printf("Enter the 1st number: ");
   scanf("%d", &n);
  
   printf("Enter the 2nd number: ");
   scanf("%d", &m);
  
   sum = add(n,m);
  
   printf("Sum of two numbers : %d", sum);
   return 0;
}

int add (int n, int m){
   int sum;
  
   if(m >= 0){        //for positive numbers of m.
       while(m--){
           sum++;
       }
   }else{                //for negative numbers of m.
       while(m++){
           sum--;
       }
   }
  
   if(n >= 0){        //for positive numbers of n.
       while(n--){
           sum++;
       }
   }else{                //for negative numbers of n.
       while(n++){
           sum--;
       }
   }
   return sum;
}

Sum becomes an really large integer.

Also for recursion, isn't there also supposed to be another sum = add(n,m) within the add() function?

Explanation / Answer

#include <stdio.h>

// iterative method

long add(int n,int m)

{

//sum of two integers can be larger than size of int

long sum = n;

  

if(m>=0)

{

while (m--)

sum++;

}

else

{

while(m++)

sum--;

}

  

return sum;

  

}

//Recursive method

long addRec(int n,int m)

{

if(m==0)

return n;

  

if(m<0)

return addRec(n, ++m)-1;

else

return addRec(n, --m)+1;

  

}

int main( int argc, char *argv[] )

{

int n,m;

  

printf("Enter first integer : ");

scanf("%d",&n);

  

printf("Enter second integer : ");

scanf("%d",&m);

  

long sum;

  

sum = add(n, m);

printf("sum of two integers using iterative method is %li ",sum);

sum = addRec(n, m);

  

printf(" sum of two integers using recursive method is %li ",sum);

  

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote