Multiplication in Java with recursion -
i sorry, not sure if title correct, if not correct once tells me called. can understand new programming...
i want accomplish following: have cycle:
for(int i=0; < this.matrix.length; i++)
i have matrix example this:
1, 2, 2 2, 2, 3 0, 1, 2
i want multiply diagonal elements 1*2*2 know how elements each step of cycle, how can used temp variable, every step multiplied new element? or not possible?
for example make variable:
double temp;
and each cycle step want new value multiply old, keeping value, not sure if explaining well. if use matrix want this:
temp = 1;
next step it
temp = 2;
next step
temp = 4;
i tried doing myself in end wrong results, understand doing multiplication wrong, because when changed 2 2 element of matrix 3 instead of 2 end result 9 instead of 6. sorry if badly explained...
- in question requesting main left-to-right diagonal output, i'm assuming goal.
- also, not specifying if matrix square or not; assume yes.
- lastly, not specifying how matrix stored in variable. i'm assuming talking bidimensional array.
here go:
public static void main (string[] args) throws exception { int[][] matrix = new int[3][]; matrix[0] = new int[] {1, 2, 2}; matrix[1] = new int[] {2, 2, 3}; matrix[2] = new int[] {0, 1, 2}; int result = 1; (int i=0; i<matrix.length; i++) { result *= matrix[i][i]; } system.out.println(result); }
edit: if want include right-to-left:
public static void main (string[] args) throws exception { int[][] matrix = new int[3][]; matrix[0] = new int[] {1, 2, 2}; matrix[1] = new int[] {2, 2, 3}; matrix[2] = new int[] {0, 1, 2}; int resultl2r = 1; int resultr2l = 1; (int i=0; i<matrix.length; i++) { resultl2r *= matrix[i][i]; resultr2l *= matrix[i][matrix.length-1-i]; } system.out.println("left-to-right: " + resultl2r); system.out.println("right-to-left: " + resultr2l); }
Comments
Post a Comment