Add element in array in C
0 255
Adding an element to an array in C involves several steps, including resizing the array if necessary.
Here's a detailed explanation along with examples and two programs:
Adding an element to an array in C typically involves several steps:
Determine Array Size: First, you need to determine the current size of the array.
Check Capacity: Check if the array has enough capacity to accommodate the new element. If not, you may need to resize the array.
Insertion: Once you have enough capacity, you can insert the new element at the desired position.
Shift Elements: If the new element is inserted in the middle of the array, you may need to shift the existing elements to make space for it.
Update Array Size: Finally, update the size of the array to reflect the addition of the new element.
Example:
Suppose we have an array arr of size n with the following elements: {10, 20, 30, 40}.
Now, we want to add the element 50 at index 2.
Check if there is enough capacity to accommodate the new element. If not, resize the array.
Insert the new element 50 at index 2:{10, 20, 50, 30, 40}
Shift the existing elements after index 2 to the right:{10, 20, 50, 30, 40}
Update the size of the array to n + 1.
Example:
Program 1: Add Element at End of Array
// program to Add Element at End of Array #include<tdio.h>void addElement(int arr[], int *sizeis, int element) { arr[*sizeis] = element; (*sizeis)++; } int main() { int arr[5] = {10, 20, 30, 40}; int sizeis = 4; int newElement = 50; addElement(arr, &sizeis, newElement); printf("Updated Array: "); for (int A = 0; A < sizeis; A++) { printf("%d ", arr[A]); } return 0; }
Output:
Updated Array: 10 20 30 40 50
Program 2: Add Element at Specific Index
// program to Add Element at Specific Index #include<stdio.h>void addElementAtIndex(int arr[], int *sizeis, int element, int index) { for (int A= *sizeis; A> index; A--) { arr[A] = arr[A - 1]; } arr[index] = element; (*size)++; } int main() { int arr[5] = {10, 20, 30, 40}; int sizeis = 4; int newElement = 50; int index = 2; addElementAtIndex(arr, &sizeis, newElement, index); printf("Updated Array: "); for (int A = 0; A< sizeis; A++) { printf("%d ", arr[A]); } return 0; }
Output:
Updated Array: 10 20 50 30 40
Share:
Comments
Waiting for your comments