Data Structure Array
Data Structure Array
LINEAR DATA STRUCTURE Array: Representation of arrays, Applications of arrays, sparse matrix and its
representation
What is an Array?
• An array is a linear data structure that stores a fixed-size sequential collection of elements of
the same data type in contiguous memory locations.
• It provides a simple, efficient way to store and access multiple values using a single variable
name and index.
“”An array is a collection of elements stored at contiguous memory locations, accessible using an
index.””
Why Arrays Are Needed?
Imagine you want to store marks of 100 students:
Without arrays:
int mark1, mark2, mark3, ..., mark100;
— Tedious, error-prone, and not scalable.
With arrays:
int marks[100];
— One variable handles all 100 values with efficient access like marks[0], marks[1], etc.
Real-Life Analogy:
Think of an array as:
• A row of lockers: numbered boxes (indices) containing items (values)
• A train with coaches: each coach (element) has a fixed position and same type (e.g.,
passenger coach)
P a g e 1 | 19
Data Structure
# Characteristic Explanation
1 Fixed Size Size must be declared at creation (e.g., int arr[10])
2 Homogeneous Elements All elements must be of the same data type (int, float, etc.)
3 Contiguous Memory All elements are stored next to each other in memory
4 Random Access Any element can be accessed directly using its index (O(1)
time)
5 Indexed Access Indexing starts from 0 up to n–1 (if size is n)
6 Efficient Traversal Elements can be looped using for, while, etc.
7 Static Memory Allocation Memory is allocated at compile time (for standard arrays)
8 Ease of Use Syntax is simple and operations are easy to implement
9 Multidimensional Support Arrays can be 1D, 2D, 3D and beyond
10 Limitation in Inserting/removing elements in the middle requires shifting
Insertion/Deletion
Advantages of Arrays
Disadvantages of Arrays
P a g e 2 | 19
Data Structure
Summary:
Advantages Disadvantages
Fast access via index (O(1)) Fixed size, static allocation
Easy traversal Costly insertion/deletion
Cache-friendly Wasted memory if overestimated
Foundation for other DS Poor for dynamic use cases
Component Meaning
data_type Type of elements (e.g., int, float)
array_name Name of the array variable
size Total number of elements in the array
P a g e 3 | 19
Data Structure
2. Initialization of Array
Arrays can be initialized during or after declaration.
Method 1: Declaration + Initialization
int a[4] = {10, 20, 30, 40};
• Stores 10 in a[0], 20 in a[1], and so on.
Important Notes:
• Index starts at 0, ends at size – 1.
• Accessing an index outside range causes undefined behavior.
• Array name (like arr) is a constant pointer to the first element &arr[0].
#include <stdio.h>
int main() {
int arr[5] = {2, 4, 6, 8, 10};
P a g e 4 | 19
Data Structure
}
return 0;
}
Summary Table
Declaration Style Example
Fixed size + values int a[4] = {1, 2, 3, 4};
Partial initialization int a[4] = {1, 2}; → rest = 0
Size auto-detected int a[] = {1, 2, 3};
Element-wise assignment a[0] = 5; a[1] = 10;
Understanding how arrays are stored in memory helps students grasp how indexing, access time, and
pointer arithmetic work. This is essential for algorithm design, performance optimization, and
interview readiness.
Example
int arr[4] = {10, 20, 30, 40};
Assume:
• int size = 4 bytes
• Base address = 1000
P a g e 5 | 19
Data Structure
Operations on 1D Arrays
Arrays support a wide range of operations essential for manipulating data. First, let’s look at the
summary table, and then we’ll explain each one in detail with examples and C programs.
printf("Array elements:\n");
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
Time Complexity: O(n)
Each element is visited once.
P a g e 7 | 19
Data Structure
Step-by-Step Algorithm:
1. Start
2. Declare an array arr[ ] and variables n (number of elements), val (value to insert), and pos
(position to insert).
3. Input n (number of elements in the array).
4. Input n elements into the array.
5. Ask the user for insertion type:
o 1 for beginning
o 2 for middle
o 3 for end
6. Input the value to be inserted (val).
7. If inserting at beginning:
o Shift all elements from end to start by one position.
o Place val at arr[0].
8. If inserting at middle (position pos):
o Ensure pos is in range (0 to n).
o Shift elements from end to pos by one position.
o Insert val at arr[pos].
9. If inserting at end:
o Place val at arr[n].
10. Increment n to reflect new size.
11. Display the updated array.
12. End
int main() {
int arr[100], n, val, pos, choice;
P a g e 8 | 19
Data Structure
return 0;
}
P a g e 9 | 19
Data Structure
Step-by-Step Algorithm:
1. Start
2. Declare an array arr[ ], size n, and variable pos for the position to delete.
3. Input the number of elements n and read n array elements.
4. Ask user for deletion type:
o 1 = Beginning
o 2 = Specific position (Middle)
o 3 = End
5. If deleting from beginning:
o Shift all elements left by one starting from index 1.
6. If deleting from a middle position (position pos):
o Check if pos is in valid range (0 to n-1).
o Shift elements left from pos+1 onward.
7. If deleting from end:
o Just reduce n by 1 (no shifting needed).
8. Decrement n (array size reduces).
9. Display the updated array.
10. End
P a g e 10 | 19
Data Structure
return 0;
}
Time Complexity:
• Beginning or Middle: O(n) due to shifting
• End: O(1)
P a g e 11 | 19
Data Structure
int main() {
int arr[100], n, pos, newVal;
// Input array
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
printf("arr[%d]: ", i);
scanf("%d", &arr[i]);
}
return 0;
}
Time Complexity: O(1)
P a g e 12 | 19
Data Structure
c
CopyEdit
#include <stdio.h>
int main() {
int arr[100], n, key, found = 0;
// Input array
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
printf("arr[%d]: ", i);
scanf("%d", &arr[i]);
}
if (!found) {
printf("Element not found in the array.\n");
}
return 0;
}
Time Complexity: O(n)
Algorithm Steps:
1. Start
2. Declare array arr[ ], size n, and loop counters i and j.
3. Input n and array elements.
4. Initialize two pointers:
P a g e 13 | 19
Data Structure
oi = 0 (start)
oj = n - 1 (end)
5. While i < j:
o Swap arr[i] and arr[j]
o Increment i, decrement j
6. Print the reversed array.
7. End
// Input array
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
printf("arr[%d]: ", i);
scanf("%d", &arr[i]);
}
return 0;
}
Time Complexity: O(n/2) = O(n)
Bubble Sorting:
1. Compare adjacent elements.
2. Swap them if they are in the wrong order.
3. Repeat for all elements until the entire array is sorted.
After each pass, the largest element is "bubbled" to its correct position at the end.
Example:
#include <stdio.h>
P a g e 14 | 19
Data Structure
int main() {
int arr[100], n, temp;
// Input
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Output
printf("Sorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Time Complexity:
• Best Case: O(n) (if optimized)
• Worst/Average: O(n²)
What is a 2D Array?
A 2D array is a collection of elements arranged in rows and columns, forming a matrix-like structure.
It's essentially an “array of arrays”.
• Think of it like a table:
int marks[3][4]; // 3 rows × 4 columns
P a g e 15 | 19
Data Structure
Syntax of Declaration
data_type array_name[rows][columns];
Examples:
int a[3][4]; // 3 rows, 4 columns
float temperature[7][2]; // 7 days, 2 times/day
char name[5][10]; // 5 strings, each of length 10
Initialization of 2D Arrays
Method 1: Static Initialization
int a[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
OR
int a[2][3] = {1, 2, 3, 4, 5, 6}; // Fills row-wise
Accessing Elements
a[0][0] = 5;
printf("%d", a[1][2]); // Access row 1, column 2
Access is always done using two indices: a[i][j]
Output Example:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
Key Points:
• Indexing starts from 0: a[0][0]
• Must specify both dimensions at declaration
• Cannot dynamically change dimensions at runtime in static arrays
• C stores 2D arrays in row-major order
.
Applications of 2D Arrays
2D arrays are extensively used in both academic problems and real-world applications due to their
structured format. Here’s a summary:
Why It Matters:
In C, even a 2D array is stored in linear memory (RAM). Understanding how 2D arrays are stored
internally helps in:
• Calculating addresses manually
• Optimizing memory access
• Solving pointer-based problems
P a g e 17 | 19
Data Structure
Order Description
Row-Major Elements are stored row by row (C, C++, Python use this)
Column-Major Elements are stored column by column (used in Fortran, MATLAB)
Example: 2D Array
int a[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
Visual Layout:
Row 0 → 10 20 30
Row 1 → 40 50 60
In Row-Major memory:
Memory layout: [10] [20] [30] [40] [50] [60]
Indexes: a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
Example Calculation
Given:
int a[3][4]; // 3 rows, 4 columns
int size = 4; // size of int = 4 bytes
Base address = 1000
Find Address of a[2][3]
Row-Major:
Address = 1000 + 4 × (2 × 4 + 3)
= 1000 + 4 × (8 + 3)
= 1000 + 4 × 11
= 1000 + 44
= 1044
Column-Major:
Address = 1000 + 4 × (3 × 3 + 2)
= 1000 + 4 × 11
= 1044
P a g e 18 | 19
Data Structure
P a g e 19 | 19