Posted on by Kalkicode
Code Matrix

Count frequencies of negative elements in matrix

The problem addressed in this code involves counting the number of negative elements within a given matrix. A matrix is a two-dimensional array consisting of rows and columns. The objective is to determine the frequency of negative elements present in the matrix.

Problem Statement

Given a matrix containing integer elements, we aim to count the number of elements that are negative.

Example

Consider the following matrix:

  1   2  -3  -4   5
    4   5   6  11 -12
    -7   8  -9  13  14

In this matrix, there are 5 negative elements: -3, -4, -12, -7, and -9.

Solution Idea

Counting negative numbers in matrix

To solve this problem, we can iterate through each element of the matrix and check whether it is negative. If an element is less than zero, we increment a counter to keep track of the frequency of negative elements.

Pseudocode

frequencies(matrix):
    negative = 0
    for each row in matrix:
        for each element in row:
            if element < 0:
                negative += 1
    print "Total Negative:", negative

Algorithm Explanation

  1. Define a function frequencies(matrix) that takes the input matrix as its parameter.
  2. Initialize a variable negative to keep track of the count of negative elements.
  3. Iterate through each row of the matrix.
  4. For each row, iterate through the elements in that row.
  5. Check if the current element is less than 0. If it is, increment the negative counter.
  6. After both loops complete, print the count of negative elements.

Code Solution

/*
  Java Program
  Count number of negative elements in matrix
*/
public class Test
{
    // Display matrix elements
    public void showData(int[][] matrix)
    {
        // Get the size of matrix
        int row = matrix.length;
        int col = matrix[0].length;
        // This loop is iterating rows
        for (int i = 0; i < row; ++i)
        {
            // This loop is iterating cols
            for (int j = 0; j < col; ++j)
            {
                // Display array element
                System.out.print("  " + matrix[i][j]);
            }
            // Include new line
            System.out.print("\n");
        }
        // Include new line
        System.out.print("\n");
    }
    // Count frequencies of negative element
    public void frequencies(int[][] matrix)
    {
        // Get the size of matrix
        int row = matrix.length;
        int col = matrix[0].length;
        // Counter
        int negative = 0;
        // This loop is iterating rows
        for (int i = 0; i < row; ++i)
        {
            // This loop is iterating cols
            for (int j = 0; j < col; ++j)
            {
                if (matrix[i][j] < 0)
                {
                    // When get new negative element
                    negative++;
                }
            }
        }
        // Display result
        System.out.println(" Total Negative : " + negative);
    }
    public static void main(String[] args)
    {
        Test task = new Test();
        // Define matrix 
        int[][] matrix = {
          { 1, 2, -3, -4, 5 }, 
          { 4, 5, 6 , 11 , -12 }, 
          {-7, 8, -9 ,13, 14} 
        };
        task.showData(matrix);
        task.frequencies(matrix);
    }
}

Output

  1  2  -3  -4  5
  4  5  6  11  -12
  -7  8  -9  13  14

 Total Negative : 5
package main
import "fmt"
/*
  Go Program
  Count number of negative elements in matrix
*/
type Test struct {}
func getTest() * Test {
  var me *Test = &Test {}
  return me
}
// Display matrix elements
func(this Test) showData(matrix[][] int) {
  // Get the size of matrix
  var row int = len(matrix)
  var col int = len(matrix[0])
  // This loop is iterating rows
  for i := 0 ; i < row ; i++ {
    // This loop is iterating cols
    for j := 0 ; j < col ; j++ {
      // Display array element
      fmt.Print("  ", matrix[i][j])
    }
    // Include new line
    fmt.Print("\n")
  }
  // Include new line
  fmt.Print("\n")
}
// Count frequencies of negative element
func(this Test) frequencies(matrix[][] int) {
  // Get the size of matrix
  var row int = len(matrix)
  var col int = len(matrix[0])
  // Counter
  var negative int = 0
  // This loop is iterating rows
  for i := 0 ; i < row ; i++ {
    // This loop is iterating cols
    for j := 0 ; j < col ; j++ {
      if matrix[i][j] < 0 {
        // When get new negative element
        negative++
      }
    }
  }
  // Display result
  fmt.Println(" Total Negative : ", negative)
}
func main() {
  var task * Test = getTest()
  // Define matrix 
  var matrix = [][] int {
    { 1, 2, -3, -4, 5 }, 
      { 4, 5, 6 , 11 , -12 }, 
      {-7, 8, -9 ,13, 14}, 
  }
  task.showData(matrix)
  task.frequencies(matrix)
}

