Java > Array-2 > fizzArray (CodingBat Solution)

Problem:

Given a number n, create and return a new int array of length n, containing the numbers 0, 1, 2, ... n-1. The given n may be 0, in which case just return a length 0 array. You do not need a separate if-statement for the length-0 case; the for-loop should naturally execute 0 times in that case, so it just works. The syntax to make a new int array is: new int[desired_length] (See also: FizzBuzz Code)

fizzArray(4) → {0, 1, 2, 3}
fizzArray(1) → {0}
fizzArray(10) → {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}


Solution:

public int[] fizzArray(int n) {
    int[] result = new int[n];
    for (int i = 0; i < n; i++)
        result[i] = i;
    return result;
}

5 comments:

  1. public int[] fizzArray(int n) {
    int[] result = new int[n];
    for(int i = 0; i < n; i++)
    {
    result[i] = i;
    }
    return result;
    }

    ReplyDelete
    Replies
    1. public int[] fizzArray(int n) {
      int[] new_int_array = new int[n];

      int c=0;

      for(int i=0; i < n; i++){
      new_int_array[i] = c;
      c++;
      }

      return new_int_array;
      }

      Delete
  2. public int[] fizzArray(int n) {
    int num=0;
    int newarr[]=new int[n];
    for(int i=0;i<n;i++)
    newarr[i]=num++;
    return newarr;
    }

    ReplyDelete
  3. public int[] fizzArray(int n)
    {
    int[] newArray = new int[n];

    for(int i = 0; i < n; i++)
    {
    newArray[i] = i;
    }

    return newArray;
    }

    ReplyDelete
  4. With Java Stream

    public static int[] fizzArray(int n) {
    int[] arr = IntStream.range(0, n).toArray();
    return arr;
    }

    ReplyDelete