ADVERTISEMENT
ADVERTISEMENT

Ruby program to calculate the sum of rows of matrix elements

Ruby Example: Write a program to calculate the sum of rows of matrix elements.
Submitted by Nidhi, on January 23, 2022

Problem Solution:

In this program, we will create a matrix using the 2D array. Then we read elements of the matrix from the user. After that, we will calculate the sum of rows of matrix elements and print the result.

Program/Source Code:

The source code to calculate the sum of rows of matrix elements is given below. The given program is compiled and executed successfully.

# Ruby program to calculate the sum of rows 
# of matrix elements

TwoDArr = Array.new(2){Array.new(2)}
sum = 0;

printf "Enter elements of MATRIX:\n";
i = 0;
while (i < 2) 
  j = 0;
  while (j < 2) 
    printf "ELEMENT [%d][%d]: ", i, j;
    TwoDArr[i][j] =  gets.chomp.to_i;
    j = j + 1;
  end
  i = i + 1;
end

printf "MATRIX:\n";
i = 0;
while (i < 2)
  j = 0;
  while (j < 2) 
    print TwoDArr[i][j]," ";
    j = j + 1;
  end
  i = i + 1;
  print "\n";
end

i=0;
j=0;
while (i < 2) 
  j = 0;
  sum = 0;
  while (j < 2) 
    sum = sum + TwoDArr[i][j];
    j = j + 1;
  end
  printf "Sum of row(%d): %d\n", i, sum;
  i = i + 1;
end

Output:

Enter elements of MATRIX:
ELEMENT [0][0]: 1
ELEMENT [0][1]: 2
ELEMENT [1][0]: 3
ELEMENT [1][1]: 4
MATRIX:
1 2 
3 4 
Sum of row(0): 3
Sum of row(1): 7

Explanation:

In the above program, we created a 2X2 matrix TwoDArr using the 2D array. Then we read the elements of the matrix. After that, we calculated the sum of rows of matrix elements and printed the result.

Ruby Arrays Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.