Array Declaration and Initialization

beginner
10 min

Array Declaration and Initialization

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.

What is an Array? šŸŽÆ

An array is a collection of elements (values) stored in contiguous memory locations. Each element has an index (or position) to uniquely identify it.

Array Declaration šŸ“

Let's see how to declare an array in some popular programming languages.

JavaScript

javascript
// Declare an empty array let myArray; // Initialize an array myArray = [1, 2, 3, 4, 5];

Python

python
# Declare an empty array my_array = [] # Initialize an array my_array = [6, 7, 8, 9, 10]

C++

cpp
// Declare an empty array int myArray[5]; // Initialize an array int myArray[] = {11, 12, 13, 14, 15};

Java

java
// Declare an empty array int[] myArray; // Initialize an array int[] myArray = {16, 17, 18, 19, 20};

Accessing Array Elements šŸ’”

Accessing array elements is as simple as referring to their index. Remember, the index starts from 0.

JavaScript

javascript
console.log(myArray[0]); // Output: 1

Python

python
print(my_array[0]); // Output: 6

C++

cpp
cout << myArray[0]; // Output: 11

Java

java
System.out.println(myArray[0]); // Output: 16
Quick Quiz
Question 1 of 1

Which of the following is the correct way to initialize an array in Python?

Multi-dimensional Arrays šŸ“

Multi-dimensional arrays are used to store multiple arrays in a single structure. They are useful for representing tables and matrices.

JavaScript

javascript
let myArray2D = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]; console.log(myArray2D[1][1]); // Output: 4

Python

python
my_array2D = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] print(my_array2D[1][1]); // Output: 4

C++

cpp
int myArray2D[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; cout << myArray2D[1][1]; // Output: 4

Java

java
int myArray2D[][] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; System.out.println(myArray2D[1][1]); // Output: 4
Quick Quiz
Question 1 of 1

What will be the output of the following code snippet in Java?

Key Takeaways āœ…

  • Arrays are a collection of elements stored in contiguous memory locations.
  • Elements in an array are accessed by their index, starting from 0.
  • Multi-dimensional arrays are used to represent tables and matrices.

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! 😊