Output

  1  2  -3  -4  5
  4  5  6  11  -12
  -7  8  -9  13  14

 Total Negative : 5
// Include header file
#include <iostream>
#include <vector>
using namespace std;
/*
  C++ Program
  Count number of negative elements in matrix
*/
class Test
{
  public:
    // Display matrix elements
    void showData(vector<vector<int>> matrix)
    {
      // Get the size of matrix
            int row = matrix.size();
            int col = matrix[0].size();
      // This loop is iterating rows
      for (int i = 0; i < row; ++i)
      {
        // This loop is iterating cols
        for (int j = 0; j < col; ++j)
        {
          // Display array element
          cout << "  " << matrix[i][j];
        }
        // Include new line
        cout << "\n";
      }
      // Include new line
      cout << "\n";
    }
  // Count frequencies of negative element
  void frequencies(vector<vector<int>> matrix)
  {
    // Get the size of matrix
        int row = matrix.size();
        int col = matrix[0].size();
    // Counter
    int negative = 0;
    // This loop is iterating rows
    for (int i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (int j = 0; j < col; ++j)
      {
        if (matrix[i][j] < 0)
        {
          // When get new negative element
          negative++;
        }
      }
    }
    // Display result
    cout << " Total Negative : " << negative << endl;
  }
};
int main()
{
  Test *task = new Test();
  // Define matrix 
  vector<vector<int>> matrix {
    {
      1 , 2 , -3 , -4 , 5
    } , {
      4 , 5 , 6 , 11 , -12
    } , {
      -7 , 8 , -9 , 13 , 14
    }
  };
  task->showData(matrix);
  task->frequencies(matrix);
  return 0;
}

Output

  1  2  -3  -4  5
  4  5  6  11  -12
  -7  8  -9  13  14

 Total Negative : 5
/*
  C Program 
  Count number of negative elements in matrix
*/
#include <stdio.h>
#define ROW 3
#define COL 5

// Display matrix elements
void show_data(int matrix[][COL])
{
    // This loop is iterating rows
    for (int i = 0; i < ROW; ++i)
    {
        // This loop is iterating cols
        for (int j = 0; j < COL; ++j)
        {
            // Display array element
            printf("%3d", matrix[i][j]);
        }
        // Include new line
        printf("\n");
    }
    // Include new line
    printf("\n");
}
// Count frequencies of negative element
void frequencies(int matrix[ROW][COL])
{
    int negative = 0;
    // This loop is iterating rows
    for (int i = 0; i < ROW; ++i)
    {
        // This loop is iterating cols
        for (int j = 0; j < COL; ++j)
        {
            if (matrix[i][j] < 0)
            {
                // When get new negative element
                negative++;
            }
        }
    }
    // Display result
    printf(" Total Negative : %d\n", negative);
}
int main()
{
    // Matrix of integer elements
    int matrix[ROW][COL] = {
        {
            1 , 2 , -3 , -4 , 5
        },
        {
            4 , 5 , 6 , 11 , -12
        },
        {
            -7 , 8 , -9 , 13 , 14
        }
    };
    show_data(matrix);
    frequencies(matrix);
    return 0;
}

Output

  1  2 -3 -4  5
  4  5  6 11-12
 -7  8 -9 13 14

 Total Negative : 5
