Pre-read - Arrays
Pre-read - Arrays
Arrays are fundamental data structures in programming, used to store multiple values of the
same type in a single variable. An array is a collection of elements, each identified by at least
one array index or key. The array's size is fixed upon creation, meaning the number of elements
it can hold is set when it's declared. Arrays are useful for storing data that is naturally structured
in a tabular format, like a list of items of the same type, and they provide quick access to their
elements via their indices.
Java
In Java, arrays are declared by specifying the type of elements they will hold, followed by
square brackets. Here's an example of declaring an array of integers:
int[] myArray;
myArray = new int[10]; // Initializes an array to hold 10 integers
Python
Python uses lists, which are more flexible than arrays but serve similar purposes. Lists in Python
do not require declaration of size or type ahead of time:
C#
In C#, arrays are declared similarly to Java, but the type and the size can be declared at once:
In C++, arrays are declared by specifying the type, followed by the size in square brackets:
Iterating over arrays involves accessing each element in the array sequentially. Here's how you
can iterate over arrays in different programming languages:
Java
You can use a traditional for loop or an enhanced for loop (also known as a "for-each" loop):
Python
In Python, iteration is straightforward using a for loop, as Python's lists are inherently iterable:
my_list = [1, 2, 3, 4, 5]
for element in my_list:
print(element)
C#
C++
C++ also supports traditional for loops and range-based for loops (since C++11):
Dynamic Arrays
Java
Python
Python lists are inherently dynamic:
C#
C++
vector<int> myVector;
myVector.push_back(1); // Adding elements dynamically
Each language provides its own tools and libraries to manage dynamic arrays efficiently,
allowing for operations like resizing, insertion, and deletion.
Java
my_list = [1, 2, 3, 4, 5]
max_value = my_list[0] # Assume the first element is the max
initially
for i in range(1, len(my_list)):
if my_list[i] > max_value:
max_value = my_list[i] # Update max if current element is
greater
print("Max:", max_value)
C#
C++
In each example, we start by assuming the first element is the maximum, and then we check
each subsequent element to see if it is greater than the current maximum. If it is, we update the
maximum. This approach ensures that we only iterate through the array once, providing an
efficient way to find the maximum value.