1

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;
Aryan poonacha
  • 451
  • 2
  • 4
  • 15
  • 1
    *"the sixth and seventh positions are 0*" What are you *expecting* them to be? Show your input, output, and *expected* output, and highlight the difference for us. – T.J. Crowder Jul 10 '16 at 13:03

2 Answers2

5

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);
    }
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
Eran
  • 387,369
  • 54
  • 702
  • 768
0

You are moving the values in the wrong way. Use this code and understand your mistake:

for(int i=6;i>=3;i--)    //Moving the 4th to 6th elements to 5th to 7th elements
    {
        A[i]=A[i-1];
    }
String a=Biff.readLine();    //Taking input for 4th empty position
A[3]=Integer.parseInt(a);

I hope I got your question right.

VatsalSura
  • 926
  • 1
  • 11
  • 27