w3resource

Java Conditional Statement Exercises: Print the Floyd's Triangle

Java Conditional Statement: Exercise-20 with Solution

Write a program in Java to print the Floyd's Triangle.

Test Data
Input number of rows : 5

Pictorial Presentation:

Java conditional statement Exercises: Print the Floyd's Triangle

Sample Solution:

Java Code:

import java.util.Scanner;
public class Exercise20 {

  public static void main(String[] args)

{
   int i,j,n,p,q;
  System.out.print("Input number of rows : ");
   Scanner in = new Scanner(System.in);
		    n = in.nextInt();

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

Sample Output:

Input number of rows : 5                                                                                      
1                                                                                                       
01                                                                                                       
101                                                                                                       
0101                                                                                                       
10101

Flowchart:

Flowchart: Java Conditional Statement Exercises - Print the Floyd's Triangle

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in Java to print such pattern like a pyramid with a number which will repeat the number in the same row.
Next: Write a program in Java to display the pattern like a diamond.

What is the difficulty level of this exercise?



Inviting useful, relevant, well-written and unique guest posts