#9 Write an object oriented C++ program to implement an algorithm for adding lar
ID: 3571065 • Letter: #
Question
#9 Write an object oriented C++ program to implement an algorithm for adding large numbers Adding Large Numbers Algorithm A) read the numerals of the first number and store the numbers corresponding to them on one stack B) read the numerals of the second number and store the numbers corresponding to them on a second stack C) result = 0; D) while at least one stack is not empty pop a number from each nonempty stack and add them to result push the unit part on the result stack store carry in result E) push carry on the result stack if it is not zero F) pop numbers from the result stack and display themExplanation / Answer
Here MaxSize is the max. length of integer result expected(Max size of Result Stack).
Feel free to comment. I hope that i answered your query.
#include <iostream>
using namespace std;
class Stack
{
int MaxStack;
int EmptyStack;
int top;
int* items;
public:
Stack(int);
~Stack();
void push(int);
int pop();
int empty();
int full();
};
Stack::Stack(int size)
{
MaxStack = size;
EmptyStack = -1;
top = EmptyStack;
items = new int[MaxStack];
}
Stack::~Stack() {delete[] items;}
void Stack::push(int c)
{
items[++top] = c;
}
int Stack::pop()
{
return items[top--];
}
int Stack::full()
{
return top + 1 == MaxStack;
}
int Stack::empty()
{
return top == EmptyStack;
}
int main()
{
unsigned long long int num1, num2, maxSize, temp, result;
cout << "Enter Max Size: >";
cin >> maxSize;
cout << "Enter num1: >";
cin >> num1;
cout << "Enter num2: >";
cin >> num2;
Stack FirstNum(maxSize), SecondNum(maxSize), ResultNum(maxSize);
temp = num1;
while(temp!=0)
{
if (!FirstNum.full())
FirstNum.push(temp%10);
temp /= 10;
}
temp = num2;
while(temp!=0)
{
if (!SecondNum.full())
SecondNum.push(temp%10);
temp /= 10;
}
result = 0;
unsigned long long int carry=0, op1=0, op2=0, opTotal = 0;
while (true)
{
op1=0,op2=0;
if (FirstNum.empty() && SecondNum.empty()) break;
if (!FirstNum.empty()) { op1 = FirstNum.pop(); }
if (!SecondNum.empty()) { op2 = SecondNum.pop(); }
opTotal = 0;
opTotal = op1 + op2 + carry;
ResultNum.push(opTotal%10);
if (opTotal >= 10) carry = 1; else carry = 0;
}
cout << "Result is" << endl;
if(carry==1)
cout << 1 << endl;
while(!ResultNum.empty())
{
cout << ResultNum.pop() << endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.