In: Computer Science
The program shall take two integer arrays as input. Each array represents a non-negative number. Each element in the array is one digit however when all digits in the array are combined a number is formed. See example below:
int Array1 = {4,5,6,7} represents number 7654
int Array2 = {2,3,4,5} represents number 5432
You will add the two numbers i.e., 7654 + 5432 = 13086 and store it
in a new array similar to how the numbers were stored earlier i.e.,
{6,8,0,3,1}. The output of your program will be this array for
given input arrays.
Your program should work with any size arrays and both arrays may not be the same size. If the result is larger than an integer (4 bytes) your program will return an empty array. Code must be written C++.
CODE:
#include <iostream>
using namespace std;
int main(){
int array1[] = {4,5,6,7};
int array2[] = {2,3,4,5};
int a=0,b=0,c=0,length1=0,length2;
int j=0;
//getting the lengths of the two arrays
length1 = *(&array1+1) - array1;
length2 = *(&array2+1) - array2;
//getting the first number
for(int i=length1-1;i>=0;i--){
a = 10*a + array1[i];
}
//getting the second number
for(int i = length2 - 1;i>=0;i--){
b = 10*b + array2[i];
}
//the addition of the two numbers is c
c = a+b;
int p = c;
int length = 0;
//getting the length of c
while(p!=0){
length += 1;
p = p/10;
}
p = c;
//storing the numbers in the array with the units digit as the
first element in the array
int *array3 = new int[length];
for(int i = 0;i<length;i++){
array3[i] = p%10;
p = p/10;
}
//displaying the output array if the size of the array
if(sizeof(array3)<=4&&sizeof(c)<=4){
cout<<"The addition of the two array numbers
"<<a<<" and "<<b<<" give the array:
"<<endl;
for(int i = 0;i<length;i++){
cout<<array3[i]<<" ";
}
cout<<endl;
}else{
cout<<"The addition of the two array numbers
"<<a<<" and "<<b<<" gives a result which is
larger than an integer"<<endl;
}
return 0;
}
______________________________________
CODE IMAGES:
__________________________________________________
OUTPUT:
________________________________________________
Feel free ti ask any questions in the comments section
Thank You!