C89 Programming - CANNOT use pointers, or addition. Has to use recursion and inc
ID: 669369 • 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 exactly work:
#include <stdio.h> //standard io header
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);
printf("Sum of two numbers : %d", sum);
return 0;
}
int add (int n, int m){
int sum;
while(m--){
sum++;
}
while(n--){
sum++;
}
return sum;
}
Explanation / Answer
The problem with your code is:
1. You missed calling the add() function from main, and assigning the value to sum. So after reading n and m, just right one more step: sum = add(n,m);
2. In the add() function, the logic you wrote works for all the positive numbers but not for negative numbers. For negative numbers, if you keep decrementing, it will go for infinity. So, if the number is negative, you should keep incrementing the number till it becomes zero, and decrementing the sum. You don't need a recursion for this.
Therefore the modified code goes here:
#include <stdio.h> //standard io header
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;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.