Here is my homework:
Write a program which does the following: It returns an integer array arr2 of length n whose first k elements are the same as the first k elements of arr, and whose remaining elements consist of repeating blocks of the first k elements. You can assume array arr has at least k elements. The function should return null if either k or n is not positive.
Examples:
fill({1,2,3,5, 9, 12,2, 1}, 3, 10) returns {1,2,3,1,2,3,1,2,3,1}. fill({4, 2, 3, 12}, 1, 5) returns {4, 4, 4, 4, 4}. fill({2, 6, 9, 0, 3}, 0, 4) returns null.
Here is my code:
public static void main (String[] args){
int [] result = fill(new int[]{1, 2, 3, 5, 9, 12, 2, 1}, 3, 10);
System.out.println(result);
}
public static int[] fill(int[] arr, int k, int n){
int[] arr2 = new int[n];
int cnt = 0;
if (k > 0 && n > 0)
{
while (cnt != n)
{
for (int j = 0; j < k; j++)
{
if (cnt != n)
{
arr2[cnt] = arr[j];
cnt++;
}
else
break;
}
}
}
else
return null;
return arr2;
}