Write a program in Java to store 25 numbers in an array then create another array to store sum of the digits. Then display only those numbers in ascending order where sum of the digits is a single digit.
package arrays;
import java.util.Arrays;
public class Start {
static int getSum(int n)
{
int sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
return sum;
}
public static void main(String[] args) {
int [] numbers = new int [25];
int [] digits = new int[25];
for(int i=0; i<25; i++){
numbers[i] = i;
digits[i]=getSum(numbers[i]);
}
int k=0;
for(int i=0; i<25; i++ ){
String x = String.valueOf(digits[i]);
if(x.length()==1){
k++;
}
System.out.println();
}
System.out.println(k);
int results [] = new int [k];
int j = 0;
for(int i=0; i<25; i++ ){
String x = String.valueOf(digits[i]);
if(x.length()==1){
results[j] = digits[i];
j++;
}
}
Arrays.sort(results);
for(int i=0; i<24; i++ ){
System.out.printf("%d ",results[i]);
}
}
}
Comments
Leave a comment