0% found this document useful (0 votes)
17 views31 pages

2D Arrays Pg. No. 9 TB

An abstract data structure (ADT) defines operations and behaviors of data without detailing implementation. Examples include lists, stacks, queues, trees, graphs, and sets, each supporting various operations like insertion and deletion. The document also discusses pseudocode for counting occurrences of the digit '8' in student exam scores and provides a breakdown of recursion using the Towers of Hanoi problem.

Uploaded by

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

2D Arrays Pg. No. 9 TB

An abstract data structure (ADT) defines operations and behaviors of data without detailing implementation. Examples include lists, stacks, queues, trees, graphs, and sets, each supporting various operations like insertion and deletion. The document also discusses pseudocode for counting occurrences of the digit '8' in student exam scores and provides a breakdown of recursion using the Towers of Hanoi problem.

Uploaded by

harshinik290
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

An abstract data structure (or abstract data type, ADT) is a model for a data structure that defines a

set of operations and the behaviors of those operations, without specifying the exact
implementation details. In other words, it focuses on what operations can be performed and how
the data behaves rather than how the data is stored or implemented.
Key Points about Abstract Data Structures (ADTs):
Definition: An abstract data structure defines the logical properties of the data, including:
The set of values the data structure can hold. The operations (methods or functions) that can be
performed on these values. The expected behavior of those operations (e.g., what the operation
does and how it behaves under different conditions).Abstraction: It hides the implementation
details. For instance, an ADT describes an operation as "insert an element" or "retrieve an element"
without specifying whether this operation will use an array, a linked list, or any other internal data
structure. The focus is on the interface and behavior of the data structure.
Operations: ADTs operations are:
Insertion: Adding an element to the structure.
Deletion: Removing an element.
Traversal: Visiting and accessing elements.
Modification: Changing the value or state of an element.
Examples of abstract data structures are:
List: A collection of elements where the order of elements matters, and you can perform
operations like insertion, deletion, and retrieval.
Stack: A collection of elements where the last element added is the first one to be removed
(LIFO – Last In, First Out).
Queue: A collection of elements where the first element added is the first one to be removed
(FIFO – First In, First Out).
Tree: A hierarchical data structure with a root and child elements, where elements can be
accessed in various orders (e.g., pre-order, in-order, post-order traversal).
Graph: A collection of nodes (vertices) and edges, where nodes are connected to each other,
and the structure can be traversed or searched (e.g., depth-first search, breadth-first
search).
Set: A collection of unique elements, typically supporting operations like union, intersection,
and difference
Pg. no. 9 in ADV. KOSTAS TB – 2D ARRAYS
Scores =
[[98,68,65,73,67],
[77,77,88,78,90],
[77,77,88,78,91],
[88,86,90,56,81]]
STUDENT = 0
EXAM = 0
TCOUNTER = 0
loop STUDENT from 0 to 3
output STUDENT +1, "Student"
loop EXAM from 0 to 4
X=1
COUNTER = 0
X = Scores [STUDENT] [EXAM]
loop while X>0
if X mod 10 = 8 then
COUNTER = COUNTER + 1
TCOUNTER = TCOUNTER +1
end if
X = div (X, 10)
end while
output "----", "The grade of exam ", EXAM+1, "has", COUNTER, "eight(s)"
end loop
Pseudocode Explanation:
STUDENT loop: Loops over each student (there are 4 students, indexed from 0 to 3).
EXAM loop: Loops over each exam (there are 5 exams, indexed from 0 to 4).
Counting eights: For each score, the digits are checked one by one to see if there is an 8.
The count of eights is stored in COUNTER for each exam, and
the total count across all exams is stored in TCOUNTER.
Key Details:X mod 10 = 8 checks if the last digit is 8.X = div(X, 10) reduces the number by
removing the last digit (integer division by 10).
Student 3 (Scores: 77, 77, 88, 78, 91)
77 → Digits: 7, 7 → No "8“
77 → Digits: 7, 7 → No "8“
88 → Digits: 8, 8 → 2 "8"s
78 → Digits: 7, 8 → 1 "8“
91 → Digits: 9, 1 → No "8“
Result for Student 3: 3 eights (Exam 3, Exam 4)
Student 4 (Scores: 88, 86, 90, 56, 81)
88 → Digits: 8, 8 → 2 "8"s
86 → Digits: 8, 6 → 1 "8“
90 → Digits: 9, 0 → No "8“
56 → Digits: 5, 6 → No "8“
81 → Digits: 8, 1 → 1 "8“
Result for Student 4: 4 eights (Exam 1, Exam 2, Exam 5)
Step-by-Step Breakdown: For each student's score, the code checks every digit. Here's how the
program works:
Student 1 (Scores: 98, 68, 65, 73, 67)
98 → Digits: 9, 8 → 1 "8“
68 → Digits: 6, 8 → 1 "8“
65 → Digits: 6, 5 → No "8“
73 → Digits: 7, 3 → No "8“
67 → Digits: 6, 7 → No "8“
Result for Student 1: 2 eights (Exam 1 and Exam 2)
Student 2 (Scores: 77, 77, 88, 78, 90)
77 → Digits: 7, 7 → No "8“
77 → Digits: 7, 7 → No "8“
88 → Digits: 8, 8 → 2 "8"s
78 → Digits: 7, 8 → 1 "8“
90 → Digits: 9, 0 → No "8“
Result for Student 2: 3 eights (Exam 3, Exam 4)
Breakdown of the score 78:The number is 78.
First Digit: We start with X = 78.
We calculate X mod 10, which gives the last digit:78 mod 10 = 8 (This is the last digit, which is 8).
Since the last digit is 8, we increment COUNTER by 1.
Now, COUNTER = 1.
We then update X using integer division:
X = X div 10 = 78 div 10 = 7.
Second Digit: Now, X = 7.
We calculate X mod 10, which gives the last digit:7 mod 10 = 7 (This is the last digit, which is 7,
not 8).
Since the digit is not 8, we do not change COUNTER.
We then update X again: X = X div 10 = 7 div 10 = 0.
Now that X = 0, we exit the while loop because there are no more digits to check. So, for 78, there
is 1 eight.
For 88: The number is 88.
First Digit: We start with X = 88.We calculate X mod 10, which gives the last digit:
88 mod 10 = 8 (This is the last digit, which is 8).
Since the last digit is 8, we increment COUNTER by 1.
Now, COUNTER = 1.
We then update X using integer division: X = X div 10 = 88 div 10 = 8.
Second Digit: Now, X = 8.
We calculate X mod 10, which gives the last digit:8 mod 10 = 8 (This is the last digit, which is 8).
Since the last digit is 8, we increment COUNTER again by 1.
Now, COUNTER = 2.We then update X again: X = X div 10 = 8 div 10 = 0.
Now that X = 0, we exit the while loop because there are no more digits to check.
So, for 88, there are 2 eights.
Pg. no. 12 in TB
Step-by-Step Breakdown:
1. Initialization: NAMES = ["Kostas", "Markos", "Anna", "Mary", "Takis"]:
This is a list of names, which contains five names: "Kostas", "Markos", "Anna", "Mary", and "Takis".

