Introduction to Arrays in C
An array in C is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow you to store and manage large amounts of data efficiently.
Key Topics
1. Declaring Arrays
The syntax for declaring an array is:
data_type array_name[array_size];
Example: Declaring an Integer Array
int numbers[5];
2. Accessing Array Elements
Array elements are accessed using indices, starting from 0.
Example: Accessing Elements
numbers[0] = 10;
int value = numbers[0];
3. Initializing Arrays
Arrays can be initialized at the time of declaration.
Example: Initializing an Array
int numbers[5] = {1, 2, 3, 4, 5};
4. Arrays of Different Data Types
Arrays can be of any data type, including char
, float
, and double
.
Example: Character Array (String)
char name[6] = {'A', 'l', 'i', 'c', 'e', '\0'};
printf("Name: %s\n", name);
Output:
Name: Alice
Example: Float Array
float temperatures[3] = {36.5, 37.0, 36.8};
for (int i = 0; i < 3; i++) {
printf("Temperature %d: %.1f\n", i + 1, temperatures[i]);
}
Output:
Temperature 1: 36.5 Temperature 2: 37.0 Temperature 3: 36.8
Example: Double Array
double distances[4] = {5.5, 10.75, 15.0, 20.25};
for (int i = 0; i < 4; i++) {
printf("Distance %d: %.2lf km\n", i + 1, distances[i]);
}
Output:
Distance 1: 5.50 km Distance 2: 10.75 km Distance 3: 15.00 km Distance 4: 20.25 km
Example: Boolean Array
#include <stdbool.h>
bool flags[3] = {true, false, true};
for (int i = 0; i < 3; i++) {
printf("Flag %d: %s\n", i + 1, flags[i] ? "true" : "false");
}
Output:
Flag 1: true Flag 2: false Flag 3: true
Best Practices
- Always ensure array indices are within bounds to prevent undefined behavior.
- Initialize arrays to avoid garbage values.
- Use meaningful names for arrays to reflect their purpose.
- Choose the appropriate data type for the array elements.
Don'ts
- Don't access array elements outside of their defined range.
- Don't neglect to initialize arrays if their values are used before assignment.
- Don't mix data types within the same array; all elements must be of the same type.
- Don't use uninitialized arrays; always assign values before use.
Key Takeaways
- Arrays store multiple elements of the same type in contiguous memory locations.
- Array indices start at 0 and go up to size - 1.
- Arrays can be of any data type, such as
int
,char
,float
, ordouble
. - Proper declaration, initialization, and usage are essential for correct array manipulation.