C-Language-Series-#29-Arrays-in-C-One-Dimensional
Welcome back to our C-Language Series! In this installment, #29, we're diving into one of the fundamental data structures in C programming: Arrays. Specifically, we'll focus on one-dimensional arrays, which are essential for organizing and managing collections of data efficiently.
Imagine you need to store the scores of 100 students, the temperatures for a week, or a list of product prices. Would you declare 100 separate variables? That would be cumbersome and impractical! This is where arrays come to the rescue, allowing you to store multiple values of the same data type under a single variable name.
What is a One-Dimensional Array?
In C, an array is a collection of elements of the same data type, stored in contiguous memory locations. A one-dimensional array can be thought of as a linear list or a row of values. Each element in the array can be accessed using an index.
- Homogeneous Data: All elements in an array must be of the same type (e.g., all integers, all characters, all floats).
- Fixed Size: Once an array is declared with a specific size, that size is fixed and cannot be changed during program execution.
- Contiguous Memory: Array elements are stored sequentially in memory, one after another. This characteristic makes accessing elements very efficient.
Declaring One-Dimensional Arrays
Before you can use an array, you must declare it. The declaration tells the compiler the type of data the array will hold and how many elements it can store. The general syntax for declaring a one-dimensional array is:
dataType arrayName[arraySize];
dataType: The type of data to be stored in the array (e.g.,int,char,float,double).arrayName: A valid identifier for the array.arraySize: An integer constant or a constant expression that specifies the number of elements the array can hold. This size must be greater than zero.
Examples:
// Declares an integer array named 'scores' that can hold 5 elements.
int scores[5];
// Declares a character array named 'name' that can hold 20 characters.
char name[20];
// Declares a float array named 'temperatures' that can hold 7 elements.
float temperatures[7];
Initializing One-Dimensional Arrays
Once declared, array elements contain garbage values (unless they are global or static arrays, which are initialized to zero by default). You'll typically want to initialize them with meaningful data. There are several ways to initialize a one-dimensional array:
1. Initialization During Declaration
You can initialize an array at the time of its declaration by providing a list of values enclosed in curly braces {}.
// Full initialization:
int numbers[5] = {10, 20, 30, 40, 50};
// Partial initialization:
// If the number of initializers is less than the array size,
// the remaining elements are automatically initialized to 0 (for numeric types)
// or null characters (for character types).
int partialArray[5] = {1, 2, 3}; // partialArray will be {1, 2, 3, 0, 0}
// Omitting the size (Implicit Sizing):
// The compiler automatically determines the size of the array based on the number of initializers.
int autoArray[] = {100, 200, 300}; // autoArray will have a size of 3.
// Initializing a character array (string literal shortcut):
char greeting[] = "Hello"; // This automatically includes the null terminator '\0'
// greeting will have a size of 6: {'H','e','l','l','o','\0'}
char letters[3] = {'A', 'B', 'C'}; // No null terminator here if size matches.
2. Initialization After Declaration (Using Loops)
You can also initialize or assign values to array elements individually after declaration, typically using a for loop.
int data[4]; // Declares an array of 4 integers
// Initialize elements using a loop
for (int i = 0; i < 4; i++) {
data[i] = (i + 1) * 10; // Assigns 10, 20, 30, 40
}
Accessing Array Elements
Each element in an array is accessed using its index. C arrays are 0-indexed, meaning the first element is at index 0, the second at index 1, and so on. For an array of size N, the valid indices range from 0 to N-1.
arrayName[index];
Examples:
int grades[3] = {85, 90, 78};
// Accessing the first element (index 0)
int firstGrade = grades[0]; // firstGrade will be 85
// Accessing the third element (index 2)
int thirdGrade = grades[2]; // thirdGrade will be 78
// Modifying an element
grades[1] = 95; // The second element is now 95
// IMPORTANT: Accessing an index outside the valid range (0 to N-1)
// leads to "out-of-bounds" access, which results in undefined behavior.
// This is a common source of bugs and security vulnerabilities in C.
// For example, grades[3] would be out of bounds for an array of size 3.
Iterating Through One-Dimensional Arrays
The most common way to process all elements of an array is by using a loop, typically a for loop. The loop counter variable serves as the array index.
int myNumbers[6] = {1, 2, 3, 4, 5, 6};
int sum = 0;
printf("Elements of the array: ");
for (int i = 0; i < 6; i++) { // Loop from index 0 to 5
printf("%d ", myNumbers[i]);
sum += myNumbers[i]; // Add element to sum
}
printf("\nSum of elements: %d\n", sum);
Pro-tip for determining array size: You can calculate the number of elements in an implicitly sized array or any array whose size you might not explicitly remember using sizeof:
int data[] = {10, 20, 30, 40, 50};
int size = sizeof(data) / sizeof(data[0]); // Size of entire array / Size of one element
printf("The array 'data' has %d elements.\n", size); // Output: 5
Complete Example Program
Let's put everything together with a full C program that demonstrates array declaration, initialization, accessing, and iteration.
#include <stdio.h> // Required for printf and scanf
int main() {
// 1. Declare a one-dimensional integer array of size 5
int studentScores[5];
// 2. Initialize the array by taking input from the user
printf("Enter scores for 5 students:\n");
for (int i = 0; i < 5; i++) {
printf("Student %d score: ", i + 1);
scanf("%d", &studentScores[i]); // Store input at current index
}
// 3. Print the original scores
printf("\n--- Student Scores (Original) ---\n");
for (int i = 0; i < 5; i++) {
printf("Score of Student %d: %d\n", i + 1, studentScores[i]);
}
// 4. Access and modify a specific element
printf("\nModifying the score of Student 3...\n");
studentScores[2] = 92; // Change the third student's score (index 2)
printf("New score for Student 3: %d\n", studentScores[2]);
// 5. Calculate and print the average score
int totalScore = 0;
for (int i = 0; i < 5; i++) {
totalScore += studentScores[i];
}
double averageScore = (double)totalScore / 5; // Cast to double for floating-point division
printf("\n--- Student Scores (Updated) ---\n");
for (int i = 0; i < 5; i++) {
printf("Score of Student %d: %d\n", i + 1, studentScores[i]);
}
printf("\nTotal Score: %d\n", totalScore);
printf("Average Score: %.2lf\n", averageScore);
// Another example: Character array (string)
char city[] = "New York"; // Automatically sized to 9 (8 characters + '\0')
printf("\n--- City Name ---\n");
printf("City: %s\n", city);
printf("First letter: %c\n", city[0]);
printf("Length of city string (excluding null terminator): %lu\n", sizeof(city) / sizeof(city[0]) -1);
return 0; // Indicate successful execution
}
Key Takeaways
- Arrays allow you to store collections of homogeneous (same type) data.
- One-dimensional arrays are linear collections accessed by a single index.
- Arrays are 0-indexed, meaning the first element is at index
0. - The size of a standard array in C is fixed at declaration.
- Accessing elements outside the declared bounds leads to undefined behavior.
forloops are typically used to iterate through and process array elements.- Elements are stored in contiguous memory locations.
One-dimensional arrays are a foundational concept in C programming. Mastering them is crucial for handling lists of data, working with strings, and preparing for more complex data structures like multi-dimensional arrays and linked lists. In our next session, we'll explore multi-dimensional arrays, which extend this concept to tabular data.
Stay tuned for more in our C-Language Series!