I try to do this problem with while and arrays but I can't get it to paint from 1 to 100 only with the even numbers.
ISSUE
public static void main(String[] args) {
int matriz1[][] = new int[5][5];
int i = 0;
int j = 0;
while (i < matriz1.length) {
matriz1[i][j]= i*matriz1.length;
System.out.print(matriz1[i][j]+" ");
while (j < matriz1[i].length) {
matriz1[i][j] = j+1;
System.out.print(matriz1[i][j]+" ");
}
j++;
}
i++;
System.out.println();
}
ATTEMPT TO RESULT TO THE PROBLEM
The increment you use only to compensate for the fact that arrays start with index 0. What you are missing is a multiplication by 2 to use only even numbers.
Result:
For examples of how to declare arrays, see here .
added as per comment
for odd ones you only have to change the calculation of the second dimension:
with a ternary, you could declare a boolean before and then differentiate in the same code:
Seeing that it is a sequence of numbers (2,4,6,8,...100), we need a variable
k
so that it increases in each iteration in both cycles.I leave you your own code, resolved and commented.
I would recommend that you use
for
when you already know when it will finish, in your case it is known from the beginning that iti
should iterate 10 times and itj
should iterate 5 times, and on the contrary, when you do not know when it will finish, you should use itwhile
check my answer to this topic , for vs while - LOOP solving with for:Hi, I'll give you a solution to generate arrays of pairs with the generalized array size.
I have divided the functionality into 2 methods so that it is well defined what each part of the code does.
If you want to put everything in the main it would be something like this