Question

Write pseudocode for a simple algorithm for addition of two n-digit numbers (one of them could...

Write pseudocode for a simple algorithm for addition of two n-digit numbers (one of
them could be < n digits with 0's appended to the left) in base-10, as follows. Assume
the digits are stored in arrays A and B, with A[1] and B[1] being the rightmost digits and
A[n] and B[n] being the leftmost digits. Use a for loop to go from right to left adding the
digits and keeping track of the carry. Now, here's the real task: write a loop invariant
that is true each time the loop iterates, prove that it is indeed an invariant, and that the
algorithm therefore accomplishes the goal.

Homework Answers

Answer #1

#include <bits/stdc++.h>
using namespace std;

int main() {
   int n; //number of digits in array
   cin >> n;
   int a[n],b[n];
   int num1=0,num2=0;
   for(int i = 0;i<n;i++)
   {
       cin >> a[i]; //input in array A
       num1 = num1 + a[i]*pow(10,i);
      
   }
  
   for(int i = 0;i<n;i++)
   {
       cin >> b[i]; //input in array B
           num2 = num2 + b[i]*pow(10,i);
  
   }
  
   cout << num1 + num2 <<endl;
  
   return 0;
}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions