Define a class to accept values in integer array of size 10. Find sum of one digit number and sum of two digit numbers entered. Display them separately.

Example:
Input: a[ ] = {2, 12, 4, 9, 18, 25, 3, 32, 20, 1}
Output:
Sum of one digit numbers : 2 + 4 + 9 + 3 + 1 = 19
Sum of two digit numbers : 12 + 18 + 25 + 32 + 20 = 107

Java Programming Language (Article) (Program)

78

Given Input:

Enter 10 numbers:
2 12 4 9 18 25 3 32 20 1

Expected Output:

Sum of one digit numbers = 19
Sum of two digit numbers = 107

Program:

import java.util.Scanner;

public class RansariDigitSum {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        
        int oneSum = 0, twoSum = 0;
        int arr[] = new int[10];
        
        // Accept 10 numbers from the user
        System.out.println("Enter 10 numbers:");
        int l = arr.length;
        
        for (int i = 0; i < l; i++) {
            arr[i] = in.nextInt();  // Fill the array with user input
        }
        
        // Calculate the sum of one-digit and two-digit numbers
        for (int i = 0; i < l; i++) {
            if (arr[i] >= 0 && arr[i] < 10)  // Check for one-digit numbers
                oneSum += arr[i];
            else if (arr[i] >= 10 && arr[i] < 100)  // Check for two-digit numbers
                twoSum += arr[i];
        }
        
        // Display the results
        System.out.println("Sum of one digit numbers = " + oneSum);
        System.out.println("Sum of two digit numbers = " + twoSum);
    }
}

Output:

Input:
Enter 10 numbers:
2 12 4 9 18 25 3 32 20 1

Output:
Sum of one digit numbers = 19
Sum of two digit numbers = 107

Explanation:

  • One-digit numbers: 2, 4, 9, 3, 1
    • The sum: 2 + 4 + 9 + 3 + 1 = 19
  • Two-digit numbers: 12, 18, 25, 32, 20
    • The sum: 12 + 18 + 25 + 32 + 20 = 107

Explanation:

  • Array Initialization: An integer array of size 10 is declared to store the values.
  • User Input: We ask the user to input 10 integers to populate the array.
  • Sum Calculation:
    • We initialize two variables oneSum and twoSum to store the sums of one-digit and two-digit numbers, respectively.
    • The program loops through each array element:
      • If the number is a one-digit number (i.e., it’s between 0 and 9), it is added to oneSum.
      • If the number is a two-digit number (i.e., it’s between 10 and 99), it is added to twoSum.
  • Display the Results: After the loop, the program prints out the sum of the one-digit numbers and the sum of the two-digit numbers.

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.