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.
/*
* C++ Program to print upper triangular portion of matrix
*/
#include <iostream>
void printTriangular(int arr[][3], int sizeX, int sizeY)
{
std::cout << "Upper-triangular matrix " << std::endl;
for (int i = 0; i < sizeY; i++)
{
for (int j = 0; j < (sizeX - i); j++)
{
std::cout << arr[i][j] << " ";
}
std::cout << "\n";
}
}
int main()
{
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printTriangular(arr, 3, 3);
}
$ 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]Related Posts:
- Check C++ Books
- Apply for Computer Science Internship
- Practice Programming MCQs
- Check Programming Books
- Apply for C++ Internship