I have an array of elements. int[] elem = new int[] {A, B, C, D, E}; I need to calculate ALL the combinations of those elements result = {0,1}*A + {0,1}*B + {0,1}*C + {1}*D + {0,1}*E {0,1} mean element can be selected or not {1} mean element is always selected. I could do something like for (int i=0;i<2;i++) for (int j=0;j<2;j++) for (int k=0;k<2;k++) for (int l=1;l<2;l++) for (int m=0;m<2;m++) result i*A + j*B + k*C + l*D + m*E But the problem the length of elem array is variable. So how should I iterate to get all values?