KEMBAR78
Data Structure Lecture Array and Recursion.pdf
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

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 • Whatis an Array? • What is an Stack? • Terminologies related to Stack. • Diagrammatic view of Stack. Dr. Mili Dhar
  • 3.
    What is anArray? • 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 anArray type array-name[]; OR type[] array-name; Example: int Arr[]; OR int [] Arr; Dr. Mili Dhar
  • 6.
    Initialization of anArray var-name = new type [size]; Example: int Arr[]; Arr = new int [20]; Dr. Mili Dhar
  • 7.
    Insert elements inan Array int[] myNum = {10, 20, 30, 40}; String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Dr. Mili Dhar
  • 8.
    Accessing of anArray 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
  • 9.
  • 10.
    class DS { publicstatic 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 Calculationfor 1-D array Dr. Mili Dhar
  • 13.
    • Array ofan 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: • Giventhe 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: • Findthe 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 typearr-name[][]; OR type[][] arr-name; Example: int Arr[][]; OR int [][] Arr; Dr. Mili Dhar
  • 17.
    Initialization of an2D-Array var-name = new type [size][size]; Example: int Arr[] []; Arr = new int [20][20]; Dr. Mili Dhar
  • 18.
    Insert elements inan Array int[][] myNum = {{10, 20}, {30, 40}}; String[] []cars = {{"Volvo", "BMW“}, {"Ford", "Mazda"}}; Dr. Mili Dhar
  • 19.
    Insert elements inan 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 of2D 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 Inrow 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 Incolumn 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 aninteger 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: Givenan 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: • Consideran 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: Givenan 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 matrixis 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. PoojaUnit -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 Matrixand 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 Matrixand 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 Matrixand 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 Matrixand 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 Matrixand 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 operationson matrices Dr. Mili Dhar
  • 37.
    8/27/2024 37 Arithmetic operationson 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 operationson matrices Dr. Mili Dhar
  • 39.
    8/27/2024 39 Arithmetic operationson 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
  • 40.
  • 41.
    Write a programto 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 programto 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 programto 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 programto 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 programto 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 programto 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 programto 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 programto 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 programto 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 programto 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 programto 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 recursionis 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 recursionis 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
  • 54.
  • 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 { staticvoid 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.*; classTree { 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 staticvoid 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 recursiveprogram 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 recursiveprogram 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 recursionProgram 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 aStack? • 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 toStack 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 Ofa 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