Inserting in Array
-
Add(x) / Append (x) : adding an element at the end of an array that is adding in the next free space
-
Insert(index, x) : It takes index and element, meaning to insert an element in a given index.
-
If the space is free the value will be inserted automatically, but if the space is already taken by another element it must be moved to next space in order to create space for the new insert value.
struct Array {
int A[10];
int size;
int length;
};
void Append(struct Array *arr, int x) {
if (arr->length < arr->size) {
arr->A[arr->length++] = x;
}
}
void Insert(struct Array *arr, int index, int x) {
int i;
if (index >= 0 && index <= arr->length) {
for (i = arr->length; i > index; i--) {
arr->A[i] = arr->A[i - 1];
}
arr->A[index] = x;
arr->length++;
}
}
int main() {
struct Array arr = {{2, 3, 4, 5, 6}, 10, 5};
Insert(&arr, 2, 10);
Display(arr);
return 0;
}