0% found this document useful (0 votes)
13 views25 pages

Data Structures in C: Overview & Applications

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views25 pages

Data Structures in C: Overview & Applications

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1

Data Structures and its applications (B24CS0302)

Data structures in C refer to ways of organizing and storing data in a computer's memory to enable
efficient access and modification. They are fundamental to programming and algorithm design.

Common Data Structures in C:

 Arrays:

Collections of elements of the same data type stored in contiguous memory locations, accessed by
an index.

 Linked Lists:

Collections of nodes where each node contains data and a pointer to the next node, allowing for
dynamic memory allocation and efficient insertion/deletion.

 Stacks:

Linear data structures that follow the Last-In, First-Out (LIFO) principle, where elements are added
and removed from the same end (the "top").

 Queues:

Linear data structures that follow the First-In, First-Out (FIFO) principle, where elements are added
at one end (the "rear") and removed from the other (the "front").

 Trees:

Non-linear data structures consisting of nodes connected in a hierarchical manner, with a root node
and child nodes. Examples include binary trees, binary search trees, and AVL trees.

 Graphs:

Non-linear data structures consisting of a set of vertices (nodes) and edges (connections) between
them, representing relationships between data elements.

 Hash Tables:

Data structures that map keys to values using a hash function, providing fast average-case lookup,
insertion, and deletion times.

Applications of Data Structures in C:

 Arrays: Storing lists of items (e.g., student grades, product inventories), implementing
matrices.

 Linked Lists: Implementing dynamic lists, managing memory, representing polynomials.

 Stacks: Function call management (recursion), expression evaluation, undo/redo


functionality in applications.
2
Data Structures and its applications (B24CS0302)

 Queues: Task scheduling, managing print jobs, simulating real-world waiting lines.

 Trees: Representing hierarchical data (e.g., file systems, organization charts), implementing
search algorithms (binary search trees), database indexing.

 Graphs: Network routing, social network analysis, shortest path algorithms (e.g., Dijkstra's
algorithm).

 Hash Tables: Implementing dictionaries, symbol tables in compilers, caching systems.

Operations on Data Structures:

Common operations performed on data structures include:

 Traversing: Visiting each element in the data structure.

 Searching: Finding a specific element within the data structure.

 Inserting: Adding a new element to the data structure.

 Deleting: Removing an existing element from the data structure.

 Sorting: Arranging elements in a specific order.

 Merging: Combining elements from two data structures.

Classifications of Data Structures

In C programming, data types are classified into two main categories: primitive (or basic) and
non-primitive (or derived/user-defined).

1. Primitive Data Types:

Primitive data types are fundamental data types predefined in the C language. They represent
simple values and have a fixed size and range of values.

 Integer Types:

Used to store whole numbers.

 char: Stores a single character or a small integer value.

 short: Stores short integer values.

 int: Stores integer values, typically the natural size for the architecture.

 long: Stores larger integer values than int.

 long long: Stores even larger integer values, introduced in C99.


3
Data Structures and its applications (B24CS0302)

 These can be further modified with signed (default) or unsigned to specify whether
they can hold negative values or only non-negative values.

Floating-Point Types:

Used to store numbers with decimal points.

 float: Stores single-precision floating-point numbers.

 double: Stores double-precision floating-point numbers, offering higher precision


than float.

 long double: Stores extended-precision floating-point numbers.

2. Non-Primitive Data Types:

Non-primitive data types are derived from primitive data types or are constructed using
them. They can store collections of values or represent more complex data structures.

 Arrays: A collection of elements of the same data type stored in contiguous memory
locations.

int numbers[5]; // An array of 5 integers

 Structures (struct): A collection of elements of different data types grouped under a single
name.

struct Student {
char name[50];
int roll_no;
float marks;
};
 Unions (union): Similar to structures, but all members share the same memory
location. Only one member can hold a value at a time.

union Data

{
int i;
float f;
char c;
};
 Pointers: Variables that store memory addresses of other variables. They are crucial for
dynamic memory allocation and working with data structures like linked lists.

int *ptr; // A pointer to an integer

 Enums (enum): User-defined data types consisting of a set of named integer constants.

enum Weekday { Monday, Tuesday, Wednesday };


4
Data Structures and its applications (B24CS0302)

What is an Array?

An array is a type of linear data structure that is defined as a collection of elements with same
or different data types. They exist in both single dimension and multiple dimensions. These data
structures come into picture when there is a necessity to store multiple elements of similar
nature together at one place.

