basil roy basil roy - 5 months ago 26
Java Question

create 2d array then using user input print the total number of odd no. and the sum of the odd numbers in that array

This what I have done so far. I can't get to print the total number of odd numbers in the array and the sum of that odd numbers.

import java.util.Scanner;

public class arrayssumofodd
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);

int rows=scan.nextInt();
int columns=scan.nextInt();
int array[][]=new int [rows][columns];

int odd=0;
int sum=0;
int num=0;

for(int i=0;i<rows;i++)
{
for(int j=0; j<columns;j++)
{
array[i][j]=scan.nextInt();
num=array[i][j];

}

for(int k=0;k<rows;k++)
{
for(int m=0;m<k;m++)
{
if(num%2!=0)
{
odd++;
sum+=odd;
}
}
}
}
System.out.println("Odd number count "+" = " +odd);
System.out.println("Sum of odd numbers "+" = " +sum);
}
}


I've tried everything to get the odd numbers to print but I haven't been able to. It keeps outputting zero when I run the program.

Answer

Your for loops are mixed with each other.

for(int i=0;i<rows;i++)
{
    for(int j=0; j<columns;j++)
    {
        array[i][j]=scan.nextInt();
        num=array[i][j];
        // you can do operation with odd count and sum here
}

Or you can use the same two for loops to go through the numbers in the 2D array and just count the odd number and find the sum.