admjwt
admjwt

Reputation: 11

How do you sort numbers in ascending order from a for loop?

i have a for loop that multiples 3 and 7 by all numbers between 1 and 100. It only shows the numbers that are less the 100 after the multiplication though. How would you sort it so that its in ascending order?

for(int i = 1; i<=100; i++){
int result1 = 3 * i;
int result2 = 7*i;
if (result1 <=100){
System.out.println(+result1);
}
if (result2 <= 100){
System.out.println(+result2);
}
}

would use another if statement to sort it?

Upvotes: 0

Views: 5265

Answers (2)

Mike
Mike

Reputation: 8100

This sounds like it'll do what you need:

[mike@mike ~]$ cat temp/SO.java 
package temp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SO {
    private static final int MAX_VAL = 100;

    public static void main(String[] args) {
        List<Integer> results = new ArrayList<Integer>();

        for (int i = 1; i <= MAX_VAL; i++) {
            int result1 = 3 * i;
            int result2 = 7 * i;

            if (result1 <= MAX_VAL) {
                results.add(result1);
            }

            if (result2 <= MAX_VAL) {
                results.add(result2);
            }
        }

        Collections.sort(results);

        System.out.println(results);
    }
}

[mike@mike ~]$ javac temp/SO.java 
[mike@mike ~]$ java temp.SO
[3, 6, 7, 9, 12, 14, 15, 18, 21, 21, 24, 27, 28, 30, 33, 35, 36, 39, 42, 42, 45, 48, 49, 51, 54, 56, 57, 60, 63, 63, 66, 69, 70, 72, 75, 77, 78, 81, 84, 84, 87, 90, 91, 93, 96, 98, 99]

Upvotes: 1

MByD
MByD

Reputation: 137392

How about:

for(int i = 1; i<=100; i++){
    if(i % 3 == 0 || i % 7 == 0)
        System.out.println(i);
}

Upvotes: 3

Related Questions