Free Response Practice Question (with solution)- Large Integer Array


<-- Back to Integer Array Next to Sales Array -->





Large Integer Array


Write a Java program that reads large numbers (long int) from the user and stores them in an array. The program then prints the number for which the sum of the digits of the number is the largest.


For e.g., consider following as the elements of an array:

23, 67, 903, 45, 1111, 600, 349, 560, 31, 91

The integer with largest sum of the digits is: 349


Solution:


import java.util.InputMismatchException;
import java.util.Scanner;

public class LargeIntegers {

    public static void main(String[] args)
    {
        int SIZE =10;

        long [] largeArr = new long [SIZE];
        try (Scanner input = new Scanner(System.in)) {

            long number;
            System.out.print("Enter 10 large integers: ");
            
            for (int k=0; k < largeArr.length; k++)
            {
                number = input.nextInt();
                largeArr[k]= number;
            }
        
            System.out.println("Numbers in the large integer array are: ");

            long maxSum=0;
            long maxNumber=0;
            long rem=0;
            long sum=0;
            for (int k=0; k < largeArr.length; k++)
            {
                System.out.print(largeArr[k]+" ");
                // calculate sum of the digits for each large integer
                number = largeArr[k];
                sum=0;
                while (number !=0)
                {
                    rem = number % 10;
                    sum = sum +rem;
                    number = number / 10;
                }
                
                if (maxSum < sum) 
                    {
                        maxSum = sum;
                        maxNumber = largeArr[k];
                    }
            }
            
            System.out.println("\n"+"The number with the largest sum is: "+ maxNumber);
            System.out.println("with a sum of: "+ maxSum);

        }
    
    catch (InputMismatchException  e)
    {
        System.out.println("Error reading input");
    }
    }
    
}


Java project file:


<-- Back to Integer Array Next to Sales Array -->