0
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;
}
Divyansh
  • 11
  • 3
  • Please [edit] and show a simple example of input along with actual vs expected output. – Jabberwocky Feb 20 '23 at 12:38
  • 1
    did you step through the code in a debugger? – OldProgrammer Feb 20 '23 at 12:39
  • @OldProgrammer no. i don't know how to use it . will learning it help me gain some understanding ? – Divyansh Feb 20 '23 at 13:03
  • _"will learning to use my debugger will help me gain some understanding"_: yes, definitely. – Jabberwocky Feb 20 '23 at 16:37
  • With a debugger, you can run your program one line at a time while monitoring the control flow and the values of all variables. That way, you should be able to see exactly in which line your program stops behaving as intended. I suggest that you read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) – Andreas Wenzel Feb 20 '23 at 20:03

2 Answers2

4

Since a is defined as int a[5], it has elements from a[0] to a[4]. Consider what happens if the compiler puts i where a[5] would be. Then, when i is 4, a[i+1] = a[i] overwrites i, which can change it to a value that stops the loop.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • the loop `scanf("%d",&a[i]);` assigns value to the elements of array from a[0] to a[3], leaving a[4] an undefined value. So, if let **a[4]=5;** before the loop `for ( i = 4; i >= (pos-1); i--)` resulting in an infinite loop, this situation would be confirmed. – user6099871 Feb 20 '23 at 12:55
  • aren't you supposed to leave one element unintialized if u want to insert another – Divyansh Feb 20 '23 at 13:19
  • @Divyansh: Whether an element is initialized or not is irrelevant. The issue is there is no element `a[5]`, you should not assign anything to `a[5]`. Start `i` at 3, not 4. – Eric Postpischil Feb 20 '23 at 13:29
  • ok . i will do that . moreover, any suggestions on resources for learning c deeply ? – Divyansh Feb 20 '23 at 13:40
  • 1
    @Divyansh: [This question](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) lists books for learning C. – Eric Postpischil Feb 20 '23 at 16:12
  • @Divyansh: Stack Overflow is itself a good resource to learn. So you’re already here..but definitely you can refer a book . Link given by Eric – user8811698 Feb 20 '23 at 16:15
0

This for loop

for ( i = 4; i >= (pos-1); i--)
{   
    a[i+1]=a[i];
}

is accessing memory outside the array when i is equal to 4 due to the expression a[i+1] that in this case is equivalent to a[5] while the valid range of indices is [0, 4].

So the code invokes undefined behavior.

Also if you want to add a new value at the position pos then using this condition in the for loop

i >= (pos-1)

instead of at least this condition

i >= pos

does not make sense.

And you should check that the value of the variable pos is in the range of valid indices. For example as the variable pos has the signed integer type int then nothing prevents the user to enter a negative value.

Instead of writing the for loop that is error prone you could use standard C string function memmove declared in the header <string.h>.

For example

#include <string.h>

//...

enum { N = 5 };
int a[N];

//...

if ( 0 <= pos && pos < N )
{
    memmove( a + pos + 1, a + pos, ( N - pos - 1 ) * sizeof( *a ) );
    a[pos] = element;
}

As for the for loop then it can look for example the following way

if ( 0 <= pos && pos < N )
{
    for (int i = N; --i != pos; )
    {
        a[i] = a[i - 1];
    }
    a[pos] = element;
}

Also pay attention to that the first for loop

for ( i = 0; i < 4; i++)
{
    scanf("%d",&a[i]);
}

leaves the last element of the array uninitialized.

Try to not use magic numbers like 4 or 5. Use named constants as for example

enum { N = 5 };
int a[N];
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • aren't you supposed to leave one element unintialized if u want to insert another – Divyansh Feb 20 '23 at 13:23
  • @Divyansh This does not make sense because the value of pos can be any. So the element can stay uninitialized. – Vlad from Moscow Feb 20 '23 at 13:24
  • ok , thanks . any suggestions on resources for learning c deeply ? – Divyansh Feb 20 '23 at 13:44
  • @Divyansh Unfortunately I myself do not use any resource to learn C.. I think that the best way is to load the C standard Draft from internet and read it. – Vlad from Moscow Feb 20 '23 at 14:53
  • 1
    Trying to learn C from the C standard draft will scare most people away, at least I would have been. @Divyansh rather use this [list of books](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) – Jabberwocky Feb 20 '23 at 16:41
  • @Jabberwocky The C Standard is the base to learn C. Having the C Standard you can use any additional resource to learn C. It is the same as if you want to learn for example HTML5 you need at first to load the HTML5 specification. – Vlad from Moscow Feb 20 '23 at 16:45