How to Generate Fibonacci Triangle in C++?

In this tutorial, we will learn how to Generate Fibonacci triangle in C++ and the program takes number of rows as input and uses for loops to print Fibonacci triangle. The first inner loop creates the indentation space and the second inner loop computes the value, creates indentation space So by using given code we can easily write the program.

To  print Fibonacci Triangle in C++

Let’s learn this with some easy steps:

  • Firstly, we start from header file in which we used two header file(iostream,conio) iostream is used for input /output stream and conio is used for console input/output.
    #include<iostream.h>
    #include<conio.h>
    
  •  then this is a main function. Void is the return type of function main() that means main function is not returning anything to OS.
void main()
  • we are using variables i and j and also a,b,c where (a=0) means initially starts from 0,(b=1) means initially starts from 1 and (c=0)means initially starts from 0.
{
  int i,j;
  int a=0,b=1,c;
  c=0;
  •  Now the for loop condition where i starts from 1 and goes till 6 then values gets increment.
for(i=1;i<=6;i++)
 
  • After that, it checks the j loop  if (j<=i) then it gets incremented and shows the output in C.” “ is used for spaces.
for(j=1;j<=i;j++)
{
 cout<<c<<" ";
}
  • However, this a=b means value of b stores at the place of a and b=c means value of c stores at the place of b and c=a+b means value of both store in C. ‘\n’ is new line.
{
c=a+b;
a=b;
b=c;
}
cout<<"\n";
  • Now combine the whole part of the program in a single window.
#include<iostream.h>
#include<conio.h>
void main()
{
  int i,j;
  int a=0,b=1,c;
  c=0;
  clrscr();
  
  for(i=1;i<=6;i++)
   {
     for(j=1;j<=i;j++)
   {
     cout<<c<<" ";
   }
   {
     c=a+b;
     a=b;
     b=c;
   }
    cout<<"\n";
   }
  getch();
}

output:

0
1  1  
2  2  2
3  3  3  3
5  5  5  5  5
8  8  8  8  8  8

Also read,

Leave a Reply

Your email address will not be published. Required fields are marked *