-1

When inserting into an array, we know the index starts from 0. So, if we want to insert an element at position 3, we've to enter the input at position 2. For readability I wanted to give the proper location, i.e., position 3 means at exact 3, not 2.

Here is the code snippet.

printf("In which position you want to enter the element? ");
scanf("%d",&k);

for (j=n; j>=k; j--)
{
    array[j+1]=array[j];
}

printf("Which element do you want to insert? ");
scanf("%d", &item);

array[k]=item;

n++;

Sample output:

How many elements? 5
Enter the values
1
2
4
5
6
In which position you want to enter the element? 2
Which element do you want to insert? 3
After insertion the array is:
1
2
3
4
5
6

I want the position to be at 3.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Imbecile
  • 13
  • 3

1 Answers1

0

This code should work.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *array;

    int size = 0;

    int position, value;

    printf("How many elements do you want to add? ");
    scanf("%d", &size);

    printf("\nEnter the values: \n");

    // allocate the array
    array = malloc(size * sizeof(int));

    // insert the elements
    for(int i = 0; i < size; i++) {
      scanf("%d", &array[i]);
    }

    // print the array
    for(int i = 0; i < size; i++) {
      printf("%d ", array[i]);
    }
    printf("\n");

    // read the position
    printf("In which position you want to enter the element? ");
    scanf("%d",&position);

    // resize the array
    size++;
    array = realloc(array, size * sizeof(int));

    // set the position to the true value
    position--;

    // read the value
    printf("Which element do you want to insert? ");
    scanf("%d", &value);

    // move the elements
    for(int i = size - 1; i > position; i--) {
      array[i] = array[i - 1];
    }

    // insert the array
    array[position] = value;

    // print the value
    for(int i = 0; i < size; i++) {
      printf("%d ", array[i]);
    }
    printf("\n");
}

Of course you should implement some error handling. Especially for the alloc.

MFisherKDX
  • 2,781
  • 3
  • 12
  • 25
Moschte
  • 102
  • 1
  • 11
  • yeah but his sample output looks like he shifts back all the values – Moschte May 14 '19 at 17:42
  • @ Moschte, This works fine. But is there any other way without forcefully decrements the position? Say, in the loop where we are inserting the value. – Imbecile May 14 '19 at 17:43
  • I think it's also possible to say in the loop for(; i > position-1;) but then you also need to change the code to array[position - 1 ] = value – Moschte May 14 '19 at 17:45
  • 1
    That I was looking for. Thanks. @Moschte – Imbecile May 14 '19 at 19:04