SlideShare a Scribd company logo
DATA STRUCTURES
Lecture 3
Dr. Mili Dhar
Assistant Professor
Galgotias University, Greater Noida
Today’s Agenda
• What is an Array?
• What is an Stack?
• Terminologies related to Stack.
• Diagrammatic view of Stack.
Dr. Mili Dhar
What is an Array?
• Array is a linear Data Structure.
• Array is a Homogeneous collection of multiple data items.
• Open from both the ends.
• Allow random access.
Dr. Mili Dhar
Declaring an Array
#include <conio.h>
#include<stdio.h>
void main()
{
int arr[5];
int i;
for(i=0;i<5;i++)
{
……
……
}
getch();
}
10 20 30 40 50 int i;
0 1 2 3 4
index
arr
Dr. Mili Dhar
Declaration of an Array
type array-name[];
OR
type[] array-name;
Example:
int Arr[];
OR
int [] Arr;
Dr. Mili Dhar
Initialization of an Array
var-name = new type [size];
Example:
int Arr[];
Arr = new int [20];
Dr. Mili Dhar
Insert elements in an Array
int[] myNum = {10, 20, 30, 40};
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Dr. Mili Dhar
Accessing of an Array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " +
i + " : "+ arr[i]);
System.out.println(cars[0]);
Dr. Mili Dhar
Array Length
System.out.println(cars.length);
Dr. Mili Dhar
class DS {
public static void main(String[] args)
{
char [] arr; declaration
arr = new char[5]; initialization
arr[0] = ‘10’; inserting elements
arr[1] = ‘20’;
arr[2] = ‘30’;
arr[3] = ‘40’;
arr[4] = ‘50’;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : " + arr[i]);
}
}
Dr. Mili Dhar
import java.util.*;
class HelloWorld {
public static void main(String[] args)
{
int []arr = new int[3];
Scanner sc = new Scanner(System.in);
for (int i =0; i<arr.length; i++) {
System.out.println("Enter the elements "+i);
arr[i]= sc.nextInt(); }
for (int i =0; i<arr.length; i++)
{
System.out.println(arr[i]);
}
}
Dr. Mili Dhar
8/27/2024 12
Address Calculation for 1-D array
Dr. Mili Dhar
• Array of an element of an array say “A[ I ]” is calculated using the
following formula:
Address of A [ I ] = B + W * ( I – LB )
Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume 0
(zero)
8/27/2024 13
Address Calculation for 1-D array
Dr. Mili Dhar
Example 1:
• Given the base address of an array B[1300…..1900] as
1020 and size of each element is 2 bytes in the memory.
Find the address of B[1700].
• Solution:
The given values are: B = 1020, LB = 1300, W = 2, I = 1700
Address of A [ I ] = B + W * ( I – LB )
= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820 [Ans]
8/27/2024 14
Address Calculation for 1-D array
Dr. Mili Dhar
Example 2:
• Find the base address of an array A[-15:65]. The size of each
element is 2 bytes in the memory and the location of A[37] is 4279.
Solution:
The given values are: LB = -15, UB = 65, W = 2, I = 37, A[37] = 4279
Address of A [ I ] = B + W * ( I – LB )
4279= B + 2 * (37 – (-15))
4279= B + 2 * 52
4279= B + 104
B= 4175 [Ans]
8/27/2024 15
Address Calculation
Dr. Mili Dhar
Declaration of 2D-Array
type arr-name[][];
OR
type[][] arr-name;
Example:
int Arr[][];
OR
int [][] Arr;
Dr. Mili Dhar
Initialization of an 2D-Array
var-name = new type [size][size];
Example:
int Arr[] [];
Arr = new int [20][20];
Dr. Mili Dhar
Insert elements in an Array
int[][] myNum = {{10, 20}, {30, 40}};
String[] []cars = {{"Volvo", "BMW“}, {"Ford", "Mazda"}};
Dr. Mili Dhar
Insert elements in an Array
import java.util.*;
class HelloWorld {public static void main(String[] args)
{
int [][]arr = new int[3][3];
Scanner sc = new Scanner(System.in);
for (int i =0; i<arr.length; i++) {
for (int j =0; j<arr.length; j++) {
System.out.println("Enter the elements "+i,j);
arr[i][j]= sc.nextInt(); } }
for (int i =0; i<arr.length; i++)
{
for (int j =0; j<arr.length; j++) {
System.out.println(arr[i][j]);
}}
}
Dr. Mili Dhar
Display elements of 2D Array
public class Main
{
public static void main(String[] args)
{
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i)
{
for(int j = 0; j < myNumbers[i].length; ++j)
{
System.out.println(myNumbers[i][j]);
}
}
}
}
Dr. Mili Dhar
Row Major Array
In row major order, the elements of a particular row are
stored at adjacent memory locations. The first element
of the array (arr[0][0]) is stored at the first location
followed by the arr[0][1] and so on. After the first row,
elements of the next row are stored next.
Dr. Mili Dhar
Column Major Array
In column major order, the elements of a column are
stored adjacent to each other in the memory.The first
element of the array (arr[0][0]) is stored at the first
location followed by the arr[1][0] and so on. After the
first column, elements of the next column are stored
stating from the top.
Dr. Mili Dhar
address[i][j] = I + W * [(i - l_row) * N + (j - l_col)]
•I : Base address
l_row : lower bound for row
l_col : lower bound for column
W : sizeof (data type)
N : Number of columns
8/27/2024 23
Address Calculation row major array
Dr. Mili Dhar
• Example:
Consider an integer array of size 3X3. The address of the first
element is 1048. Calculate the address of the element at index i =
2, j = 1. (0 based index)
• I = 1048, l_row = 0 = l_col, i = 2, j = 1, W = 2, N = 3
• address[2][1] = I + W * [(i-l_row) * N + (j - l_col)]
• address[2][1] = 1048 + 2 *[ 2 * 3 + 1 ]= 1048 + 12 + 2 = 1062
8/27/2024 24
Address Calculation row major array
Dr. Mili Dhar
• Example:
Example: Given an array, arr[1………10][1………15] with base
value 100 and the size of each element is 1 Byte in memory. Find
the address of arr[8][6] with the help of row-major order.
8/27/2024 25
Address Calculation row major array
Base address B = 100
W = 1 Bytes, I = 8, J = 6
LR = 1, LC = 1
N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1 = 15
Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210
Dr. Mili Dhar
address[i][j] = I + W * ((j – l_col) * M + (i – l_row))
I : Base address
l_row : lower bound for row
l_col : lower bound for column
W : sizeof (data type)
M : Number of rows
8/27/2024 26
Address Calculation column major array
Dr. Mili Dhar
• Example:
• Consider an integer array of size 3X3. The address of the first
element is 1048. Calculate the address of the element at index i = 2, j
= 1. (0 based index)
• I = 1048, l_row = 0 = l_col, i = 2, j = 1, W = 2, M = 3
• address[2][1] = I + W * [(j - l_col) * M + (i - l_row)]
• address[2][1] = 1048 + 2 * [1 * 3 + 2 ]= 1048 + 6 + 4 = 1058
8/27/2024 27
Address Calculation column major array
Dr. Mili Dhar
• Example:
Example: Given an array, arr[1………10][1………15] with base
value 100 and the size of each element is 1 Byte in memory. Find
the address of arr[8][6] with the help of column-major order.
8/27/2024 28
Address Calculation column major array
Base address B = 100
W = 1 Bytes, I = 8, J = 6
LR = 1, LC = 1
N = Upper Bound – Lower Bound + 1
= 10 – 1 + 1 = 10
Solution:
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157
Dr. Mili Dhar
• A matrix is a two-dimensional data object made of m rows and
n columns, therefore having total m x n values. If most of the
elements of the matrix have 0 value, then it is called a sparse
matrix.
Why to use Sparse Matrix instead of simple matrix ?
• Storage: There are lesser non-zero elements than zeros and
thus lesser memory can be used to store only those elements.
• Computing time: Computing time can be saved by logically
designing a data structure traversing only non-zero elements..
8/27/2024 29
Sparse Matrix and its representations
Dr. Mili Dhar
8/27/2024 Dr. Pooja Unit -1 30
Sparse Matrix and its representations
• Representing a sparse matrix by a 2D array leads to wastage of lots of
memory as zeroes in the matrix are of no use in most of the cases.
So, instead of storing zeroes with non-zero elements, we only store
non-zero elements. This means storing non-zero elements with
triples- (Row, Column, value).
Dr. Mili Dhar
8/27/2024 31
Sparse Matrix and its representations
• Sparse Matrix Representations can be done in many ways following
are two common representations:
• Array representation
• Linked list representation
Dr. Mili Dhar
8/27/2024 32
Sparse Matrix and its representations
int size = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++)
{
if (sparseMatrix[i][j] != 0)
{
size++;
}
}
}
class DS
{
public static void main(String[]
args)
{
int sparseMatrix[][]
= {
{0, 0, 3, 0, 4},
{0, 0, 5, 7, 0},
{0, 0, 0, 0, 0},
{0, 2, 6, 0, 0}
};
Dr. Mili Dhar
8/27/2024 33
Sparse Matrix and its representations
// number of columns in compactMatrix (size) must be
// equal to number of non - zero elements in sparseMatrix
int compactMatrix[][] = new int[3][size];
// Making of new matrix
int k = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++)
{
Dr. Mili Dhar
8/27/2024 34
Sparse Matrix and its representations
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}
}
}
Dr. Mili Dhar
8/27/2024 35
Sparse Matrix and its representations
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < size; j++)
{
System.out.printf("%d ", compactMatrix[i][j]);
}
System.out.printf("n");
}
}
}
Dr. Mili Dhar
8/27/2024 36
Arithmetic operations on matrices
Dr. Mili Dhar
8/27/2024 37
Arithmetic operations on matrices
public class MatrixAdditionExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//adding and printing addition of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j]; //use - for subtraction
System.out.print(c[i][j]+" ");
}
System.out.println(); //new line
}
}}
Dr. Mili Dhar
8/27/2024 38
Arithmetic operations on matrices
Dr. Mili Dhar
8/27/2024 39
Arithmetic operations on matrices
public class MM{
public static void main(String
args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store
the multiplication of two matrices
int c[][]=new int[3][3];
//multiplying and printing
multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");}
System.out.println();//new line
}
}}
Dr. Mili Dhar
Dr. Mili Dhar
Write a program to insert an element in ith
position of the array.
import java.io.*;
import java.lang.*;
import java.util.*;
class InsertElement
{
// Function to insert x in arr at position pos
public static int[] insertX(int n, int arr[], int x, int pos)
{
int i;
// create a new array of size n+1
int newarr[] = new int[n + 1];
Dr. Mili Dhar
Write a program to insert an element in ith
position of the array.
// insert the elements from the old array into the new
// array. insert all elements till pos then insert x at
pos then insert rest of the elements
for (i = 0; i < n + 1; i++) {
if (i < pos - 1)
newarr[i] = arr[i];
else if (i == pos - 1)
newarr[i] = x;
else
newarr[i] = arr[i - 1];
}
return newarr;
}
Dr. Mili Dhar
Write a program to insert an element in ith
position of the array.
// Main function
public static void main(String[] args)
{
int n = 10;
int i;
// initial array of size 10
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// print the original array
System.out.println("Initial Array:n" + Arrays.toString(arr));
// element to be inserted
int x = 50;
Dr. Mili Dhar
Write a program to insert an element in ith
position of the array.
// position at which element is to be inserted
int pos = 5;
// call the method to insert x in arr at position pos
arr = insertX(n, arr, x, pos);
// print the updated array
System.out.println("nArray with " + x + " inserted at
position " + pos + ":n" + Arrays.toString(arr));
}
}
Dr. Mili Dhar
Write a program to delete ith element
of the array.
import java.util.Arrays;
class DeleteElement {
// Function to remove the element
public static int[] removeTheElement(int[] arr, int index)
{
// If the array is empty
// or the index is not in array range
// return the original array
if (arr == null || index < 0 || index >= arr.length) {
return arr;
}
Dr. Mili Dhar
Write a program to delete ith element
of the array.
// Create another array of size one less
int[] anotherArray = new int[arr.length - 1];
// Copy the elements except the index
// from original array to the other array
for (int i = 0, k = 0; i < arr.length; i++) {
// if the index is the removal element index
if (i == index) {
continue;
}
Dr. Mili Dhar
Write a program to delete ith element
of the array.
// if the index is not the removal element index
anotherArray[k++] = arr[i];
}
// return the resultant array
return anotherArray;
}
// Driver Code
public static void main(String[] args)
{
// Get the array
int[] arr = { 1, 2, 3, 4, 5 };
// Print the resultant array
System.out.println("Original Array: " + Arrays.toString(arr));
Dr. Mili Dhar
Write a program to delete ith element
of the array.
// Get the specific index
int index = 2;
// Print the index
System.out.println("Index to be removed: " + index);
// Remove the element
arr = removeTheElement(arr, index);
// Print the resultant array
System.out.println("Resultant Array: " +
Arrays.toString(arr));
}
}
Dr. Mili Dhar
Write a program to reverse the element
of the array.
import java.util.Scanner;
public class ArrayReverser {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
Dr. Mili Dhar
Write a program to reverse the element
of the array.
reverseArray(array);
System.out.println("Reversed array:");
for (int num : array) {
System.out.print(num + " ");
}
}
Dr. Mili Dhar
Write a program to delete ith element
of the array.
public static void reverseArray(int[] array) {
int startIndex = 0;
int endIndex = array.length - 1;
while (startIndex < endIndex) {
int temp = array[startIndex];
array[startIndex] = array[endIndex];
array[endIndex] = temp;
startIndex++;
endIndex--;
}
}
}
Dr. Mili Dhar
Tail Recursion
Tail recursion is defined as a recursive function in which the
recursive call is the last statement that is executed by the
function. So basically nothing is left to execute after the
recursion call.
static void print(int n)
{
if (n < 0)
return;
System.out.print(" " + n);
print(n - 1);
}
Dr. Mili Dhar
Head Recursion
Head recursion is defined as a recursive function in which the
recursive call is the first statement that is executed by the
function. So basically nothing is left to execute before the
recursion call.
static void print(int n)
{
if (n < 0)
return;
else
print(n - 1);
System.out.print(" " + n);
}
Dr. Mili Dhar
Dr. Mili Dhar
Tree Recursion
Tree Recursion: If a recursive function calling itself for one time then
it’s known as Linear Recursion. Otherwise if a recursive function
calling itself for more than one time then it’s known as Tree
Recursion.
Dr. Mili Dhar
Tree Recursion
class tree
{
static void fun(int n)
{
if (n > 0) {
System.out.print(" "+ n);
fun(n - 1);
fun(n - 1);
}
}
public static void main(String[] args)
{
fun(3);
}
}
Dr. Mili Dhar
Tree Recursion
import java.util.*;
class Tree
{
static int fib(int n)
{
// Stop condition
if (n == 0)
return 0;
if (n == 1 || n == 2)
return 1;
else
return (fib(n - 1) + fib(n - 2));
}
Dr. Mili Dhar
Tree Recursion
public static void main(String []args)
{
// Initialize variable n.
int n = 5;
System.out.print("Fibonacci series of 5 numbers is: ");
// for loop to print the fibonacci series.
for (int i = 0; i < n; i++)
{
System.out.print(fib(i)+" ");
}
}
}
Dr. Mili Dhar
Nested Recursion
Nested Recursion: In this recursion, a recursive function
will pass the parameter as a recursive call. That means
“recursion inside recursion”.
import java.util.*;
class NestedRecursion {
static int fun(int n)
{
if (n > 100)
return n - 10;
return fun(fun(n + 11));
}
public static void main(String
args[])
{
int r;
r = fun(95);
System.out.print(" "+ r);
} }
Dr. Mili Dhar
Write a recursive program to print an
array in reverse order.
import java.util.Scanner;
public class PrintArrayReverseOrder {
static void ReverseArray(int arr[], int n)
{
int i;
if(n>0)
{
i=n-1;
System.out.print(arr[i]+" ");
ReverseArray(arr,i);
}
}
Dr. Mili Dhar
Write a recursive program to print an
array in reverse order.
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
int n,i;
System.out.println("Enter your Array Size:");
n=cs.nextInt();
int arr[]=new int[n];
System.out.println("Enter the Array Element:");
for(i=0;i<n;i++)
{
arr[i]=cs.nextInt();
}
System.out.print("After reversing Array Element Are:");
ReverseArray(arr,n);
cs.close();
}
}
Dr. Mili Dhar
Write a recursion Program to find a^b
class Power {
public static void main(String[] args) {
int base = 3, powerRaised = 4;
int result = power(base, powerRaised);
System.out.println(base + "^" + powerRaised + "=" + result);
}
public static int power(int base, int powerRaised)
{
if (powerRaised != 0) {
return (base * power(base, powerRaised - 1));
}
else {
return 1;
}
}
}
Dr. Mili Dhar
What is a Stack?
• A Stack is a linear Data Structure just like an array.
• Stack is a restricted form of Array.
• Stack is Open from one end only and closed from the other
end.
• Stack doesn’t allow random access of data, rather the data is
accessed in the sequential manner.
• Like array it is also a homogeneous collection of elements.
• Like array it is also index based.
Dr. Mili Dhar
Terminologies related to Stack
1. PUSH
1. POP
1. LIFO
1. PEEP
1. TOS
1. OVERFLOW
1. UNDERFLOW
Dr. Mili Dhar
PUSH, POP & LIFO
• PUSH - Push is a process of inserting elements in the
Stack, one at a time.
• POP - Pop is the process of removing elements from the
Stack, one at a time.
• LIFO - Since stack is open from one end only, the element
inserted(PUSHED) last will be the one to be
removed(POPPED) first. Thus we say a stack is based on
LAST IN FIRST OUT order.
Dr. Mili Dhar
PEEP, TOS, OVERFLOW &
UNDERFLOW
PEEP: The process of accessing (not removing) the top elements
of the stack.
OVERFLOW & UNDERFLOW: These are conditions which arise
when we try to PUSH data in a FULL STACK, or we try to POP data
from an EMPTY stack, Respectively.
Dr. Mili Dhar
Diagrammatic View Of a Stack
20
10
10
arr
tos
-1
4
3
2
1
0
4
3
2
1
0
arr
0
tos
1
tos
arr
push(10); push(20);
4
3
2
1
0
Dr. Mili Dhar

