Inverted Triangle | Write a program in java to print an inverted triangle. | ISC Computer Science | ICSE Computer Applications
Algorithm
- Start
- n:=0
- Print "Enter a number"
- Read n
- i=0
- If i<=n, go to step 7 or else go to step 19
- j=0
- If j<i, g to step 9 or else go to step 11
- Print " "
- j++. Go to step 7
- k=0
- If k<(n-i)*2, go to step 13 or else go to step 15
- Print "*"
- k++. Go to step 12
- If i==n, go to step 16 or else go to step 17
- Print "*"
- Go to next line.
- i++. Go to step 6
- Stop
Program
Buffered Reader
import java.io.*;
class InvertedTriangle
{
int n;
void accept() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number");
n=Integer.parseInt(br.readLine());
}
void display()
{
for(int i=0;i<=n;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(" ");
}
for(int k=0;k<(n-i)*2;k++)
{
System.out.print("*");
}
if(i==n)
{
System.out.println("*");
}
System.out.println();
}
}
void main() throws IOException
{
accept();
display();
}
}
Scanner
import java.util.*;
class InvertedTriangle
{
int n;
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
n=sc.nextInt();
}
void display()
{
for(int i=0;i<=n;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(" ");
}
for(int k=0;k<(n-i)*2;k++)
{
System.out.print("*");
}
if(i==n)
{
System.out.println("*");
}
System.out.println();
}
}
void main()
{
accept();
display();
}
}
Documentation
Variable Description
Data Type | Variable Name | Description |
int | n | To store the height of the triangle |
int | i | To act as a counter variable |
int | j | To act as a counter variable |
Method Description
Return Type | Method Name | Description |
void | accept() | To accept data from the user |
void | display() | To display an inverted triangle. |
void | main() | To act as an entry gateway for the compiler. |
Output
Share with all ISC Computer Science Students you know.
Comment below with all your program requests and blog suggestions.
Follow us on social media by clicking on these links.
Instagram : @ISCJavaCode
Twitter: @ISCJavaCode
Quora: ISC Java Code
Reddit: @ISCJavaCode
Stay Healthy
Stay Happy
Stay Helpful
Comments
Post a Comment