0 Replies - 1394 Views - Last Post: 06 March 2011 - 09:03 AM

#1 Tapas Bose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 472
  • Joined: 09-December 09

Row-sum and column-sum of a square matrix

Posted 06 March 2011 - 09:03 AM

Description: The following shell script computes the row and column sum for each row and column of a matrix taking input from user
#!/bin/bash

## Shell script that takes a n*n matrix as input. The program is required to
## find out the sum of individual row element and individual column element
##
## This script simulate a two dimensional array by a one dimensional array


echo -n "Enter the number of row or column: "
read row

echo
declare -a array

rowSquare=`expr $row * $row`
adjustment=0

for (( i = 0; i < $row; i++ ))
do 
	k=0
	for (( j = 0; j < $rowSquare; j += $row ))
	do
		## In the following script the indexes of a 3x3 (for row=3) matrix will be represented as
		##
		## 0+0+0 0+3-2 0+6-4 
		## 1+0+2 1+3+0 1+6-2 
		## 2+0+4 2+3+2 2+6+0
		##
		## By 0+0+0 it means (value of i)+(value of j)+(value of adjustment)

		index=`expr $i + $j + $adjustment`
		adjustment=`expr $adjustment - $row + 1`
		echo -n "Enter the value of A`expr $i + 1``expr $k + 1`: "
		read array[index]
		k=`expr $k + 1`
	done
	adjustment=`expr $adjustment + $rowSquare - 1`
done

echo
echo "The given matrix is: "
adjustment=0

for (( i = 0; i < $row; i++ ))
do
	for (( j = 0; j < $rowSquare; j += $row ))
	do
		index=`expr $i + $j + $adjustment`
		adjustment=`expr $adjustment - $row + 1`
		echo -n "${array[index]} "
	done
	adjustment=`expr $adjustment + $rowSquare - 1`
	echo
done

adjustment=0

for (( i = 0; i < $row; i++ ))
do
	colSum=0
	rowSum=0		
	for (( j = 0; j < $rowSquare; j += $row ))
	do
		colIndex=`expr $i + $j`		
		colSum=`expr $colSum + ${array[colIndex]}`				
		rowIndex=`expr $i + $j + $adjustment`
		rowSum=`expr $rowSum + ${array[rowIndex]}`
		adjustment=`expr $adjustment - $row + 1`
	done	
	adjustment=`expr $adjustment + $rowSquare - 1`
	echo
	echo "Sum of `expr $i + 1`th column: $colSum"
	echo "Sum of `expr $i + 1`th row: $rowSum"
done

echo
echo -n "Press enter to continue ..."
read key
exit 0


Is This A Good Question/Topic? 0
  • +

Page 1 of 1