1. Shift array elements

Hello guys, I'm a newbie, and I've started to learn C language about 3 months ago. It's going ok, I'm not super content with my progress, but ok. Anyways, I'm learning from a book Let us C by Yashavant Kanetkar, and I came across a problem where I need a better solution.

***Given an array p, write a function to shift it circularly left by two positions. Thus, if p = 15, p= 30, p = 28, p= 19 and p = 61 then after the shift p = 28, p = 19, p = 61, p = 15 and p = 30. Call this function for a (4 x 5 ) matrix and get its rows left shifted.***

My code looks like this. Obviously I haven't done the whole task, only shifted the elements of an array (in the main function). It does its job, but I don't like the code. Nothing comes on my mind when it comes to shifting the first and the second element to an array. Any comment would be helpful! Thank you in advance.

Capture — ImgBB 2. Code should be copy/pasted between [code][/code] tags.
Fuzzy pictures on temporary external sites don't allow us to test your code, or for people in the future to even see your code. 3. Sorry, here is the code Code:

#include <stdio.h>
int main ()
{
int p={15,30,28,19,61};
int *a;
a=p;

int i,fir,sec,temp;

printf ("Before shift: ");
for (i=0;i<5;i++)
{
printf ("%d ",*(a+i));
}

printf ("\n");
printf ("After shift:");
fir=a;
sec=a;
for (i=0;i<3;i++)
{
temp=a[i];
a[i]=a[i+2];
a[i+2]=temp;
}

*(a+3)=fir;
*(a+4)=sec;

for (i=0;i<5;i++)
printf ("%d ",a[i]);

return 0;
} 4. Maybe you might want to add a couple of functions, making you 'main()' function look something like this:

Code:
int main ()
{
int p={15,30,28,19,61};

printArray("Before shift", p, 5);

shiftByTwo(p,5);

printArray("After shift", p, 5);

return 0;
}
Sadly there really isn't a much better way to do the shifting... 5. Thanks for the reply. I've added a function, and now the code looks decent, at least. 6. Code:
static void arrayShiftLeft( int *arr, size_t nelems )
{
if ( nelems )
{
int tmp = *arr;
memmove( arr, arr+1, (nelems - 1)*sizeof *arr );
arr[nelems - 1] = tmp;
}
}

void arrayShiftElementsLeft( int *arr, size_t nelems, unsigned int n )
{
if ( nelems ) // to avoid unecessary calls
while ( n-- )
arrayShiftLeft( arr, nelems );
} Popular pages Recent additions array, function, left, p, shift 