Lets write C program to print Floyd’s Triangle, using nested for loop.
Floyd’s Triangle: is a right angled Triangle formed with natural numbers.
Related Read:
For Loop In C Programming Language
Nested For Loop In C Programming Language
C Program To Print Floyd’s Triangle
Video Tutorial: C Program To Print Floyd’s Triangle using For Loop
We ask the user to input the number of rows for Floyd’s Triangle, we store it inside variable num.
Outer For loop
In our C program, row number and the total numbers to be printed for that row is present inside variable row. So the outer for loop selects the row number and the number of elements to be printed in that row.
We initialize the row to 1 and iterate through the outer for loop until row is less than or equal to user entered number. For each iteration of the outer for loop we increment the value of row by 1. That way selecting the next row for each iteration.
Inner For loop
Inner for loop prints natural numbers in each selected row. Variable col is assigned to 1 for each iteration of outer for loop, so that the numbers gets printed from the first position in any selected row.
Inner for loop prints the natural number from the first position till the selected row number of times.
For Example, if user enters num = 5, the following Triangle will be printed:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Note that the Triangle printed is a right angled Triangle and has 5 rows of natural numbers.
Important Note:
Also note that first row has 1 number. Second row has 2 numbers. Third row has 3 numbers and so on. So row number and total numbers in that particular row are always equal in any Floyd’s Triangle.
#include<stdio.h> int main() { int num, row, col, count = 1; printf("Enter number of rows for Floyd's Triangle\n"); scanf("%d", &num); printf("\n"); for(row = 1; row <= num; row++) { for(col = 1; col <= row; col++) { printf("%d ", count++); } printf("\n"); } return 0; }
Output 1:
Enter number of rows for Floyd’s Triangle
5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Output 2:
Enter number of rows for Floyd’s Triangle
14
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91
92 93 94 95 96 97 98 99 100 101 102 103 104 105
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert