Define a class to accept values in an integer array of size 10. Find the sum of one digit numbers and the 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
Topic: Summing one-digit and two-digit numbers in an array
Answer
import java.util.Scanner;
class SumDigits { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int a[] = new int[10]; int sum1 = 0, sum2 = 0;
System.out.println("Enter 10 integers :"); for(int i = 0; i < 10; i++) a[i] = sc.nextInt();
for(int i = 0; i < 10; i++) { if(a[i] >= 0 && a[i] <= 9) sum1 = sum1 + a[i]; else if(a[i] >= 10 && a[i] <= 99) sum2 = sum2 + a[i]; }
System.out.println("Sum of one digit numbers : " + sum1); System.out.println("Sum of two digit numbers : " + sum2); } }
The whole question is about how you decide the number of digits.
The simplest test is the range itself: a one-digit number lies between 0 and 9, a two-digit number between 10 and 99. That reads directly and needs no extra loop.
An equally acceptable method is to count digits by repeated division — while(n > 0) { n = n / 10; count++; } — and then test count == 1 or count == 2. Use whichever you find clearer, but the range test is shorter and less error-prone under examination conditions.
Note the else if rather than a second if: a number cannot be both, and else if makes that explicit. Numbers of three digits or more simply fall through and are ignored, which is what the question wants.
Check with the sample: 2 + 4 + 9 + 3 + 1 = 19 and 12 + 18 + 25 + 32 + 20 = 107 — both match the paper.
a[] int[10] - the ten integers entered by the user sum1 int - running total of the one-digit numbers sum2 int - running total of the two-digit numbers i int - loop variable sc Scanner - object used to read input