DSA Lab
DSA Lab
Instructions: make a folder with your name and take screenshots of your code
and output and paste it on a word file. If anyone caught with cheating
material or talking with your partner will get deduction in total marks.
Q1. Write a program using stack operations, which accepts a non-negative base 10
as a parameter, and display binary representation of a number. (10 marks)
Ans:
import java.util.*;
// Convert decimal to binary using division by 2 and push the remainder onto the stack
while (decimal > 0) {
int remainder = decimal % 2;
stack.push(remainder);
decimal /= 2;
}
// Pop the stack and append the elements to a string to get the binary representation
StringBuilder binary = new StringBuilder();
while (!stack.isEmpty()) {
binary.append(stack.pop());
}
return binary.toString();
}
// Convert decimal to octal using division by 8 and push the remainder onto the stack
while (decimal > 0) {
int remainder = decimal % 8;
stack.push(remainder);
decimal /= 8;
}
// Pop the stack and append the elements to a string to get the octal representation
StringBuilder octal = new StringBuilder();
while (!stack.isEmpty()) {
octal.append(stack.pop());
}
return octal.toString();
}
// Convert decimal to binary and octal using stack operations and display the result
System.out.println("Binary representation: " + decimalToBinary(decimal));
System.out.println("Octal representation: " + decimalToOctal(decimal));
}
}
Screenshot:
Q2. Take a single string as input. Using this input string, you have to create
multiple queries in which each queue will comprise of separate word appeared in
input string. At the end, you will again concatenate all queries to a single queue. At
the end concatenate all queues and display them. (10 marks)
Ans:
import java.util.Arrays;
import java.util.Scanner;
}
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);System.out.print("Input the String: ");
String input = Scan.nextLine();
String[] words = input.split("\\s+");
QueueConcatination[] queues = new QueueConcatination[words.length];
Q3. Write down any 3 real world applications of stack and queue data structures?
(5 marks)
Ans: