An array is a fundamental data structure that stores a fixed-size sequential collection of elements of the same type. It is one of the most basic and widely used data structures in computer programming.
Operation | Time Complexity |
---|---|
Access | O(1) |
Search | O(n) |
Insertion | O(n) |
Deletion | O(n) |
package main
import "fmt"
func main() {
// Declaring and initializing an array
var numbers [5]int = [5]int{1, 2, 3, 4, 5}
// Accessing elements
fmt.Println("First element:", numbers[0])
// Modifying elements
numbers[2] = 10
// Iterating through array
fmt.Println("Array elements:")
for i := 0; i < len(numbers); i++ {
fmt.Printf("%d ", numbers[i])
}
// Using range
fmt.Println("\nUsing range:")
for index, value := range numbers {
fmt.Printf("numbers[%d] = %d\n", index, value)
}
}
public class ArrayExample {
public static void main(String[] args) {
// Declaring and initializing an array
int[] numbers = {1, 2, 3, 4, 5};
// Accessing elements
System.out.println("First element: " + numbers[0]);
// Modifying elements
numbers[2] = 10;
// Iterating through array
System.out.println("Array elements:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
// Using enhanced for loop
System.out.println("\nUsing enhanced for loop:");
for (int number : numbers) {
System.out.println(number);
}
}
}
# In Python, lists are used as dynamic arrays
# Creating an array (list)
numbers = [1, 2, 3, 4, 5]
# Accessing elements
print("First element:", numbers[0])
# Modifying elements
numbers[2] = 10
# Array operations
print("Array elements:", numbers)
# Adding elements
numbers.append(6) # Add at end
numbers.insert(1, 7) # Insert at specific position
# Removing elements
numbers.pop() # Remove last element
numbers.remove(7) # Remove specific element
# Iterating through array
print("Using for loop:")
for i in range(len(numbers)):
print(f"numbers[{i}] = {numbers[i]}")
# Using enumerate
print("Using enumerate:")
for index, value in enumerate(numbers):
print(f"numbers[{index}] = {value}")
Advantages:
Disadvantages:
Use arrays when:
Avoid arrays when:
Arrays are fundamental to understanding more complex data structures and algorithms. They provide a solid foundation for learning other programming concepts and are essential in solving many programming problems efficiently.