NAMES_C = new Collection():


Here, a new Collection object is created to store items (names in this case). It's like an empty box
where we'll keep things later.

STACK_NAMES = new Stack(): This creates a new Stack. A stack is a data structure that follows the
Last In, First Out (LIFO) principle. This means that the last item pushed into the stack will be
the first one popped out.

I = 0: This initializes a counter variable I to 0. It will be used to loop through the names list.

2. Loop through the Names List:


loop I from 0 to 4: This loop will run 5 times, from I = 0 to I = 4. Each time, the loop will push a name
from the NAMES list into the STACK_NAMES.

STACK_NAMES.push(NAMES[I]): This pushes a name from the NAMES list into the stack.
In each iteration, the current name at position I is added to the stack.
So after the loop runs, the stack will contain all the names in reverse order because of the LIFO
principle.
First iteration (I = 0): STACK_NAMES.push("Kostas")
Second iteration (I = 1): STACK_NAMES.push("Markos")
Third iteration (I = 2): STACK_NAMES.push("Anna")
Fourth iteration (I = 3): STACK_NAMES.push("Mary")
Fifth iteration (I = 4): STACK_NAMES.push("Takis")
After the loop finishes, the stack contains:["Takis", "Mary", "Anna", "Markos", "Kostas"]

3. Output "Add names in the collection":


