×

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle

An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or random alphabetical elements grouped. It a pattern-based programming practice that is implemented using nested loops.

There is a certain number of ways of generating alphabetical triangles. Let us look at some of the most practiced ways through the coding examples below.

Example 1:

 #include<bits/stdc++.h>
 using namespace std;
 int main()
 {
         int i, j, increment=1, count;
         cout<<"Enter Rows : ";
         cin>>count;
         cout<<"\n";
         char ch = 'A';
         for(i=0; i<count; i++)
         {
                 for(j=0; j<increment; j++)
                 {
                         cout<<ch<<" ";
                         ch++;
                 }
                 cout<<"\n";
                 increment = increment + 1;
         }
         return 0;
 } 

Output:

C ++ Program: Alphabet Triangle and Number Triangle

Explanation:

In the above code, we have declared a variable 'count' and 'increment'. Here the count variable takes the number of rows as input from the user and a loop iterates till the count. Another loop is used for columns that keep the alphabet incremented by 1 so that the letters consequently proceed one by one. The variable 'char' is initialized by 'A' so that the looping starts from A to the next word.

Note: The triangle above is also known as Floyd’s Triangle.

Example 2:

 #include<bits/stdc++.h>
 using namespace std;
 int main()
 {
 char s[]="india";
 int i,j;
 for(i=0;s[i];i++)
 {
 for(j=0;j<=i;j++)
 cout<<s[j];
 cout<<"\n";
 }
 } 

Output:

C ++ Program: Alphabet Triangle and Number Triangle

Explanation:

The above code is made interesting just to understand the flow of making an alphabetical triangle. In this example, we have initialized a character array known as a string and assigned the string as "India". Two nested loops are used to access the rows and columns and print them consequently in the next line keeping the previous row element the same.

Example:

 #include<bits/stdc++.h>
 using namespace std;
 int main()
 {
   int i,j;
   int n=5;
   for(i=n;i>=1;i--)
      {
          for(j=1;j<=i;j++)
          {
              cout<<((char)(i+64));
          }
          cout<<endl;
      }
   return 0;
 } 

Output:

C ++ Program: Alphabet Triangle and Number Triangle

Explanation:

Here, the same pattern is printed just in inverted or say upside-down order. This can be done just by doing minor changes in the above-explained codes. In this case, the loop is executed from the number itself and the term associated with it in the loop. The loop starts to iterate from E since and then the E is printed on the console. The process is then decreased 5 folds until the end condition is reached i.e. till A.

Note: There are various other approaches to do this yet this is the most practiced approach.

Number Triangle:

A number triangle is exactly similar to the alphabetical triangle provided words are replaced just by numbers. The logic of coding is just the same. A number triangle is also generated using nested loops. To ace this, one must be ideally clear with the concept of nested loops.

Let us now look at coding examples for better understanding.

Example 1:

 #include<bits/stdc++.h>
 using namespace std;
 int main()
 {
     int num;
     cout<<"Please enter no. of rows: ";
     cin>>num;
     for(int i = 1;i <=num;i++)
     {
         for(int j = 1;j<=i;j++)
         {
             cout << j;
         }
         cout << "\n";
     }
 return 0;
 } 

Output:

C ++ Program: Alphabet Triangle and Number Triangle

Explanation:

Here we have used two loops that iterate for rows and columns respectively. As soon as the user enters the number of rows, the outer loop is executed which runs from 1 to the number entered. The loop then enters the column and prints the value on the console and later the number is incremented from 1 to 2 and so on.

Example 2:

 #include<bits/stdc++.h>
 using namespace std;
 int main()
 {  
     int number;
     cout<<"Enter the size of triangle: ";
     cin>>number;
     for(int i = 1; i <=10;i++)
     {
         for(int j= number-i;j>= 1;j--)
         {
             cout << j;
         }
         cout<<"\n";
     }
     return 0;
 } 

Output:

C ++ Program: Alphabet Triangle and Number Triangle

Explanation:

In the above code, we have tried to invert the number triangle just to make the users understand the flow switches in the nested loops.

Here, we have initialized the outer loop from 1 to the number and the inner loop is further executed from the number minus the value from the outer loop. The inner loop is then decremented using the post-decrement operator. It gives the value in decreasing order in the next line till the value reaches its end.

There are still various other ways to print number triangles in C++ but we have discussed the most basic and easy to learn approaches for solving these pattern related problems.


Related Topics

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.