Arrays in C
Arrays in C are used to store multiple values in a single variable. They allow you to store values of the same data type in a contiguous block of memory.
Definition
An array is a collection of variables of the same data type that are stored in contiguous memory locations. Each element in an array can be accessed using an index.
Syntax:
data_type array_name[array_size];
Example 1: Declaring and Initializing an Array
{% raw %}
#include <stdio.h>
int main()
{
int numbers[5] = {1, 2, 3, 4, 5}; // Array initialization
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
{% endraw %}
Output
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Array Types
C supports different types of arrays based on the data they store:
- int[]: Array of integers.
- float[]: Array of floating-point numbers.
- char[]: Array of characters.
- double[]: Array of double precision floating-point numbers.
Example 2: Array of Floating-Point Numbers
{% raw %}
#include <stdio.h>
int main()
{
float numbers[3] = {3.14, 2.71, 1.41}; // Array of floats
for (int i = 0; i < 3; i++) {
printf("Element %d: %.2f\n", i, numbers[i]);
}
return 0;
}
{% endraw %}
Output
Element 0: 3.14
Element 1: 2.71
Element 2: 1.41
Element 1: 2.71
Element 2: 1.41
Example 3: Using a Character Array
{%raw%}
#include <stdio.h>
int main()
{
char name[10] = "John"; // Array of characters (string)
printf("Name: %s\n", name);
return 0;
}
{%endraw%}
Output
Name: John
Key Points
- Arrays must be declared with a fixed size or initialized with a set number of values.
- Array indices start from 0.
- Arrays can be multi-dimensional (e.g., 2D arrays).
- Always ensure the array size is large enough to hold all the values.
- C does not perform bounds checking, so accessing an index outside the array range leads to undefined behavior.
Example 4: Multidimensional Array
{%raw%}
#include <stdio.h>
int main()
{
int matrix[2][2] = {{1, 2}, {3, 4}}; // 2D array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("Element [%d][%d]: %d\n", i, j, matrix[i][j]);
}
}
return 0;
}
{%endraw%}
Output
Element [0][0]: 1
Element [0][1]: 2
Element [1][0]: 3
Element [1][1]: 4
Element [0][1]: 2
Element [1][0]: 3
Element [1][1]: 4