Arrays
Arrays are one of the most basic and commonly used data structures in programming. They are a collection of elements of the same type, stored in contiguous memory locations. For example, an array of integers would hold a sequence of integer values.
Arrays have several important characteristics:
- Fixed Size: The size of an array is determined at the time of creation and cannot be changed.
- Indexed Access: Elements in an array are accessed using an index, starting from 0.
- Random Access: Since the elements of an array are stored in contiguous memory locations, it allows for efficient random access. This means we can access any element in constant time.
Let's take a look at an example in Java to understand arrays better:
1class Main {
2 public static void main(String[] args) {
3 int[] numbers = {1, 2, 3, 4, 5};
4
5 // Accessing elements of an array
6 System.out.println(numbers[0]); // Output: 1
7 System.out.println(numbers[2]); // Output: 3
8
9 // Modifying elements of an array
10 numbers[1] = 10;
11 System.out.println(numbers[1]); // Output: 10
12
13 // Calculating the sum of all elements
14 int sum = 0;
15 for (int i = 0; i < numbers.length; i++) {
16 sum += numbers[i];
17 }
18 System.out.println(sum); // Output: 20
19 }
20}
In this example, we create an array numbers
with 5 elements. We can access and modify the elements using the index. We can also perform operations on the elements of the array, such as calculating the sum of all elements.
Arrays are versatile and can be used in various programming scenarios. From simple tasks like storing a list of numbers to more complex tasks like implementing data structures such as stacks and queues, arrays play a fundamental role in programming.
It's important to note that arrays have a fixed size, meaning you need to know the number of elements beforehand. If you need a data structure that can dynamically change in size, you may want to consider other data structures like ArrayList or LinkedList.
Now that we have covered the basics of arrays, let's move on to the next topic: Linked Lists.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Accessing elements of an array
System.out.println(numbers[0]); // Output: 1
System.out.println(numbers[2]); // Output: 3
// Modifying elements of an array
numbers[1] = 10;
System.out.println(numbers[1]); // Output: 10
// Calculating the sum of all elements
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println(sum); // Output: 20
}
}