This outputs the message: "Add names in the collection:". It's just a message to indicate that the
next steps are related to adding names to the NAMES_C collection.

4. Pop Names from Stack and Add to Collection:


loop while NOT(STACK_NAMES.isEmpty()): This loop continues as long as the stack is not empty. It
will pop names from the stack and add them to the NAMES_C collection.
NAME = STACK_NAMES.pop():
The pop() method removes the top name from the stack and assigns it to the NAME variable. This
follows the LIFO principle, meaning it will pop the last name pushed into the stack.
NAMES_C.addItem(NAME): This adds the popped name to the collection NAMES_C.

output NAME, "was entered in the collection":


This outputs the name that was just added to the collection.
Example (Iteration 1):First, NAME = STACK_NAMES.pop() gets "Takis".
Then, "Takis was entered in the collection" is printed.The collection NAMES_C now contains:
["Takis"].
Example (Iteration 2):Next, NAME = STACK_NAMES.pop() gets "Mary". Then, "Mary was entered in
the collection" is printed. The collection NAMES_C now contains: ["Takis", "Mary"].
This process
5. Output thecontinues
Names inuntil the stack is empty.
the Collection:
output "": This just prints an empty line for better readability.
output "Names stored in the collection:": This prints a message to indicate that the next part of the
output will show the names in the collection.
Loop through the Collection and Print Names:
loop while NAMES_C.hasNext(): This loop continues as long as there are more items in the
collection. The hasNext() method checks if there are still names left in the collection.
output NAMES_C.getNext(): The getNext() method retrieves the next name from the collection and
outputs it.
Ex: First, NAMES_C.getNext() retrieves and prints "Takis".Second, NAMES_C.getNext() retrieves and
prints "Mary".This continues for all the names in the collection.
Question 1: What is recursion? Explain with an example.Answer: Recursion is a process in which a
function calls itself directly or indirectly in order to solve a problem. The function continues calling
itself until a base case is met, which stops the recursion.
Ex: Here’s a simple recursive function that calculates the factorial of a number:
Function factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)

