diff --git a/src/navs/program.js b/src/navs/program.js index ffb7e0d9..758a84f5 100644 --- a/src/navs/program.js +++ b/src/navs/program.js @@ -7,5 +7,10 @@ const pages = createPageList( export const programsNav = { 'Getting started': [pages['introduction']], - Introduction: [pages['print-an-integer'], pages['add-two-integers'], pages['check-even-or-odd']], + Introduction: [ + pages['print-an-integer'], + pages['add-two-integers'], + pages['check-even-or-odd'], + pages['java-program-to-add-two-binary-numbers'], + ], } diff --git a/src/pages/programs/java-program-to-add-two-binary-numbers.mdx b/src/pages/programs/java-program-to-add-two-binary-numbers.mdx new file mode 100644 index 00000000..aadb7585 --- /dev/null +++ b/src/pages/programs/java-program-to-add-two-binary-numbers.mdx @@ -0,0 +1,63 @@ +--- +title: Java Program to Add two Binary Numbers +shortTitle: Add two Binary Numbers +description: In this tutorial we will write a java program to add two binary numbers. +--- + +Binary number system has only two symbols **0** & **1** so a **binary numbers** consists of only 0’s and 1’s. Before we write a program for addition, lets see how we do the addition on paper, this is shown in the diagram below: +![Addition of two binary numbers](https://via.placeholder.com/800x500.webp?text=Addition+of+two+binary+numbers) + +## Adding binary numbers in Java + +### Code: + +```java +import java.util.Scanner; +public class JavaExample { + public static void main(String[] args) + { + //Two variables to hold two input binary numbers + long b1, b2; + int i = 0, carry = 0; + + //This is to hold the output binary number + int[] sum = new int[10]; + + //To read the input binary numbers entered by user + Scanner scanner = new Scanner(System.in); + + //getting first binary number from user + System.out.print("Enter first binary number: "); + b1 = scanner.nextLong(); + //getting second binary number from user + System.out.print("Enter second binary number: "); + b2 = scanner.nextLong(); + + //closing scanner after use to avoid memory leak + scanner.close(); + while (b1 != 0 || b2 != 0) + { + sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2); + carry = (int)((b1 % 10 + b2 % 10 + carry) / 2); + b1 = b1 / 10; + b2 = b2 / 10; + } + if (carry != 0) { + sum[i++] = carry; + } + --i; + System.out.print("Output: "); + while (i >= 0) { + System.out.print(sum[i--]); + } + System.out.print("\n"); + } +} +``` +### Output: + +```text +Enter first binary number: 11100 +Enter second binary number: 10101 +Output: 110001 +```