Home > front end >  Coding a loop inside of an Array in pseudocode
Coding a loop inside of an Array in pseudocode

Time:10-07

I'm new to computer science. I've been told there is only 1 bug in the following Java type pseudo-code but i'm unable to figure it out. Isn't there more then 1? First the if statement means it won't loop as size doesn't equal max size, but i think the loop is also incorrect as rather then i<=size shouldn't it be i<=maxsize?

private int size = 0;
private int maxsize = 16;
private int[] arr = new int[maxsize];

public void append(val, list)
{
    if (size == maxsize)
    {
        int[] newArr = new int[maxsize * 2];
        for (i = 0; i <= size ; i  )
            newArr[i] = arr[i];
        arr = newArr;
        maxsize = maxsize*2;
    }
    arr[size  ] = val;
}

Out of these options, which one is correct?

  • Line 1 should read: private int size = 16;
  • Line 7 should read: if (size > maxsize)
  • Line 10 should read: for (i = 0 ; i <= maxsize ; i )
  • Line 13 should come before line 10
  • Line 15 should read: arr[ size] = val;

CodePudding user response:

There is certainly more than one bug/issue in this code. Here are some I found

  • The for loop uses the variable i without declaring it
  • size = 0 so the code inside the for loop never actually runs
  • newArr has all of its elements set equal to the elements in arr, and then you go and assign arr to newArr! This means that the newArr variable will point to the same array as the arr variable, meaning they are no longer duplicates but rather the exact same piece of data
  • Your function takes in list but doesn't use it. This is clearly an issue if the function's intention was to append the val to list
  • Your function and maxsize constant should be static unless these are fields inside of an object and intend to be used as such

I've gone ahead and fixed your code: (Try it here)

public static void main(String args[]) {
    int[] myInts = new int[]{1, 2, 4};
    for(int i = 0; i < myInts.length; i  ){
        System.out.print(myInts[i]  " ");
    }
    System.out.println();
    myInts = append(5, myInts);
    for(int i = 0; i < myInts.length; i  ){
        System.out.print(myInts[i]  " ");
    }
}
private static int maxsize = 16;
public static int[] append(int val, int[] list){
    int size = list.length;
    if(size < maxsize){
        int[] newArr = new int[size 1];
        for (int i = 0; i < size ; i  ){
            newArr[i] = list[i];
        }
        newArr[size] = val;
        return newArr;
    }
    return list;
}

CodePudding user response:

There’s just an off-by-one error. The code is trying to copy size 1 elements from the old array into the new, but the old array only has size elements.

  • Related