Gabriel Morais
Gabriel Morais

Reputation: 61

Inserting a number in the middle of a vector

I made this code below:

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

main()
{
    int n, i, v[1000];
    printf("Type the size of the vector: ");
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        printf("Type a number: ");
        scanf("%d", &v[i]);
    }
    for(i=0;i<n;i++){
        printf ("%d ", v[i]);
    }
    system ("pause");
    return 0;
}

It is working, but what I need to do now is to put another number right in the middle of this vector. So if you put 4 numbers on it, 1, 2, 3 and 4 for example, I need to make it possible to put another number in the middle, so it would be 1, 2, 9, 3 and 4 for example. Does anyone know how to do that?

Upvotes: 0

Views: 118

Answers (2)

user586399
user586399

Reputation:

int k;

k = n / 2;

for (i = n; i > k; --i)
   v[i] = v[i - 1];
v[k] = insertionValue;

Upvotes: 3

phaazon
phaazon

Reputation: 2002

You have to realloc your vector, shift all value after the middle 1 to right, then assign the value you want to the middle.

Upvotes: 0

Related Questions