More Related Content

PPTX
Basic of array and data structure, data structure basics, array, address calc...
PDF
PPTX
ADVANCED DATA STRUCTURES AND ALGORITHMS.pptx
PPTX
arrays.pptx
PPTX
data structure unit -1_170434dd7400.pptx
PPTX
Address_Calculation_Arrays .pptx
PDF
cluod.pdf
PPTX
polynomial_linked list for electrical engineer
Basic of array and data structure, data structure basics, array, address calc...
ADVANCED DATA STRUCTURES AND ALGORITHMS.pptx
arrays.pptx
data structure unit -1_170434dd7400.pptx
Address_Calculation_Arrays .pptx
cluod.pdf
polynomial_linked list for electrical engineer

Similar to Data Structure Lecture Array and Recursion.pdf (20)

PDF
PPTX
arrays.pptx
PPTX
Data Structures - Array presentation .pptx
PPTX
TMK_DSA_Unit 2 part1(array and stack).pptx
PPTX
unit-2-dsa.pptx
PDF
2D Array
PPTX
DSA Unit II array.pptx
PPT
Two Dimensional Array
PPTX
Ch-11-Arrays.ppt-1.pptx eurhrbdhdbdhrhdhdh
PPTX
Data structure array
PPT
1st lecture.ppt
PPTX
javaArrays.pptx
PPTX
2. Array in Data Structure
PPTX
UNIT-5_Array in c_part1.pptx
PPT
Chapter 3 ds
PPT
1st lecture of DSA computer science 2024.ppt
PPTX
Module_3_Arrays - Updated.pptx............
PPT
One Dimensional Array
PPTX
6_Array.pptx
PPTX
U2.pptx Advanced Data Structures and Algorithms
arrays.pptx
Data Structures - Array presentation .pptx
TMK_DSA_Unit 2 part1(array and stack).pptx
unit-2-dsa.pptx
2D Array
DSA Unit II array.pptx
Two Dimensional Array
Ch-11-Arrays.ppt-1.pptx eurhrbdhdbdhrhdhdh
Data structure array
1st lecture.ppt
javaArrays.pptx
2. Array in Data Structure
UNIT-5_Array in c_part1.pptx
Chapter 3 ds
1st lecture of DSA computer science 2024.ppt
Module_3_Arrays - Updated.pptx............
One Dimensional Array
6_Array.pptx
U2.pptx Advanced Data Structures and Algorithms
Ad

