# 如何递归计数直到小于 n。

go评论61阅读模式

How do I recursively count up to less than n

# 问题

arr[1,2,3,1,2,3,1,2,3];

arr[1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4];

``````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));
}
``````

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...

``````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 &lt; n; i++) {
for(int j = 0; j &lt; n; j++) {
arr[i] = n ;
}
}

System.out.println(Arrays.toString(arr));
}
``````

# 答案1

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...

>arr[i] = n;

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));
``````

}

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...

``````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 &lt; n; i++) {
for(int j = 0; j &lt; n; j++) {
arr[i*n+j] = j+1 ;
}
}

System.out.println(Arrays.toString(arr));
}
``````

• 本文由 发表于 2020年8月2日 21:18:13
• 转载请务必保留本文链接：https://go.coder-hub.com/63216458.html
• algorithm
• arrays
• implementation
• java
• loops

go 50

go 45

go 46

go 82