Sum of columns of a 2-D Matrix where first element is odd
Last Updated :
14 Sep, 2022
Given a matrix mat[][], the task is to print the sum of the columns where the first element is odd.
Examples:
Input: mat[][] = {
{8, 2, 3, 5},
{9, 8, 7, 6},
{1, 2, 5, 5} }
Output: 31
Only the third and the fourth columns start with an odd element.
And, sum = 3 + 7 + 5 + 5 + 6 + 5 = 31
Input: mat[][] = {
{10, 80, 20, 12, 40},
{10, 21, 23, 45, 29},
{19, 18, 17, 16, 15},
{10, 11, 12, 13, 14} }
Output: -1
Approach: Initialize sum = 0 and start traversing the first row. If any element in the first row is odd, then add all the elements of that column to the sum. Print the sum at the end.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int sumColumns( int arr[][4], int r, int c)
{
int sum = 0;
for ( int j = 0; j < c; j++)
{
if (arr[0][j] % 2 != 0)
{
for ( int i = 0; i < r; i++)
sum += arr[i][j];
}
}
return sum;
}
int main()
{
int arr[3][4] = {{8, 2, 3, 5},{9, 8, 7, 6}, {1, 2, 5, 5}};
int r = sizeof (arr)/ sizeof (arr[0]);
int c = sizeof (arr[0])/ sizeof ( int );
cout<<(sumColumns(arr, 3, 4));
}
|
Java
import java.io.*;
class GFG
{
static int sumColumns( int arr[][], int r, int c)
{
int sum = 0 ;
for ( int j = 0 ; j < c; j++)
{
if (arr[ 0 ][j] % 2 != 0 )
{
for ( int i = 0 ; i < r; i++)
sum += arr[i][j];
}
}
return sum;
}
public static void main (String[] args)
{
int arr[][] = {{ 8 , 2 , 3 , 5 },{ 9 , 8 , 7 , 6 }, { 1 , 2 , 5 , 5 }};
System.out.println(sumColumns(arr, 3 , 4 ));
}
}
|
Python3
def sumColumns(arr, r, c):
sum = 0
for j in range (c):
if (arr[ 0 ][j] % 2 ! = 0 ):
for i in range (r):
sum + = arr[i][j]
return sum
arr = [ [ 8 , 2 , 3 , 5 ], [ 9 , 8 , 7 , 6 ], [ 1 , 2 , 5 , 5 ] ]
r = len (arr)
c = len (arr[ 0 ])
print (sumColumns(arr, r, c))
|
C#
using System;
class GFG
{
static int sumColumns( int [,]arr, int r, int c)
{
int sum = 0;
for ( int j = 0; j < c; j++)
{
if (arr[0, j] % 2 != 0)
{
for ( int i = 0; i < r; i++)
sum += arr[i, j];
}
}
return sum;
}
public static void Main()
{
int [,]arr= {{8, 2, 3, 5}, {9, 8, 7, 6}, {1, 2, 5, 5}};
Console.WriteLine(sumColumns(arr, 3, 4));
}
}
|
PHP
<?php
function sumColumns( $arr , $r , $c )
{
$sum = 0;
for ( $j = 0; $j < $c ; $j ++)
{
if ( $arr [0][ $j ] % 2 != 0)
{
for ( $i = 0; $i < $r ; $i ++)
$sum += $arr [ $i ][ $j ];
}
}
return $sum ;
}
$arr = array ( array (8, 2, 3, 5),
array (9, 8, 7, 6),
array (1, 2, 5, 5));
$r = sizeof( $arr );
$c = sizeof( $arr [0]);
echo (sumColumns( $arr , $r , $c ));
?>
|
Javascript
<script>
function sumColumns(arr, r, c)
{
var sum = 0;
for ( var j = 0; j < c; j++)
{
if (arr[0][j] % 2 != 0)
{
for ( var i = 0; i < r; i++)
sum += arr[i][j];
}
}
return sum;
}
var arr = [[8, 2, 3, 5],[9, 8, 7, 6], [1, 2, 5, 5]];
var r = arr.length;
var c = arr[0].length;
document.write(sumColumns(arr, 3, 4));
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...