Data Structures using C
Arrays
Module I: Arrays. Arrays are one of the most fundamental data structures in C. They are used to store multiple elements of the same data type in contiguous memory locations and provide efficient access through indexes.
Introduction to Arrays
An array stores a collection of similar elements under a single variable name. Each element is accessed using an index, and indexing starts from 0 in C.
- Stores multiple values using one variable
- Elements occupy contiguous memory locations
- Allows direct access through indexes
Declaration and Initialization
Arrays are declared using a data type, array name and size.
int numbers[5];
int values[5] = {10,20,30,40,50};Common Array Operations
Arrays support several common operations used to manipulate and process elements.
Accessing Elements
Individual elements are accessed using indexes.
int arr[5]={10,20,30,40,50};
printf("%d",arr[2]);Time Complexity: O(1)
Traversal
Traversal means visiting each element of the array one by one.
for(int i=0;i<5;i++){
printf("%d ",arr[i]);
}Time Complexity: O(n)
Searching
Searching is used to find a specific element in an array.
int key=30;
for(int i=0;i<5;i++){
if(arr[i]==key)
printf("Found");
}Time Complexity: O(n)
Insertion
Insertion adds a new element at a specific position by shifting elements.
for(int i=n;i>pos;i--){
arr[i]=arr[i-1];
}
arr[pos]=value;Time Complexity: O(n)
Deletion
Deletion removes an element and shifts remaining elements.
for(int i=pos;i<n-1;i++){
arr[i]=arr[i+1];
}Time Complexity: O(n)
Updating Elements
Updating changes an existing value using its index.
arr[1]=100;
Time Complexity: O(1)
Applications of Arrays
- Searching algorithms
- Sorting algorithms
- Matrix representation
- Implementation of stacks and queues
Advantages of Arrays
- Fast access using indexes
- Easy traversal of elements
- Efficient memory usage for fixed-size data
Limitations of Arrays
- Fixed size once declared
- Insertion and deletion operations are costly
- Stores only same data type elements
Ready to test your Module I: Arrays knowledge?
Module I: Arrays
Test your fundamental knowledge of array data structures in C, covering properties, time complexities, and common operations.