C++ Program to Display Upper Triangular Matrix

This C++ program displays the upper triangular matrix for a given n x n square matrix. The program uses a function which has three parameters – the two-dimensional array, the horizontal and the vertical dimension. The function runs a loop over the whole vertical dimension and on each iteration of the outer loop, the inner loop runs one less than the previous number of iterations of the inner loop.

Here is the source code of the C++ program displays the upper triangular matrix for a given n x n square matrix. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to print upper triangular portion of matrix
  3.  */
  4. #include <iostream>
  5.  
  6. void printTriangular(int arr[][3], int sizeX, int sizeY)
  7. {
  8.     std::cout << "Upper-triangular matrix " << std::endl;
  9.     for (int i = 0; i < sizeY; i++)
  10.     {
  11.        for (int j = 0; j < (sizeX - i); j++)
  12.        {
  13.            std::cout << arr[i][j] << "  ";
  14.        }
  15.        std::cout << "\n";
  16.     }
  17. }
  18.  
  19. int main()
  20. {
  21.     int arr[3][3] = { 
  22.     	{1, 2, 3},
  23.         {4, 5, 6},
  24.         {7, 8, 9}
  25.     };
  26.     printTriangular(arr, 3, 3);
  27. }

$ a.out
Upper-triangular matrix
1  2  3
4  5
7

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.