Sunday, September 28, 2014

Elements before 4 in an int array

Ques:Given a non-empty array of ints, return a new array containing the elements from the original array that come before the first 4 in the original array.

Ans:
 public static int[] pre4(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
                  if (nums[i] == 4) {
                break;
            }
            count++;
        }
        int[] tempArray=new int[count];
        for(int j=0;j<count;j++){
            tempArray[j]=nums[j];
              }
     return tempArray;
    }

No comments:

Post a Comment