Mark Newbie
Mark Newbie

Reputation: 21

For loop java making the output into 2 columns

Hi I'm a beginner and I'm still learning and if someone could help me in this one thx in advance my code is:

for(int i = 0; i < 10; i++) {
    System.out.println(i);
}

and the output should be like this:

0 1
2 3
4 5
6 7
8 9

Upvotes: 1

Views: 1070

Answers (3)

kason gu
kason gu

Reputation: 1

To do what you want you can either do something like this:

for(int i = 0; i < 10; i ++){  
    if(i % 2 == 0){
        System.out.print(i); //Only for evens
    }else{
        System.out.println(i);  //Only for odds
    }
}

Or you could simplify it even more with something like this:

for(int i = 0; i < 5; i += 2){
    System.out.println(i + " " + (i + 1));
}

Upvotes: 0

Rweinz
Rweinz

Reputation: 190

You can do something like this:

for (int i = 0; i < 10; i++) {
  System.out.print(i);
  System.out.println(++i);
}

The first print uses the current i value and using System.out.print. The second print is using println so it goes one line down and also takes ++i so it will advance i by 1 and will also print the new value.

Each loop iteration is printing two values and advances i by total of 2.

Upvotes: 2

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

Just use next line only for odd numbers:

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0)
        System.out.format("%2d", i);
    else
        System.out.format(" %2d\n", i);
}

Output:

 0  1
 2  3
 4  5
 6  7
 8  9

P.S. For more general usage, I would extract it into separate method

public static void printTwoColumns(int min, int max) {
    int width = String.valueOf(max).length();

    for (int i = min; i < max; i++) {
        String str = String.format("%" + width + 'd', i);

        if (i % 2 == 0)
            System.out.print(str);
        else {
            System.out.print(' ');
            System.out.println(str);
        }
    }
}

Upvotes: 1

Related Questions