C Arrays - Complete Guide
Master C arrays including 1D and 2D arrays with detailed syntax, practical examples, memory representation, and programming best practices.
1D & 2D Arrays
Complete coverage
Memory Representation
Visual understanding
Matrix Operations
Real-world applications
Introduction to C Arrays
Arrays are fundamental data structures in C that store a collection of elements of the same type in contiguous memory locations. They provide efficient access to elements using indices and are essential for handling multiple data items.
Why Use Arrays?
- Memory Efficiency: Contiguous memory allocation
- Fast Access: O(1) access time using index
- Code Simplicity: Single name for multiple elements
- Loop Integration: Perfect with for/while loops
- Data Organization: Structured data storage
Array Types in C
- 1D Arrays: Linear collection of elements
- 2D Arrays: Table/matrix of elements
- Multidimensional Arrays: 3D, 4D, etc.
- Character Arrays: Strings
- Array of Pointers: Advanced usage
Important Array Concepts
Arrays in C are fixed-size collections stored in contiguous memory. Elements are accessed using zero-based indexing. Array name represents the base address of the first element.
Array Types Comparison
Here is a comprehensive comparison of array types in C with their key characteristics:
| Array Type | Syntax | Memory Layout | When to Use |
|---|---|---|---|
|
1D Array
Single dimension
|
|
[0]
[1]
[2]
[3]
[4]
|
|
|
2D Array
Rows × Columns
|
|
[0][0]
[0][1]
[0][2]
[1][0]
[1][1]
[1][2]
|
|
1D Arrays - Complete Guide
One-dimensional arrays store elements in a linear sequence. Each element is accessed using a single index with zero-based indexing.
Syntax:
data_type array_name[array_size];
Key Characteristics:
- Zero-based indexing: First element at index 0
- Contiguous memory: Elements stored in adjacent memory locations
- Fixed size: Size determined at compile time
- Fast access: O(1) access time using index
1D Array Examples:
#include <stdio.h>
int main() {
// Method 1: Declaration then initialization
int numbers[5]; // Declaration
numbers[0] = 10; // Initialization
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Method 2: Declaration with initialization
int scores[] = {85, 90, 78, 92, 88}; // Size automatically calculated
// Method 3: Partial initialization (rest are 0)
int data[10] = {1, 2, 3}; // data[3] to data[9] are 0
// Method 4: All zeros
int zeros[10] = {0};
// Display array elements
printf("Scores array:\n");
for(int i = 0; i < 5; i++) {
printf("scores[%d] = %d\n", i, scores[i]);
}
return 0;
}
Scores array:
scores[0] = 85
scores[1] = 90
scores[2] = 78
scores[3] = 92
scores[4] = 88
#include <stdio.h>
int main() {
int arr[10];
int n = 10;
printf("Enter 10 integers:\n");
// 1. Input array elements
for(int i = 0; i < n; i++) {
printf("arr[%d] = ", i);
scanf("%d", &arr[i]);
}
// 2. Display array
printf("\nArray elements: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 3. Find sum and average
int sum = 0;
for(int i = 0; i < n; i++) {
sum += arr[i];
}
float average = (float)sum / n;
printf("Sum: %d, Average: %.2f\n", sum, average);
// 4. Find maximum and minimum
int max = arr[0];
int min = arr[0];
for(int i = 1; i < n; i++) {
if(arr[i] > max) max = arr[i];
if(arr[i] < min) min = arr[i];
}
printf("Maximum: %d, Minimum: %d\n", max, min);
// 5. Search for an element
int search, found = 0;
printf("\nEnter element to search: ");
scanf("%d", &search);
for(int i = 0; i < n; i++) {
if(arr[i] == search) {
printf("Element %d found at position %d\n", search, i);
found = 1;
break;
}
}
if(!found) printf("Element not found!\n");
// 6. Reverse the array
printf("\nArray in reverse: ");
for(int i = n-1; i >= 0; i--) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
1D Array Visualization: int numbers[5] = {10, 20, 30, 40, 50};
2D Arrays - Complete Guide
Two-dimensional arrays represent matrices or tables with rows and columns. Elements are accessed using two indices: row index and column index.
Syntax:
data_type array_name[rows][columns];
Memory Layout (Row-Major Order):
Logical View:
| [0][0] | [0][1] | [0][2] |
| [1][0] | [1][1] | [1][2] |
Memory Layout:
Key Characteristics:
- Row-major order: C stores 2D arrays row by row in memory
- Double indexing: Access elements using [row][column]
- Nested loops: Typically use nested loops for traversal
- Matrix operations: Ideal for mathematical computations
2D Array Examples:
#include <stdio.h>
int main() {
int rows = 3, cols = 3;
int A[3][3], B[3][3], C[3][3];
printf("Enter elements for Matrix A (3x3):\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
printf("A[%d][%d] = ", i, j);
scanf("%d", &A[i][j]);
}
}
printf("\nEnter elements for Matrix B (3x3):\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
printf("B[%d][%d] = ", i, j);
scanf("%d", &B[i][j]);
}
}
// Matrix Addition
printf("\n=== MATRIX ADDITION ===\n");
printf("A + B =\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
printf("%d\t", C[i][j]);
}
printf("\n");
}
// Matrix Multiplication
printf("\n=== MATRIX MULTIPLICATION ===\n");
printf("A × B =\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
C[i][j] = 0;
for(int k = 0; k < cols; k++) {
C[i][j] += A[i][k] * B[k][j];
}
printf("%d\t", C[i][j]);
}
printf("\n");
}
return 0;
}
#include <stdio.h>
void displayBoard(char board[3][3]) {
printf("\n");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf(" %c ", board[i][j]);
if(j < 2) printf("|");
}
printf("\n");
if(i < 2) printf("---+---+---\n");
}
printf("\n");
}
int main() {
char board[3][3] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'}
};
printf("=== TIC-TAC-TOE GAME ===\n");
displayBoard(board);
// Game logic would go here...
return 0;
}
Memory Calculation Formula
Total Memory = rows × columns × sizeof(data_type)
Example: int matrix[100][100] = 100 × 100 × 4 = 40,000 bytes (40 KB)
Practical Array Applications
Arrays are used in various real-world applications. Here are some practical examples:
#include <stdio.h>
int main() {
int students = 5, subjects = 3;
int marks[5][3];
char *sub_names[] = {"Math", "Science", "English"};
// Input marks
for(int i = 0; i < students; i++) {
printf("\n=== Student %d ===\n", i+1);
for(int j = 0; j < subjects; j++) {
printf("Enter marks for %s: ", sub_names[j]);
scanf("%d", &marks[i][j]);
}
}
// Calculate and display results
printf("\n=== STUDENT REPORT CARD ===\n");
printf("Student\tMath\tScience\tEnglish\tTotal\tAverage\tGrade\n");
printf("--------------------------------------------------------\n");
for(int i = 0; i < students; i++) {
int total = 0;
for(int j = 0; j < subjects; j++) {
total += marks[i][j];
}
float average = (float)total / subjects;
char grade;
if(average >= 90) grade = 'A';
else if(average >= 80) grade = 'B';
else if(average >= 70) grade = 'C';
else if(average >= 60) grade = 'D';
else grade = 'F';
printf("%d\t", i+1);
for(int j = 0; j < subjects; j++) {
printf("%d\t", marks[i][j]);
}
printf("%d\t%.2f\t%c\n", total, average, grade);
}
return 0;
}
Common Mistakes and Best Practices
Array Best Practices:
- Always initialize arrays before use
- Use symbolic constants for array sizes (#define)
- Validate array indices before access
- Pass array size as parameter when using functions
- Use sizeof() operator to calculate array size
- Choose appropriate array dimension (1D vs 2D)
- Document array purpose and structure
- Test with boundary cases (empty, single, full)
Key Takeaways
- Arrays store homogeneous elements in contiguous memory
- 1D arrays use single indexing; 2D arrays use row-column indexing
- C uses zero-based indexing (first element at index 0)
- 2D arrays are stored in row-major order in memory
- Always specify array size (except with initialization)
- Arrays are passed by reference to functions
- Use loops for array traversal and operations
- Watch for index out of bounds errors
- Arrays have fixed size determined at compile time
- Initialize arrays to avoid garbage values