One-Dimensional Arrays (1D Arrays)
Tags: #◇CCPROG2 #◇C Programming #◇Programming #◇Computer Science #◇Data Structures #◇Data Types #◇Structured Programming #◇Memory Management
◇Overview
dataType arrayName[arraySize];
◇Details / Theory
Declaration
Syntax:
dataType arrayName[arraySize];
`dataType`: Type of elements (e.g., `int`, `float`, `char`)
`arrayName`: Name of the array
`arraySize`: Positive integer constant
**Examples**:
```c
int numbers[10];
float prices[5];
char name[30];
Memory Allocation:
If int takes 4 bytes, then:
int numbers[10]; // allocates 10 × 4 = 40 bytes
Initialization
Syntax:
dataType arrayName[arraySize] = {value1, value2, ..., valueN};
Examples:
int marks[5] = {10, 15, 12, 18, 17};
float temps[] = {23.5f, 24.0f, 22.8f};
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char message[] = "Hello";
Uninitialized elements:
int data[5] = {1, 2}; // remaining values depend on storage type
Personal Note: Always initialize arrays to avoid garbage values.
Accessing Elements
Arrays are zero-indexed.
Syntax:
arrayName[index]
Examples:
int scores[3];
scores[0] = 90;
scores[1] = 85;
scores[2] = 92;
Out-of-Bounds Access:
Accessing indices outside 0 to arraySize - 1 results in undefined behavior.
Personal Note: This is a common security risk. Be cautious with loop limits.
Traversing Arrays
Forward Traversal:
for (int i = 0; i < 5; i++) {
printf("%d\n", values[i]);
}
Backward Traversal:
for (int i = 4; i >= 0; i--) {
printf("%d\n", values[i]);
}
◇Common Pitfalls
Off-by-one errors — valid indices for arr[n] are 0 to n-1; accessing arr[n] is out of bounds Forgetting to initialize all elements — uninitialized local arrays contain garbage values in C Using <= instead of < in traversal loops — for (i = 0; i <= n; i++) accesses one element past the array Reversing traversal direction without adjusting bounds — backward traversal starts at n-1 and ends at 0 (inclusive)
◇Summary
TL;DR — 1D arrays are declared as
type name[size], zero-indexed (0tosize-1). Initialize with{}or a loop. Traverse forward (i = 0ton-1) or backward (i = n-1to0). Always guard against out-of-bounds access.
◇Links
Related: Source / Reference:
◇References & Navigation
- Previous Topic: ◇Dimensions of Arrays
- Next Topic: ◇Two-Dimensional Arrays (2D Arrays)
- Related Notes: ◇Dimensions of Arrays, ◇Two-Dimensional Arrays (2D Arrays)
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
Which best describes a 1D array?
How do you access the very first element of a 1D array named list?
In a 1D array of size N, what is the index of the last element?