Ans:
factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1 (base case)
Topic 5- TB Pg, no.11
. Return address of methodB (0x200)
Argument x (3)
Argument y (5)
Argument z (10)
Return address of methodA (0x100)
Argument a (3)
Local b (5)
Local c (10)
Returning from methodB: Once methodB finishes, it needs to return to the address it was called
from. It pops the return address (0x200) off the stack. After popping the return address, the stack
also removes the arguments x, y, and z that were passed to methodB
TOWERS OF HANOI
How the Recursion Unfolds:
• move(3, 1, 2, 3):
Call move(2, 1, 3, 2)
Call move(1, 1, 2, 3)
Call move(0, 1, 3, 2) → Base case, returns.
Move disk 1 from peg 1 to peg 3.
Call move(0, 2, 1, 3) → Base case, returns.
Move disk 2 from peg 1 to peg 2.
Call move(1, 3, 2, 1)
Call move(0, 3, 2, 1) → Base case, returns.
Move disk 1 from peg 3 to peg 2.
Move disk 3 from peg 1 to peg 3.
Call move(2, 2, 1, 3)
(similar recursive steps as above).
The recursion unwinds after each disk is moved, and the problem is solved step-by-step!
Backtracking to move(2, 1, 3, 2):
Once the recursive call move(1, 1, 2, 3) finishes, the function moves back to the original move(2, 1,
3, 2).
Now, we move the largest disk (disk 2) from peg 1 to peg 2:
t = PEGS[1].pop(): This removes disk 2 from peg 1.
PEGS[2].push(t): Disk 2 is placed onto peg 2.
Now, PEGS[1] might look like [], PEGS[2] has [2], and PEGS[3] might look like [1].
After that, we make the second recursive call move(1, 3, 1, 2) to move the remaining disk from peg 3
to peg 2 using peg 1 as the auxiliary peg.
Summary: The recursive call move(1, 1, 2, 3) is a smaller version of the original problem
where we move 1 disk from peg 1 to peg 3 using peg 2 as the auxiliary peg. This is where
the values of b and c switch:In move(2, 1, 3, 2), peg b = 3 and peg c = 2.In move(1, 1, 2, 3), peg
b = 2 and peg c = 3.These values change because of the recursive structure, where we break down
the original problem into smaller subproblems.You
Now that we’ve completed the recursive step move(0, 1, 3, 2), we can move the nth disk (disk 1)
from peg 1 to peg 3.
t = PEGS[1].pop(): This removes disk 1 from peg 1.
PEGS[3].push(t): This places disk 1 onto peg 3.
Now, PEGS[1] = [3, 2], PEGS[2] = [], and PEGS[3] = [1].
Display
Step 4:isRecursive
called to show
Callthe current2,state
move(0, of the pegs.
1, 3)
After moving disk 1, we need to move the n-1 disks (disk 2) from peg 2 to peg 3 using
peg 1 as the auxiliary peg.
We call move(0, 2, 1, 3). Since n = 0, the function does nothing and returns.
Key Change in b and c Between move(2, 1, 3, 2) and move(1, 1, 2, 3):
When we call move(1, 1, 2, 3), the values of b and c switch compared to the original move(2, 1, 3, 2)
call.
In move(2, 1, 3, 2):b = 3 (auxiliary peg)c = 2 (destination peg)
In move(1, 1, 2, 3):b = 2 (auxiliary peg)c = 3 (destination peg)
This change occurs because in the recursive call, we are effectively trying to move 1 disk from peg 1
to peg 3, using peg 2 as an auxiliary peg. This is part of the recursive breakdown of the problem:
moving smallerInside
What Happens subproblems
move(1,to1,simpler
2, 3)?Atones
this by "swapping"
point, roles
we handle theofbase
pegs.
case (n = 1), and the steps
within move(1, 1, 2, 3) are:
Recursive call move(0, 1, 3, 2):
This step handles the base case (n = 0), so nothing happens and we return.
Move the largest disk (disk 1) from peg 1 to peg 3:
t = PEGS[1].pop(): The largest disk (disk 1) is removed from peg 1.
PEGS[3].push(t): The disk is placed onto peg 3.
Now, PEGS[1] might look like [2], PEGS[2] is empty, and PEGS[3] might look like [1].
Recursive call move(0, 2, 1, 3):This handles the base case again, so nothing happens and we return.
Thus, we have completed moving 1 disk from peg 1 to peg 3 using peg 2 as an auxiliary peg.

Once the recursive call move(1, 1, 2, 3) finishes, the function moves back to the original move(2, 1, 3,
2).
Now, we move the largest disk (disk 2) from peg 1 to peg 2:t = PEGS[1].pop():
This removes disk 2 from peg 1.PEGS[2].push(t): Disk 2 is placed onto peg 2.
Now, PEGS[1] might look like [], PEGS[2] has [2], and PEGS[3] might look like [1].
After that, we make the second recursive call move(1, 3, 1, 2) to move the remaining disk from peg 3
to peg
The 2 usingcall
recursive pegmove(1,
1 as the1,auxiliary peg.
2, 3) is a smaller version of the original problem where we move 1 disk
from peg 1 to peg 3 using peg 2 as the auxiliary peg. This is where the values of b and c switch:
In move(2, 1, 3, 2), peg b = 3 and peg c = 2.
In move(1, 1, 2, 3), peg b = 2 and peg c = 3.These values change because of the recursive
structure, where we break down the original problem into smaller subproblems.
PRACTICE QUESTONS on Recursion: -
Q.1. Determine the output of the code below with it’s working a=‘1’, b=‘2’, n =2
public static void charOut(char a, char b, int n)
{
if (n > 0)
{
System.out.println(a); // Print first character
charOut(b, a, n - 1); // Recursive call with modified parameters
System.out.println(b); // Print second character after recursion
}
}

