Array declaration
An array is a data structure that stores a collection of elements of the same data type in a contiguous memory block. It provides an indexed way to access and manipulate individual elements. The process of creating an array is known as array declaration.
Let's go through array declaration in each of the above mentioned programming languages.
In Python, arrays are represented using lists. Lists are dynamic arrays that can hold elements of different data types. You don't need to declare the size of the array explicitly; it grows as you add elements.
1 2# Array declaration in Python (using lists) 3 4my_list = [1, 2, 3, 4, 5] # An array with integer elements 5 6 7 8# Accessing array elements 9 10print(my_list[0]) # Output: 1 11 12 13 14# Modifying array elements 15 16my_list[2] = 10 17 18print(my_list) # Output: [1, 2, 10, 4, 5] 19 20 21 22# Adding elements to the array 23 24my_list.append(6) 25 26print(my_list) # Output: [1, 2, 10, 4, 5, 6] 27
In C, arrays are fixed-size collections of elements. You need to specify the size when declaring an array. The array index starts from 0 and goes up to the size minus one.
1 2// Array declaration in C 3 4int my_array[5]; // An array of integers with size 5 5 6 7 8// Initializing array elements 9 10my_array[0] = 1; 11 12my_array[1] = 2; 13 14my_array[2] = 3; 15 16my_array[3] = 4; 17 18my_array[4] = 5; 19 20 21 22// Accessing array elements 23 24printf("%d\n", my_array[2]); // Output: 3 25 26 27 28// Modifying array elements 29 30my_array[2] = 10; 31 32 33 34// Looping through array elements 35 36for (int i = 0; i < 5; i++) { 37 printf("%d ", my_array[i]); 38} 39 40// Output: 1 2 10 4 5 41
In JavaScript, arrays are dynamic and can hold elements of different data types, similar to Python lists.
1 2// Array declaration in JavaScript 3 4let myArray = [1, 2, 3, 4, 5]; // An array with integer elements 5 6 7 8// Accessing array elements 9 10console.log(myArray[0]); // Output: 1 11 12 13 14// Modifying array elements 15 16myArray[2] = 10; 17 18console.log(myArray); // Output: [1, 2, 10, 4, 5] 19 20 21 22// Adding elements to the array 23 24myArray.push(6); 25 26console.log(myArray); // Output: [1, 2, 10, 4, 5, 6] 27
In all three languages, arrays provide a way to store and manipulate collections of elements, but the syntax and behavior may vary. Python and JavaScript support dynamic arrays, while C uses fixed-size arrays.