Print Lower Hessenberg matrix of order N
Given a positive integer N, the task is to print the Lower Hessenberg matrix of order N which includes any one-digit random positive integer as its non-zero elements.
Lower Hessenberg matrix is a square matrix in which all of its elements above the super-diagonal are zero. In mathematical term mat[i][j] = 0 for all j > i + 1.
Examples:
Input: N = 3
Output:
1 2 0
1 3 4
2 3 4
Input: N = 4
Output:
1 2 0 0
1 3 4 0
2 3 4 2
2 3 1 4
Approach: For printing a Lower Hessenberg matrix with one-digit positive elements print zero for all cells of the matrix where j > i + 1 and any single-digit random number with help of rand() function.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void LowerHessenbergMatrix( int n)
{
for ( int i = 1; i <= n; i++) {
for ( int j = 1; j <= n; j++) {
if (j > i + 1)
cout << '0' << " " ;
else
cout << rand () % 10 << " " ;
}
cout << "\n" ;
}
}
int main()
{
int n = 4;
LowerHessenbergMatrix(n);
return 0;
}
|
Java
class GFG
{
static void LowerHessenbergMatrix( int n)
{
for ( int i = 1 ; i <= n; i++)
{
for ( int j = 1 ; j <= n; j++)
{
if (j > i + 1 )
System.out.print( '0' + " " );
else
{
System.out.printf( "%.0f" ,Math.random() * 10 );
System.out.print( " " );
}
}
System.out.println( "\n" );
}
}
public static void main(String[] args)
{
int n = 4 ;
LowerHessenbergMatrix(n);
}
}
|
Python3
import random
def UpperHessenbergMatrix(n):
for i in range ( 1 , n + 1 ):
for j in range ( 1 , n + 1 ):
if (j > i + 1 ):
print ( '0' , end = " " )
else :
print (random.randint( 1 , 10 ),
end = " " )
print ()
n = 4 ;
UpperHessenbergMatrix(n)
|
C#
using System;
class GFG
{
static void LowerHessenbergMatrix( int n)
{
Random rand = new Random();
for ( int i = 1; i <= n; i++)
{
for ( int j = 1; j <= n; j++)
{
if (j > i + 1)
Console.Write(0 + " " );
else
Console.Write(rand.Next(1, 10) + " " );
}
Console.WriteLine();
}
}
static public void Main ()
{
int n = 4;
LowerHessenbergMatrix(n);
}
}
|
Javascript
<script>
function LowerHessenbergMatrix(n)
{
for ( var i = 1; i <= n; i++) {
for ( var j = 1; j <= n; j++) {
if (j > i + 1)
document.write( '0' + " " );
else
document.write(Math.floor(Math.random() * 10) + " " );
}
document.write( "<br>" );
}
}
var n = 4;
LowerHessenbergMatrix(n);
</script>
|
Output:
3 6 0 0
7 5 3 0
5 6 2 9
1 2 7 0
Time Complexity: O(n2)
Auxiliary Space: O(1)
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...