-1

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 < n; i++) {
        for(int j = 0; j < n; j++) {
            arr[i] = n ;
        }
    }
    
    System.out.println(Arrays.toString(arr));
}
Yash Shah
  • 1,634
  • 1
  • 5
  • 16
Sylas Coker
  • 25
  • 1
  • 7
  • 2
    "*here's my code so far, someone please let me know what the variable "j" does specifically*" - It is your code, why don't you tell us? – Turing85 Aug 02 '20 at 13:21
  • I'm guessing when i =0, j will count up from 0 to n and stop once it's been fulfilled, then when i = 1, j will count up from 0 to n again, if i'm correct? – Sylas Coker Aug 02 '20 at 13:25
  • why not [debug](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) your application and find out? – Turing85 Aug 02 '20 at 13:28
  • You're almost there :) Your array has n*n items which is correct. You have a double loop which executes n*n times, also correct. Look at arr[i] = n. Maybe use a debugger or print i and j. But let's keep the suspense for you :) – aeberhart Aug 02 '20 at 13:29
  • I have and i'm currently doing that on eclipse but it prints out "2" in just the index of 0. – Sylas Coker Aug 02 '20 at 13:30
  • @aeberthart Thanks thought i may have done something wrong beforehand, hopefully there isn't suspense for too long :) – Sylas Coker Aug 02 '20 at 13:31

1 Answers1

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

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));
}
Yash Shah
  • 1,634
  • 1
  • 5
  • 16
  • 2
    Thank you, it's worked out fine, i can't wrap my head around j properly but i'm starting to see why it wokrs when i'm writing it down on paper, thank you. – Sylas Coker Aug 02 '20 at 13:38