183k views
1 vote
Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces. For each printed line, print the leading spaces, then the number, and then a newline. Hint: Use i and j as loop variables (initialize i and j explicitly). Note: Avoid any other spaces like spaces after the printed number. Ex: userNum = 3 prints:

0
1
2
3

Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number-example-1
User Wrikken
by
5.6k points

1 Answer

0 votes

Answer:

Here is an example of how you could use Java to print the numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces:

import java.util.Scanner;

public class NumberIndent {

public static void main(String[] args) {

// Create a Scanner object to read input from the user

Scanner input = new Scanner(System.in);

// Prompt the user to enter a number

System.out.print("Enter a number: ");

int userNum = input.nextInt();

// Use two loop variables, i and j, to print the numbers

for (int i = 0; i <= userNum; i++) {

for (int j = 0; j < i; j++) {

// Print a space for each iteration of the inner loop

System.out.print(" ");

}

// Print the number after the spaces

System.out.println(i);

}

}

}

Step-by-step explanation:

This code uses a nested for loop to print the numbers 0, 1, 2, ..., userNum, with each number indented by that number of spaces. The outer loop iterates through the numbers, and the inner loop prints a space for each iteration of the outer loop. Finally, the number is printed after the spaces.

I hope this helps! Let me know if you have any questions.

User Hermann Schwarz
by
5.2k points