Question

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.

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;

}

ADVERTISEMENT

Get Answers For Free

Most questions answered within 1 hours.

ADVERTISEMENT

asked 3 minutes ago

asked 7 minutes ago

asked 25 minutes ago

asked 51 minutes ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 2 hours ago

asked 2 hours ago

asked 2 hours ago

asked 2 hours ago