we have to find the sum of the elements of the middle row of the matrix, but my code isn't printing anything | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

we have to find the sum of the elements of the middle row of the matrix, but my code isn't printing anything

public class que2 { public static int Sum(int[][] nums) { int m = nums.length; int n = nums[0].length; int sum=0; for(int i=0;i<m;i++) { for(int j=0;i<n;j++) { if(i==1) { sum += nums[i][j]; } } } return sum; } public static void main(String[] args) { int[][] nums = {{1,4,9},{11,4,3},{2,2,3}}; System.out.println(Sum(nums)); } }

13th Dec 2022, 8:01 AM
RISHABH BHUTANI
RISHABH BHUTANI - avatar
4 Answers
+ 2
It's same. But you took mid row value as 1 directly. You have only 3 rows so you are taking 1 for middle row value in nums[1][j] . What if you have more rows then find middle row as int mid = nums.length / 2; Then find sum by sum += nums[ mid ] [ j ] ; This works fine if rows are odd in number. If it is even rows then you need to take sum of mid, mid-1 rows. See like nums[][] = { {1, 4, 9}, {11, 4,3}, {2, 2,3} }; sum of mid row(1) is 11+4+3= 18 What if nums[][] = { {1, 4, 9}, {11,4,3}, {2,3,4}, {2,2,3} }; sum of middle rows 1,2 are 11+4+3=18 and 2+3+4 = 9 , then final sum = 18+9=27.
14th Dec 2022, 8:41 AM
Jayakrishna 🇮🇳
+ 2
@jayakrishna can you elaborate that more?? I made a new solution to that and it's working but still I wanna know your method. public class que2 { public static int Sum(int[][] nums) { int n = nums[0].length; int sum=0; for(int j=0;j<n;j++) { sum += nums[1][j]; } return sum; } public static void main(String[] args) { int[][] nums = {{1,4,9},{11,4,3},{2,2,3}}; System.out.println(Sum(nums)); } }
13th Dec 2022, 7:27 PM
RISHABH BHUTANI
RISHABH BHUTANI - avatar
+ 2
Got it! Thanks
14th Dec 2022, 8:47 AM
RISHABH BHUTANI
RISHABH BHUTANI - avatar
+ 1
What do you mean by i==1 condition? It you need only one row then no need 2 loops.. Directly use i as : Middle row : you can find by i=nums.length / 2 if nums.length is odd then take i and i-1 rows. And loop from j=0 to nums[i].length. Hope it helps...
13th Dec 2022, 8:21 AM
Jayakrishna 🇮🇳