https://github.com/roseewood/dsa
Learn Data Structures and Algorithms
https://github.com/roseewood/dsa
c cpp data-structures-and-algorithms python
Last synced: 2 months ago
JSON representation
Learn Data Structures and Algorithms
- Host: GitHub
- URL: https://github.com/roseewood/dsa
- Owner: roseewood
- License: mit
- Created: 2025-09-03T05:49:15.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2025-09-26T17:45:00.000Z (10 months ago)
- Last Synced: 2025-09-26T19:27:18.966Z (10 months ago)
- Topics: c, cpp, data-structures-and-algorithms, python
- Language: Python
- Homepage:
- Size: 4.88 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
Data Structures and Algorithm
Introduction
What are Data Structures?
Data
Data is information that has been translated or converted into binary digital form
so that it can be efficiently processed or moved in computing systems.
The term raw data refers to data in its most basic and unprocessed form.
Why Do We Need Data Structures?
- Each data structure allows data to be stored differently.
- It enables efficient data search and retrieval.
- Specific data structures are chosen to solve specific problems.
- DS enables the management of large amounts of data such as large databases and indexing services like hash tables.
Examples
Linked List Data Structure
If we have a playlist with three songs, the second song plays after the first,
and the third song plays after the second because all songs are linked as nodes in a linked list.
Stack Data Structure
In a stack of books, we must remove the topmost book before accessing the desired book.
To add a new book, we place it on the top.
It follows the LIFO (Last In, First Out) principle.
Queue Data Structure
Any traditional queue follows the FIFO (First In, First Out) principle.
The first element inserted is the first one removed.
Graph Data Structure
Google Maps works like a graph where locations are connected and multiple paths exist.
Algorithms can be used to find the shortest path.
Array Data Structure
If searching for the word “simplilearn” in a dictionary, we look under the letter “s”.
Arrays allow indexed and ordered access.
Types of Data Structures
1. Linear Data Structure
Elements are arranged sequentially one after another.
They are simple to implement because the order is fixed.
Array Data Structure
- Elements are stored in continuous memory locations.
- All elements are of the same data type.
- The data type is predefined by the program.
┌─┐ ┌─┐ ┌─┐
│4│ │8│ │2│
└─┘ └─┘ └─┘
0 1 2
Linked List Data Structure
- Data elements are connected using nodes.
- Each node contains data and the address of the next node.
┌─┬─┐ ┌─┬─┐
│8│ │ │ │ │
└─┴─┘ └─┴─┘
(Head) (Null)
Stack Data Structure
- Follows LIFO (Last In, First Out) principle.
- Operations occur at one end called the top.
Push ↘ ↗ Pop
┌─┐
Top → │5│
└─┘
┌─┐
│7│
└─┘
┌─┐
│4│
└─┘
Queue Data Structure
- Follows FIFO (First In, First Out) principle.
- Insertion and deletion occur at opposite ends.
Insertion ↘
┌─┐ ┌─┐ ┌─┐
│5│ │7│ │4│
└─┘ └─┘ └─┘
↖ Deletion
2. Non-Linear Data Structures
Elements are not arranged sequentially.
They are organized hierarchically or interconnected.
Tree Data Structure
- The top node is called the root.
- Each node can have zero or more children.
- Nodes with no children are called leaves.
- Each child has exactly one parent except the root.
→
(8)──────(5)
│ │
↓ │ │ ↑ [8 ↘ 9]
│ │
(2)──────(9)
→
Graph Data Structure
- Consists of nodes (vertices) and edges.
- Can be directed or undirected.
- Can be weighted or unweighted.
- Can be cyclic or acyclic.
- Can be connected or disconnected.
(9)
↙ / \ ↘
/ \
(6) (5)
Importance
- Widely used in almost every aspect of computer science.
- Used in AI, graphics, big data, and operating systems.
- Essential component of algorithms.
- Proper selection improves program efficiency.
Time Complexity
Time Complexity is the amount of time an algorithm takes to run as a function of input size.
The length of the input determines how many operations the algorithms will do.
It will provide information about the variance ( increase or decrease) in execution time as the no. of operations in an algorithm increases or decreases.
Types of Time Complexity
1. Constant Time — O(1)
Execution time does not depend on input size.
When an algorithm is not reliant on the input sixe n, it is said to have constant time with order 0(1).
The run time will always be same regardless of input size (n)
main()
{
int a;
print ("Enter value of a = ");
scanf("%d", &a);
printf("a = %d", a);
}
2. Linear Time — O(n)
Execution time increases linearly with input size.
When running time of an algorithm rises linearly with the length of the inpu, it is said to have linear time complexity.
main(){
int a [5] = {2,3,5,7,9};
printf("elements of a = \n");
for(int i = 0; i<5; i++>);
printf("a= %D", a);}
Note:When a function checks all the values in an input data set,
it is said to have Time complexity of order 0(n)
3. Logarithmic Time — O(log n)
Input size is reduced in each step. Example: Binary Search.
Whena an algorithm lowers the amount of the input data in each step, it is said to have a logarithmic time complexity.
Binary trees and binary search functions are same of the algorithm with lagarithmic time complexity.
int binary Search (int arr[], int 1, int r, int x){if(r>i){
int mid = 1 +(r-1)/2;
if arr[mid] == x);
return mid;if (arr[mid] > x);
return binary search (arr, 1mid -1,x);
return binary search(arr, mid +1,r,x);
}
}
4. Quadratic Time — O(n²)
Execution time grows non-linearly, commonly seen in nested loops.
When the execution time of an algorithm rises non-lineaerly (n square) with thelength of the input, it is said to have a quadratic time complexity.
In general, nested loops fall into the quadratic time complexity order, ewhere one loop takes 0(n) and if the function contains loops inside loops, it takes
0(n) * 0(n) = 0(n square)
for (int i = 0; i);
{
for (int j=0; j);
{
printf("%d", arr[i][j])'
}
}
How to Evaluate Time Complexity
int fib (int n)
{
int f[n+2]; +1
int i; +1
f[0]= 0; +1
f[1]= 1; +1for (i =2; i<=n; i++ );
{
f[1] = f[i-1] + f[i-2]; +n
}return f[n]; +1
}
Total time taken = n + 5
Total complexity = O(n + 5)
= O(n)
Time Complexity of Algorithms
Algorithm
Best Case
Worst Case
Insertion Sort
O(n)
O(n²)
Merge Sort
O(n log n)
O(n log n)
Quick Sort
O(n log n)
O(n²)
Bubble Sort
O(n)
O(n²)
Linear Search
O(1)
O(n)
Binary Search
O(1)
O(log n)
1. Insertion Sort
void insertion sort (int arr[], int n)
{
int i, key, j;
for (i=1; i){
key = arr[i];
j=i=1;
while(j>=0 && arr [j] > key){
arr [j + 1] = arr[j];
j=j-1;}
arr [j + 1] = key;}
}
2. Merge Sort
void merge sort (int array[], int const begin, int const end)
{
if (begin >= end)
return; // Return recursivlyauto mid = begin + (end - begin)/2;
merge sort (array, begin, mid);
merge sort (array, mid + 1, end);
merge sort array, mid, begin, end;
}
3. Quick Sort
void quicksort (int arr[], int low, int high)
{
if (low < high)
{
int pi = partition (arr, low, high);
//seprately sor elements before
//partition and after partition
quicksort (arr, low, pi, 1);
quicksort (arr, pi + 1, high);
}
}
4. Bubble Sort
void bubble sort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i ++);
//last i elements are already placefor(j = 0; j < n -i - 1; j ++>);
if(arr [j]> arr[j + 1]);
swap(&arr [j], & arr[j+1]);
}
5.Linear Search
int search (int arr [], int n, int x)
{
int i;
for (i=0; i);
if (arr [i] == x);
return i;
return -1;
}
6. Binary Search
int binary Search (int arr[], int 1, int r, int x)if (r >=1){;
if (arr [mid] == x)
int mid = 1 + (r-1)/2;if (arr [mid] == x)
return mid;
if (arr[mid]>x)
return binary search (arr, 1, mid-1, x);
return binary search (arr, mid +1, r, x);
}
Conclusion
- The time of the execution increases with the type of operations we make using the inputs.
- The lesser the time complexity, the faster the execution.
- In case if a code is 1000s of lines then it takes a toll on processor of the PC. So, it is important to check and reduce the time complexity as we can.
Pointers in C
A pointer is a variable to the address of another variable . If is declared along wiht an asterisk symbol (*).
The syntax to declare a pointer is as follows:
datatype * var 1
The syntax to Assign address of a variable to a pointer is:
datatype var1, * var2
# include
using namespace std;
main()
{
int a = 5, * ptr;
ptr = &a;
cout << "a =" << a << endl;
cout << "a =" << * ptr << endl;
return 0;
}
Result
a = 5
a = 5
Types of Pointer
1. Null Pointer
When a null value is assigned to a pointer during its declaration.
int *var = NULL;# include
using namespace std;
main()
{
int *var;
*var = NULL;
cout<< *var;
return 0;
}Result:
---------------
2. Void Pointer
When a pointer is declared with a void keyword.
To print the value we need to typecast this pointer.
Syntax:
void *var;
#include
using namespace std;
main()
{
int a = 5;
void *ptr;
ptr = &a;
+------------------+
| cout << *ptr; | -------> ERROR
+------------------+
| return 0;
|
|
|
|
} |
|
|
|
Result:cout<< *(int *) ptr;
= 5
3. Wild Pointer
It is only declared but not assigned an address of any variable.
These pointers are very tricky and they may cause segmenatation errors.
#include
sung namespace std;
main()
{
int *ptr;
cout<< *ptr;
return 0;
}Result:
---------------
4. Dangling Pointer
Let's suppose there is a pointer p pointing at a variable at memory 10004. This pointer will point at a deleted variable if we dellocate this memory.
We deallocate memory using a free () function.
#include
using namespace std;
main()
{
int *ptr = (int *)m alloc(sizeof(int));
int a = 5;
ptr = &a;
free (ptr);
cout<< *ptr;
return 0;
}Result:
----------------
Use Cases
1. Pointer Arithmetic
NOTE: Pointer Arithemetic is of no use if not used in Arrays.
i) Increment (++)
We can use this operator to jump from one index to the next insex in an array.
Syntax:
ptr++
arr[0] -------------> arr[1]-----------> arr[2]
#include
using namespace.std;
main()
{
int arr [3] = {2,3,5};
int *tr;
tr = &arr [0];
for(int i = 0; i<3; i++)
{
cout <<* tr<< end l;
++;
}
return 0;
}Result:
2, 3, 5
ii) Decrement (--)
We use this operator to jump from one index to the previous index in an array.
Syntax:
ptr --
arr[2] ------------> arr[1] -------------> arr[0]
#include ;
using namespace std;
main()
{
int arr[3] = {2,3,5}
int *ptr;
ptr = & arr[2];
for (int i=0; i=3; i++)
{cout << *ptr<< endl;
ptr--;
}
return 0;
}Result:
5, 3, 2
iii) Integers added to a Pointer:
We use this operator to jump from one index to the next index in an array.
Syntax:
ptr + = i; (where 'i' is an integer)
arr[0] ------------> arr[2] -------------> arr[4]
#include ;
using namespace std;
main()
{
int arr[7] = {2,3,5,7,11,13,17}
int *ptr;
ptr = & arr[0];
int n =2;
for (int i=0; i<7>; i++)
{cout << *ptr<< endl;
ptr + n;
}
return 0;
}Result:
2, 5, 11, 17, 2
iv) Integers subtracted from a Pointer:
We use this operator to jump from one index to the previous index in an array.
Syntax:
ptr - = i; (where 'i' is an integer)
arr[2] ------------> arr[2] -------------> arr[0]
#include ;
using namespace std;
main()
{
int arr[7] = {2,3,5,7,11,13,17}
int *ptr;
ptr = & arr[6];
int n =2;
for (int i=0; i<7>; i++)
{cout << *ptr<< endl;
ptr - n;
}
return 0;
}Result:
17, 11, 5, 2
(v) Precedence
- Operators * and & are given the same priorities as unary operators (increment ++, decrement --)
- The unary operators *, &, ++, -- are ecaluated from right to left in the same expression.
- If a p pointer points to and X variable, then we can interchange X with *p.
Expression
Equivalent Expression
Y = X + 1
Y = *p + 1
X = X + 10
*p = *p + 10
X + = 2
*p += 2
++X
++ *p
X ++
(*p) ++
2. Pointer to Pointer
In this situation, a pointer will indirectly point to a variable via another pointer.
Syntax:
int **ptr
Pointer 2 ------------> Pointer 1-------------> Variable
#include ;
using namespace std;
main()
{
int var, *ptr1, **ptr2;
var 5;
ptr1 = &var;
ptr2 = &ptr1;
cout << "var=" << var << endl << "ptr1=" <<*ptr1 << endl <<"ptr2=" <<**ptr2;
}
return 0;
}Result:
var = 5
ptr1 = 5
**ptr = 25
3. Array of Pointer
An array of pointer is an array whose every element is a pointer.
Syntax:
int * arr[n] (where n is size of array)
ptr[0] ------------> ptr[1]-------------> ptr[2]
a[0] ----------> a[1] ---------->a[2]
#include ;
using namespace std;
main()
{
int a [3] = {2, 3, 5};
int *ptr[3];
for (int i=0; i<3; i++)
{
ptr[i] = &a [i];
}
for (int i = 0; i<3; i ++)
{
cout << *ptr [i] << endl;
}
return 0;
}
4. Call by Value
In call by value, we copy the variables values and pass it in function vall as a parameter. If we modify change the value of the actual variable.
Syntax:
Variable A ------------> Variable A (copy)
Variable B ------------> Variable B (copy)
#include ;
using namespace std;
main()
{
int X = 10;
func (X);
cout << X << endl;
return 0;
}
{
X = 200;
cout << "X =" << X << endl;
return 0;
}
5. Call by Reference:
In call by reference, we take the variables address and pass it in function called as a parameter.
If we modify these parameters, then it will change the value of the actual variable as well.
Syntax:
Variable A ------------> (address) Variable A
Variable B ------------> (address) Variable B
#include ;
using namespace std;
main()
{
int X = 10;
func (&X);
cout << "X=" << endl;
return 0;
}
void func (int *X)
{
X = 200;
cout << "in func function X = " << X << endl;
return 0;
}
Advantages
- Pointers are helpful to access a memory location.
- Pointers are an effective way to access the array structure elements.
- Pointers are used for the allocation of dynamic memory and the distribution.
- Pointers are used to build complecated data structures like a linked list graph, tree etc.
Disadvantages
- Poointers are a bit difficult to understand.
- Pointers acan cause several errors, such as segmentation errors or unrequired memory access.
- If a pointer has an incorrect value, it may corrupt the memeory.
- Pointers may corrupt the memory.
- The pointers are relatively slower than the variables.
Key Points
- A pointer is simply a storage location for data in memory.
- Pointers can be used to traverse the array more efficiently.
- We can use function pointers to invoke a function dynamically.
- Pointer arithemetic is the process of performing arithmetic opearations on pointer.
- In an array of pointers, it can point to functions, making it simple to call different functions.
Arrays
Need of Arrays
Ler us imagine that we were supposed keep track of the students marks and also honor them with degrees. If we done this in traditional ways of declaring individual variables for each student, then it would be time-consuming.
Example:-
Score: 1 2 3 4 5
Student: 1 2 3 4 5
So, what if there is an option where one variable could do the job of 'n' variables.
So with a similar approach, the array data structure were designed
Arrays
An array is a linear data structure that collects elements of same data type and stores them in a contiguous and adjavent memory locations.
Memory Representation
Let's create an array of five elements.
[ A ] [ R ] [ R ] [ A ] [ Y ]
Note: The element in an array are stored using memory block address and Array Index.
┌─────────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐
│ Address │→ │ 11 │ │ 12 │ │ 13 │ │ 14 │ │ 15 │
└─────────┘ └────┘ └────┘ └────┘ └────┘ └────┘
┌────────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐
│ Array │→ │ A │ │ R │ │ R │ │ A │ │ Y │
└────────┘ └────┘ └────┘ └────┘ └────┘ └────┘
┌─────────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐
│ Index │→ │ 01 │ │ 02 │ │ 03 │ │ 04 │ │ 05 │
└─────────┘ └────┘ └────┘ └────┘ └────┘ └────┘
Types
i) One Dinemsional Array
ii) Multidimensional Array
a) 2D b) 3D
1. One Dimensional Array
It requires only one subscript specify element in array.
int marks [10] = {0, 1, 2, 3, 4, 5, 6, 7, 8,9}
Elements- [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]
Index- 0 1 2 3 4 5 6 7 8 9
2. Multdimensional Array
It requires more than one subscript to specify the element in an arrays.
a) 2D Arrays
It is organised in the forn of matrix which can be represented as a collection of Rows and Columns.
int num [3] [3] ={1,2,3}, {4,5,6}, {7,8,9}
0 1 2
┌───┬───┬───┐
0 │ 1 │ 2 │ 3 │
├───┼───┼───┤
1 │ 4 │ 5 │ 6 │
├───┼───┼───┤
2 │ 7 │ 8 │ 9 │
└───┴───┴───┘
b) 3D Arrays
It is a collection of 2D arrays which consists of three subscripts- Block size, Row size and Column size.
int num [2] [3] [2] =
num[row] [col][0] num[row] [col] [1]
0 1 2 0 1 2
┌───┬───┬───┐ ┌───┬───┬───┐
0 │ │ │ │ 0 │ │ │ │
├───┼───┼───┤ ├───┼───┼───┤
1 │ │ │ │ 1 │ │ │ │
└───┴───┴───┘ └───┴───┴───┘
Declearation of Arrays
Syntax: datatype array_name[array_size];
For Example:- An array of integer can be declared as follows.
int(example) [6];
┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐
│ │ │ │ │ │ │ │ │ │ │ │
└───┘ └───┘ └───┘ └───┘ └───┘ └───┘
0 1 2 3 4 5
Compiler will allocate a contiguous memory block okf size = 6 * sizeof (int)
Initialization of Arrays
Method 1
int a [5] = {1, 2,3,4,5};
a = [1][2][3][4][5]
0 1 2 3 4
Method 2
int a [ ] = {1,2,3,4,5};
a = [1][2][3][4][5]
0 1 2 3 4
Method 3
int a [5];
a [0] = 1;
a [1] = 2;
a [2] = 3;
a [3] = 4;
a [4] = 5;
a = [1][2][3][4][5]
0 1 2 3 4
Method 4
int a [5]
for( i = 0; i < 5; i ++>)
{scanf ("%d", a[i]);
}
a = [1][2][3][4][5]
0 1 2 3 4
Accessing Elements of Array
To access an array elements: name_of_array[sizeofarray];
int xyz[5];
┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐
└───┘ └───┘ └───┘ └───┘ └───┘
0 1 2 3 4
- Accessing the first element in an array can be done using the first index.
e.g. xyz [0] - Accessing the second element in an array can be done using the second index.
e.g. xyz [1] and so on.
Operation on Array Elements
Traversal
- Traversal in an array is a process of visiting each elements once.
- It can be done by various means.
i) Counting the array elements.
ii) Printing the values stored in an arrays.
iii) Sum of elements present in an arrays and many more.
↓ ↓ ↓ ↓ ↓
┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐
│10 │ │20 │ │30 │ │40 │ │50 │
└───┘ └───┘ └───┘ └───┘ └───┘
Insertion
- Insertion in an array is the process of including one or more elements in an array
- Insertion of elements can be done:
i) At the begining,
ii) At the end, and
iii) At any given index of an Array
┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐
│10 │ │20 │ │30 │ │50 │ │60 │ | |
└───┘ └───┘ └───┘ └───┘ └───┘ └───┘
|____↗ |____↗┌───┐
|40 |
└───┘
Deletion
- Deletion of an element is the process of removing the desired elements and re-organize it.
- Deletion of elements can be done by different way:
i) From the begining,
ii) From the end, and
iii) From any given index
Searching
- It is the process of finding a given value in a list of values.
- It decides whether the search key is present is an array or not.
- It is an algorithmic process of finding a particular item in collection of data.
0 1 2 3 4
┌─────┬─────┬─────┬─────┬─────┐
│ 10 │ 20 │ 30 │ 40 │ 50 │
└─────┴─────┴─────┴─────┴─────┘
↑
┌─────┬─────┬─────┬─────┬─────┐
│ 10 │ 20 │ 30 │ 40 │ 50 │
└─────┴─────┴─────┴─────┴─────┘
↑
┌─────┬─────┬─────┬─────┬─────┐
│ 10 │ 20 │ 30 │ 40 │ 50 │
└─────┴─────┴─────┴─────┴─────┘
↑
Sorting
- It is the process in which element sorted in a user defined order.
For Ex- Numerical, Alphabetical etc. - This process is done in ascending order.
┌────┐ ┌────┐
│ 30 │ │ 10 │
├────┤ ├────┤
│ 10 │ │ 20 │
├────┤ ├────┤
Before │ 50 │ ------> │ 30 │ After
Sorting ├────┤ ├────┤ Sorting
│ 20 │ │ 40 │
├────┤ ├────┤
│ 40 │ │ 50 │
└────┘ └────┘
Advantages
- Arrays stores multiple elemlents of same type with the same name.
- Elements in an array can access randomly using an index number.
- Array memory is predefined, so there is no extra memory loss.
- They avoid memory loss.
- 2D arrays can represent the tabular data.
Disadvantages
- The no. of elements in an array should be pre-defined.
- It is static in nature , it's size cannot be varied after declaration.
- Allocating excess memory than required may lead to memory wastage.
- Insertion and deletion opearation in an array is quite difficult as array stores elements in contuous form.
Two Dimensional Arrays
- These array are called arrays of arrays.
- It is created to execute relational database which is like data structure.
- These arrays organised as matrices which are the colleection of rows and columns.
- It consists rows and columns.
Need of 2-D Arrays
- The main advantage of this is grouping of elements.
For Example: Consider we have a class consisting four students-
Each student consists of three subjejctjs namely English, Science, and Mathematics.And we want to represent marks of each student.
Students
1 2 3 4
┌───┬───┬───┬───┐
English │70 │90 │80 │75 │
├───┼───┼───┼───┤
Science │65 │75 │60 │55 │
├───┼───┼───┼───┤
Maths │50 │65 │75 │80 │
└───┴───┴───┴───┘So, the above table represents whole class marks.
Syntax:
data_type name_of_array[R][C];
R → No. of Rows, C → No. of Columns
Note: Columns should not be empty.
e.g
float arr [ 3 ] [ 4 ];
char names [ 7 ] [ 15 ];
Visualizing
I tis a collection of rows and columns.
int array[6][4];
↓ Columns
┌──────────┬──────────┬──────────┬──────────┬──────────┬──────────┐
│ │ │ │ │ │ │
├──────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│ │ │ │ │ │ │
├──────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│ │ │ │ │ │ │
├──────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│ │ │ │ │ │ │
└──────────┴──────────┴──────────┴──────────┴──────────┴──────────┘
--→ RowsNote: This 2-D Array consist 6 no. of rows and 4 no. of columns.
Total 6 * 4 = 24
Initialization
1. First Method
int first[2][2]= {9,6,1,144,70,50,10,12,78};
Column Index ↘
0 1 2 0 1 2
┌────────┬────────┬────────┐ ┌────────┬────────┬────────┐
0 │ 9 │ 6 │ 1 │ 0 │ (0,0) │ (0,1) │ (0,2) │
├────────┼────────┼────────┤ ├────────┼────────┼────────┤
1 │ 114 │ 70 │ 50 │ 1 │ (1,0) │ (1,1) │ (1,2) │
├────────┼────────┼────────┤ ├────────┼────────┼────────┤
2 │ 10 │ 12 │ 78 │ 2 │ (2,0) │ (2,1) │ (2,2) │
└────────┴────────┴────────┘ └────────┴────────┴────────┘
↖ Row IndexNote:Index start from Zero
2. Second Method
int second[2][2]= {9,6,1}, {144,70,50}, {10,12,78};
Column Index ↘
1 2 3 1 2 3
┌────────┬────────┬────────┐ ┌────────┬────────┬────────┐
1 │ 9 │ 6 │ 1 │ 1 │ [0][0] │ [0][1] │ [0][2] │ 1st Row
├────────┼────────┼────────┤ ├────────┼────────┼────────┤
2 │ 114 │ 70 │ 50 │ 2 │ [1][0] │ [1][1] │ [1][2] │ 2nd Row
├────────┼────────┼────────┤ ├────────┼────────┼────────┤
3 │ 10 │ 12 │ 78 │ 3 │ [2][0] │ [2][1] │ [2][2] │ 3rd Row
└────────┴────────┴────────┘ └────────┴────────┴────────┘
↖ Row Index
Accessing
int first [3][3]
0 1 2
┌────────┬────────┬────────┐
0 │ 9 │ 6 │ 1 │
├────────┼────────┼────────┤
1 │ 114 │ 70 │ 50 │
├────────┼────────┼────────┤
2 │ 10 │ 12 │ 78 │
└────────┴────────┴────────┘
--→ first [ 0 ] [ 0 ]
first [ 0 ] [ 1 ] = 6
first [ 0 ] [ 2 ] = 1
first [ 1 ] [ 0 ] = 144
first [ 1 ] [ 1 ] = 70
first [ 1 ] [ 2 ] = 50
first [ 2 ] [ 0 ] = 10
first [ 2 ] [ 1 ] = 12
first [ 2] [ 2 ] = 78
#include
int main()
{
int first [3][3] = {9,6,1,144,70,50,10,12,78};
int i,j;
for (i=0; i<3; i++);
{
for (j= 0; j<3; j++);
{
printf (%d, first [i][j];)
}
}
}Result:
9 6 1 144 70 10 12 78
Three Dimensional Arrays
- These arrays are called arrays of arrays of arrays.
- It is an extension of 2-D arrays and is used to represent 3D data structures.
- These arrays are organized as layers, rows, and columns.
- It consists of depth (layer), rows, and columns.
Need of 3-D Arrays
- The main advantage is storing complex data like 3D matrices, images, or multiple tables.
For Example: Consider a school where we store marks of students for different classes.
Each class has students and each student has marks in subjects like English, Science, Maths.
Layer 0 (Class 1)┌───────────────┐
│ 70 90 80 │
│ 65 75 60 │
│ 50 65 75 │
└───────────────┘Layer 1 (Class 2)
┌───────────────┐
│ 75 85 95 │
│ 60 70 80 │
│ 55 65 75 │
└───────────────┘Each box is a 2-D array, and multiple such boxes form a 3-D array.
Syntax:
data_type name_of_array[D][R][C];
D → Depth (Layers), R → Rows, C → Columns
Note: Columns must always be specified.
e.g
int arr[2][3][3];
float data[4][2][5];
Visualizing
It is a collection of multiple 2-D arrays (layers).
int array[2][3][3];
Layer 0 Layer 1
┌───────────┐ ┌───────────┐
│ │ │ │
│ 3x3 │ │ 3x3 │
│ Matrix │ │ Matrix │
│ │ │ │
└───────────┘ └───────────┘Total Elements = 2 × 3 × 3 = 18
Initialization
1. First Method
int first[2][3][3] = {
9,6,1, 144,70,50, 10,12,78,
5,4,3, 20,30,40, 11,22,33
};
Values are filled layer by layer.
2. Second Method
int second[2][3][3] = {
{
{9,6,1},
{144,70,50},
{10,12,78}
},
{
{5,4,3},
{20,30,40},
{11,22,33}
}
};
This method is more readable and preferred.
Accessing Elements
int first[2][3][3]
Access format:
first[layer][row][column]Example:
first[0][0][0] = 9
first[0][1][2] = 50
first[1][2][1] = 22
Traversal (Print)
#include <stdio.h>int main()
{
int first[2][3][3] = {
{ {9,6,1}, {144,70,50}, {10,12,78} },
{ {5,4,3}, {20,30,40}, {11,22,33} }
};int i,j,k;
for(i=0; i<2; i++)
{
printf("Layer %d:\n", i);for(j=0; j<3; j++)
{
for(k=0; k<3; k++)
{
printf("%d ", first[i][j][k]);
}
printf("\n");
}
printf("\n");
}return 0;
}Output:
Layer 0:
9 6 1
144 70 50
10 12 78Layer 1:
5 4 3
20 30 40
11 22 33
Key Points
- 3-D arrays store data in layers (depth).
- Indexing starts from 0.
- Total elements = D × R × C.
- Used in graphics, games, simulations.