// Include namespace system
using System;
/*
  Csharp Program
  Count number of negative elements in matrix
*/
public class Test
{
  // Display matrix elements
  public void showData(int[,] matrix)
  {
    // Get the size of matrix
        int row = matrix.GetLength(0);
        int col = matrix.GetLength(1);
    // This loop is iterating rows
    for (int i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (int j = 0; j < col; ++j)
      {
        // Display array element
        Console.Write("  " + matrix[i,j]);
      }
      // Include new line
      Console.Write("\n");
    }
    // Include new line
    Console.Write("\n");
  }
  // Count frequencies of negative element
  public void frequencies(int[,] matrix)
  {
    // Get the size of matrix
        int row = matrix.GetLength(0);
        int col = matrix.GetLength(1);
    // Counter
    int negative = 0;
    // This loop is iterating rows
    for (int i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (int j = 0; j < col; ++j)
      {
        if (matrix[i,j] < 0)
        {
          // When get new negative element
          negative++;
        }
      }
    }
    // Display result
    Console.WriteLine(" Total Negative : " + negative);
  }
  public static void Main(String[] args)
  {
    Test task = new Test();
    // Define matrix 
    int[,] matrix = {
      {
        1 , 2 , -3 , -4 , 5
      },
      {
        4 , 5 , 6 , 11 , -12
      },
      {
        -7 , 8 , -9 , 13 , 14
      }
    };
    task.showData(matrix);
    task.frequencies(matrix);
  }
}

Output

  1  2  -3  -4  5
  4  5  6  11  -12
  -7  8  -9  13  14

 Total Negative : 5
<?php
/*
  Php Program
  Count number of negative elements in matrix
*/
class Test
{
  // Display matrix elements
  public  function showData($matrix)
  {
    // Get the size of matrix
    $row = count($matrix);
    $col = count($matrix[0]);
    // This loop is iterating rows
    for ($i = 0; $i < $row; ++$i)
    {
      // This loop is iterating cols
      for ($j = 0; $j < $col; ++$j)
      {
        // Display array element
        echo("  ".$matrix[$i][$j]);
      }
      // Include new line
      echo("\n");
    }
    // Include new line
    echo("\n");
  }
  // Count frequencies of negative element
  public  function frequencies($matrix)
  {
    // Get the size of matrix
    $row = count($matrix);
    $col = count($matrix[0]);
    // Counter
    $negative = 0;
    // This loop is iterating rows
    for ($i = 0; $i < $row; ++$i)
    {
      // This loop is iterating cols
      for ($j = 0; $j < $col; ++$j)
      {
        if ($matrix[$i][$j] < 0)
        {
          // When get new negative element
          $negative++;
        }
      }
    }
    // Display result
    echo(" Total Negative : ".$negative."\n");
  }
}

function main()
{
  $task = new Test();
  // Define matrix 
  $matrix = array(
      array(1, 2, -3, -4, 5), 
      array(4, 5, 6, 11, -12), 
      array(-7, 8, -9, 13, 14)
    );
  $task->showData($matrix);
  $task->frequencies($matrix);
}
main();

Output

  1  2  -3  -4  5
  4  5  6  11  -12
  -7  8  -9  13  14

 Total Negative : 5
/*
  Node JS Program
  Count number of negative elements in matrix
*/
class Test
{
  // Display matrix elements
  showData(matrix)
  {
    // Get the size of matrix
    var row = matrix.length;
    var col = matrix[0].length;
    // This loop is iterating rows
    for (var i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (var j = 0; j < col; ++j)
      {
        // Display array element
        process.stdout.write("  " + matrix[i][j]);
      }
      // Include new line
      process.stdout.write("\n");
    }
    // Include new line
    process.stdout.write("\n");
  }
  // Count frequencies of negative element
  frequencies(matrix)
  {
    // Get the size of matrix
    var row = matrix.length;
    var col = matrix[0].length;
    // Counter
    var negative = 0;
    // This loop is iterating rows
    for (var i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (var j = 0; j < col; ++j)
      {
        if (matrix[i][j] < 0)
        {
          // When get new negative element
          negative++;
        }
      }
    }
    // Display result
    console.log(" Total Negative : " + negative);
  }
}

