Harleen Kaur Lab 2
Harleen Kaur Lab 2
Student ID : 229583770
Lab 2
Ans 1) a:
Ans 1) b:
Ans 1) c:
Recursion in Java involves dissecting a problem into identical subproblems, applying the same
method iteratively to progressively smaller input, and assembling the results to solve the original
problem while respecting specific termination criteria.
Ans 1) d:
With each recursive invocation in Java, the problem size undergoes reduction by narrowing the
scope of the function's operation to a more compact and manageable segment of the initial data.
This decrease typically entails subdividing the problem into subproblems structurally identical to the
original one but focusing on a smaller data segment. As successive recursive calls occur, they operate
on a reduced portion of the input, often approaching the base case or termination condition,
progressively diminishing the problem's scale during each recursion step. This recurrent process
continues until the base case is achieved, at which point the problem is directly resolved for that
particular subset, enabling the unwinding of recursion to consolidate outcomes and, ultimately,
resolve the initial, broader problem.
Ans 1) e:
The base case in recursion is the simplest problem instance where the algorithm can directly provide
a solution without further recursion. Its selection depends on the specific problem and serves as the
stopping point, ensuring the recursive calls eventually reach this elementary case. For example, in
factorial calculations, the base case is often factorial(0) = 1, while for Fibonacci sequences, it's
typically fib(0) = 0 and fib(1) = 1. A well-defined base case is vital to prevent infinite recursion and
maintain algorithm accuracy.
Ans 1) f:
Whether a recursive solution reaches the base case depends on how it's set up. If it's designed well,
it should gradually simplify the problem until it hits the base case. But if the setup isn't right—like
missing rules to stop—it might never reach the base case. That can lead to big problems, like the
program running forever or crashing. So, making sure there are clear ways to stop is super important
in recursive solutions.
Ans 1) g:
To correct the solution, ensure clear and appropriate termination conditions in the recursive
algorithm. This means adding checks to stop recursion when needed, aligning them with the
problem's requirements and constraints.
Ans 1) h:
Ans 2)
public class DataLab1
{
public static char maximumChar(String str, char max) {
if (str.isEmpty()) {
return max;
}
if (number < 0)
{
isNegative = true;
number = -number;
}
if (isNegative)
{
return reversedNumber + "-";
} else {
return reversedNumber;
}
}