Question:
A user provides a number and I need to draw a triangle using loops based on the users input:
This is what the output should look like:
This is what the output should look like:
Enter number: 5 x xx xxx xxxx xxxxx
Answer:
Use a nested for loop.
Code:
import java.util.Scanner; public class Triangle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter number: "); int number = sc.nextInt(); for (int i=1;i<=number;i++) { for(int j=1; j<=i; ++j) { System.out.print("x"); } System.out.println(); } } }
Output:
$ java Triangle Enter number: 10 x xx xxx xxxx xxxxx xxxxxx xxxxxxx xxxxxxxx xxxxxxxxx xxxxxxxxxx