Home > Net >  How to create a single array from for loop values
How to create a single array from for loop values

Time:11-16

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number: ");
        int a = sc.nextInt();
        for ( int i = 1; i < a; i  ) {
            int []div = {a/i};
            if (a%i == 0 ) System.out.print(Arrays.toString(div)   " ");
        }
}

Input: 68 Output : [68] [34] [17] [4] [2]

Question is how to make a single array so it looks like [68, 34, 17, 4, 2] ?

CodePudding user response:

Since you can't know how many elements the div has in advance (it requires factorization of a), you have several options:

1. Calculate the size of div as a separate step:

int a = 68;
int n = 0; // length of the result
for (int i = 1; i < a; i  ) {
    if (a % i == 0) {
        n  ;
    }
}
int[] div = new int[n];
n = 0;

for (int i = 1; i < a; i  ) {
    if (a % i == 0) {
        div[n  ] = a / i;
    }
}
System.out.println(Arrays.toString(div));

2. Use mutable growing collection instead of the array:

int a = 68;
List<Integer> div = new ArrayList<>();
for (int i = 1; i < a; i  ) {
    if (a % i == 0) {
        div.add(a / i);
    }
}
System.out.println(div);

If you need, you can convert the collection to the primitive array afterwards:

int[] divArr = div.stream().mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(divArr));

3. One-liner using Stream:

As @Eritrean suggested in the comments, you can use IntStream to build your array:

int a = 68;
int[] div = IntStream
    .range(1, a)
    .filter(i -> a % i == 0)
    .map(i -> a / i)
    .toArray();
System.out.println(Arrays.toString(div));

It will be more efficient than the second variant, as it avoids creating Integer wrappers.


P.S. I omitted main method and Scanner initialization for brevity. You can put it back, if you need, for example:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number: ");
    int a = sc.nextInt();
    int n = 0; // length of the result
    for (int i = 1; i < a; i  ) {
        if (a % i == 0) {
            n  ;
        }
    }
    int[] div = new int[n];
    n = 0;

    for (int i = 1; i < a; i  ) {
        if (a % i == 0) {
            div[n  ] = a / i;
        }
    }
    System.out.println(Arrays.toString(div));
}
  • Related