Sunday, 23 September 2018

Printing Floyd's triangle n number of times in C++

Floyd's triangle 

Floyd's triangle is a right-angled triangular array of natural numbers. This triangle was named after Robert Floyd. It is obtained by writing natural numbers serially in right-angled triangular shape. We can also observe that nth row contain n numbers.E.g the fifth row contains five numbers (11,12,13,14,15).


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


Write a program in C++ to print Floyd's triangle with n number of rows. 

Firstly we will take the number of rows the user wants to print in Floyd's triangle. We will use a nested for loop statement to print Floyd's triangle. In this program, we will use two nested for loop. The first loop is used for the execution of the number of rows and the second loop is used for the execution of the number of columns. We will declare a counter with initial value 1 and print it inside the inner for loop(i.e. the loop that executes the no of columns).


Program

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int i,j,n,count=1;
clrscr();
cout<<"Enter the number of rows=";
cin>>n;
for(i=1;i<=n;i++)
          {
for(j=1;j<=i;j++)
{
cout<<setw(2)<<count<<" ";
count++;
}
     cout<<"\n";
}
getch();
}



Output



Program to print Floyd's triangle
PRINTING OF FLOYD'S TRIANGLE











Explanation

In the program, the user wants to print 6 rows(i.e. n=6). The nested for loop are executed as follows:

i=1 to 6        j=1 to i                   Action                                                count++
1                   j=1 to 1                 
                     j=1                        1 is printed on the screen.                    2
2                   j=1 to 2                   
                     j=1                        2 is printed on the screen.                    3 
                     j=2                        3 is printed on the screen.                    4
3                   j=1 to 3                   
                     j=1                        4 is printed on the screen.                    5 
                     j=2                        5 is printed on the screen.                    6
                     j=2                        6 is printed on the screen.                    7

The process continues till i=6. Finally, we get Floyd's triangle with n number of rows.                     





No comments:

Post a Comment