Write a program to generate a triangle or an inverted triangle till n terms based upon
the user's choice
Answers
Answer:
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
*
*/
import java.io.*;
class questionFIVE2009
{
public static void main(String args[]) throws IOException
{
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("**************MENU*************");
System.out.println("Type 1 for a triangle and ");
System.out.println("Type 2 for an inverted triangle");
int ch=Integer.parseInt(br.readLine());
System.out.println("Enter the number of terms");
int terms=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
for(i=1; i<=terms; i++)
{
for(j=1; j<=i; j++)
{
System.out.print(i);
}
System.out.println("");
}
break;
case 2:
for(i=terms; i>=1; i--)
{
for(j=1; j<=i; j++)
{
System.out.print(i);
}
System.out.println("");
}
break;
default:
System.out.println("Wrong choice");
}
}
}
Answer:
Answer by scanner input
Explanation:
import java.util.*;
class triangle
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int i,j,a,b;
System.out.println("Press 1 for triangle");
System.out.println("Press 2 for inverted trianglr");
System.out.println("Press 3 for EXIT");
b=s.nextInt();
System.out.println("Enter the no. of terms you want:");
a=s.nextInt();
switch(b)
{
case 1:
for(i=1;i<=a;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println("");
}
break;
case 2:
for(i=a;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println("");
}
break;
case 3:
System.exit(0);
}
}
}