I currently have an array where the user inputs the number of rows and columns, then the system outputs it and sums all elements. I know how to sum all elements in the array, but don't understand how to specifically sum elements only in ODD columns. Since the column indexes start with 0, it would have to start with the second column, skip one and sum all elements in the one after that and so on.
This code outputs the array and sums all elements. I think I have to add another loop before the "sum" ones, but don't know how. Thanks in advance.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row, col, sum;
row = sc.nextInt();
col = sc.nextInt();
sum = 0;
int [][] a = new int [row] [col];
for (int i=0; i<a.length; i ) {
for (int j=0; j<a[i].length; j ) {
a[i][j] = i j 1;
}
}
for (int[] rows : a) {
for (int item : rows) {
System.out.print(item " ");
}
System.out.println();
}
for (int[] arr : a) {
for(int i: arr) {
sum =i;
}
}
System.out.print("sum=" sum);
sc.close();
}
}
CodePudding user response:
Simply iterate over every other column in the array, and add up every element in that column:
int sum = 0;
for (int i = 1; i < arr.length; i = 2)
for (int j = 0; j < arr[i].length; j )
sum = arr[i][j];
live example here.
CodePudding user response:
You can add a counter to your foreach each loop, when the counter is even, skip to the next iteration, when it is odd, do the summation operations.
int counter =0;
for (int[] arr : a) {
if (counter %2 == 0){
counter =1;
continue;
}
else{
for(int i: arr) {
counter =1;
sum =i;
}
}
}