Free Response Practice Question (with solution)- Integer Array


<-- Back to Increasing Order Array Next to Large Integer Array -->





Integer Array


Write a Java program that reads 10 integers (positive, zeros or negative) from the user and stores them in an array. The program should display the absolute sum of the integers.

Note: Do not make use of any inbuilt function to calculate the absolute value of a number.


For e.g., consider following as the elements of an array: -2, 1, 78, 0, -45, 34, 2, 8, -56, 5

The sum will be = |-2|+ |1| + |78| + |0| + |-45| + |34| + |2| + |8| + |-56| + |5|

= 2 + 1 + 78 + 0 + 45 + 34 + 2 + 8 + 56 + 5 = 231


Solution:


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

public class IntegerArray {

    public static void main(String[] args)
    {
        int SIZE =10;
        int absSum=0;
        int[] integerArr = new int[SIZE];
        try (Scanner input = new Scanner(System.in)) {

            int number;
            System.out.print("Enter 10 numbers (positive, zero or negative): ");
            
            for (int k=0; k < integerArr.length; k++)
            {
                number = input.nextInt();
                integerArr[k]= number;
            }
        
            System.out.println("Numbers in the integer array are: ");

            for (int k=0; k < integerArr.length; k++)
            {
                System.out.print(integerArr[k]+" ");
                if (integerArr[k] >= 0) absSum = absSum + integerArr[k];
                else absSum = absSum + (integerArr[k]*(-1));
            }
            
            System.out.println("\n" +"Absolute sum is: "+absSum);

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




Java project file:


<-- Back to Increasing Order Array Next to Large Integer Array -->