Q. 2. Observe the below recursive algorithm and answer the que:


FUN (X,N)
if N<=0 then
return 1
else
return X * FUN(X, N-1)
End if
The return stmt gives the value that the algorithm generates.
a. Determine how many ties multiplication is performed when this algorithm is executed?
b. Determine the value of FUN(2,3) showing all your working
c. State the purpose of this recursive algorithm
Q.3. Write a recursive function to calculate the sum of the first n natural numbers.
Q.4. How does recursion differ from iteration?
Q.5. What is the base case in recursion? Why is it important?
Q.6. What will be the output of the following recursive function for n = 3?
Function fun(n):
if n == 0:
return 0
else:
return n + fun(n-1)
Q.7. Write a recursive function to calculate the nth Fibonacci number.
Ans: for Q.2.Example (for 𝑁=3):For 𝐹𝑈𝑁(𝑋,3), the function will compute 𝑋× 𝐹𝑈𝑁( 𝑋,2).
Then, 𝐹𝑈𝑁(𝑋,2) will compute 𝑋×𝐹𝑈𝑁(𝑋,1)
Then, 𝐹𝑈𝑁(𝑋,1) will compute 𝑋×𝐹𝑈𝑁(𝑋,0).
Finally, 𝐹𝑈𝑁(𝑋,0) returns 1, and no multiplication occurs in the base case.
Therefore, multiplication happens 3 times.
2. Determining the Value of FUN(2,3) -We will trace the algorithm step-by-step for FUN(2,3):
Step-by-Step Calculation:
•Call: FUN(2,3)
•Since N=3>0 , we proceed to:
2×FUN(2,2)
•Call: FUN(2,2)
•Since N=2>0 , we proceed to:
2×FUN(2,1)
•Call: FUN(2,1)
Since N=1>0, we proceed to:
2×FUN(2,0)
•Call: FUN(2,0)
Since N=0, we return 1 (base case).
Now we begin returning from the recursive calls:
FUN(2,1)=2×1=2
FUN(2,2)=2×2=4
FUN(2,3)=2×4=8
Thus, the value of FUN(2,3)=8
• Q. 3: Write a recursive function to calculate the sum of the first n natural numbers.
Ans :
Function sum(n):
if n == 1:
return 1
else:
return n + sum(n-1)
For example, sum(4) would be computed as:
sum(4) = 4 + sum(3)
sum(3) = 3 + sum(2)
sum(2) = 2 + sum(1)
sum(1) = 1 (base case)
Result: sum(4) = 4 + 3 + 2 + 1 = 10.
Q.4. How does recursion differ from iteration?
Answer: Recursion is a process where a function calls itself directly or indirectly to solve smaller
instances of the problem until a base case is reached.
Iteration involves repeating a set of instructions using loops (such as for or while), and it doesn't
involve function calls.
Example of Iteration (for factorial):
factorial(n):
result = 1
for i = 1 to n:
result = result * i
return result
In recursion, the function keeps calling itself, while in iteration, a loop is used to repeat a process.
Question 4: What is the base case in recursion? Why is it important?
Answer: The base case in recursion is the condition that stops the recursive calls. It is crucial
because without a base case, the function would keep calling itself indefinitely, leading to a stack
overflow error.For example, in the factorial function, the base case is when n == 1 or n == 0:
Question 5: What will be the output of the following recursive function for n = 3?
Function fun(n):
if n == 0:
return 0
else:
return n + fun(n-1)
Ans: To compute fun(3), we trace the recursion:
fun(3) = 3 + fun(2)
fun(2) = 2 + fun(1)
fun(1) = 1 + fun(0)
fun(0) = 0 (base case)
substituting the values back:
fun(1) = 1 + 0 = 1
fun(2) = 2 + 1 = 3
fun(3) = 3 + 3 = 6
Thus, the output of fun(3) is 6.
Q. 6: Write a recursive function to calculate the nth Fibonacci number.
Answer: The Fibonacci sequence is a series of numbers in which each number is the sum of the two
preceding ones. Here’s the recursive function to calculate the nth Fibonacci number:
Function fibonacci(n):
if n == 0:
return 0
else if n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
Ans: For fibonacci(5):
fibonacci(5) = fibonacci(4) + fibonacci(3)
fibonacci(4) = fibonacci(3) + fibonacci(2)
fibonacci(3) = fibonacci(2) + fibonacci(1)
fibonacci(2) = fibonacci(1) + fibonacci(0)
fibonacci(1) = 1 (base case)
fibonacci(0) = 0 (base case)
Thus, fibonacci(5) = 5.
Q.1.Ans” Key Points to Understand:
 Recursion calls the same method again with updated parameters (n-1).
 Base case (n = 0) stops further recursion and returns control to the previous call.
 Backtracking happens after the base case is hit. Once the recursive call finishes, execution returns
