Here are four different C++ programs on Floyd's triangle. First program print Floyd's triangle using for-loop, second program print Floyd's triangle using pointers, third program print Floyd's triangle using recursion and fourth program print Floyd's triangle using function.
Floyd's triangle is a right angled triangle of natural numbers. A sample Floyd's triangle with 4 rows is shown below.
1
2 3
4 5 6
7 8 9 10
Floyd's triangle is a right angled triangle of natural numbers. A sample Floyd's triangle with 4 rows is shown below.
1
2 3
4 5 6
7 8 9 10
C++ program to print Floyd's triangle using for-loop
#include<iostream>
using namespace std;
int main()
{
int row,i,j,k,s=1;
cout<<"Enter the value ";
cin>>row;
for(i=0;i<row;i++)
{
for(k=0;k<=i;k++,s++)
cout<<s<<" ";
cout<<endl;
}
return 0;
}
using namespace std;
int main()
{
int row,i,j,k,s=1;
cout<<"Enter the value ";
cin>>row;
for(i=0;i<row;i++)
{
for(k=0;k<=i;k++,s++)
cout<<s<<" ";
cout<<endl;
}
return 0;
}
C++ program to print Floyd's triangle using pointers
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int row,i,j,k=1,*p;
p=&k;
cout<<"Enter the value ";
cin>>row;
for(i=0;i<row;i++)
{
for(j=0;j<=i;j++)
{
cout<<*p<<" ";
*p=*p+1;
}
cout<<endl;
}
return 0;
}
#include<stdio.h>
using namespace std;
int main()
{
int row,i,j,k=1,*p;
p=&k;
cout<<"Enter the value ";
cin>>row;
for(i=0;i<row;i++)
{
for(j=0;j<=i;j++)
{
cout<<*p<<" ";
*p=*p+1;
}
cout<<endl;
}
return 0;
}
C++ program to print Floyd's triangle using recursion
#include<iostream>
using namespace std;
void print(int col,int s,int i)
{
if(col>i)
return;
cout<<s<<" ";
print(col+1,s+1,i);
}
void floyd(int row,int s,int i)
{
if(row==0)
return;
print(0,s,i);
cout<<endl;
floyd(row-1,s+i+1,i+1);
}
int main()
{
int row,i=0,s=1;
cout<<"Enter the value ";
cin>>row;
floyd(row,s,i);
return 0;
}
using namespace std;
void print(int col,int s,int i)
{
if(col>i)
return;
cout<<s<<" ";
print(col+1,s+1,i);
}
void floyd(int row,int s,int i)
{
if(row==0)
return;
print(0,s,i);
cout<<endl;
floyd(row-1,s+i+1,i+1);
}
int main()
{
int row,i=0,s=1;
cout<<"Enter the value ";
cin>>row;
floyd(row,s,i);
return 0;
}
C++ program to print Floyd's triangle using function
#include<iostream>
using namespace std;
void floyd(int row)
{
int i=0,j=0,s=1;
while(i<row)
{
while(j<=i)
{
cout<<s++<<" ";
j++;
}
i++,j=0;
cout<<endl;
}
}
int main()
{
int row,i=0,s=1;
cout<<"Enter the value ";
cin>>row;
floyd(row);
return 0;
}
using namespace std;
void floyd(int row)
{
int i=0,j=0,s=1;
while(i<row)
{
while(j<=i)
{
cout<<s++<<" ";
j++;
}
i++,j=0;
cout<<endl;
}
}
int main()
{
int row,i=0,s=1;
cout<<"Enter the value ";
cin>>row;
floyd(row);
return 0;
}
please explain 3rd code
ReplyDelete