printf("Enter position : ");
scanf("%d", &pos);
printf("Enter element : ");
scanf("%d", &element);
for ( i = 4; i >= (pos-1); i--)
{
a[i+1]=a[i]; // why is this loop only working one time when pos=3
}
this is the portion of my code where i am trying to insert an element into an array of size 5 with 4 elements by starting to shift elements to the next indexes but i am shifting from the fifth element itself that is 0(or garbage value) . i know this is not the correct way to achieve insertion but my question is why this line of code is not working
a[i+1]=a[i];
also the loop doesn't seem to work 3 times but instead 1 time .( which is my main question )
my original code :
#include<stdio.h>
int main(){
int a[5],i, pos , element;
printf("Enter elements : ");
for ( i = 0; i < 4; i++)
{
scanf("%d",&a[i]);
}
printf("Enter position : ");
scanf("%d", &pos);
printf("Enter element : ");
scanf("%d", &element);
for ( i = 4; i >= (pos-1); i--)
{
a[i+1]=a[i];
}
a[pos-1]=element;
for ( i = 0; i < 5; i++)
{
printf("%d ",a[i]);
}
return 0;
}