Search code examples
javaarraysinsertion

Simple Array Insertion Program Producing Incorrect Output


Here's an extremely simple java program where I declare any array with 7 elements, input the first six, move the fourth to sixth elements to the fifth to seventh positions, and obtain a value for the fourth empty position:

int A[]=new int[7];
        for(int i=0;i<6;i++)
        {
            System.out.println("Enter an integer");
            String a=Biff.readLine();
            A[i]=Integer.parseInt(a);
        }
        for(int i=4;i<6;i++)
        {
            A[i]=A[i+1];
        }
        System.out.println("Enter the integer to be inserted");
        String a=Biff.readLine();
        A[4]=Integer.parseInt(a);

However, when all array elements are printed, the sixth and seventh positions are 0, and I have no idea why. Reasons and fixes will be greatly appreciated. Note: I can't use any array methods, have to keep it very simple.

  • Input: 1,2,3,4,5,6; Then 1;
  • Desired Output: 1,2,3,4,5,1,6;
  • Actual Output: 1,2,3,4,1,0,0;

Solution

  • Your initial loop is not assigning anything to the 7th element, so it remains 0.

    And later you copy the 7th element to the 6th one

     A[i]=A[i+1];
    

    so both the 6th and 7th elements should be 0.

    Change the loop to :

        for(int i=0;i<A.length;i++)
        { //         ^^^^^^^^^------------------------ change is here
            System.out.println("Enter an integer");
            String a=Biff.readLine();
            A[i]=Integer.parseInt(a);
        }