C++ add(char* num1, char* num2, int base) I need a function that adds two dynami
ID: 3882995 • Letter: C
Question
C++
add(char* num1, char* num2, int base)
I need a function that adds two dynamic arrays using pointers and walkers.
- don't convert to integer. Instead subtract '0' to grab the number.
- Make sure to pad with zeros if one array is shorter than the other.
Use ONLY the pointer notation:
don't use [ ] operator.
don't use *(p + i) notation.
use if you need to access a cell in the array, get a walker and point to the cell you want to access
you may use walker = walker + 1 or walker = walker+i
- don't forget to delete dynamic memory and add null to your array.
IF You have any questions please comment and I'll clear things up. please include main. thumbs up if provide something helpful.
Base is used to carry numbers when adding together. In this case we are using base 10.
Explanation / Answer
Given below is the code for the function with main. Hope it helps. If it does, please don't forget to rate the answer. Thank you very much.
#include <iostream>
#include <cstring>
using namespace std;
char* add(char* num1, char* num2, int base);
int main()
{
char num1[] = "999";
char num2[] = "5";
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
char *num3 = add(num1, num2, 10);
cout << "num1 + num2 = " << num3 << endl;
delete []num3; //deallocate dynamic memory
}
char* add(char* num1, char* num2, int base)
{
int len1 = strlen(num1), len2 = strlen(num2);
int len3 = 1 + (len1 > len2 ? len1 : len2); //1 extra for overflow
char* num3 = new char[len3 + 1]; //allocate space for resulting answer and null terminator
char* walker1 = num1 + len1 - 1; //the rightmost digit in num1
char* walker2 = num2 + len2 - 1; //the rightmost digit in num2
char* walker3 = num3 + len3;
int digit1, digit2, sum = 0, carry = 0;
*walker3 = ''; //store ending
walker3 = walker3 - 1;
while(walker3 >= num3)
{
if(walker1 >= num1)
{
digit1 = *walker1 - '0'; //extract numeric value from ascii char
walker1 = walker1 - 1;
}
else
digit1 = 0;
if(walker2 >= num2)
{
digit2 = *walker2 - '0'; //extract numeric value from ascii char
walker2 = walker2 - 1;
}
else
digit2 = 0;
sum = digit1 + digit2 + carry;
if(sum >= base)
{
sum -= base;
carry = 1;
}
else
carry = 0;
*walker3 = sum + '0'; //convert the digit to ascii char
walker3 = walker3 - 1;
}
return num3;
}
output
num1 = 999
num2 = 5
num1 + num2 = 1004
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.