The difference between an array index and a memory address is that the array index acts like a
key value to label the elements in the array. However, a memory address is the starting address
of free memory available.

Following are the important terms to understand the concept of Array.

 Element − Each item stored in an array is called an element.

 Index − Each location of an element in an array has a numerical index, which is used to
identify the element.

Syntax

Creating an array in C and C++ programming languages −

data_type array_name[array_size]={elements separated by commas}

or,

data_type array_name[array_size];

Creating an array in Java programming language −

data_type[] array_name = {elements separated by commas}

or,
5
Data Structures and its applications (B24CS0302)

data_type array_name = new data_type[array_size];

Advertisement

Need for Arrays

Arrays are used as solutions to many problems from the small sorting problems to more
complex problems like travelling salesperson problem. There are many data structures other
than arrays that provide efficient time and space complexity for these problems, so what makes
using arrays better? The answer lies in the random access lookup time.

Arrays provide O(1) random access lookup time. That means, accessing the 1st index of the
array and the 1000th index of the array will both take the same time. This is due to the fact that
array comes with a pointer and an offset value. The pointer points to the right location of the
memory and the offset value shows how far to look in the said memory.

array_name[index]

| |

Pointer Offset

Therefore, in an array with 6 elements, to access the 1st element, array is pointed towards the
0th index. Similarly, to access the 6th element, array is pointed towards the 5th index.

Array Representation

Arrays are represented as a collection of buckets where each bucket stores one element. These
buckets are indexed from '0' to 'n-1', where n is the size of that particular array. For example, an
array with size 10 will have buckets indexed from 0 to 9.

This indexing will be similar for the multidimensional arrays as well. If it is a 2-dimensional
array, it will have sub-buckets in each bucket. Then it will be indexed as array_name[m][n],
where m and n are the sizes of each level in the array.
6
Data Structures and its applications (B24CS0302)

As per the above illustration, following are the important points to be considered.

 Index starts with 0.

 Array length is 9 which means it can store 9 elements.

 Each element can be accessed via its index. For example, we can fetch an element at index 6
as 23.

Basic Operations in Arrays

The basic operations in the Arrays are insertion, deletion, searching, display, traverse, and
update. These operations are usually performed to either modify the data in the array or to
report the status of the array.

Following are the basic operations supported by an array.

 Traverse − print all the array elements one by one.

 Insertion − Adds an element at the given index.

 Deletion − Deletes an element at the given index.

 Search − Searches an element using the given index or by the value.

 Update − Updates an element at the given index.

 Display − Displays the contents of the array.


7
Data Structures and its applications (B24CS0302)

In C, when an array is initialized with size, then it assigns defaults values to its elements in
following order.

Data Type Default Value

bool false

char 0

int 0

float 0.0

double 0.0f

void

wchar_t 0

Array - Insertion Operation

In the insertion operation, we are adding one or more elements to the array. Based on the
requirement, a new element can be added at the beginning, end, or any given index of array.
This is done using input statements of the programming languages.

Algorithm

Following is an algorithm to insert elements into a Linear Array until we reach the end of the
array −

1. Start

2. Create an Array of a desired datatype and size.

3. Initialize a variable 'i' as 0.

4. Enter the element at ith index of the array.

5. Increment i by 1.

6. Repeat Steps 4 & 5 until the end of the array.

7. Stop
8
Data Structures and its applications (B24CS0302)

Example

Here, we see a practical implementation of insertion operation, where we add data at the end of
the array −

#include <stdio.h>