to the previous level, and the remaining code after the recursive call (System.out.println(b)) gets
executed.
 Printing Order: The prints happen in the order of backtracking, meaning the method
prints values as it returns from deeper recursive calls.
Final Output: 1 2 1 2
Determine the output of the code below with it’s working
a=‘1’, b=‘2’, n =2

public static void charOut(char a, char b, int n)


{
if (n > 0)
{
System.out.println(a); // Print first character
charOut(b, a, n - 1); // Recursive call with modified
parameters
System.out.println(b); // Print second character after
recursion
}
}
Parameters Passed:
a = '1'b = '2'n = 2
Step-by-Step Execution: Let's trace the function call to see how the output is generated.
First Call (charOut('1', '2', 2)):
n > 0, so we enter the if block.
The first statement System.out.println(a) will print the character '1’.
Output so far:1
Now, the recursive call charOut(b, a, n - 1) is made, which is charOut('2', '1', 1).
Second Call (charOut('2', '1', 1)):n > 0, so we again enter the if block.
The first statement System.out.println(a) will print the character '2’.
Output so far:1 2
Now, the recursive call charOut(b, a, n - 1) is made, which is charOut('1', '2', 0).
Third Call (charOut('1', '2', 0)):n = 0, so the condition n > 0 is false.
The function does not enter the if block and simply returns without doing anything. There is no output
from this call.
Back to Second Call (charOut('2', '1', 1)):
After the recursive call returns (when n = 0), we execute the statement System.out.println(b), which
will print the character '1’.
Output so far:1 2 1
The second call (charOut('2', '1', 1)) is now complete, and we return to the first call (charOut('1', '2',
2)).
Back to First Call (charOut('1', '2', 2)):After the recursive call returns (when n = 1), we execute the
statement System.out.println(b), which will print the character '2’.
Final Output:1 2 1 2
Full Breakdown:
First, charOut('1', '2', 2) prints '1’.
Then it makes a recursive call to charOut('2', '1', 1), which prints '2’.
This call makes another recursive call to charOut('1', '2', 0), which doesn't print anything and
just returns.
Now, the second call (charOut('2', '1', 1)) prints '1' after the third call returns.
Finally, the first call (charOut('1', '2', 2)) prints '2' after the second call returns.

Why Control Doesn't Jump Back Immediately:The key thing to understand is that recursion
works in layers.
When a recursive call happens:The current function call pauses and waits for the inner call to
finish.The function call stack is built up (you can think of it like stacking books).The function
only returns to the previous call once the deeper call has finished.This is why, after charOut('2',
'1', 1) prints '2', it does not immediately jump back to the original charOut('1', '2', 2) call. It first
needs to finish the recursion (by calling charOut('1', '2', 0)), and only after that is completed
does it return to the previous call and continue executing the remaining code.

You might also like