Home
/
Programs
/
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 = 19Sum of two digit numbers : 12 + 18 + 25 + 32 + 20 = 107
Programming Example
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
Study this program carefully to understand the logic, output, and explanation in a structured way.
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);
}
}
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
<h3><strong>Explanation:</strong></h3>
<ul class="list-group">
<li class="list-group-item"><strong>One-digit numbers</strong>: <code>2, 4, 9, 3, 1</code>
<ul class="list-group">
<li class="list-group-item">The sum: <code>2 + 4 + 9 + 3 + 1 = 19</code></li>
</ul>
</li>
<li class="list-group-item"><strong>Two-digit numbers</strong>: <code>12, 18, 25, 32, 20</code>
<ul class="list-group">
<li class="list-group-item">The sum: <code>12 + 18 + 25 + 32 + 20 = 107</code></li>
</ul>
</li>
</ul>