Welcome to the exciting world of Data Structures and Algorithms! Today, we're diving into Arrays - one of the fundamental building blocks of programming. By the end of this lesson, you'll be able to declare and initialize arrays in various programming languages.
An array is a collection of elements (values) stored in contiguous memory locations. Each element has an index (or position) to uniquely identify it.
Let's see how to declare an array in some popular programming languages.
// Declare an empty array
let myArray;
// Initialize an array
myArray = [1, 2, 3, 4, 5];# Declare an empty array
my_array = []
# Initialize an array
my_array = [6, 7, 8, 9, 10]// Declare an empty array
int myArray[5];
// Initialize an array
int myArray[] = {11, 12, 13, 14, 15};// Declare an empty array
int[] myArray;
// Initialize an array
int[] myArray = {16, 17, 18, 19, 20};Accessing array elements is as simple as referring to their index. Remember, the index starts from 0.
console.log(myArray[0]); // Output: 1print(my_array[0]); // Output: 6cout << myArray[0]; // Output: 11System.out.println(myArray[0]); // Output: 16Which of the following is the correct way to initialize an array in Python?
Multi-dimensional arrays are used to store multiple arrays in a single structure. They are useful for representing tables and matrices.
let myArray2D = [[0, 1, 2], [3, 4, 5], [6, 7, 8]];
console.log(myArray2D[1][1]); // Output: 4my_array2D = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
print(my_array2D[1][1]); // Output: 4int myArray2D[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
cout << myArray2D[1][1]; // Output: 4int myArray2D[][] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
System.out.println(myArray2D[1][1]); // Output: 4What will be the output of the following code snippet in Java?
In the next lesson, we'll explore how to manipulate arrays using various operations. Until then, practice your skills by declaring and accessing arrays in different programming languages! š
Happy coding! š