Imagine trying to store the weekly view counts for a YouTube channel using seven completely separate variables, one for each day. Not only would this quickly become unmanageable as the amount of data grows, but processing all seven values together, such as calculating a total or an average, would require repeating similar code seven separate times. Arrays solve this exact problem by allowing a group of related values to be stored under a single name.
An array is one of the most fundamental data structures in programming, and C's implementation of arrays forms the foundation for understanding more advanced structures you will encounter later, including strings, which are themselves simply arrays of characters. Learning arrays thoroughly also prepares you well for working with pointers, since arrays and pointers are closely related in C.
In this tutorial, you will learn what an array is, how to declare and initialize one-dimensional arrays, how to access and modify individual elements, how multidimensional arrays extend this idea into rows and columns, and how arrays can be passed to functions for further processing.
An array is a collection of elements, all of the same data type, stored in contiguous memory locations and accessed using a single variable name combined with an index number. Instead of creating separate variables for each related value, an array groups them together, making it far easier to store, access, and process large amounts of similar data.
#include <stdio.h>
int main() {
int weeklyViews[5] = {1500, 1800, 2100, 1950, 2200};
printf("Views on day 3: %d", weeklyViews[2]);
return 0;
}
Views on day 3: 2100
Here, a single array named weeklyViews stores five related values together, and any individual value can be accessed using its position, referred to as an index, inside square brackets.
Declaring an array involves specifying its data type, a name, and the number of elements it should hold. Initialization can happen at the same time as declaration, or values can be assigned to individual elements afterward.
dataType arrayName[size];
#include <stdio.h>
int main() {
int ratings[4];
ratings[0] = 5;
ratings[1] = 4;
ratings[2] = 5;
ratings[3] = 3;
printf("First rating: %d", ratings[0]);
return 0;
}
First rating: 5
In this example, the array is first declared with a fixed size of four elements, and each individual position is assigned a value separately afterward using its index.
One of the most important concepts to understand about arrays in C is that indexing always begins at zero rather than one. This means the first element of an array is accessed using index 0, and the last element is accessed using an index that is one less than the total size of the array.
| Array Size | Valid Index Range |
|---|---|
| 5 | 0 to 4 |
| 10 | 0 to 9 |
Attempting to access an index outside this valid range does not necessarily produce an error message during compilation, but it results in undefined behavior, since the program would be reading or writing memory outside the space actually reserved for the array.
Arrays and loops work together naturally, since a loop can iterate through every index of an array, allowing repeated operations to be performed on each element without writing separate code for every single position.
#include <stdio.h>
int main() {
int weeklyViews[5] = {1500, 1800, 2100, 1950, 2200};
int total = 0;
int i;
for (i = 0; i < 5; i++) {
total += weeklyViews[i];
}
printf("Total weekly views: %d", total);
return 0;
}
Total weekly views: 9550
This example demonstrates one of the most common patterns in C programming, using a for loop to visit every element of an array in sequence and accumulate a result, such as a running total.
Another common task involving arrays is searching through the elements to find a particular value, such as the largest or smallest number in a dataset.
#include <stdio.h>
int main() {
int dailyUploads[6] = {2, 4, 1, 5, 3, 4};
int maxUploads = dailyUploads[0];
int i;
for (i = 1; i < 6; i++) {
if (dailyUploads[i] > maxUploads) {
maxUploads = dailyUploads[i];
}
}
printf("Highest number of uploads in a single day: %d", maxUploads);
return 0;
}
Highest number of uploads in a single day: 5
This pattern starts by assuming the first element is the largest, then compares every remaining element against the current maximum, updating it whenever a larger value is found.
While a one-dimensional array represents a simple list of values, a multidimensional array organizes data into rows and columns, similar to a table or grid. The most common form is the two-dimensional array, which is particularly useful for representing structured data such as a grid of scores or a small table of values.
dataType arrayName[rows][columns];
#include <stdio.h>
int main() {
int scores[2][3] = {
{85, 90, 78},
{88, 76, 95}
};
printf("Score of student 2, subject 3: %d", scores[1][2]);
return 0;
}
Score of student 2, subject 3: 95
Here, the array represents two students and three subjects, and a specific score is accessed by providing both a row index and a column index, corresponding to the desired student and subject.
Just as a one-dimensional array is typically processed using a single loop, a two-dimensional array is usually processed using two nested loops, one handling the rows and the other handling the columns.
#include <stdio.h>
int main() {
int scores[2][3] = {
{85, 90, 78},
{88, 76, 95}
};
int row, col;
for (row = 0; row < 2; row++) {
for (col = 0; col < 3; col++) {
printf("%d ", scores[row][col]);
}
printf("\n");
}
return 0;
}
85 90 78 88 76 95
The outer loop moves through each row, while the inner loop moves through each column within that particular row, together visiting every single element in the entire two-dimensional array exactly once.
Arrays can be passed to functions, allowing calculations and processing logic to be separated from the main program, which keeps code organized and reusable. When an array is passed to a function in C, it is effectively passed by reference, meaning the function works directly with the original array rather than a separate copy.
#include <stdio.h>
int calculateAverage(int arr[], int size) {
int sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += arr[i];
}
return sum / size;
}
int main() {
int watchTimes[4] = {6, 8, 5, 9};
int average = calculateAverage(watchTimes, 4);
printf("Average watch time: %d minutes", average);
return 0;
}
Average watch time: 7 minutes
Notice that the function also receives the size of the array as a separate parameter, since an array passed to a function does not automatically carry information about its own length.
| Concept | Explanation |
|---|---|
| Contiguous Storage | All elements of an array are stored next to each other in memory, which allows fast access using an index. |
| Fixed Size | The size of a standard array is fixed at the time of declaration and cannot be changed afterward. |
| Array Name as Address | The name of an array represents the memory address of its first element, which is why array names behave differently from ordinary variables in certain contexts. |
| Mistake | Correct Practice |
|---|---|
| Forgetting that array indexing starts at zero rather than one. | Remember that the first element is always accessed using index 0, not 1. |
| Accessing an index beyond the array's declared size. | Always ensure loop conditions and manual indices stay within the valid range of the array. |
| Assuming a function automatically knows the size of a passed array. | Always pass the array's size as a separate parameter alongside the array itself. |
| Confusing rows and columns when working with multidimensional arrays. | Double-check the order of indices, remembering that the first index typically refers to the row and the second to the column. |
Arrays provide an efficient way to store and organize multiple related values under a single name, eliminating the need for numerous individual variables and making it far easier to process large amounts of data using loops. One-dimensional arrays handle simple lists of values, while multidimensional arrays extend this concept to represent structured data such as grids and tables.
In this tutorial, you learned how to declare and initialize arrays, how indexing works in C, how to process array elements using loops, how multidimensional arrays are structured and traversed, and how arrays can be passed to functions for further processing. With arrays firmly understood, you are ready to move on to strings, which are themselves a specialized form of character array in C.