Arrays
Let's dive into arrays in C! Arrays are essential when you want to work with collections of data (like a list of numbers, or names).
What is an Array?
An array is a sequence of elements that are stored in contiguous memory locations. Each element in the array is of the same data type, and you can access them using an index.
Key Points:
All elements in an array are of the same type (e.g., all integers, all floats).
The index of an array starts at
0
.Arrays are fixed in size, meaning you must define the size when you declare the array.
Array Declaration and Initialization
To declare an array, you specify the type, the name, and the number of elements (size). You can also initialize the array with values.
Syntax:
Example:
Array Initialization
You can initialize an array when you declare it by listing its values in curly braces {}
.
Example:
The array
numbers
holds the values10, 20, 30, 40, 50
.
If you don’t initialize all the elements, the remaining elements are automatically set to 0
.
Example:
Accessing Elements in an Array
You can access array elements using their index. Remember, the first element has an index of 0
.
Syntax:
Example:
Modifying Elements
You can change the value of a specific element by assigning it a new value.
Example:
Looping through Arrays
Using loops, especially for
loops, is the easiest way to work with arrays.
Example:
This loop prints all the elements of the
numbers
array.
Multidimensional Arrays
C allows you to create arrays with more than one dimension. A two-dimensional array can be thought of as a grid or matrix.
Syntax:
Example:
This creates a 2x3 array (2 rows and 3 columns).
You can access elements of a 2D array like this:
Practical Example: Sum of Array Elements
Let’s sum all elements of an integer array.
This code adds up the elements of the
numbers
array and prints the sum (150
in this case).
Arrays Summary
Array Declaration
type arrayName[size];
- Fixed size, elements stored in sequence.
Indexing
Arrays are indexed starting from 0.
Initialization
Arrays can be initialized when declared (e.g., {1, 2, 3}
) or left uninitialized.
Access/Modification
Use arrayName[index]
to access or modify elements.
Looping Through Arrays
Use loops to iterate over elements (e.g., for
loop).
Multidimensional Arrays
Arrays with more than one dimension (e.g., int matrix[2][3]
).
Last updated
Was this helpful?