function main()
{
  var task = new Test();
  // Define matrix 
  var matrix = [
    [1, 2, -3, -4, 5],
    [4, 5, 6, 11, -12],
    [-7, 8, -9, 13, 14]
  ];
  task.showData(matrix);
  task.frequencies(matrix);
}
main();

Output

  1  2  -3  -4  5
  4  5  6  11  -12
  -7  8  -9  13  14

 Total Negative : 5
#  Python 3 Program
#  Count number of negative elements in matrix
class Test :
  #  Display matrix elements
  def showData(self, matrix) :
    #  Get the size of matrix
    row = len(matrix)
    col = len(matrix[0])
    i = 0
    #  This loop is iterating rows
    while (i < row) :
      j = 0
      #  This loop is iterating cols
      while (j < col) :
        #  Display list element
        print("  ", matrix[i][j], end = "")
        j += 1
      
      #  Include new line
      print(end = "\n")
      i += 1
    
    #  Include new line
    print(end = "\n")
  
  #  Count frequencies of negative element
  def frequencies(self, matrix) :
    #  Get the size of matrix
    row = len(matrix)
    col = len(matrix[0])
    #  Counter
    negative = 0
    i = 0
    #  This loop is iterating rows
    while (i < row) :
      j = 0
      #  This loop is iterating cols
      while (j < col) :
        if (matrix[i][j] < 0) :
          #  When get new negative element
          negative += 1
        
        j += 1
      
      i += 1
    
    #  Display result
    print(" Total Negative : ", negative)
  

def main() :
  task = Test()
  #  Define matrix 
  matrix = [
    [1, 2, -3, -4, 5],
    [4, 5, 6, 11, -12],
    [-7, 8, -9, 13, 14]
  ]
  task.showData(matrix)
  task.frequencies(matrix)

if __name__ == "__main__": main()

Output

   1   2   -3   -4   5
   4   5   6   11   -12
   -7   8   -9   13   14

 Total Negative :  5
#  Ruby Program
#  Count number of negative elements in matrix
class Test 
  #  Display matrix elements
  def showData(matrix) 
    #  Get the size of matrix
    row = matrix.length
    col = matrix[0].length
    i = 0
    #  This loop is iterating rows
    while (i < row) 
      j = 0
      #  This loop is iterating cols
      while (j < col) 
        #  Display array element
        print("  ", matrix[i][j])
        j += 1
      end

      #  Include new line
      print("\n")
      i += 1
    end

    #  Include new line
    print("\n")
  end

  #  Count frequencies of negative element
  def frequencies(matrix) 
    #  Get the size of matrix
    row = matrix.length
    col = matrix[0].length
    #  Counter
    negative = 0
    i = 0
    #  This loop is iterating rows
    while (i < row) 
      j = 0
      #  This loop is iterating cols
      while (j < col) 
        if (matrix[i][j] < 0) 
          #  When get new negative element
          negative += 1
        end

        j += 1
      end

      i += 1
    end

    #  Display result
    print(" Total Negative : ", negative, "\n")
  end

end

def main() 
  task = Test.new()
  #  Define matrix 
  matrix = [
    [1, 2, -3, -4, 5],
    [4, 5, 6, 11, -12],
    [-7, 8, -9, 13, 14]
  ]
  task.showData(matrix)
  task.frequencies(matrix)
end

main()

Output

  1  2  -3  -4  5
  4  5  6  11  -12
  -7  8  -9  13  14

 Total Negative : 5
/*
  Scala Program
  Count number of negative elements in matrix
*/
class Test()
{
  // Display matrix elements
  def showData(matrix: Array[Array[Int]]): Unit = {
    // Get the size of matrix
    var row: Int = matrix.length;
    var col: Int = matrix(0).length;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        // Display array element
        print("  " + matrix(i)(j));
        j += 1;
      }
      // Include new line
      print("\n");
      i += 1;
    }
    // Include new line
    print("\n");
  }
  // Count frequencies of negative element
  def frequencies(matrix: Array[Array[Int]]): Unit = {
    // Get the size of matrix
    var row: Int = matrix.length;
    var col: Int = matrix(0).length;
    // Counter
    var negative: Int = 0;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        if (matrix(i)(j) < 0)
        {
          // When get new negative element
          negative += 1;
        }
        j += 1;
      }
      i += 1;
    }
    // Display result
    println(" Total Negative : " + negative);
  }
}
object Main
{
  def main(args: Array[String]): Unit = {
    var task: Test = new Test();
    // Define matrix 
    var matrix: Array[Array[Int]] = Array(
          Array(1, 2, -3, -4, 5), 
          Array(4, 5, 6, 11, -12), 
          Array(-7, 8, -9, 13, 14)
        );
    task.showData(matrix);
    task.frequencies(matrix);
  }
}

