I would like to add two 10-digit numbers using 3 arrays. I wrote these lines:
import java.util.*;
public class addition {
public static void main(String[] args){
Scanner enter = new Scanner(System.in);
int[] arr1= new int[10];
int[] arr2 = new int[10];
int [] result = new int [11];
System.out.print("Enter the first array: ");
for(int i=0; i<10; i++)
{
arr1[i]=enter.nextInt();
}
System.out.print("Enter the second array: ");
for(int i=0; i<10; i++)
{
arr2[i]=enter.nextInt();
}
for(int i=0; i<10; i++)
{
int b;
int c;
int a = arr1[9-i]+ arr2[9-i];
if(a>9){
b = a%10;
c = a/10;
result[9-i] = b;
result[10-i] += c;
}
result[9-i]=a;
}
System.out.print("Result: ");
for(int i=10; i>=0; i--)
{
System.out.print(result[i]);
}
}
}
But the program does not work correctly. The result is not true.
Console:
Enter the first array: 8
6
9
5
3
9
9
1
4
2
Enter the second array: 8
5
3
8
0
0
3
1
6
6
Result: 09103129414131216
What should I do?
resultarray when you add two digits that sum to more than 9; you also need to store a result digit when the two digits sum to 9 or less.result[9-i]=a;should be in else part of yourif (a>9)statement