I am struggling with the problem of having applications of loops and arrays.
I have a variable “n” which represents the limit of the loop, i.e.
if n = 3, the array would look like:
arr[1,2,3,1,2,3,1,2,3];
or if n = 4, it would look like:
arr[1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4];
here’s my code so far, someone please let me know the mistake I have made in implementing the above problem…
JavaScript
x
public static void main(String[] args) {
countingUp(3);
}
public static void countingUp(int n) {
int[] arr = new int[n * n];
int k = n;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
arr[i] = n ;
}
}
System.out.println(Arrays.toString(arr));
}
Advertisement
Answer
This is the major mistake you have done…
arr[i] = n ;
You should update value after each interval of length n which can be controlled by the loop running with i and the value inside each interval could be controlled with the loop j. See that one change I have made in the code below…
JavaScript
public static void main(String[] args) {
countingUp(3);
}
public static void countingUp(int n) {
int[] arr = new int[n * n];
int k = n;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
arr[i*n+j] = j+1 ;
}
}
System.out.println(Arrays.toString(arr));
}