int main(){

int LA[3] = {}, i;

printf("Array Before Insertion:\n");

for(i = 0; i < 3; i++)

printf("LA[%d] = %d \n", i, LA[i]);

printf("Inserting Elements.. \n");

printf("The array elements after insertion :\n"); // prints array values

for(i = 0; i < 3; i++) {

LA[i] = i + 2;

printf("LA[%d] = %d \n", i, LA[i]);

return 0;

Output

Array Before Insertion:

LA[0] = 0

LA[1] = 0

LA[2] = 0

Inserting elements..

Array After Insertion:

LA[0] = 2

LA[1] = 3

LA[2] = 4
9
Data Structures and its applications (B24CS0302)

LA[3] = 5

LA[4] = 6

Array - Deletion Operation

In this array operation, we delete an element from the particular index of an array. This deletion
operation takes place as we assign the value in the consequent index to the current index.

Algorithm

Consider LA is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to delete an element available at the Kth position of LA.

1. Start

2. Set J = K

3. Repeat steps 4 and 5 while J < N

4. Set LA[J] = LA[J + 1]

5. Set J = J+1

6. Set N = N-1

7. Stop

Example

Following are the implementations of this operation in various programming languages −

#include <stdio.h>

void main(){

int LA[] = {1,3,5};

int n = 3;

int i;

printf("The original array elements are :\n");

for(i = 0; i<n; i++)

printf("LA[%d] = %d \n", i, LA[i]);

for(i = 1; i<n; i++) {

LA[i] = LA[i+1];
10
Data Structures and its applications (B24CS0302)

n = n - 1;

printf("The array elements after deletion :\n");

for(i = 0; i<n; i++)

printf("LA[%d] = %d \n", i, LA[i]);

Output

The original array elements are :

LA[0] = 1

LA[1] = 3

LA[2] = 5

The array elements after deletion :

LA[0] = 1

LA[1] = 5

Array - Search Operation

Searching an element in the array using a key; The key element sequentially compares every
value in the array to check if the key is present in the array or not.

Algorithm

Consider LA is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to find an element with a value of ITEM using sequential search.

1. Start

2. Set J = 0

3. Repeat steps 4 and 5 while J < N

4. IF LA[J] is equal ITEM THEN GOTO STEP 6

5. Set J = J +1

6. PRINT J, ITEM

7. Stop
11
Data Structures and its applications (B24CS0302)

Example

Following are the implementations of this operation in various programming languages −

#include <stdio.h>

void main(){

int LA[] = {1,3,5,7,8};

int item = 5, n = 5;

int i = 0, j = 0;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

for(i = 0; i<n; i++) {

if( LA[i] == item ) {

printf("Found element %d at position %d\n", item, i+1);

Output

The original array elements are :

LA[0] = 1

LA[1] = 3

LA[2] = 5

LA[3] = 7

LA[4] = 8

Found element 5 at position 3

Array - Traversal Operation


12
Data Structures and its applications (B24CS0302)

This operation traverses through all the elements of an array. We use loop statements to carry
this out.

Algorithm

Following is the algorithm to traverse through all the elements present in a Linear Array −

1 Start

2. Initialize an Array of certain size and datatype.

3. Initialize another variable i with 0.

4. Print the ith value in the array and increment i.

5. Repeat Step 4 until the end of the array is reached.

6. End

Example

Following are the implementations of this operation in various programming languages −

#include <stdio.h>

int main(){

int LA[] = {1,3,5,7,8};

int item = 10, k = 3, n = 5;

int i = 0, j = n;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

Output

The original array elements are :

LA[0] = 1

LA[1] = 3

LA[2] = 5
13
Data Structures and its applications (B24CS0302)

LA[3] = 7

LA[4] = 8

Array - Update Operation

Update operation refers to updating an existing element from the array at a given index.

Algorithm

Consider LA is a linear array with N elements and K is a positive integer such that K<=N.
Following is the algorithm to update an element available at the Kth position of LA.

1. Start

2. Set LA[K-1] = ITEM

3. Stop

Example

Following are the implementations of this operation in various programming languages −

#include <stdio.h>

void main(){

int LA[] = {1,3,5,7,8};

int k = 3, n = 5, item = 10;

int i, j;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

LA[k-1] = item;

printf("The array elements after updation :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

}
14
Data Structures and its applications (B24CS0302)

Output

The original array elements are :

LA[0] = 1

LA[1] = 3

LA[2] = 5

LA[3] = 7

LA[4] = 8

The array elements after updation :

LA[0] = 1

LA[1] = 3

LA[2] = 10

LA[3] = 7

LA[4] = 8

Array - Display Operation

This operation displays all the elements in the entire array using a print statement.

Algorithm

Consider LA is a linear array with N elements. Following is the algorithm to display an array
elements.

1. Start

2. Print all the elements in the Array

3. Stop

Example

Following are the implementations of this operation in various programming languages −

#include <stdio.h>

int main(){

int LA[] = {1,3,5,7,8};

int n = 5;
15
Data Structures and its applications (B24CS0302)

int i;

printf("The original array elements are :\n");

for(i = 0; i<n; i++) {

printf("LA[%d] = %d \n", i, LA[i]);

Output

The original array elements are :

LA[0] = 1

LA[1] = 3

LA[2] = 5

LA[3] = 7

LA[4] = 8

Array is a collection of items of the same variable type that are stored at contiguous memory
locations. It is one of the most popular and simple data structures used in programming.

Basic terminologies of Array

 Array Index: In an array, elements are identified by their indexes. Array index starts from
0.

 Array element: Elements are items stored in an array and can be accessed by their index.

 Array Length: The length of an array is determined by the number of elements it can
contain.

Memory representation of Array

In an array, all the elements are stored in contiguous memory locations. So, if we initialize an
array, the elements will be allocated sequentially in memory. This allows for efficient access and
manipulation of elements.

Declaration of Array
16
Data Structures and its applications (B24CS0302)

Arrays can be declared in various ways in different languages. For better illustration, below are
some language-specific array declarations:

// This array will store integer type element

int arr[5];

// This array will store char type element

char arr[10];

// This array will store float type element

float arr[20];

Initialization of Array

Arrays can be initialized in different ways in different languages. Below are some language-
specific array initializations:

int arr[] = { 1, 2, 3, 4, 5 };

char arr[5] = { 'a', 'b', 'c', 'd', 'e' };

float arr[10] = { 1.4, 2.0, 24, 5.0, 0.0 };

Why do we Need Arrays?

Assume there is a class of five students and if we have to keep records of their marks in
examination then, we can do this by declaring five variables individual and keeping track of
records but what if the number of students becomes very large, it would be challenging to
manipulate and maintain the data.

What it means is that, we can use normal variables (v1, v2, v3, ..) when we have a small number
of objects. But if we want to store a large number of instances, it becomes difficult to manage
them with normal variables.

The idea of an array is to represent many instances in one variable.


17
Data Structures and its applications (B24CS0302)

Types of Arrays

Arrays can be classified in two ways:

 On the basis of Size


18
Data Structures and its applications (B24CS0302)

 On the basis of Dimensions

Types of Arrays on the basis of Size

1. Fixed Sized Arrays

We cannot alter or update the size of this array. Here only a fixed size (i,e. the size that is
mentioned in square brackets []) of memory will be allocated for storage. In case, we don't
know the size of the array then if we declare a larger size and store a lesser number of elements
will result in a wastage of memory or we declare a lesser size than the number of elements then
we won't get enough memory to store all the elements. In such cases, static memory allocation
is not preferred.

// Method 1 to create a fixed sized array.

// Here the memory is allocated at compile time.

int arr[5];
19
Data Structures and its applications (B24CS0302)

// Another way (creation and initialization both)

int arr2[5] = {1, 2, 3, 4, 5};

// Method 2 to create a fixed sized array

// Here memory is allocated at run time (Also

// known as dynamically allocated arrays)

int *arr = new int[5];

2. Dynamic Sized Arrays

The size of the array changes as per user requirements during execution of code so the coders
do not have to worry about sizes. They can add and removed the elements as per the need. The
memory is mostly dynamically allocated and de-allocated in these arrays.

#include<vector>

// Dynamic Integer Array

vector<int> v;

Types of Arrays on the basis of Dimensions

1. One-dimensional Array(1-D Array): You can imagine a 1d array as a row, where


elements are stored one after another

2. Multi-dimensional Array: A multi-dimensional array is an array with more than one


dimension. We can use multidimensional array to store complex data in the form of tables, etc.
We can have 2-D arrays, 3-D arrays, 4-D arrays and so on.
20
Data Structures and its applications (B24CS0302)

 Two-Dimensional Array(2-D Array or Matrix): 2-D Multidimensional arrays can be


considered as an array of arrays or as a matrix consisting of rows and columns.

 Three-Dimensional Array(3-D Array): A 3-D Multidimensional array contains three


dimensions, so it can be considered an array of two-dimensional arrays.

Operations on Array

1. Array Traversal
21
Data Structures and its applications (B24CS0302)

Array traversal refers to the process of accessing and processing each element of an array
sequentially. This is one of the most fundamental operations in programming, as arrays are
widely used data structures for storing multiple elements in a single variable.

How Array Traversal Works?

When an array is created, it occupies a contiguous block of memory where elements are stored
in an indexed manner. Each element can be accessed using its index, which starts from 0 in
most programming languages.

For example, consider an array containing five integers:

arr = [10, 20, 30, 40, 50]

Here:

 The first element (10) is at index 0.

 The second element (20) is at index 1.

 The last element (50) is at index 4.

Array traversal means accessing each element from start to end (or sometimes in reverse
order), usually by using a loop.

Types of Array Traversal

Array traversal can be done in multiple ways based on the requirement:

1. Sequential (Linear) Traversal

 This is the most common way of traversing an array.

 It involves iterating through the array one element at a time from the first index to
the last.

 Used for printing elements, searching, or performing calculations (such as sum or


average).

2. Reverse Traversal

 Instead of starting from index 0, the traversal begins from the last element and
moves towards the first.

 This is useful in cases where we need to process elements from the end.

2. Insertion in Array
22
Data Structures and its applications (B24CS0302)

Insertion in an array refers to the process of adding a new element at a specific position while
maintaining the order of the existing elements. Since arrays have a fixed size in static
implementations, inserting an element often requires shifting existing elements to make space.

How Insertion Works in an Array?

Arrays are stored in contiguous memory locations, meaning elements are arranged in a
sequential block. When inserting a new element, the following happens:

1. Identify the Position: Determine where the new element should be inserted.

2. Shift Elements: Move the existing elements one position forward to create space for the
new element.

3. Insert the New Element: Place the new value in the correct position.

4. Update the Size (if applicable): If the array is dynamic, its size is increased.

For example, if we have the array:

arr = [10, 20, 30, 40, 50]

and we want to insert 25 at index 2, the new array will be:

arr = [10, 20, 25, 30, 40, 50]

Here, elements 30, 40, and 50 have shifted right to make space.

Types of Insertion

1. Insertion at the Beginning (Index 0)

 Every element must shift one position right.

 This is the least efficient case for large arrays as it affects all elements.

2. Insertion at a Specific Index

 Elements after the index shift right.

 If the index is in the middle, half of the array moves.

3. Insertion at the End

 The simplest case since no shifting is required.

 Used in dynamic arrays where size increases automatically (e.g., Python lists,
Java ArrayList).

To read more about Insertion in Array Refer, Inserting Elements in an Array – Array Operations
23
Data Structures and its applications (B24CS0302)

3. Deletion in Array

Deletion in an array refers to the process of removing an element from a specific position while
maintaining the order of the remaining elements. Unlike linked lists, where deletion is efficient,
removing an element from an array requires shifting elements to fill the gap.

How Deletion Works in an Array?

Since arrays have contiguous memory allocation, deleting an element does not reduce the
allocated memory size. Instead, it involves:

1. Identify the Position: Find the index of the element to be deleted.

2. Shift Elements: Move the elements after the deleted element one position to the left.

3. Update the Size (if applicable): If using a dynamic array, the size might be reduced.

For example, consider the array:

arr = [10, 20, 30, 40, 50]

If we delete the element 30 (index 2), the new array will be:

arr = [10, 20, 40, 50]

Here, elements 40 and 50 shifted left to fill the gap.

Types of Deletion

1. Deletion at the Beginning (Index 0)

 Every element shifts left by one position.

 This is the most expensive case as it affects all elements.

2. Deletion at a Specific Index

 Only elements after the index shift left.

 If the index is in the middle, half of the array moves.

3. Deletion at the End

 The simplest case since no shifting is required.

 The size of the array is reduced (in dynamic arrays).

4. Searching in Array
24
Data Structures and its applications (B24CS0302)

Searching in an array refers to the process of finding a specific element in a given list of
elements. The goal is to determine whether the element exists in the array and, if so, find its
index (position).

Searching is a fundamental operation in programming, as it is used in data retrieval, filtering,


and processing.

Types of Searching in an Array

There are two main types of searching techniques in an array:

1. Linear Search (Sequential Search)

 This is the simplest search algorithm.

 It traverses the array one element at a time and compares each element with the target
value.

 If a match is found, it returns the index of the element.

 If the element is not found, the search continues until the end of the array.

Example:

Consider an array:

arr = [10, 20, 30, 40, 50]

If we search for 30, the algorithm will:

1. Compare 10 with 30 → No match.

2. Compare 20 with 30 → No match.

3. Compare 30 with 30 → Match found at index 2.

2. Binary Search (Efficient Search for Sorted Arrays)

 Works only on sorted arrays (in increasing or decreasing order).

 Uses a divide and conquer approach.

 It repeatedly divides the search space in half until the target element is found.

How Binary Search Works?

1. Find the middle element of the array.

2. If the target is equal to the middle element, return its index.

3. If the target is less than the middle element, search the left half.
25
Data Structures and its applications (B24CS0302)

4. If the target is greater than the middle element, search the right half.

5. Repeat until the element is found or the search space is empty.

Example:

Consider a sorted array:

arr = [10, 20, 30, 40, 50]

If we search for 30:

1. Middle element = 30 → Match found!

2. The search ends in just one step, making it much faster than linear search.

You might also like