Embed presentation
Download to read offline
![Using NetBeans
Q1. Write a program that uses a stack to convert a number in base 10 to a number in base 2.
Solution
import java.util.Scanner;
public class Decimal2BinaryDemo {
public static void main(String args[]) {
Scanner in =new Scanner(System.in);
System.out.println("Enter decimal number =");
int num=in.nextInt();
Stack s4 = new Stack();
int n=num;
int i = 0;
while (n > 0) {
s4.push(n % 2);
n = n / 2;
i++;
}
//s4.print();
System.out.print(num+" is convert to binary ->");
while (i > 0) {
System.out.print(s4.pop()+" ");
i--;
}
}
}](https://image.slidesharecdn.com/usingnetbeansq1-230706033722-9d0e4efa/75/Using-NetBeansQ1-Write-a-program-that-uses-a-stack-to-convert-a-n-pdf-1-2048.jpg)
The document provides a Java program that converts a decimal number to its binary equivalent using a stack data structure. It includes user input for the decimal number and processes the conversion by pushing the binary digits onto the stack before popping them to display the final binary number. The code snippet demonstrates the use of basic programming constructs in Java such as loops, conditionals, and the stack data structure.
![Using NetBeans
Q1. Write a program that uses a stack to convert a number in base 10 to a number in base 2.
Solution
import java.util.Scanner;
public class Decimal2BinaryDemo {
public static void main(String args[]) {
Scanner in =new Scanner(System.in);
System.out.println("Enter decimal number =");
int num=in.nextInt();
Stack s4 = new Stack();
int n=num;
int i = 0;
while (n > 0) {
s4.push(n % 2);
n = n / 2;
i++;
}
//s4.print();
System.out.print(num+" is convert to binary ->");
while (i > 0) {
System.out.print(s4.pop()+" ");
i--;
}
}
}](https://image.slidesharecdn.com/usingnetbeansq1-230706033722-9d0e4efa/75/Using-NetBeansQ1-Write-a-program-that-uses-a-stack-to-convert-a-n-pdf-1-2048.jpg)