📚 C Arrays – Storing Multiple Values
In C, an array is a collection of variables that are of the same type. Arrays allow you to store multiple values in a single variable, making it easier to handle large amounts of data. The elements in an array are stored in contiguous memory locations and can be accessed using an index.
🔹 What is an Array?
An array is a data structure that holds a fixed number of elements of the same data type. The elements are accessed using indices, with the first element starting at index 0.
📝 Example 1: Declaring an Array
Here’s how you declare an array in C:
#include <stdio.h> int main() { int numbers[5]; // Declaring an array of 5 integers numbers[0] = 10; // Assigning value to the first element numbers[1] = 20; // Assigning value to the second element printf("First element: %d\n", numbers[0]); printf("Second element: %d\n", numbers[1]); return 0; }
🔹 Initializing an Array
You can initialize an array at the time of declaration, assigning values to its elements directly.
📝 Example 2: Initializing an Array
Here’s how you can initialize an array during declaration:
#include <stdio.h> int main() { int numbers[5] = {10, 20, 30, 40, 50}; // Initializing the array with values printf("First element: %d\n", numbers[0]); printf("Second element: %d\n", numbers[1]); return 0; }
🔹 Accessing Array Elements
You can access individual elements of an array by using the index. The index starts at 0 for the first element, 1 for the second, and so on.
📝 Example 3: Accessing Array Elements
In this example, we access each element of the array and print it.
#include <stdio.h> int main() { int numbers[5] = {10, 20, 30, 40, 50}; // Accessing and printing each element for (int i = 0; i < 5; i++) { printf("Element %d: %d\n", i + 1, numbers[i]); } return 0; }
🎯 Key Points about Arrays
- Arrays are fixed-size data structures that hold elements of the same type.
- Elements are stored in contiguous memory locations, and they are accessed using indices.
- The index starts at 0 for the first element and goes up to
size-1
for the last element.
💡 Practice Challenge
Try modifying the array's size and its elements. Add loops to iterate through the array and experiment with different ways to initialize and access array elements!