IT Developer

Nested for Loops in Java

Chapter 10

Nested for Loops in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Triangle or Inverted Triangle Pattern in Java


6. Write a program to generate a triangle or an inverted triangle till n terms based upon the user's choice of triangle to be displayed.

Example 1


Input:
Type 1 for a triangle and type 2 for an inverted triangle
1
Enter the number of terms
5


Output:

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

 

Example 2


Input:
Type 1 for a triangle and type 2 for an inverted triangle
2
Enter the number of terms
6


Output:

6 6 6 6 6 6

5 5 5 5 5

4 4 4 4

3 3 3

2 2

1

Program Title 1 : Value of sum After Nested Loops Execution in Java

import java.util.Scanner;

 

public class NumberTriangle

{

    public static void main(String[] args)

    {

        Scanner sc = new Scanner(System.in);

 

        System.out.println("Type 1 for a triangle and type 2 for an inverted triangle");

        int choice = sc.nextInt();

 

        System.out.println("Enter the number of terms");

        int n = sc.nextInt();

 

        switch(choice)

        {

            case 1: // Normal Triangle

                for(int i = 1; i <= n; i++)

                {

                    for(int j = 1; j <= i; j++)

                    {

                        System.out.print(i + " ");

                    }

                    System.out.println();

                }

                break;

 

            case 2: // Inverted Triangle

                for(int i = n; i >= 1; i--)

                {

                    for(int j = 1; j <= i; j++)

                    {

                        System.out.print(i + " ");

                    }

                    System.out.println();

                }

                break;

 

            default:

                System.out.println("Invalid Choice");

        }

 

        sc.close();

    }

}

Output

Sample Output 1: 
Type 1 for a triangle and type 2 for an inverted triangle
1
Enter the number of terms
5
1 
2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5 

Sample Output 2: 
Type 1 for a triangle and type 2 for an inverted triangle
2
Enter the number of terms
6
6 6 6 6 6 6 
5 5 5 5 5 
4 4 4 4 
3 3 3 
2 2 
1 

📝 Explanation

When user enters 1

Outer loop runs from 1 to n
Inner loop prints the number i, i times

Example (n = 5):

 

When user enters 2

Outer loop runs from n to 1
Inner loop prints the number i, i times

Example (n = 6):