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

C++ Accurately adding large numbers using stacks You can use stacks to add very

ID: 3700848 • Letter: C

Question

C++

Accurately adding large numbers using stacks

You can use stacks to add very large numbers. You may use the stack template to implement stacks.

Read in from a file two very large numbers and store them in the stacks, add the result.

Display the resulting answer.

Make sure your code is commented.

Sample run

Enter 1st number to be added

398877192309843792837423784

Enter 2nd number to be added

434820384038402384023840234

Answer is: 398877192309843792837423784 + 434820384038402384023840234 = 833697576348246176861264018

Press any key to continue

Try these pairs of numbers:

6000770088

99112233445

101

22233

Notice the simplicity of the last number, it’s easy to see if you are getting the right answer.

Explanation / Answer

here is your program : ------------->>>>>>>>>

#include<iostream>
#include<fstream>
#include<stack>

using namespace std;

string readNumber(ifstream &ifs){
string s = "";
if(ifs.eof()){
  exit(0);
}
ifs>>s;
return s;
}

void pushOnStack(string s,stack<int> &st){
for(int i = 0;i<s.length();i++){
  st.push(((int)(s[i] - '0')));
}
}
void add(stack<int> num1,stack<int> num2,stack<int> &res){
int n1,n2,r;
int carry = 0;
while(!num1.empty() || !num2.empty()){
  if(!num1.empty()){
   n1 = num1.top();
   num1.pop();
  }else{
   n1 = 0;
  }
  
  if(!num2.empty()){
   n2 = num2.top();
   num2.pop();
  }else{
   n2 = 0;
  }
  r = carry+n1+n2;
  if(r > 9){
   r = r-10;
   carry = 1;
  }else{
   carry = 0;
  }
  
  res.push(r);
}
res.push(carry);
}

void printStack(stack<int> n){
while(!n.empty()){
  cout<<n.top();
  n.pop();
}
}

void print(string s1,string s2,stack<int> res){
cout<<" Answer is = ";
cout<<s1<<" + ";
cout<<s2<<" = ";
printStack(res);
}

int main(){
stack<int> num1;
stack<int> num2;
stack<int> res;
string file;
cout<<" Enter the File name to read large number : ";
cin>>file;
string s1,s2;
ifstream ifs;
ifs.open(file.c_str());
if(!ifs.is_open()){
  cout<<" File opening error ";
  return -1;
}
while(!ifs.eof()){
  s1 = readNumber(ifs);
  pushOnStack(s1,num1);
  s2 = readNumber(ifs);
  pushOnStack(s2,num2);
  add(num1,num2,res);
  print(s1,s2,res);
  while(!num1.empty()){
   num1.pop();
  }
  while(!num2.empty()){
   num2.pop();
  }
  while(!res.empty()){
   res.pop();
  }
}
ifs.close();
}