Arrays are foundational data structures in computer science, and they offer various operations that make data storage and management efficient and straightforward. This article delves into the basic operations supported in arrays, providing a thorough explanation of each one along with detailed examples and output. These operations are crucial for anyone learning programming or delving into data structures, as arrays are widely used in algorithm development.
Table of Contents
Introduction to Arrays
An array is a collection of elements, each identified by at least one array index or key. Arrays are one of the most commonly used data structures due to their simple, linear organization and efficiency in storing large numbers of elements. In programming, arrays are often defined by specifying a fixed length and type, such as an array of integers or an array of strings.
Array Characteristics
- Fixed Size: Once declared, the size of an array cannot be altered.
- Index-Based Access: Elements are accessed based on their position (index) within the array.
- Homogeneous Elements: All elements in an array must be of the same data type.
Basic Operations in Arrays
Basic operations in arrays are essential for manipulating and managing data stored in an array. These operations include traversal, which involves visiting each element in the array to perform an action like printing or processing; insertion, which allows adding an element at a specific index, whether at the beginning, middle, or end of the array; deletion, where an element is removed from a specific index, and the remaining elements are shifted to fill the gap; search, which helps in finding an element by its value or index; and update, where an element’s value is modified at a given index.
Each of these operations is fundamental for array manipulation and is implemented in various programming languages using loops and conditional statements to efficiently manage the data structure.
Traversal Operation
The traversal operation allows us to access each element in an array sequentially. Traversing is particularly useful when we need to print or process every element in an array.
Example of Traversal Operation
In this example, we will traverse an array of integers and print each element.
Code:
#include <stdio.h>
void main() {
int Arr[5] = {18, 30, 15, 70, 12};
int i;
printf("Elements of the array are:\n");
for(i = 0; i < 5; i++) {
printf("Arr[%d] = %d ", i, Arr[i]);
}
}
Explanation
int Arr[5] = {18, 30, 15, 70, 12};
initializes an array of integers with five elements.- The
for
loop traverses the array from index0
to4
. printf("Arr[%d] = %d ", i, Arr[i]);
prints each element’s index and value.
Output
Elements of the array are:
Arr[0] = 18, Arr[1] = 30, Arr[2] = 15, Arr[3] = 70, Arr[4] = 12
Code:
#include <iostream>
using namespace std;
int main() {
int Arr[5] = {18, 30, 15, 70, 12}; // Step 1: Declare an array of 5 integers
cout << "Elements of the array are:" << endl;
for (int i = 0; i < 5; i++) { // Step 2: Loop through each element in the array
cout << "Arr[" << i << "] = " << Arr[i] << " "; // Step 3: Print each element and its index
}
return 0; // Step 4: End of the program
}
Explanation
- Step 1: Declare an integer array
Arr
with 5 elements. - Step 2: Use a
for
loop to traverse each element by its index from0
to4
. - Step 3: Inside the loop, print each element with its index using
cout
. - Step 4:
return 0
signifies the end of the program.
Output
Elements of the array are:
Arr[0] = 18 Arr[1] = 30 Arr[2] = 15 Arr[3] = 70 Arr[4] = 12
Code:
using System;
class Program {
static void Main() {
int[] Arr = {18, 30, 15, 70, 12}; // Step 1: Declare and initialize an array
Console.WriteLine("Elements of the array are:");
for (int i = 0; i < Arr.Length; i++) { // Step 2: Loop through each element using array length
Console.Write("Arr[{0}] = {1} ", i, Arr[i]); // Step 3: Print element and index
}
}
}
Explanation
- Step 1: Define and initialize an integer array
Arr
. - Step 2: Loop through each element in
Arr
usingArr.Length
to determine the number of elements. - Step 3: Print each element with its index using
Console.Write()
with placeholders{0}
and{1}
for formatting.
Output
Elements of the array are:
Arr[0] = 18 Arr[1] = 30 Arr[2] = 15 Arr[3] = 70 Arr[4] = 12
Code:
public class Main {
public static void main(String[] args) {
int[] Arr = {18, 30, 15, 70, 12}; // Step 1: Declare and initialize an array
System.out.println("Elements of the array are:");
for (int i = 0; i < Arr.length; i++) { // Step 2: Loop through each element
System.out.print("Arr[" + i + "] = " + Arr[i] + " "); // Step 3: Print element with index
}
}
}
Explanation
- Step 1: Declare an integer array
Arr
and initialize it with values. - Step 2: Loop through the array using
Arr.length
to ensure all elements are accessed. - Step 3: Print each element with its index using
System.out.print()
.
Output
Elements of the array are:
Arr[0] = 18 Arr[1] = 30 Arr[2] = 15 Arr[3] = 70 Arr[4] = 12
Code:
let Arr = [18, 30, 15, 70, 12]; // Step 1: Declare and initialize an array
console.log("Elements of the array are:");
for (let i = 0; i < Arr.length; i++) { // Step 2: Loop through each element
console.log(`Arr[${i}] = ${Arr[i]}`); // Step 3: Print each element and its index using template literals
}
Explanation
- Step 1: Declare and initialize an array
Arr
with values. - Step 2: Use a
for
loop withArr.length
to iterate over each element. - Step 3: Print each element with its index using
console.log()
and template literals (backticks with${}
).
Output
Elements of the array are:
Arr[0] = 18
Arr[1] = 30
Arr[2] = 15
Arr[3] = 70
Arr[4] = 12
Code:
Arr = [18, 30, 15, 70, 12] # Step 1: Declare and initialize an array
print("Elements of the array are:")
for i in range(len(Arr)): # Step 2: Loop through each element using range and length of array
print(f"Arr[{i}] = {Arr[i]}", end=" ") # Step 3: Print each element with index using f-string
Explanation
- Step 1: Define and initialize a list
Arr
(lists are the closest equivalent to arrays in Python). - Step 2: Use
range(len(Arr))
to loop through each element by index. - Step 3: Print each element with its index using an
f-string
.end=" "
keeps all output on one line.
Output
Elements of the array are:
Arr[0] = 18 Arr[1] = 30 Arr[2] = 15 Arr[3] = 70 Arr[4] = 12
Each code example demonstrates array traversal, allowing easy access to each element in the array.
Insertion Operation
The insertion operation allows adding an element to the array. The insertion can be done at the beginning, end, or specific index.
Example of Insertion Operation
In this example, we insert the element 50
at index 3
.
Code:
#include <stdio.h>
int main()
{
int arr[20] = {18, 30, 15, 70, 12};
int i, x, pos, n = 5;
printf("Array elements before insertion\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
x = 50; // Element to be inserted
pos = 4;
n++;
for (i = n - 1; i >= pos; i--)
arr[i] = arr[i - 1];
arr[pos - 1] = x;
printf("Array elements after insertion\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Explanation
- Initialization:
arr[20]
is declared to have enough space, but only5
elements are initially used. x = 50; pos = 4;
sets the element to be inserted and the position.- The loop
for (i = n - 1; i >= pos; i--)
shifts elements to the right to make room at the desired position. - The new element
50
is assigned toarr[pos - 1]
.
Output
Array elements before insertion:
18 30 15 70 12
Array elements after insertion:
18 30 15 50 70 12
Code:
#include <iostream>
using namespace std;
int main() {
int arr[20] = {18, 30, 15, 70, 12}; // Step 1: Declare an array of 20 elements with 5 initialized values
int n = 5; // Step 2: Set the number of current elements in the array
int x = 50; // Step 3: Element to be inserted
int pos = 4; // Step 4: Position at which to insert the new element (1-based index)
cout << "Array elements before insertion: ";
for (int i = 0; i < n; i++) { // Step 5: Print original array
cout << arr[i] << " ";
}
cout << endl;
n++; // Step 6: Increment the number of elements in the array
for (int i = n - 1; i >= pos; i--) { // Step 7: Shift elements to the right to make space for the new element
arr[i] = arr[i - 1];
}
arr[pos - 1] = x; // Step 8: Insert the new element at the specified position (adjusted for 0-based indexing)
cout << "Array elements after insertion: ";
for (int i = 0; i < n; i++) { // Step 9: Print array after insertion
cout << arr[i] << " ";
}
cout << endl;
return 0; // Step 10: End of program
}
Output
Array elements before insertion:
18 30 15 70 12
Array elements after insertion:
18 30 15 50 70 12
Code:
using System;
class Program {
static void Main() {
int[] arr = new int[20] {18, 30, 15, 70, 12}; // Step 1: Declare an array with extra space
int n = 5; // Step 2: Number of elements currently in the array
int x = 50; // Step 3: Element to be inserted
int pos = 4; // Step 4: Position to insert the element (1-based index)
Console.WriteLine("Array elements before insertion:");
for (int i = 0; i < n; i++) { // Step 5: Print original array
Console.Write(arr[i] + " ");
}
Console.WriteLine();
n++; // Step 6: Increase the array size by 1
for (int i = n - 1; i >= pos; i--) { // Step 7: Shift elements to the right
arr[i] = arr[i - 1];
}
arr[pos - 1] = x; // Step 8: Insert the element at the specified position
Console.WriteLine("Array elements after insertion:");
for (int i = 0; i < n; i++) { // Step 9: Print updated array
Console.Write(arr[i] + " ");
}
}
}
Output
Array elements before insertion:
18 30 15 70 12
Array elements after insertion:
18 30 15 50 70 12
Code:
public class Main {
public static void main(String[] args) {
int[] arr = new int[20];
arr[0] = 18;
arr[1] = 30;
arr[2] = 15;
arr[3] = 70;
arr[4] = 12; // Step 1: Initialize an array with space for extra elements
int n = 5; // Step 2: Current size of array
int x = 50; // Step 3: Element to insert
int pos = 4; // Step 4: Position to insert the element (1-based index)
System.out.println("Array elements before insertion:");
for (int i = 0; i < n; i++) { // Step 5: Print original array
System.out.print(arr[i] + " ");
}
System.out.println();
n++; // Step 6: Increase the count of elements
for (int i = n - 1; i >= pos; i--) { // Step 7: Shift elements to the right
arr[i] = arr[i - 1];
}
arr[pos - 1] = x; // Step 8: Insert the element at the specified position
System.out.println("Array elements after insertion:");
for (int i = 0; i < n; i++) { // Step 9: Print updated array
System.out.print(arr[i] + " ");
}
}
}
Output
Array elements before insertion:
18 30 15 70 12
Array elements after insertion:
18 30 15 50 70 12
Code:
let arr = [18, 30, 15, 70, 12]; // Step 1: Initialize an array
let x = 50; // Step 2: Element to insert
let pos = 4; // Step 3: Position to insert element (1-based index)
console.log("Array elements before insertion:");
console.log(arr.join(" ")); // Step 4: Print original array
arr.splice(pos - 1, 0, x); // Step 5: Insert the element using splice (position adjusted for 0-based index)
console.log("Array elements after insertion:");
console.log(arr.join(" ")); // Step 6: Print updated array
Output
Array elements before insertion:
18 30 15 70 12
Array elements after insertion:
18 30 15 50 70 12
Code:
arr = [18, 30, 15, 70, 12] # Step 1: Initialize an array
x = 50 # Step 2: Element to insert
pos = 4 # Step 3: Position to insert element (1-based index)
print("Array elements before insertion:")
print(" ".join(map(str, arr))) # Step 4: Print original array
arr.insert(pos - 1, x) # Step 5: Insert the element using the insert method (adjusted for 0-based indexing)
print("Array elements after insertion:")
print(" ".join(map(str, arr))) # Step 6: Print updated array
Output
Array elements before insertion:
18 30 15 70 12
Array elements after insertion:
18 30 15 50 70 12
Each version of the code demonstrates the Insertion operation:
- Initialize the Array – Declare and initialize the array with a few elements.
- Insert Element – Insert the new element at a specified position by shifting elements and updating the array length.
- Print Array – Print the array before and after the insertion for comparison.
Deletion Operation
The deletion operation removes an element from a specific index in the array, after which the elements are reorganized to fill the gap.
Example of Deletion Operation
This example removes the element at index 1
from the array.
Code:
#include <stdio.h>
void main() {
int arr[] = {18, 30, 15, 70, 12};
int k = 30, n = 5;
int i, j;
printf("Given array elements are:\n");
for(i = 0; i < n; i++) {
printf("arr[%d] = %d ", i, arr[i]);
}
j = 1;
while (j < n) {
arr[j - 1] = arr[j];
j = j + 1;
}
n = n - 1;
printf("\nElements of array after deletion:\n");
for(i = 0; i < n; i++) {
printf("arr[%d] = %d ", i, arr[i]);
}
}
Explanation
- Initialization: An array
arr[]
with five elements. while (j < n)
shifts elements to the left to remove the element at index1
.n = n - 1;
reduces the count of elements to reflect the deletion.
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Elements of array after deletion:
arr[0] = 18 arr[1] = 15 arr[2] = 70 arr[3] = 12
Code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {18, 30, 15, 70, 12}; // Step 1: Initialize the array with elements
int n = 5; // Step 2: Number of elements in the array
int k = 30; // Step 3: Element to delete
cout << "Given array elements are:\n";
for (int i = 0; i < n; i++) { // Step 4: Print the original array
cout << "arr[" << i << "] = " << arr[i] << " ";
}
cout << endl;
int j = 1; // Step 5: Start from index 1
while (j < n) { // Step 6: Shift each element one position to the left
arr[j - 1] = arr[j];
j++;
}
n = n - 1; // Step 7: Decrement the size of the array
cout << "\nElements of array after deletion:\n";
for (int i = 0; i < n; i++) { // Step 8: Print the array after deletion
cout << "arr[" << i << "] = " << arr[i] << " ";
}
cout << endl;
return 0; // Step 9: End of program
}
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Elements of array after deletion:
arr[0] = 30 arr[1] = 15 arr[2] = 70 arr[3] = 12
Code:
using System;
class Program {
static void Main() {
int[] arr = {18, 30, 15, 70, 12}; // Step 1: Initialize the array
int n = 5; // Step 2: Number of elements in the array
int k = 30; // Step 3: Element to delete
Console.WriteLine("Given array elements are:");
for (int i = 0; i < n; i++) { // Step 4: Print the original array
Console.Write("arr[" + i + "] = " + arr[i] + " ");
}
Console.WriteLine();
int j = 1; // Step 5: Start from index 1
while (j < n) { // Step 6: Shift each element one position to the left
arr[j - 1] = arr[j];
j++;
}
n--; // Step 7: Decrement the size of the array
Console.WriteLine("\nElements of array after deletion:");
for (int i = 0; i < n; i++) { // Step 8: Print the array after deletion
Console.Write("arr[" + i + "] = " + arr[i] + " ");
}
}
}
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Elements of array after deletion:
arr[0] = 30 arr[1] = 15 arr[2] = 70 arr[3] = 12
Code:
public class Main {
public static void main(String[] args) {
int[] arr = {18, 30, 15, 70, 12}; // Step 1: Initialize the array
int n = 5; // Step 2: Number of elements in the array
int k = 30; // Step 3: Element to delete
System.out.println("Given array elements are:");
for (int i = 0; i < n; i++) { // Step 4: Print the original array
System.out.print("arr[" + i + "] = " + arr[i] + " ");
}
System.out.println();
int j = 1; // Step 5: Start from index 1
while (j < n) { // Step 6: Shift each element one position to the left
arr[j - 1] = arr[j];
j++;
}
n--; // Step 7: Decrement the size of the array
System.out.println("\nElements of array after deletion:");
for (int i = 0; i < n; i++) { // Step 8: Print the array after deletion
System.out.print("arr[" + i + "] = " + arr[i] + " ");
}
}
}
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Elements of array after deletion:
arr[0] = 30 arr[1] = 15 arr[2] = 70 arr[3] = 12
Code:
let arr = [18, 30, 15, 70, 12]; // Step 1: Initialize the array
let n = 5; // Step 2: Number of elements in the array
let k = 30; // Step 3: Element to delete
console.log("Given array elements are:");
for (let i = 0; i < n; i++) { // Step 4: Print the original array
process.stdout.write(`arr[${i}] = ${arr[i]} `);
}
console.log();
let j = 1; // Step 5: Start from index 1
while (j < n) { // Step 6: Shift each element one position to the left
arr[j - 1] = arr[j];
j++;
}
n--; // Step 7: Decrement the size of the array
console.log("\nElements of array after deletion:");
for (let i = 0; i < n; i++) { // Step 8: Print the array after deletion
process.stdout.write(`arr[${i}] = ${arr[i]} `);
}
console.log();
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Elements of array after deletion:
arr[0] = 30 arr[1] = 15 arr[2] = 70 arr[3] = 12
Code:
arr = [18, 30, 15, 70, 12] # Step 1: Initialize the array
n = 5 # Step 2: Number of elements in the array
k = 30 # Step 3: Element to delete
print("Given array elements are:")
for i in range(n): # Step 4: Print the original array
print(f"arr[{i}] = {arr[i]}", end=" ")
print()
j = 1 # Step 5: Start from index 1
while j < n: # Step 6: Shift each element one position to the left
arr[j - 1] = arr[j]
j += 1
n -= 1 # Step 7: Decrement the size of the array
print("\nElements of array after deletion:")
for i in range(n): # Step 8: Print the array after deletion
print(f"arr[{i}] = {arr[i]}", end=" ")
print()
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Elements of array after deletion:
arr[0] = 30 arr[1] = 15 arr[2] = 70 arr[3] = 12
Each code demonstrates the Deletion Operation:
- Initialize the Array – Set up the array with the elements to work with.
- Delete the Element – Shift the elements from the target position, effectively removing the element.
- Print the Array – Display the array before and after the deletion for clarity.
Search Operation
The search operation locates an element in the array by value or index.
Example of Search Operation
Here, we search for the element 70
and display its position.
Code:
#include <stdio.h>
void main() {
int arr[] = {18, 30, 15, 70, 12};
int k = 30, n = 5;
int i, j;
printf("Given array elements are:\n");
for(i = 0; i < n; i++) {
printf("arr[%d] = %d ", i, arr[i]);
}
j = 1;
while (j < n) {
arr[j - 1] = arr[j];
j = j + 1;
}
n = n - 1;
printf("\nElements of array after deletion:\n");
for(i = 0; i < n; i++) {
printf("arr[%d] = %d ", i, arr[i]);
}
}
Explanation
- Initialization: An array
arr[]
with five elements. while (j < n)
shifts elements to the left to remove the element at index1
.n = n - 1;
reduces the count of elements to reflect the deletion.
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Elements of array after deletion:
arr[0] = 18 arr[1] = 15 arr[2] = 70 arr[3] = 12
Code:
#include <iostream>
using namespace std;
int main() {
int arr[5] = {18, 30, 15, 70, 12}; // Step 1: Initialize the array with elements
int item = 70; // Step 2: Element to be searched
int j = 0; // Step 3: Initialize the index variable to 0
cout << "Given array elements are:\n";
for (int i = 0; i < 5; i++) { // Step 4: Print the elements of the array
cout << "arr[" << i << "] = " << arr[i] << " ";
}
cout << endl;
cout << "\nElement to be searched = " << item << endl; // Step 5: Display the item to be searched
while (j < 5) { // Step 6: Loop through the array to search for the element
if (arr[j] == item) { // Step 7: If the item is found
break;
}
j++;
}
cout << "\nElement " << item << " is found at position " << j + 1 << endl; // Step 8: Output the result
return 0;
}
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Element to be searched = 70
Element 70 is found at position 4
Code:
using System;
class Program {
static void Main() {
int[] arr = {18, 30, 15, 70, 12}; // Step 1: Initialize the array with elements
int item = 70; // Step 2: Element to be searched
int j = 0; // Step 3: Initialize the index variable to 0
Console.WriteLine("Given array elements are:");
for (int i = 0; i < 5; i++) { // Step 4: Print the elements of the array
Console.Write("arr[" + i + "] = " + arr[i] + " ");
}
Console.WriteLine();
Console.WriteLine("\nElement to be searched = " + item); // Step 5: Display the item to be searched
while (j < 5) { // Step 6: Loop through the array to search for the element
if (arr[j] == item) { // Step 7: If the item is found
break;
}
j++;
}
Console.WriteLine("\nElement " + item + " is found at position " + (j + 1)); // Step 8: Output the result
}
}
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Element to be searched = 70
Element 70 is found at position 4
Code:
public class Main {
public static void main(String[] args) {
int[] arr = {18, 30, 15, 70, 12}; // Step 1: Initialize the array with elements
int item = 70; // Step 2: Element to be searched
int j = 0; // Step 3: Initialize the index variable to 0
System.out.println("Given array elements are:");
for (int i = 0; i < 5; i++) { // Step 4: Print the elements of the array
System.out.print("arr[" + i + "] = " + arr[i] + " ");
}
System.out.println();
System.out.println("\nElement to be searched = " + item); // Step 5: Display the item to be searched
while (j < 5) { // Step 6: Loop through the array to search for the element
if (arr[j] == item) { // Step 7: If the item is found
break;
}
j++;
}
System.out.println("\nElement " + item + " is found at position " + (j + 1)); // Step 8: Output the result
}
}
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Element to be searched = 70
Element 70 is found at position 4
Code:
let arr = [18, 30, 15, 70, 12]; // Step 1: Initialize the array with elements
let item = 70; // Step 2: Element to be searched
let j = 0; // Step 3: Initialize the index variable to 0
console.log("Given array elements are:");
for (let i = 0; i < 5; i++) { // Step 4: Print the elements of the array
process.stdout.write(`arr[${i}] = ${arr[i]} `);
}
console.log();
console.log(`\nElement to be searched = ${item}`); // Step 5: Display the item to be searched
while (j < 5) { // Step 6: Loop through the array to search for the element
if (arr[j] === item) { // Step 7: If the item is found
break;
}
j++;
}
console.log(`\nElement ${item} is found at position ${j + 1}`); // Step 8: Output the result
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Element to be searched = 70
Element 70 is found at position 4
Code:
arr = [18, 30, 15, 70, 12] # Step 1: Initialize the array with elements
item = 70 # Step 2: Element to be searched
j = 0 # Step 3: Initialize the index variable to 0
print("Given array elements are:")
for i in range(5): # Step 4: Print the elements of the array
print(f"arr[{i}] = {arr[i]}", end=" ")
print()
print(f"\nElement to be searched = {item}") # Step 5: Display the item to be searched
while j < 5: # Step 6: Loop through the array to search for the element
if arr[j] == item: # Step 7: If the item is found
break
j += 1
print(f"\nElement {item} is found at position {j + 1}") # Step 8: Output the result
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Element to be searched = 70
Element 70 is found at position 4
Steps Explanation
- Initialize the Array: The array is defined with the elements
18, 30, 15, 70, 12
. - Display the Array Elements: We print all the elements of the array to the console for visibility.
- Search Item: The item to search (in this case,
70
) is stored in a variable. We loop through the array and compare each element to the item we want to find. - Looping: If an element matches the search item, the loop breaks. Otherwise, we continue checking the next elements.
- Output: Once the item is found, we display its position (index + 1 to convert from zero-based indexing to one-based).
Each of the implementations follows the same algorithm and produces the same output.
Update Operation
The update operation modifies an element at a specified index.
Example of Update Operation
Here, we update the element at position 3
with the value 50
.
Code:
#include <stdio.h>
void main() {
int arr[5] = {18, 30, 15, 70, 12};
int item = 50, i, pos = 3;
printf("Given array elements are:\n");
for(i = 0; i < 5; i++) {
printf("arr[%d] = %d ", i, arr[i]);
}
arr[pos - 1] = item;
printf("\nArray elements after updation:\n");
for(i = 0; i < 5; i++) {
printf("arr[%d] = %d ", i, arr[i]);
}
}
Explanation
- Assignment:
arr[pos - 1] = item;
updates the element at the specific index.
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Array elements after updation:
arr[0] = 18 arr[
1] = 30 arr[2] = 50 arr[3] = 70 arr[4] = 12
Code:
#include <iostream>
using namespace std;
int main() {
int arr[5] = {18, 30, 15, 70, 12}; // Step 1: Initialize the array with elements
int item = 50; // Step 2: Element to be updated
int pos = 3; // Step 3: Position to update (3rd index, which is index 2 in C++)
cout << "Given array elements are:\n";
for (int i = 0; i < 5; i++) { // Step 4: Print the elements of the array
cout << "arr[" << i << "] = " << arr[i] << " ";
}
cout << endl;
arr[pos - 1] = item; // Step 5: Update the array element at the specified index (pos - 1)
cout << "\nArray elements after updation:\n";
for (int i = 0; i < 5; i++) { // Step 6: Print the updated array
cout << "arr[" << i << "] = " << arr[i] << " ";
}
cout << endl;
return 0;
}
Output:
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Array elements after updation:
arr[0] = 18 arr[1] = 30 arr[2] = 50 arr[3] = 70 arr[4] = 12
Code:
using System;
class Program {
static void Main() {
int[] arr = {18, 30, 15, 70, 12}; // Step 1: Initialize the array with elements
int item = 50; // Step 2: Element to be updated
int pos = 3; // Step 3: Position to update (3rd index, which is index 2 in C#)
Console.WriteLine("Given array elements are:");
for (int i = 0; i < 5; i++) { // Step 4: Print the elements of the array
Console.Write("arr[" + i + "] = " + arr[i] + " ");
}
Console.WriteLine();
arr[pos - 1] = item; // Step 5: Update the array element at the specified index (pos - 1)
Console.WriteLine("\nArray elements after updation:");
for (int i = 0; i < 5; i++) { // Step 6: Print the updated array
Console.Write("arr[" + i + "] = " + arr[i] + " ");
}
Console.WriteLine();
}
}
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Array elements after updation:
arr[0] = 18 arr[1] = 30 arr[2] = 50 arr[3] = 70 arr[4] = 12
Code:
public class Main {
public static void main(String[] args) {
int[] arr = {18, 30, 15, 70, 12}; // Step 1: Initialize the array with elements
int item = 50; // Step 2: Element to be updated
int pos = 3; // Step 3: Position to update (3rd index, which is index 2 in Java)
System.out.println("Given array elements are:");
for (int i = 0; i < 5; i++) { // Step 4: Print the elements of the array
System.out.print("arr[" + i + "] = " + arr[i] + " ");
}
System.out.println();
arr[pos - 1] = item; // Step 5: Update the array element at the specified index (pos - 1)
System.out.println("\nArray elements after updation:");
for (int i = 0; i < 5; i++) { // Step 6: Print the updated array
System.out.print("arr[" + i + "] = " + arr[i] + " ");
}
System.out.println();
}
}
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Array elements after updation:
arr[0] = 18 arr[1] = 30 arr[2] = 50 arr[3] = 70 arr[4] = 12
Code:
let arr = [18, 30, 15, 70, 12]; // Step 1: Initialize the array with elements
let item = 50; // Step 2: Element to be updated
let pos = 3; // Step 3: Position to update (3rd index, which is index 2 in JavaScript)
console.log("Given array elements are:");
for (let i = 0; i < 5; i++) { // Step 4: Print the elements of the array
process.stdout.write(`arr[${i}] = ${arr[i]} `);
}
console.log();
console.log(`\nElement to be updated = ${item}`); // Step 5: Display the item to be updated
arr[pos - 1] = item; // Step 6: Update the array element at the specified index (pos - 1)
console.log("\nArray elements after updation:");
for (let i = 0; i < 5; i++) { // Step 7: Print the updated array
process.stdout.write(`arr[${i}] = ${arr[i]} `);
}
console.log();
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Element to be updated = 50
Array elements after updation:
arr[0] = 18 arr[1] = 30 arr[2] = 50 arr[3] = 70 arr[4] = 12
Code:
arr = [18, 30, 15, 70, 12] # Step 1: Initialize the array with elements
item = 50 # Step 2: Element to be updated
pos = 3 # Step 3: Position to update (3rd index, which is index 2 in Python)
print("Given array elements are:")
for i in range(5): # Step 4: Print the elements of the array
print(f"arr[{i}] = {arr[i]}", end=" ")
print()
print(f"\nElement to be updated = {item}") # Step 5: Display the item to be updated
arr[pos - 1] = item # Step 6: Update the array element at the specified index (pos - 1)
print("\nArray elements after updation:")
for i in range(5): # Step 7: Print the updated array
print(f"arr[{i}] = {arr[i]}", end=" ")
print()
Output
Given array elements are:
arr[0] = 18 arr[1] = 30 arr[2] = 15 arr[3] = 70 arr[4] = 12
Element to be updated = 50
Array elements after updation:
arr[0] = 18 arr[1] = 30 arr[2] = 50 arr[3] = 70 arr[4] = 12
Steps Explanation
- Initialize the Array: An array
arr
is initialized with 5 elements:[18, 30, 15, 70, 12]
. - Element to be Updated: The variable
item
stores the value50
, which is the value to be inserted into the array. - Position to Update: The variable
pos
holds the index of the position (in this case,3
), which represents the 3rd element of the array. Since array indices are zero-based, we subtract1
to access the correct index (index2
in C++, Java, JavaScript, and Python). - Print Initial Array: The array is printed to the console.
- Update the Element: The element at position
pos - 1
is updated with the value ofitem
(i.e.,arr[2]
becomes50
). - Print Updated Array: After the update, the array is printed again to show the updated values.
The steps above are followed in all the programming languages, and the output confirms that the element at index 2
is updated to 50
.
Conclusion
Mastering basic operations on arrays is essential in programming. This article has covered traversal, insertion, deletion, search, and update operations. By understanding these operations and practicing the examples provided, you will be well-equipped to handle arrays in various programming contexts. Arrays, despite their simplicity, remain one of the most powerful tools in a programmer’s toolkit.
Frequently Asked Questions (FAQs)
What is an array in programming?
An array is a linear data structure that stores elements of a similar data type in contiguous memory locations. Arrays allow for efficient data access and manipulation because each element is stored at a specific index, which enables quick retrieval.
What are the basic operations supported in an array?
The basic operations in arrays are:
- Traversal – Accessing each element of the array sequentially.
- Insertion – Adding an element at a specific position.
- Deletion – Removing an element from a specific position.
- Search – Finding an element by its value or index.
- Update – Modifying an element at a specific index.
How do you perform a traversal operation on an array?
To perform traversal, use a loop to access each element in the array by its index and print or process it. Traversal visits each element one by one, allowing you to view or modify each item in sequence.
What is an insertion operation in an array?
Insertion is the process of adding an element at a specified index in the array. It can be done at the beginning, end, or any specific position within the array. After inserting a new element, the array may shift other elements to make room.
Can you explain the deletion operation in an array with an example?
The deletion operation removes an element from a specified index in the array. After deletion, other elements are shifted left to fill the empty spot. For instance, if you delete an element at index 2
, each element from index 3
onwards will shift one position to the left to maintain the array’s structure.
How does the search operation work in an array?
The search operation locates an element in the array based on its value or index. For a linear search, you can use a loop to compare each element until you find the one that matches the specified value.
What is an update operation, and how is it performed in an array?
The update operation modifies the value of an element at a specified index. By assigning a new value to the array element at a given index, you can update its value. For example, arr[3] = 50;
would update the element at index 3
to 50
.
How do you insert an element into a specific position in an array in C?
To insert an element at a specific position, first shift all elements from that position to the right to make room for the new element. Then, assign the new element to that position. Here’s a code snippet:
int arr[20] = {18, 30, 15, 70, 12};
int x = 50, pos = 3;
int n = 5;
for (int i = n; i > pos; i--)
arr[i] = arr[i - 1];
arr[pos] = x;
n++;
How can you search for an element’s position in an array if the index is unknown?
If the index is unknown, you can use a linear search to find an element’s position. This involves looping through the array and comparing each element with the desired value. Once a match is found, you can print or return the index.
What is the importance of array operations in programming?
Array operations are fundamental in programming because they allow efficient data manipulation. Operations like insertion, deletion, and search are essential for data management, and they are widely used in algorithms and applications for sorting, searching, and managing data efficiently.