Recently uploaded (20)

PDF
composite construction of structures.pdf
DOCX
573137875-Attendance-Management-System-original
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
UNIT 4 Total Quality Management .pptx
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Current and future trends in Computer Vision.pptx
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Sustainable Sites - Green Building Construction
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Well-logging-methods_new................
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
PPT on Performance Review to get promotions
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Geodesy 1.pptx...............................................
composite construction of structures.pdf
573137875-Attendance-Management-System-original
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
UNIT 4 Total Quality Management .pptx
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Automation-in-Manufacturing-Chapter-Introduction.pdf
Current and future trends in Computer Vision.pptx
R24 SURVEYING LAB MANUAL for civil enggi
additive manufacturing of ss316l using mig welding
Sustainable Sites - Green Building Construction
Foundation to blockchain - A guide to Blockchain Tech
Lecture Notes Electrical Wiring System Components
Well-logging-methods_new................
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPT on Performance Review to get promotions
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Embodied AI: Ushering in the Next Era of Intelligent Systems
Geodesy 1.pptx...............................................
Ad

Data Structure Lecture Array and Recursion.pdf

  • 1. DATA STRUCTURES Lecture 3 Dr. Mili Dhar Assistant Professor Galgotias University, Greater Noida
  • 2. Today’s Agenda • What is an Array? • What is an Stack? • Terminologies related to Stack. • Diagrammatic view of Stack. Dr. Mili Dhar
  • 3. What is an Array? • Array is a linear Data Structure. • Array is a Homogeneous collection of multiple data items. • Open from both the ends. • Allow random access. Dr. Mili Dhar
  • 4. Declaring an Array #include <conio.h> #include<stdio.h> void main() { int arr[5]; int i; for(i=0;i<5;i++) { …… …… } getch(); } 10 20 30 40 50 int i; 0 1 2 3 4 index arr Dr. Mili Dhar
  • 5. Declaration of an Array type array-name[]; OR type[] array-name; Example: int Arr[]; OR int [] Arr; Dr. Mili Dhar
  • 6. Initialization of an Array var-name = new type [size]; Example: int Arr[]; Arr = new int [20]; Dr. Mili Dhar
  • 7. Insert elements in an Array int[] myNum = {10, 20, 30, 40}; String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Dr. Mili Dhar
  • 8. Accessing of an Array for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : "+ arr[i]); System.out.println(cars[0]); Dr. Mili Dhar
  • 10. class DS { public static void main(String[] args) { char [] arr; declaration arr = new char[5]; initialization arr[0] = ‘10’; inserting elements arr[1] = ‘20’; arr[2] = ‘30’; arr[3] = ‘40’; arr[4] = ‘50’; // accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : " + arr[i]); } } Dr. Mili Dhar
  • 11. import java.util.*; class HelloWorld { public static void main(String[] args) { int []arr = new int[3]; Scanner sc = new Scanner(System.in); for (int i =0; i<arr.length; i++) { System.out.println("Enter the elements "+i); arr[i]= sc.nextInt(); } for (int i =0; i<arr.length; i++) { System.out.println(arr[i]); } } Dr. Mili Dhar
  • 12. 8/27/2024 12 Address Calculation for 1-D array Dr. Mili Dhar
  • 13. • Array of an element of an array say “A[ I ]” is calculated using the following formula: Address of A [ I ] = B + W * ( I – LB ) Where, B = Base address W = Storage Size of one element stored in the array (in byte) I = Subscript of element whose address is to be found LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero) 8/27/2024 13 Address Calculation for 1-D array Dr. Mili Dhar
  • 14. Example 1: • Given the base address of an array B[1300…..1900] as 1020 and size of each element is 2 bytes in the memory. Find the address of B[1700]. • Solution: The given values are: B = 1020, LB = 1300, W = 2, I = 1700 Address of A [ I ] = B + W * ( I – LB ) = 1020 + 2 * (1700 – 1300) = 1020 + 2 * 400 = 1020 + 800 = 1820 [Ans] 8/27/2024 14 Address Calculation for 1-D array Dr. Mili Dhar
  • 15. Example 2: • Find the base address of an array A[-15:65]. The size of each element is 2 bytes in the memory and the location of A[37] is 4279. Solution: The given values are: LB = -15, UB = 65, W = 2, I = 37, A[37] = 4279 Address of A [ I ] = B + W * ( I – LB ) 4279= B + 2 * (37 – (-15)) 4279= B + 2 * 52 4279= B + 104 B= 4175 [Ans] 8/27/2024 15 Address Calculation Dr. Mili Dhar
  • 16. Declaration of 2D-Array type arr-name[][]; OR type[][] arr-name; Example: int Arr[][]; OR int [][] Arr; Dr. Mili Dhar
  • 17. Initialization of an 2D-Array var-name = new type [size][size]; Example: int Arr[] []; Arr = new int [20][20]; Dr. Mili Dhar
  • 18. Insert elements in an Array int[][] myNum = {{10, 20}, {30, 40}}; String[] []cars = {{"Volvo", "BMW“}, {"Ford", "Mazda"}}; Dr. Mili Dhar
  • 19. Insert elements in an Array import java.util.*; class HelloWorld {public static void main(String[] args) { int [][]arr = new int[3][3]; Scanner sc = new Scanner(System.in); for (int i =0; i<arr.length; i++) { for (int j =0; j<arr.length; j++) { System.out.println("Enter the elements "+i,j); arr[i][j]= sc.nextInt(); } } for (int i =0; i<arr.length; i++) { for (int j =0; j<arr.length; j++) { System.out.println(arr[i][j]); }} } Dr. Mili Dhar
  • 20. Display elements of 2D Array public class Main { public static void main(String[] args) { int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; for (int i = 0; i < myNumbers.length; ++i) { for(int j = 0; j < myNumbers[i].length; ++j) { System.out.println(myNumbers[i][j]); } } } } Dr. Mili Dhar
  • 21. Row Major Array In row major order, the elements of a particular row are stored at adjacent memory locations. The first element of the array (arr[0][0]) is stored at the first location followed by the arr[0][1] and so on. After the first row, elements of the next row are stored next. Dr. Mili Dhar
  • 22. Column Major Array In column major order, the elements of a column are stored adjacent to each other in the memory.The first element of the array (arr[0][0]) is stored at the first location followed by the arr[1][0] and so on. After the first column, elements of the next column are stored stating from the top. Dr. Mili Dhar
  • 23. address[i][j] = I + W * [(i - l_row) * N + (j - l_col)] •I : Base address l_row : lower bound for row l_col : lower bound for column W : sizeof (data type) N : Number of columns 8/27/2024 23 Address Calculation row major array Dr. Mili Dhar
  • 24. • Example: Consider an integer array of size 3X3. The address of the first element is 1048. Calculate the address of the element at index i = 2, j = 1. (0 based index) • I = 1048, l_row = 0 = l_col, i = 2, j = 1, W = 2, N = 3 • address[2][1] = I + W * [(i-l_row) * N + (j - l_col)] • address[2][1] = 1048 + 2 *[ 2 * 3 + 1 ]= 1048 + 12 + 2 = 1062 8/27/2024 24 Address Calculation row major array Dr. Mili Dhar
  • 25. • Example: Example: Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1 Byte in memory. Find the address of arr[8][6] with the help of row-major order. 8/27/2024 25 Address Calculation row major array Base address B = 100 W = 1 Bytes, I = 8, J = 6 LR = 1, LC = 1 N = Upper Bound – Lower Bound + 1 = 15 – 1 + 1 = 15 Solution: Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1)) = 100 + 1 * ((7) * 15 + (5)) = 100 + 1 * (110) Address of A[I][J] = 210 Dr. Mili Dhar
  • 26. address[i][j] = I + W * ((j – l_col) * M + (i – l_row)) I : Base address l_row : lower bound for row l_col : lower bound for column W : sizeof (data type) M : Number of rows 8/27/2024 26 Address Calculation column major array Dr. Mili Dhar
  • 27. • Example: • Consider an integer array of size 3X3. The address of the first element is 1048. Calculate the address of the element at index i = 2, j = 1. (0 based index) • I = 1048, l_row = 0 = l_col, i = 2, j = 1, W = 2, M = 3 • address[2][1] = I + W * [(j - l_col) * M + (i - l_row)] • address[2][1] = 1048 + 2 * [1 * 3 + 2 ]= 1048 + 6 + 4 = 1058 8/27/2024 27 Address Calculation column major array Dr. Mili Dhar
  • 28. • Example: Example: Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1 Byte in memory. Find the address of arr[8][6] with the help of column-major order. 8/27/2024 28 Address Calculation column major array Base address B = 100 W = 1 Bytes, I = 8, J = 6 LR = 1, LC = 1 N = Upper Bound – Lower Bound + 1 = 10 – 1 + 1 = 10 Solution: Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1)) = 100 + 1 * ((5) * 10 + (7)) = 100 + 1 * (57) Address of A[I][J] = 157 Dr. Mili Dhar
  • 29. • A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse matrix. Why to use Sparse Matrix instead of simple matrix ? • Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those elements. • Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero elements.. 8/27/2024 29 Sparse Matrix and its representations Dr. Mili Dhar
  • 30. 8/27/2024 Dr. Pooja Unit -1 30 Sparse Matrix and its representations • Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing non-zero elements with triples- (Row, Column, value). Dr. Mili Dhar
  • 31. 8/27/2024 31 Sparse Matrix and its representations • Sparse Matrix Representations can be done in many ways following are two common representations: • Array representation • Linked list representation Dr. Mili Dhar
  • 32. 8/27/2024 32 Sparse Matrix and its representations int size = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { if (sparseMatrix[i][j] != 0) { size++; } } } class DS { public static void main(String[] args) { int sparseMatrix[][] = { {0, 0, 3, 0, 4}, {0, 0, 5, 7, 0}, {0, 0, 0, 0, 0}, {0, 2, 6, 0, 0} }; Dr. Mili Dhar
  • 33. 8/27/2024 33 Sparse Matrix and its representations // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in sparseMatrix int compactMatrix[][] = new int[3][size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { Dr. Mili Dhar
  • 34. 8/27/2024 34 Sparse Matrix and its representations if (sparseMatrix[i][j] != 0) { compactMatrix[0][k] = i; compactMatrix[1][k] = j; compactMatrix[2][k] = sparseMatrix[i][j]; k++; } } } Dr. Mili Dhar
  • 35. 8/27/2024 35 Sparse Matrix and its representations for (int i = 0; i < 3; i++) { for (int j = 0; j < size; j++) { System.out.printf("%d ", compactMatrix[i][j]); } System.out.printf("n"); } } } Dr. Mili Dhar
  • 36. 8/27/2024 36 Arithmetic operations on matrices Dr. Mili Dhar
  • 37. 8/27/2024 37 Arithmetic operations on matrices public class MatrixAdditionExample{ public static void main(String args[]){ //creating two matrices int a[][]={{1,3,4},{2,4,3},{3,4,5}}; int b[][]={{1,3,4},{2,4,3},{1,2,4}}; //creating another matrix to store the sum of two matrices int c[][]=new int[3][3]; //3 rows and 3 columns //adding and printing addition of 2 matrices for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ c[i][j]=a[i][j]+b[i][j]; //use - for subtraction System.out.print(c[i][j]+" "); } System.out.println(); //new line } }} Dr. Mili Dhar
  • 38. 8/27/2024 38 Arithmetic operations on matrices Dr. Mili Dhar
  • 39. 8/27/2024 39 Arithmetic operations on matrices public class MM{ public static void main(String args[]){ //creating two matrices int a[][]={{1,1,1},{2,2,2},{3,3,3}}; int b[][]={{1,1,1},{2,2,2},{3,3,3}}; //creating another matrix to store the multiplication of two matrices int c[][]=new int[3][3]; //multiplying and printing multiplication of 2 matrices for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ c[i][j]=0; for(int k=0;k<3;k++) { c[i][j]+=a[i][k]*b[k][j]; } System.out.print(c[i][j]+" ");} System.out.println();//new line } }} Dr. Mili Dhar
  • 41. Write a program to insert an element in ith position of the array. import java.io.*; import java.lang.*; import java.util.*; class InsertElement { // Function to insert x in arr at position pos public static int[] insertX(int n, int arr[], int x, int pos) { int i; // create a new array of size n+1 int newarr[] = new int[n + 1]; Dr. Mili Dhar
  • 42. Write a program to insert an element in ith position of the array. // insert the elements from the old array into the new // array. insert all elements till pos then insert x at pos then insert rest of the elements for (i = 0; i < n + 1; i++) { if (i < pos - 1) newarr[i] = arr[i]; else if (i == pos - 1) newarr[i] = x; else newarr[i] = arr[i - 1]; } return newarr; } Dr. Mili Dhar
  • 43. Write a program to insert an element in ith position of the array. // Main function public static void main(String[] args) { int n = 10; int i; // initial array of size 10 int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // print the original array System.out.println("Initial Array:n" + Arrays.toString(arr)); // element to be inserted int x = 50; Dr. Mili Dhar
  • 44. Write a program to insert an element in ith position of the array. // position at which element is to be inserted int pos = 5; // call the method to insert x in arr at position pos arr = insertX(n, arr, x, pos); // print the updated array System.out.println("nArray with " + x + " inserted at position " + pos + ":n" + Arrays.toString(arr)); } } Dr. Mili Dhar
  • 45. Write a program to delete ith element of the array. import java.util.Arrays; class DeleteElement { // Function to remove the element public static int[] removeTheElement(int[] arr, int index) { // If the array is empty // or the index is not in array range // return the original array if (arr == null || index < 0 || index >= arr.length) { return arr; } Dr. Mili Dhar
  • 46. Write a program to delete ith element of the array. // Create another array of size one less int[] anotherArray = new int[arr.length - 1]; // Copy the elements except the index // from original array to the other array for (int i = 0, k = 0; i < arr.length; i++) { // if the index is the removal element index if (i == index) { continue; } Dr. Mili Dhar
  • 47. Write a program to delete ith element of the array. // if the index is not the removal element index anotherArray[k++] = arr[i]; } // return the resultant array return anotherArray; } // Driver Code public static void main(String[] args) { // Get the array int[] arr = { 1, 2, 3, 4, 5 }; // Print the resultant array System.out.println("Original Array: " + Arrays.toString(arr)); Dr. Mili Dhar
  • 48. Write a program to delete ith element of the array. // Get the specific index int index = 2; // Print the index System.out.println("Index to be removed: " + index); // Remove the element arr = removeTheElement(arr, index); // Print the resultant array System.out.println("Resultant Array: " + Arrays.toString(arr)); } } Dr. Mili Dhar
  • 49. Write a program to reverse the element of the array. import java.util.Scanner; public class ArrayReverser { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the size of the array:"); int size = scanner.nextInt(); int[] array = new int[size]; System.out.println("Enter " + size + " elements:"); for (int i = 0; i < size; i++) { array[i] = scanner.nextInt(); } Dr. Mili Dhar
  • 50. Write a program to reverse the element of the array. reverseArray(array); System.out.println("Reversed array:"); for (int num : array) { System.out.print(num + " "); } } Dr. Mili Dhar
  • 51. Write a program to delete ith element of the array. public static void reverseArray(int[] array) { int startIndex = 0; int endIndex = array.length - 1; while (startIndex < endIndex) { int temp = array[startIndex]; array[startIndex] = array[endIndex]; array[endIndex] = temp; startIndex++; endIndex--; } } } Dr. Mili Dhar
  • 52. Tail Recursion Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. static void print(int n) { if (n < 0) return; System.out.print(" " + n); print(n - 1); } Dr. Mili Dhar
  • 53. Head Recursion Head recursion is defined as a recursive function in which the recursive call is the first statement that is executed by the function. So basically nothing is left to execute before the recursion call. static void print(int n) { if (n < 0) return; else print(n - 1); System.out.print(" " + n); } Dr. Mili Dhar
  • 55. Tree Recursion Tree Recursion: If a recursive function calling itself for one time then it’s known as Linear Recursion. Otherwise if a recursive function calling itself for more than one time then it’s known as Tree Recursion. Dr. Mili Dhar
  • 56. Tree Recursion class tree { static void fun(int n) { if (n > 0) { System.out.print(" "+ n); fun(n - 1); fun(n - 1); } } public static void main(String[] args) { fun(3); } } Dr. Mili Dhar
  • 57. Tree Recursion import java.util.*; class Tree { static int fib(int n) { // Stop condition if (n == 0) return 0; if (n == 1 || n == 2) return 1; else return (fib(n - 1) + fib(n - 2)); } Dr. Mili Dhar
  • 58. Tree Recursion public static void main(String []args) { // Initialize variable n. int n = 5; System.out.print("Fibonacci series of 5 numbers is: "); // for loop to print the fibonacci series. for (int i = 0; i < n; i++) { System.out.print(fib(i)+" "); } } } Dr. Mili Dhar
  • 59. Nested Recursion Nested Recursion: In this recursion, a recursive function will pass the parameter as a recursive call. That means “recursion inside recursion”. import java.util.*; class NestedRecursion { static int fun(int n) { if (n > 100) return n - 10; return fun(fun(n + 11)); } public static void main(String args[]) { int r; r = fun(95); System.out.print(" "+ r); } } Dr. Mili Dhar
  • 60. Write a recursive program to print an array in reverse order. import java.util.Scanner; public class PrintArrayReverseOrder { static void ReverseArray(int arr[], int n) { int i; if(n>0) { i=n-1; System.out.print(arr[i]+" "); ReverseArray(arr,i); } } Dr. Mili Dhar
  • 61. Write a recursive program to print an array in reverse order. public static void main(String[] args) { Scanner cs=new Scanner(System.in); int n,i; System.out.println("Enter your Array Size:"); n=cs.nextInt(); int arr[]=new int[n]; System.out.println("Enter the Array Element:"); for(i=0;i<n;i++) { arr[i]=cs.nextInt(); } System.out.print("After reversing Array Element Are:"); ReverseArray(arr,n); cs.close(); } } Dr. Mili Dhar
  • 62. Write a recursion Program to find a^b class Power { public static void main(String[] args) { int base = 3, powerRaised = 4; int result = power(base, powerRaised); System.out.println(base + "^" + powerRaised + "=" + result); } public static int power(int base, int powerRaised) { if (powerRaised != 0) { return (base * power(base, powerRaised - 1)); } else { return 1; } } } Dr. Mili Dhar
  • 63. What is a Stack? • A Stack is a linear Data Structure just like an array. • Stack is a restricted form of Array. • Stack is Open from one end only and closed from the other end. • Stack doesn’t allow random access of data, rather the data is accessed in the sequential manner. • Like array it is also a homogeneous collection of elements. • Like array it is also index based. Dr. Mili Dhar
  • 64. Terminologies related to Stack 1. PUSH 1. POP 1. LIFO 1. PEEP 1. TOS 1. OVERFLOW 1. UNDERFLOW Dr. Mili Dhar
  • 65. PUSH, POP & LIFO • PUSH - Push is a process of inserting elements in the Stack, one at a time. • POP - Pop is the process of removing elements from the Stack, one at a time. • LIFO - Since stack is open from one end only, the element inserted(PUSHED) last will be the one to be removed(POPPED) first. Thus we say a stack is based on LAST IN FIRST OUT order. Dr. Mili Dhar
  • 66. PEEP, TOS, OVERFLOW & UNDERFLOW PEEP: The process of accessing (not removing) the top elements of the stack. OVERFLOW & UNDERFLOW: These are conditions which arise when we try to PUSH data in a FULL STACK, or we try to POP data from an EMPTY stack, Respectively. Dr. Mili Dhar
  • 67. Diagrammatic View Of a Stack 20 10 10 arr tos -1 4 3 2 1 0 4 3 2 1 0 arr 0 tos 1 tos arr push(10); push(20); 4 3 2 1 0 Dr. Mili Dhar