Search code examples
javaloopsincrementdecrement

Anyone know how to increment and decrement at the same time and put the output side by side?


Write an application that will ask the user to input a number. Your program will then display a number that starts and ends based on the number you entered and on the right side to reverse the numbers you displayed on the left side.

Expected output:

Enter a number: 5
1 5
2 4
3 3
4 2
5 1

I tried making a hollow box with increasing and decreasing numbers and making the other codes a comment to try and make the expected output. But I still can't manage to do so.

import java.util.Scanner;
public class MyClass {
public static void main(String args[])
{
    System.out.print("Enter a number: ");
    Scanner input = new Scanner (System.in);
    int num = input.nextInt();
    System.out.print("\n");

    for (int i = 0; i < num; ++i) {
        for (int j = 0; j < num; ++j) {
            if (i == 0) {
                System.out.print((j + 1) + " ");
            //} else if (i == num-1) {
                System.out.print((num - j) + " ");
            } else if (j == 0) {
                System.out.print((i + 1) + " ");
            //} else if (j == num-1) {
                System.out.print((num - i) + " ");
            //} else {
                System.out.print("  ");
            }
        }
        System.out.println();
        }
    }
} 

Solution

  • You're thinking too hard (;->). It's not so complicated.

    Here's one possible way:

    public class MyClass {
    public static void main(String args[])
    {
        System.out.print("Enter a number: ");
        Scanner input = new Scanner (System.in);
        int num = input.nextInt();
        System.out.print("\n");
        int i = 1;
        int j = num;
        while (i >= num) {
            System.out.println(i + " " + j);
            i++;
            j--;
        }
    } 
    

    Here's another:

    public class MyClass {
    public static void main(String args[])
    {
        System.out.print("Enter a number: ");
        Scanner input = new Scanner (System.in);
        int num = input.nextInt();
        System.out.print("\n");
        for (int i = 1; i <= num; ++i) {
            System.out.println(i + " " + (num - i + 1));
        }
    }