Advertisements
Advertisements
Question
Write a program to generate a triangle or an inverted triangle till n terms based upon the user's choice.
Example 1: | Example 2: |
Input: Type 1 for a triangle and Type 2 for an inverted triangle Enter your choice 1 |
Input: Type 1 for a triangle and Type 2 for an inverted triangle Enter your choice 2 |
Sample Output: 1 |
Sample Output: 6 6 6 6 6 6 |
Answer in Brief
Solution
import java.util.*;
public class Q10
{ public static void main(String az[])
{int n, i, j, x;
Scanner sn = new Scanner(System.in);
System.out.printin("*****MENU****");
System.out.println("1. Pattern - Triangle ");
System.out.println("2. Pattern - Inverted Triangle ");
System.out.printIn("Enter your choice 1 (or) 2");
x = sn.nextInt();
switch(x)
{
case 1: System.out.printIn("Enter the number of terms");
n = sn.nextInt();
for (i = 1; i <= n; i++)
{ System.out.println();
for (j = 1; j <= i; j++)
System.out.print(i);
}
break;
case 2: System.out.printIn("Enter the number of terms");
n = sn.nextInt();
for (i = n: i >= 1; i--)
{ System.out.println();
for (j = i; j >= 1; j--)
System.out.print(i);
}
break;
default: System.out.println("Invalid Entry");
}
}}
shaalaa.com
Is there an error in this question or solution?
Chapter 1.1: Nested Loop - EXERCISES [Page 147]