Here, we will build a C Program To Print Floyd Triangle Pattern using 2 approaches i.e.
- Using for loop
- Using while loop
Input:
n = 5
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1. Using for loop
The first for loop is used to iterate the number of rows and the second for loop is used to repeat the number of columns. Then print the number and increment the number to print the next number.
C
// C program to Print Floyd Triangle Pattern // using for loop #include <stdio.h> int main()
{ int rows, columns, number = 1, n = 5;
// first for loop is used to identify number of rows
for (rows = 0; rows <= n; rows++) {
// second for loop is used to identify number of
// columns and here the values will be changed
// according to the first for loop
for (columns = 0; columns < rows; columns++) {
// printing number pattern based on the number
// of columns
printf ( "%d " , number);
// incrementing number at each column to print
// the next number
number++;
}
// print the next line for each row
printf ( "\n" );
}
return 0;
} |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2. Using while loop:
The while loops check the condition until the condition is false. If the condition is true then enters into the loop and execute the statements.
C
// C program to Print Floyd Triangle Pattern // using while loop #include <stdio.h> int main()
{ int rows = 1, columns = 0, n = 5;
// 1 value is assigned to the number
// helpful to print the number pattern
int number = 1;
// while loops check the condition and repeat
// the loop until the condition is false
while (rows <= n) {
while (columns <= rows - 1) {
// printing number to get required pattern
printf ( "%d " , number);
// incrementing columns value
columns++;
// incrementing number value to print the next
// number
number++;
}
columns = 0;
// incrementing rows value
rows++;
printf ( "\n" );
}
return 0;
} |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15