Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Create find_the_trace_of_a_matrix.pl (#5648)
Browse files Browse the repository at this point in the history
Co-authored-by: Ritesh Kokam <[email protected]>
  • Loading branch information
charan-hash and RiteshK-611 authored Apr 30, 2024
1 parent 1dabce2 commit ee87f40
Showing 1 changed file with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
sub find_trace {
my ($matrix) = @_;
my $trace = 0;
my $size = scalar(@$matrix);
for (my $i = 0; $i < $size; $i++) {
$trace += $matrix->[$i][$i];
}
return $trace;
}

# Function to create a matrix from user input
sub create_matrix {
print "Enter the size of the square matrix: ";
my $size = <STDIN>;
chomp($size);

my @matrix;
for (my $i = 0; $i < $size; $i++) {
print "Enter row ", $i + 1, " elements separated by space: ";
my $row_input = <STDIN>;
chomp($row_input);
my @row = split(/\s+/, $row_input);
push @matrix, \@row;
}
return \@matrix;
}

# Create matrix
my $matrix = create_matrix();

# Calculate trace
my $trace = find_trace($matrix);
print "Trace of the matrix is: $trace\n";

0 comments on commit ee87f40

Please sign in to comment.