Saturday, November 13, 2010

Binary Addition Using BlueJ Program

How to proceed in the binary addition program



This BlueJ program is on addition of two binary numbers. In this program, we will take two binary numbers in two string objects. The smaller string object will be stored on 'bin1' and the greater or same string object will be stored on 'bin2'. Here length of the strings are considered for smaller or greater strings.

Then characters from the end of both string objects are extracted and numeric addition is done on both of them. If the result exceeds 1, it will be reset on 0,1 will be carried forward and the result will be concatenated with another string object 'str'. Ultimately 'str' will be displayed from reverse direction..

import java.io.*;
class Blue
{
public static void main(String args[])throws IOException
{
Blue ob=new Blue();
ob.take();
}
public void take()throws IOException
{
String bin1,bin2;
int i,a,b,c,len1,len2,flag=0;
String str=" ",str1;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter 1st binary Number:");
bin1=br.readLine().trim();
System.out.println("Enter 2nd binary Number:");
bin2=br.readLine().trim();
if(bin1.length()>bin2.length())
{
str1=bin1;
bin1=bin2;
bin2=str1;
}
len1=bin1.length()-1;
len2=bin2.length()-1;
for(i=len1;i>=0;i--)
{
a=bin1.charAt(i)-48;
b=bin2.charAt(len2)-48;
len2--;
c=a+b+flag;
flag=0;
if(c>1)
{
c=0;
flag=1;
}
str=str+c;
}
if(len2==-1 && flag==1)
str=str+flag;
else
{
for(i=len2;i>=0;i--)
{
a=bin2.charAt(i)-48;
c=a+flag;
flag=0;
str=str+c;
}
}
str=str.trim();
len1=str.length()-1;
System.out.println("Sum of the binary numbers are:");
for(i=len1;i>=0;i--)
System.out.print(str.charAt(i));
}
}

Related Post:  BlueJ Programs on String/Sentence
Related PostBlueJ Programs on Number

8 comments:

  1. a=bin1.charAt(i)-48;
    b=bin2.charAt(len2)-48;
    please explain this line once.........

    ReplyDelete
  2. Ascii values of '0' to '9' are from 48 to 57. Using charAt() function we are getting the character format value of the digits. Suppose we get '9', to convert it in numeric value means 9, subtract 48 from '9', it will give numeric 9.

    ReplyDelete
  3. can we take binary numbers as input, pass it to a function which converts them to decimal, then add the numbers and convert it back to binary?

    ReplyDelete
  4. Sir please tell some important expected ISC 2012 practicle questions ...as we have it on 24th Feb 2012!!!!!!!!

    ReplyDelete
  5. very complicated i did it in just 5 line

    ReplyDelete
  6. too long and strong

    ReplyDelete

Subscribe via email

Enter your email address:

Delivered by FeedBurner