Shifting array to the right – homework

You can do something like:

 public static void shiftRight( char [] letters )
    {

        char last = letters[letters.length-1];          // save off first element

        // shift right
        for( int index =letters.length-2; index >= 0 ; index-- )
            letters[index+1] = letters [index];

        // wrap last element into first slot
        letters[0] = last;
        System.out.print("\nshifted Array: " + Arrays.toString(letters) );

    }

I only modified your: letters.length-1 into letters.length-2 and printed the array.

Another, easier approach is to use, System.arraycopy like:

last = letters[letters.length-1];
System.arraycopy(letters, 0, letters, 1, letters.length-1 );
letters[0] = last;

To print the array you can also use:

System.out.print("{");
for (int i=0;i<letters.length-1;i++)
    System.out.print("'"+letters[i]+",");
System.out.println("'"+letters[letters.length-1]+"'}");

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)