# Adding two Integers in an Array

I was wondering if I could get a second look at my program before I turn it in. The job was to code a program in java that adds two integers to an array gather the sum while displaying the integers that belong in the carry column section. I am curious if there is a simpler way to do what I am trying to do. I hope the output is enough to give you the idea behind the program.

Here is a sample output.

Enter the first number : 9999
Enter the second number : 9999
Carry : 1110
Num1 : 9999
Num2 : 9999
Sum : 19998
Continue(Y/N)

import java.util.Arrays;
import java.util.Scanner;
import java.util.*;

public class Main {

public static void main(String args[]) {

Integer[]  num1 = new Integer[10];
Integer[]  num2 = new Integer[10];
Integer[]  temp = new Integer[10];
Integer[] carry = new Integer[10];
Integer[]   sum = new Integer[10];

Scanner input = new Scanner(System.in);

do{

int g;
int a=0;
int b=0;
int t;
int s1;
int c=0;

//Read two integer values from user input
System.out.print("\n Enter the first number : ");
int m = input.nextInt();

System.out.print("\n Enter the second number : ");
int n = input.nextInt();

for(int i = 0; i < 10; i++){

num1[i]=0;
num2[i]=0;

}

//Placing the two integer numbers into array
while(m > 0){

g = m % 10;
m = m / 10;
num1[a] = g;
temp[a] = g;
a++;

}

while(n > 0){

g = n % 10;
n = n / 10;
num2[b] = g;
b++;
}

if(a > b) c = a;
else   c = b;

for(int i = 0; i < c; i++){

carry[i]=0;
sum[i]=0;

}

//finding sum and handling carry
for(int i = 0; i < c; i++){

sum[i] = num1[i]+num2[i];
s1=sum[i];
t=0;

while(s1 > 0){

s1= s1 / 10;
t++;

}

if(t > 1 && ((i+1)<c)){

carry[i+1] = 1;
num1[i+1] = num1[i+1] + 1;
sum[i] = sum[i] % 10;

}

}

// Printing the sum value to user
System.out.print("\n Carry : " );
for(int x = c-1; x >= 0; x--)
System.out.print(carry[x]);

System.out.print("\n");
System.out.print("\n Num1 : " );
for(int x=c-1;x>=0;x--)
System.out.print(temp[x]);
System.out.print("\n");

System.out.print("\n Num2 : " );
for(int x=c-1;x>=0;x--)
System.out.print(num2[x]);
System.out.print("\n");

System.out.print("\n Sum : " );
for(int x=c-1;x>=0;x--)
System.out.print(sum[x]);
System.out.print("\n");

} while(Continue());
}

public static boolean Continue(){

char choice;

Scanner input = new Scanner(System.in);
System.out.println("Continue(Y/N)");
choice = input.next().charAt(0);

return Character.toLowerCase(choice) == 'y';

}

}

• "I am curious if there is a simpler way to do what I am trying to do." So, what exactly are the requirements — to be able to produce output like the sample, or do you have to use arrays to do it? Mar 10, 2017 at 9:51
• I had to use array's Mar 13, 2017 at 16:39

Code quality has 3 priorities:

1. the code works as expected
2. the code is easy to read and does not surprise the reader
3. the code is (almost) free from duplications

## Naming

Finding good names is the hardest part in software development so always take your time to improve the names of your identifiers.

### Single letter names

Do not use single letter names or abbreviations. There are only few exceptions like loop variables or very common abbreviations. While reading this code your brain has to do additional work to resolve single letters to their meaning.

Always use expressive names for your identifiers taken from the problem domain, not from the technical solution.

### Naming Conventions

Please keep to the Java Naming Conventions. This will make the life of your coworkers easier as it does for you when your coworkers follow this suggestion.

eg.:
You have this method:

public static boolean Continue()


In Java only class names start with an uppercase letter. Also the method name (if correctly spelled) would collide with a reserved Java key word (which is no technical problem since java does distinguish between keywords and method names). This may confuse the reader.

Also since the method returns a boolean its name should start with is or has.

### Names should express intention

Your method Continue() reveals another problem: it does not what its name implies.

What it really does is to ask the user what to do. So its name should be ie.: isUserRepeating()

Comments should always describe why the code is like it is.

Your comments somehow structure the code into individual sections. You should better extract those individual sections to separate methods with names derived from the comments you wrote.

When doing so this will support a very important principle of object oriented programming: separation of concerns.

## Visibility scopes

All your variables are declared at the top of your main method or the top of your main loop.

You should reduce the visibility to the least possible block which means that you should declare them at first use. This will help to refactor your code later.

## Code duplications

You have lots of duplicated code which does merrily the same but the names of the variables differ. eg.:

 //Placing the two integer numbers into array
while(m > 0){
g = m % 10;
m = m / 10;
num1[a] = g;
temp[a] = g;
a++;
}
while(n > 0){
g = n % 10;
n = n / 10;
num2[b] = g;
b++;
}


The only difference is that the first loop additionally sets the values in the temp array.

So the better approach would be to fill the temp array in its own loop (for now, but there are even better approaches):

 //Placing the two integer numbers into array
while(m > 0){
g = m % 10;
m = m / 10;
num1[a] = g;
a++;
}
a=0; // reset the currentDigitIndex
while(m > 0){
g = m % 10;
m = m / 10;
temp[a] = g;
a++;
}
while(n > 0){
g = n % 10;
n = n / 10;
num2[b] = g;
b++;
}


now you can create a method that does the loop:

private static int placeIntegerIntoArray(int numberToSplit, Integer[] individualDigits){
int currentDigitIndex=0;
while(numberToSplit > 0){
int currentDigit = numberToSplit % 10;
numberToSplit = numberToSplit / 10;
individualDigits[currentDigitIndex] = currentDigit;
currentDigitIndex++;
}
return currentDigitIndex;
}


and in your main you change to:

a = placeIntegerIntoArray(m, num1);
placeIntegerIntoArray(m, temp); // initialite to same as num1
b = placeIntegerIntoArray(n, num2);


BTW: this removes variable g from the scope of the main method.

## Magic numbers.

Your code uses some literal numbers. You should extract them to constants so that you can give them meaningful names.

eg.: the literal number 10 in

 sum[i] = sum[i] % 10;


might be the SINGLE_DIGIT_MAX_VALUE

whereas in

 Integer[]  num1 = new Integer[10];


it might be the MAXIMUM_DIGIT_LENGTH

Firstly, a suggestion. If there is such a use-case where you have to add two numbers by taking them as separate arrays, you should not assume the size of the number you'll get.

It could be possible that you get a number above the range of Integer.

So it is better to create an array directly out of the input String.

String firstInput = input.next();
String secondInput = input.next();

int lengthOfSumArray = (firstInput.length() > secondInput.length() ? firstInput.length() : secondInput.length()) + 1;

int[] sum = new int[lengthOfSumArray]


Next, you do need to initialize every element in an integer array to 0. Java by default takes care of it. Check default values here.

When it comes to implementation details you can check @Timothy's answer or if you're willing to use Java-8 you could do something like this:

Arrays.setAll(result, i -> num1[i] + num2[i]);


Here is the documentation

• Thank you for this. I never thought I could do that with an array. Mar 13, 2017 at 16:39