Arrays in C: Working with Single-Dimensional Arrays

Arrays are fundamental data structures in C that store multiple values of the same data type in contiguous memory locations [web:125]. Instead of declaring separate variables for related data—like score1, score2, score3—arrays allow you to store all values under a single name and access them using an index. This not only makes code cleaner but also enables powerful operations like loops to process large datasets efficiently. Understanding arrays is essential for working with collections of data in C programming.
This comprehensive guide explores single-dimensional arrays in C, covering declaration syntax, initialization techniques, element access, array traversal methods, and common operations including searching and sorting [web:127][web:130]. By mastering these fundamentals, you'll be equipped to handle data collections efficiently and lay the groundwork for more advanced data structures like multi-dimensional arrays and linked lists.
Array Declaration and Syntax
Declaring an array in C requires specifying the data type, array name, and size within square brackets [web:127]. The size determines how many elements the array can hold and must be a positive integer constant. Once declared, the array occupies a fixed block of contiguous memory, with each element accessible through its index starting from 0.
#include <stdio.h>
int main() {
// Basic array declaration syntax:
// datatype array_name[size];
// Declaring arrays of different types
int numbers[5]; // Array of 5 integers
float temperatures[7]; // Array of 7 floats
char grades[10]; // Array of 10 characters
double salaries[100]; // Array of 100 doubles
// Size must be a constant
#define MAX_SIZE 50
int scores[MAX_SIZE]; // Using defined constant
// Size can be an expression of constants
int data[10 * 5]; // Valid: evaluates to 50
// Memory layout for int numbers[5]:
// [0] [1] [2] [3] [4] <- Indices
// Contiguous memory locations
printf("Arrays declared successfully\n");
printf("Size of numbers array: %zu bytes\n", sizeof(numbers));
printf("Number of elements: %zu\n", sizeof(numbers) / sizeof(numbers[0]));
return 0;
}Array Initialization Techniques
C provides several ways to initialize arrays during declaration [web:127][web:129]. You can provide explicit values, let the compiler determine the size, partially initialize, or initialize all elements to zero. Understanding these techniques helps you write more concise initialization code.
#include <stdio.h>
int main() {
// Method 1: Explicit initialization with size
int numbers[5] = {10, 20, 30, 40, 50};
// Method 2: Compiler determines size (recommended for known values)
int values[] = {5, 10, 15, 20, 25}; // Size automatically set to 5
// Method 3: Partial initialization (rest are set to 0)
int scores[10] = {95, 87, 92}; // First 3 set, remaining 7 are 0
// Method 4: Initialize all to zero
int zeros[100] = {0}; // All 100 elements set to 0
// Method 5: Initialize using loop (post-declaration)
int squares[10];
for (int i = 0; i < 10; i++) {
squares[i] = i * i; // 0, 1, 4, 9, 16, ...
}
// Character array (string) initialization
char name[] = "Alice"; // Size is 6 (includes null terminator)
char grade[5] = {'A', 'B', 'C', 'D', 'F'};
// Printing initialized arrays
printf("Numbers: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
printf("Partial scores (first 5): ");
for (int i = 0; i < 5; i++) {
printf("%d ", scores[i]);
}
printf("\n");
printf("Squares: ");
for (int i = 0; i < 10; i++) {
printf("%d ", squares[i]);
}
printf("\n");
return 0;
}Accessing and Modifying Array Elements
Array elements are accessed using the subscript operator [] with an index value [web:129]. The index specifies which element you want to access, with 0 being the first element. You can both read values from and write values to array elements using this notation.
#include <stdio.h>
int main() {
int scores[5] = {85, 90, 78, 92, 88};
// Accessing individual elements
printf("First score: %d\n", scores[0]); // 85
printf("Third score: %d\n", scores[2]); // 78
printf("Last score: %d\n", scores[4]); // 88
// Modifying elements
scores[1] = 95; // Change second score from 90 to 95
scores[4] = scores[4] + 5; // Add 5 to last score
printf("\nAfter modifications:\n");
printf("Second score: %d\n", scores[1]); // 95
printf("Last score: %d\n", scores[4]); // 93
// Using array elements in expressions
int total = scores[0] + scores[1] + scores[2] + scores[3] + scores[4];
float average = total / 5.0;
printf("\nTotal: %d\n", total);
printf("Average: %.2f\n", average);
// Finding array size
int size = sizeof(scores) / sizeof(scores[0]);
printf("Array size: %d elements\n", size);
// Common mistake: Accessing out of bounds
// scores[5] = 100; // DANGER! Array only has indices 0-4
// scores[-1] = 50; // DANGER! Negative index is invalid
return 0;
}Array Traversal: Processing All Elements
Array traversal means visiting each element in the array sequentially to perform some operation [web:130][web:133]. This is typically done using loops, most commonly for loops. Traversal is fundamental to array processing and forms the basis for operations like searching, sorting, and calculating statistics.
#include <stdio.h>
int main() {
int numbers[] = {12, 45, 23, 67, 34, 89, 56};
int size = sizeof(numbers) / sizeof(numbers[0]);
// Method 1: For loop (most common)
printf("Using for loop:\n");
for (int i = 0; i < size; i++) {
printf("Element at index %d: %d\n", i, numbers[i]);
}
// Method 2: While loop
printf("\nUsing while loop:\n");
int i = 0;
while (i < size) {
printf("%d ", numbers[i]);
i++;
}
printf("\n");
// Method 3: Do-while loop
printf("\nUsing do-while loop:\n");
i = 0;
do {
printf("%d ", numbers[i]);
i++;
} while (i < size);
printf("\n");
// Practical example: Calculate sum and average
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
float average = (float)sum / size;
printf("\nSum: %d\n", sum);
printf("Average: %.2f\n", average);
// Find maximum value
int max = numbers[0];
for (int i = 1; i < size; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
printf("Maximum: %d\n", max);
// Find minimum value
int min = numbers[0];
for (int i = 1; i < size; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
printf("Minimum: %d\n", min);
return 0;
}sizeof(array) / sizeof(array[0]) rather than hardcoding numbers. This makes code maintainable and prevents errors when array size changes.Common Array Operations
Beyond simple traversal, arrays support numerous operations that form the foundation of data manipulation in programming. These include searching for elements, inserting and deleting values, reversing order, and copying arrays.
#include <stdio.h>
// Function to print array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Function to reverse array
void reverseArray(int arr[], int size) {
int start = 0, end = size - 1;
while (start < end) {
// Swap elements
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
// Function to copy array
void copyArray(int source[], int dest[], int size) {
for (int i = 0; i < size; i++) {
dest[i] = source[i];
}
}
// Function to find element
int findElement(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
// Function to count occurrences
int countOccurrences(int arr[], int size, int value) {
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == value) {
count++;
}
}
return count;
}
int main() {
int numbers[] = {10, 20, 30, 20, 40, 50, 20};
int size = 7;
printf("Original array: ");
printArray(numbers, size);
// Reverse array
reverseArray(numbers, size);
printf("Reversed array: ");
printArray(numbers, size);
// Reverse again to restore
reverseArray(numbers, size);
// Copy array
int copy[7];
copyArray(numbers, copy, size);
printf("Copied array: ");
printArray(copy, size);
// Find element
int target = 30;
int index = findElement(numbers, size, target);
if (index != -1) {
printf("%d found at index %d\n", target, index);
} else {
printf("%d not found\n", target);
}
// Count occurrences
int count = countOccurrences(numbers, size, 20);
printf("Value 20 appears %d times\n", count);
return 0;
}Searching Algorithms
Searching is one of the most common operations performed on arrays [web:131]. Linear search examines each element sequentially, while binary search (for sorted arrays) uses a divide-and-conquer approach for much faster results.
#include <stdio.h>
// Linear Search - works on any array
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Element found at index i
}
}
return -1; // Element not found
}
// Binary Search - requires sorted array
int binarySearch(int arr[], int size, int target) {
int low = 0, high = size - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // Avoid overflow
if (arr[mid] == target) {
return mid; // Element found
}
else if (arr[mid] < target) {
low = mid + 1; // Search right half
}
else {
high = mid - 1; // Search left half
}
}
return -1; // Element not found
}
int main() {
// Unsorted array for linear search
int unsorted[] = {64, 34, 25, 12, 22, 11, 90};
int size1 = 7;
int result = linearSearch(unsorted, size1, 22);
if (result != -1) {
printf("Linear Search: Found 22 at index %d\n", result);
}
// Sorted array for binary search
int sorted[] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
int size2 = 9;
result = binarySearch(sorted, size2, 50);
if (result != -1) {
printf("Binary Search: Found 50 at index %d\n", result);
}
// Performance comparison:
// Linear Search: O(n) - checks every element in worst case
// Binary Search: O(log n) - much faster for large arrays
return 0;
}Sorting Algorithms
Sorting arranges array elements in a specific order (ascending or descending) [web:131]. While C provides qsort() in the standard library, understanding basic sorting algorithms like bubble sort and selection sort builds fundamental algorithmic thinking skills.
#include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Bubble Sort - simple but inefficient
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
// Swap if element is greater than next
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Selection Sort - finds minimum and places it
void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
// Find minimum element in unsorted portion
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap minimum with first unsorted element
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
int main() {
int arr1[] = {64, 34, 25, 12, 22, 11, 90};
int size = 7;
printf("Original array: ");
printArray(arr1, size);
// Test bubble sort
int bubbleArr[] = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(bubbleArr, size);
printf("After Bubble Sort: ");
printArray(bubbleArr, size);
// Test selection sort
int selectArr[] = {64, 34, 25, 12, 22, 11, 90};
selectionSort(selectArr, size);
printf("After Selection Sort: ");
printArray(selectArr, size);
// Time complexity:
// Bubble Sort: O(n²)
// Selection Sort: O(n²)
// For large arrays, use more efficient algorithms
return 0;
}Array Limitations and Best Practices
Understanding array limitations helps you write safer, more efficient code and know when to consider alternative data structures. Arrays in C have several important constraints and considerations.
- Fixed Size: Array size is determined at declaration and cannot be changed during runtime—use dynamic allocation with malloc() for flexible sizing
- No Bounds Checking: C doesn't validate array indices—accessing out-of-bounds causes undefined behavior and potential crashes
- No Built-in Size Tracking: Arrays don't store their own size—always pass size as a separate parameter to functions
- Contiguous Memory: Arrays require continuous memory block—large arrays may fail to allocate if memory is fragmented
- Pass by Reference: Arrays passed to functions decay to pointers—functions receive the address, not a copy
- Homogeneous Elements: All elements must be the same type—use structures for mixed-type collections
Best Practices
- Always initialize arrays: Uninitialized arrays contain garbage values that cause unpredictable behavior
- Validate indices: Before accessing arr[i], ensure
i >= 0 && i < sizeto prevent buffer overflows - Use sizeof() carefully:
sizeof(array)works only in the scope where the array is declared, not in functions - Pass size to functions: Always include array size as a parameter when passing arrays to functions
- Consider const: Use
const int arr[]in function parameters if the function shouldn't modify the array - Use descriptive names:
studentScores[]is clearer thanarr[]ordata[]
Conclusion
Arrays are indispensable data structures in C programming, providing efficient storage and access to collections of related data. Understanding proper declaration syntax, initialization techniques, and element access through indexing forms the foundation for working with arrays. Mastering array traversal enables you to process datasets efficiently, while common operations like searching, sorting, reversing, and copying give you the tools to manipulate data effectively.
Remember that arrays have important limitations including fixed size, lack of bounds checking, and the requirement for contiguous memory. By following best practices—always initializing arrays, validating indices, and passing sizes to functions—you'll write safer, more reliable code. The skills you develop working with single-dimensional arrays prepare you for more advanced topics including multi-dimensional arrays, pointers, and dynamic memory allocation. Practice these concepts through coding exercises, and you'll build the solid foundation needed for all data structure and algorithm work in C.
$ share --platform
$ cat /comments/ (0)
$ cat /comments/
// No comments found. Be the first!


