The program to print number triangles uses two loops (usually while or for loop) and prints a triangle of numbers. In this example, we will see four such patterns of number triangle.
This program is written using Dev C++ version 4.9.9.2 installed on a Windows 7 64-bit PC. You may use any standard C++ compiler and the code in this program will still work.
The intent of this program is to develop an understanding of C++ loops for beginner C++ programmers.
How a loop starts and terminates?
How does a nested loop works?
These are some of the questions, we tried to answer using these examples. However, you as a learner must try to write the program on your own and then compare your results given here.
Problem Definition
We want to following 4 number triangles using nested for loops. You may try a different combination of loops for better learning. The number patterns are given below.
Each of this program take two “for” loop. The outer loop is for rows and inner loop is for columns.
Program Code – Pattern 1
The program code for pattern 1 is given below.
/* C++ Program to print the following number triangle
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1 */
#include <conio.h>
#include <iostream.h>
#include <cstdlib>
int main()
{
int i,j,n;
n = 10;
for( i = 1; i < n; i++)
{
for( j=i;j >= 1; j--)
{
cout << j;
}
cout << "\n";
}
getch();
return 0;
}
Output – Pattern 1
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
Program Code – Pattern 2
The program code for pattern 2 is given below.
/* C++ program to print following number triangle
1
12
123
1234
12345
123456
1234567
12345678
123456789 */
#include <conio.h>
#include <iostream.h>
#include <cstdlib>
using namespace std;
int main()
{
int i,j,n;
n = 10;
for(i = 1;i < n;i++)
{
for(j = 1;j<=i;j++)
{
cout << j;
}
cout << "\n";
}
getch();
return EXIT_SUCCESS;
}
Output – Pattern 2
1
12
123
1234
12345
123456
1234567
12345678
123456789
Program Code – Pattern 3
The program code for pattern 1 is given below.
/* C++ Program to Print
987654321
87654321
7654321
654321
54321
4321
321
21
1 */
#include <conio.h>
#include <iostream.h>
#include <cstdlib>
using namespace std;
int main()
{
int i,j,n;
n = 10;
for(i = 1; i <=10;i++) { for( j= n-i;j>= 1;j--)
{
cout << j;
}
cout << "\n";
}
getch();
return EXIT_SUCCESS;
}
Output – Pattern 3
Program Code – Pattern 4
The program code for pattern 4 is given below.
/* C++ Program to print
123456789
12345678
1234567
123456
12345
1234
123
12
1 */
#include <conio.h>
#include <iostream.h>
#include <cstdlib>
using namespace std;
int main()
{
int i,j,n;
n = 10;
for(i = 1; i <= n;i++)
{
for(j = 1; j <= n - i; j++)
{
cout << j;
}
cout << "\n";
}
getch();
return EXIT_SUCCESS;
}