Write a program that does the following in Java Declare a 2

Write a program that does the following in Java:

Declare a 2 dimensional ragged array of ints.   

There is no user input. You can just copy/paste these lines:

int[][] table1 = {

       { 13, 12, 53, 19},

       {1, 9, 6, 25,18,17},

       {7, 28 4}

};

int[][] table2 = {

            { 13, 13, -85},

{11, 19},

{31, -89, 47, 26, +895 }

};

Write a method called count odds. The signature of the method will be like this:

public static int countOdds(int[][] table)

This method will return the number of elements in the array that are odd numbers. Note that the arrays might be rectangular or ragged.

You might call the method from the main method like this:

int odds;

odds = countOdds(table1);

System.out.println(“There are “ + odds +“ odd numbers in table 1.”);

The answer should be 8.

Demonstrate that it works with table2, and another table that you create.

Solution


// Count.java

import java.util.*;
public class Count
{
   public static int countOdds(int[][] table)
   {
       int count = 0;
       for (int i = 0; i< table.length ;i++ )
       {
           for (int j = 0; j < table[i].length ; j++ )
           {
               if(table[i][j]%2 != 0)
                   count++;
           }  
       }

       return count;
   }
    public static void main(String[] args)
    {
      
        int[][] table1 = {{ 13, 12, 53, 19},{1, 9, 6, 25,18,17},{7, 28, 4}};
       int[][] table2 = {{ 13, 13, -85},{11, 19},{31, -89, 47, 26, 895 }};

        int odds = countOdds(table1);
       System.out.println(\"There are \"+ odds +\" odd numbers in table 1.\");

       odds = countOdds(table2);
       System.out.println(\"There are \"+ odds +\" odd numbers in table 2.\");
    }
  
}

/*
output:

There are 8 odd numbers in table 1.
There are 9 odd numbers in table 2.

*/

Write a program that does the following in Java: Declare a 2 dimensional ragged array of ints. There is no user input. You can just copy/paste these lines: int[
Write a program that does the following in Java: Declare a 2 dimensional ragged array of ints. There is no user input. You can just copy/paste these lines: int[

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site