2D array even odd java -
2D array even odd java -
i have segregate , odd numbers in 2d array in java in 2 different rows (even in row 1 , odd in row two). have included output of code bellow here have:
class twodimensionarrays { public static void main(string[] args) { int sum = 0; int row = 2; int column = 10; int[][] iarrays = new int[row][column]; for(int rowcount = 0; rowcount < iarrays.length /*&& rowcount % 2 == 0*/; rowcount++) { for(int columncount = 0; columncount < iarrays[0].length /*&& columncount % 2 != 0*/; columncount++) { if(columncount % 2 != 0 /*&& rowcount % 2 == 0*/) { iarrays[rowcount][columncount] = columncount + 1; } } } system.out.println("the array has " + iarrays.length + " rows"); system.out.println("the array has " + iarrays[0].length + " columns"); for(int rowcount = 0; rowcount < iarrays.length; rowcount++) { for(int columncount = 0; columncount < iarrays[0].length; columncount++) { system.out.print(iarrays[rowcount][columncount] + " "); sum += iarrays[rowcount][columncount]; } system.out.println(); } system.out.println("the sum is: " +sum); } } //output// /*the array has 2 rows array has 10 columns 0 2 0 4 0 6 0 8 0 10 0 2 0 4 0 6 0 8 0 10 sum is: 60*/ can lend hand?
thank in advance.
instead of passing on list twice seek this:
for(int v = 0; v < 20; v++) { iarrays[v % 2][(int)v/2] = v; } this set iarrays to:
[[0,2,4,6,8,10,12,14,16,18], [1,3,5,7,9,11,13,15,17,19]] what happening row beingness set remainder of v % 2 (0 if v even, 1 if v odd) , col beingness set corresponding index (with cast int drop fraction). can generalize this:
public static int[][] group(int groups, int size){ int[][] output = new int[groups][size]; for(int value = 0; value < (groups*size); value++) { output[value % groups][(int)value/groups] = value; } homecoming output; } then phone call group(2, 10) return:
[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]] java arrays multidimensional-array
Comments
Post a Comment