You are on page 1of 4

DS-LAB 5

22K-4818

Q1.

public class Task1 {


public static int sum(int start, int end) {
if (start > end) {
return 0;
} else {
return start + sum(start + 1, end);
}
}
public static void main(String[] args) {
int result = sum(5, 10);
System.out.println("Sum between 5 and 10: " + result);
}
}

Q2A.
public class Task2a
{
public static void main(String[] args) {
int n = 7;
Sequence(1, 0, n);
}

public static void Sequence(int term, int current, int n) {


if (term <= n) {
System.out.print(current + term + " ");
Sequence(term + 1, current + term, n);
}
}
}

Q2b.
public class Task2b {
public static void Fibonacci(int a, int b, int n) {
if (n > 0) {
System.out.print(a + " ");
Fibonacci(b, a + b, n - 1);
}
}
public static void main(String[] args) {
Fibonacci(0, 1, 13);
}

Q3.
import java.util.Scanner;

public class Task3 {


public static boolean isPalindrome(String str) {
if (str.length() <= 1) {
return true;
} else if (str.charAt(0) != str.charAt(str.length() - 1)) {
return false;
} else {
return isPalindrome(str.substring(1, str.length() - 1));
}
}
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("Give input to check");
String input = inp.next();
if (isPalindrome(input)) {
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}

Q4.
public class Task4 {
public static boolean Sorted(int[] arr, int index) {
if (index == arr.length - 1) {
return true;
}
return arr[index] <= arr[index + 1] && Sorted(arr, index + 1);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
if (Sorted(arr, 0)) {
System.out.println("Array is sorted.");
} else {
System.out.println("Array is not sorted.");
}
}

Q5.
import java.util.ArrayList;
import java.util.List;

public class Task5 {


private static void Subsets(int[] nums, int target, int index,
List<Integer> curr, List<List<Integer>> result) {
if (target == 0) {
result.add(new ArrayList<>(curr));
return;
}
if (index >= nums.length || target < 0) {
return;
}

Subsets(nums, target, index + 1, curr, result);


curr.add(nums[index]);
Subsets(nums, target - nums[index], index + 1, curr, result);
curr.remove(curr.size() - 1);
}
public static List<List<Integer>> SubsetsWithSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Subsets(nums, target, 0, new ArrayList<>(), result);
return result;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4};
int target = 7;
List<List<Integer>> subsets = SubsetsWithSum(nums, target);

if (subsets.isEmpty()) {
System.out.println("No subsets found with the target sum.");
} else {
System.out.println("Subsets that sum to " + target + ":");
for (List<Integer> subset : subsets) {
System.out.println(subset);
}
}
}
}

You might also like