Home C C++ Java Python Perl PHP SQL JavaScript Linux Selenium QT Online Test

Home » C++ » Programs on various Tree Problems

C++ Programs on various Tree Problems


Printing Reverse Rectangle using numbers


5 4 3 2 1
  4 3 2 1
    3 2 1
      2 1
        1

Solution:-

#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {
int count = 5;
int i,j,k;

for(i = 0 ; i<5; i++)
{
	for(j=0; j<i; j++)
	cout<<" ";
	for(k=count; k>0; k-- )
        cout<<k;	
	count--;
	cout<<"\n";
}
return 0;
}

Printing Triangle Pattern using numbers


1
1 2
1 2 3
1 2
1

Solution:- 

#include<iostream>
using namespace std;

int main(int argc, char *argv[]) {
int count = 0;
int i,j;
int rows = 5;

for(i = 0 ; i<rows; i++)
{
	if(i<=(rows/2))
	count++;
	else
	count--;
	
	for(j=1; j<=count; j++ )
        cout<<j;	
    cout<<"\n";
}

return 0;
}

Printing Rectangle one on Another Pattern using numbers


1 2 3
1 2
1
1 2
1 2 3

Solution:- 

#include<iostream>
using namespace std;

int main(int argc, char *argv[]) {
int count = 0;
int i,j;
int rows = 5;
count = rows/2 +1;

for(i = 0 ; i<rows; i++)
{
	for(j=1; j<=count; j++ )
        cout<<j;	
	cout<<"\n";
	
	if(i+1 <= count)
	count --;
	else
	count++;
}
return 0;
}

Printing two Rectangle Pattern using numbers


1 2 3 4 5 4 3 2 1
1 2 3 4   4 3 2 1
1 2 3       3 2 1
1 2           2 1
1               1

Solution:-

#include<iostream>
using namespace std;

int main(int argc, char *argv[]) {
int count = 0;
int i,j;
int rows = 5;
int temp = rows;
count = rows/2 +1;

for(i = 0 ; i<rows; i++)
{
    for(j=1; j<=temp; j++)
        cout<<j;
    for(j=0; j<i; j++)
        cout<<"  ";
    for(j=temp;j>=1;j--)
        cout<<j;
    cout<<"\n";
    temp--;
}
return 0;

}