Arrays in C
An array is a collection of elements of the same data type stored in contiguous memory locations, accessed using an index.
---
1. One-Dimensional Arrays
Declaration:
data_type array_name[size];
int marks[5];
Initialisation:
int marks[5] = {85, 90, 78, 92, 88};
int zeros[5] = {0}; /* all elements 0 */
int arr[] = {1, 2, 3, 4, 5}; /* size inferred */
Accessing elements:
marks[0] = 85; /* first element (index 0) */
marks[4] = 88; /* last element (index 4) */
Traversal:
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
---
2. Two-Dimensional Arrays (Matrices)
Declaration:
int matrix[3][3];
Initialisation:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Matrix addition example:
int a[2][2] = {{1,2},{3,4}};
int b[2][2] = {{5,6},{7,8}};
int c[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
c[i][j] = a[i][j] + b[i][j];
---
3. String as Character Array
char name[20] = "Alice";
char greeting[] = {'H','e','l','l','o','\0'}; /* null-terminated */
Common string functions (string.h):
| Function | Purpose |
|---|---|
strlen(s) | Length of string |
strcpy(dest, src) | Copy string |
strcat(dest, src) | Concatenate strings |
strcmp(s1, s2) | Compare strings |
strupr(s) | Convert to uppercase |
strlwr(s) | Convert to lowercase |
---
Passing Arrays to Functions
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int data[] = {5, 10, 15, 20};
printArray(data, 4);
return 0;
}
Note: Arrays are always passed by reference — the function receives a pointer to the first element.