Output

  1  2  -3  -4  5
  4  5  6  11  -12
  -7  8  -9  13  14

 Total Negative : 5
import Foundation;
/*
  Swift 4 Program
  Count number of negative elements in matrix
*/
class Test
{
  // Display matrix elements
  func showData(_ matrix: [[Int]])
  {
    // Get the size of matrix
    let row: Int = matrix.count;
    let col: Int = matrix[0].count;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        // Display array element
        print("  ", matrix[i][j], terminator: "");
        j += 1;
      }
      // Include new line
      print(terminator: "\n");
      i += 1;
    }
    // Include new line
    print(terminator: "\n");
  }
  // Count frequencies of negative element
  func frequencies(_ matrix: [
    [Int]
  ])
  {
    // Get the size of matrix
    let row: Int = matrix.count;
    let col: Int = matrix[0].count;
    // Counter
    var negative: Int = 0;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        if (matrix[i][j] < 0)
        {
          // When get new negative element
          negative += 1;
        }
        j += 1;
      }
      i += 1;
    }
    // Display result
    print(" Total Negative : ", negative);
  }
}
func main()
{
  let task: Test = Test();
  // Define matrix 
  let matrix: [[Int]] = [
    [1, 2, -3, -4, 5],
    [4, 5, 6, 11, -12],
    [-7, 8, -9, 13, 14]
  ];
  task.showData(matrix);
  task.frequencies(matrix);
}
main();

Output

   1   2   -3   -4   5
   4   5   6   11   -12
   -7   8   -9   13   14

 Total Negative :  5
/*
  Kotlin Program
  Count number of negative elements in matrix
*/
class Test
{
  // Display matrix elements
  fun showData(matrix: Array < Array < Int >> ): Unit
  {
    // Get the size of matrix
    val row: Int = matrix.count();
    val col: Int = matrix[0].count();
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        // Display array element
        print("  " + matrix[i][j]);
        j += 1;
      }
      // Include new line
      print("\n");
      i += 1;
    }
    // Include new line
    print("\n");
  }
  // Count frequencies of negative element
  fun frequencies(matrix: Array < Array < Int >> ): Unit
  {
    // Get the size of matrix
    val row: Int = matrix.count();
    val col: Int = matrix[0].count();
    // Counter
    var negative: Int = 0;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        if (matrix[i][j] < 0)
        {
          // When get new negative element
          negative += 1;
        }
        j += 1;
      }
      i += 1;
    }
    // Display result
    println(" Total Negative : " + negative);
  }
}
fun main(args: Array < String > ): Unit
{
  val task: Test = Test();
  // Define matrix 
  val matrix: Array < Array < Int >> = arrayOf(
      arrayOf(1, 2, -3, -4, 5), 
      arrayOf(4, 5, 6, 11, -12), 
      arrayOf(-7, 8, -9, 13, 14)
    );
  task.showData(matrix);
  task.frequencies(matrix);
}

Output

  1  2  -3  -4  5
  4  5  6  11  -12
  -7  8  -9  13  14

 Total Negative : 5

Output Explanation

The given matrix is displayed, and the output indicates the count of negative elements in the matrix. In this case, there are 5 negative elements, as indicated by the output.

Time Complexity

The time complexity of this algorithm is O(rows * cols), where rows is the number of rows in the matrix and cols is the number of columns in the matrix. This is because we iterate through each element of each row once in a nested loop structure.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment