Java Program to Convert a Decimal Number to Binary Number using Stacks
Java is high level, compiled as well as interpreted programming language. Stack is an abstract data type used in most of the programming languages and can be implemented using arrays or linked list. Stack data structure follows the principle of LIFO (Last In First Out) . Stack allows push, pop, peek operations to be performed. The push operation is used to insert a new element into the stack. The pop operation is used to remove an element from the top of the stack. The peek operation is used to get the top element of the stack without removing it from the stack. A decimal number can be converted into binary number using the push and pop operation of the Stack. Now, Java provides inbuilt Stack class which can be used to suit our purpose.
Converting a decimal number to binary number using stacks:
- Using predefined stack.
- Using array as a stack.
Method 1: Using Predefined Stack
- A predefined stack class is used to create a stack.
- The user is asked to enter a decimal number.
- Next, a while loop is executed where the mod result of the number by 2 is pushed into the stack and the number is divided by 2.
- This is repeated till the number is greater than 0.
- When the number is 0 the while loop is terminated and another while loop is starts to print the binary equivalent of the decimal number.
- The remainders stored in the stack are popped in LIFO which gives the desired binary representation.
Enter a decimal number: Binary equivalent: 10111
Method 2: Using Array as a stack
- The inbuilt stack class is not used rather an array is used and push and pop methods are defined to perform insertion and removal of the elements.
- The stack is implemented using the static array.
- The static variable count keeps track of the number of the elements inserted.
- The remaining procedure is exactly similar to the previous example.
Enter a decimal number: Binary equivalent: 101110