Binary Triangle in Java

I’ve come across a number of C/C++/Java forums across the Internet, where people ask for code to print Binary Triangles. This triangle actually looks a lot like the Pascal’s triangle. I’ve written a code snippet in Java. Have fun. 🙂


import java.util.Scanner;
class floyd
{
public static void main(String args[])
{

int i,j,k,numOfLines;
Scanner s=new Scanner(System.in);
System.out.print("Enter the number of lines:");
numOfLines=s.nextInt();

for(i=1;i<=numOfLines;i++)
{

for(k=numOfLines-i;k>=1;k--){

System.out.print(" ");

}

if(i%2!=0)

{

for(j=1;j<=i;j++)
{
if(j%2==0)
{

System.out.print("0 ");
}

else
{
System.out.print("1 ");
}
}
}

else if(i%2==0)
{
for(j=1;j<=i;j++)
{
if(j%2==0)
{
System.out.print("1 ");
}
else
{
System.out.print("0 ");
}
}
}

System.out.println();
}
}
}

Here’s a sample  screenshot of what the output will look like.

Binary Triangle ScreenShot

Binary Triangle ScreenShot

Advertisements

About Manikandan Surendren

A PeopleSoft Techno-functional Consultant. An engineering graduate in Computer Science. Technology Enthusiast. Movie freak. Gadget geek.
This entry was posted in Code. Bookmark the permalink.

2 Responses to Binary Triangle in Java

    • JavaD says:

      But this is the real binary triangle..

      class Pattern2
      {

      public static void main(String args[])
      {
      int n=4;
      for(int i=1;i<=n;i++)
      {

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

      System.out.print((i+j)%2+" ");

      }

      System.out.println();

      }

      }

      }

      You can substitute 'n' with Scanner or BufferedReader

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s