hi
i am right now new to c language..and i have been facing problem in 1 array problem where i have to insert an element in to an array...i would like ur help plzz..i have tried everything but i m not able to make out from where i should start although i know the logic but i don't know what will be the code as i have not reached to any conclusion....so plz help me out ..... :?: :sad:

Recommended Answers

All 2 Replies

To insert a value into an array, you need to shift every value after the location you want to insert. This way you make a hole for the new value. Of course, this can be a problem if the array is already full. You would most likely end up throwing away the last value in the list. If that's acceptable then the logic is very simple: start from the end and copy the previous item to the current element until you hit the location you want to insert. A simple implementation might look like this:

#include <stdio.h>

#define length(x) (sizeof x / sizeof *x)

int insert(int *array, int val, size_t size, size_t at)
{
  size_t i;

  /* In range? */
  if (at >= size)
    return -1;

  /* Shift elements to make a hole */
  for (i = size - 1; i > at; i--)
    array[i] = array[i - 1];
  /* Insertion! */
  array[at] = val;

  return 0;
}

int main(void)
{
  int a[11] = {0,1,2,3,4,5,6,7,8,9};
  int i;

  if (insert(a, 6, length(a), 3) != -1) {
    for (i = 0; i < length(a); i++)
      printf("%-3d", a[i]);
    printf("\n");
  }
  else
    fprintf(stderr, "Insertion failed\n");

  return 0;
}

from your previous post (looking at the post times you must of missed this one otherwise you wouldnt post again!)

#include <iostream>
using namespace std;

int main(void)
{
    int array[11] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // allow for extra insert (11 and not 10 items!)
    int num = 0; 
    int data;
    
    do
    {
        cout << "Where do you want to insert an element (0-10)"; // replace it with 1 option
        cin >> num; // no ascii check here, watch out!
    } while (num < 0 || num > 10); // ask until num is in range (untested)
    
    // the intended position is in num
    cout << "enter data to insert ";
    cin >> data;
    // the element is in data

    for(int i = 9; i > num - 1; i--) // i goes from num to 10
        array[i + 1] = array[i]; // shift
    array[num] = data; // insert
 
    cout << "Final Array: ";
    for(int i = 0; i < 11; i++)
        cout << array[i] << ",";   
    cin >> num;
    return 0;
}

solved your specific problem - narue's is the same but put into a function which is more useful to you - and her's is in c

sorry for butting in narue! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.