Here in this program, I will teach you how to write a C Program To Print Floyd Triangle Using While Loop. So let’s take a simple example to understand the concept of a while loop to print the Floyd Triangle.
C Program To Print Floyd Triangle Using While Loop:
In this program, first, you have to know about the syntax of the while loop because we know that the while loop is a little bit different from for loop. The syntax of the while loop is the initialization of a variable outside the body of the while loop then the while keyword and then the body of the while.
In this type of loop condition portion is with the keyword of the while like (while(condition)) then statements and at the last increment or decrement according to your program’s requirement.
So, this is a short introduction to the while loop. In the following example, we have taken some variables ‘i’ and ‘j’ for the loops because every pattern is printed with the help of nested loops so that’s why we use nested while loop in this program.
We declared the variable rows for the number of rows that have been entered by the user and count=0 because in this program we have to print the Floyd triangle increased by 1 so that’s why we initialize count to 0 to avoid the garbage value.
When i is equal to 1 it will check the condition that if your condition meets then the body of the while loop will be executed. Suppose the rows we have entered are 5 and i is equal to 1. It means i is less than 5 condition is true it will move inside the body of the while loop.
In the inner loop j is initialized to 1 and if j is less than or equal to i then it will execute the body of the loop and print the number 1 because we address the %d to count and the count is equal to 0 so after the first iteration, it will print 1. After this j will be incremented from 1 to 2 it will again check the condition of the inner loop.
This time j is equal to 2 and i is equal to 1 so if the condition is false it will move to the outer loop and read the print statement and then i is incremented from 1 to 2. So this is the procedure it will execute until your given condition is false.
Best Example Of While Loop To Print Floyd Triangle:
#include<stdio.h> int main(){ int i,rows,j,count=0; printf("ENTER THE NUMBER OF ROWS\n"); scanf("%d",&rows); i=1; while(i<=rows){ j=1; while(j<=i){ printf("%d\t",++count); j++; } printf("\n"); i++; } }
Output:
Conclusion:
From the above example, we can print the Floyd triangle by while loop. User is supposed to enter the rows of their own will. In the above image, we will enter 5 number of rows from the user according to our condition it will print the result of our program. So this is all about C Program To Print Floyd Triangle Using While Loop that how can we use while loops to print patterns.
If you want to check the program for the for loop then click C Program To Print Reverse Floyd Triangle.