Floyd Triangle In Java

In the following post you will learn floyd triangle in java. Basically it is an algorithm, named after computer scientist Robert Floyd.

Floyd’s Triangle

Floyd Triangle is defined as right-angled triangular array of natural numbers consisting of numbers starting with 1 in the top left corner.

Floyd’s triangle example

1
2 3
4 5 6
7 8 9 10

As you can see above numbers are filled in rows of triangle. Now let’s see floyd triangle in java,

Example: floyd triangle in java

```import java.util.Scanner;

public class FloydTriangle
{
public static void main(String[] args)
{
int x;
int number = 1;
int y;
int z;

Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows to print Floyd's Triangle: ");
x = sc.nextInt();
System.out.println("Floyd Triangle:");

for(y = 1; y <= x; y++)
{
for(z = 1; z <= y; z++)
{
System.out.println(number + " ");
number++;
}
System.out.println();
}
}
}

```

Output:

Enter the number of rows to print Floyd’s Triangle: 5
Floyd Triangle:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Using functions

Now let’s learn how to print a java program to print floyd’s triangle,

```import java.util.Scanner;

public class FloydTriangle
{
public static void main(String[] args)
{
int rows;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows to print Floyd Triangle : ");
rows = sc.nextInt();
floyd(rows);
sc.close();
}

public static void floyd(int rows)
{
int a, b, number = 1;
for(a = 1 ; a <= rows; a++)
{
for(b = 1 ; b <= a; b++)
{
System.out.format("%d ", number);
number++;
}
System.out.println("");
}
}
}

```

Output:

Enter the number of rows to print Floyd Triangle : 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Printing “*” symbol

Now let’s see how to print “*” asterisk symbol using floyd’s triangle in java or how to print floyd triangle without numbers,

```import java.util.Scanner;

public class FloydTriangleExample
{
public static void main(String[] args)
{
int row, a, b;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows to print Floyd Triangle : ");
row = sc.nextInt();

for(a = 1 ; a <= row; a++)
{
for(b = 1 ; b <= a; b++)
{
System.out.format("* ");
}
System.out.println("");
}
sc.close();
}
}

```

Output:

Enter the number of rows to print Floyd Triangle : 6
*
* *
* * *
* * * *
* * * * *
* * * * * *

conclusion

That’s it guys. This is all about how to print floyd triangle in java using for loop.

I hope you have understood the concept. You can subscribe to my blog flower brackets if you haven’t already.