Monday, February 4, 2013

ISC Practical 2013 - Expected Question

Two decimal numbers converted into binary and sum in binary form

import java.util.*;
class BinaryAdd
{
public int n,m,p,q,r;
public void input()
{
// two decimal numbers converted into binary
// and sum is also converted into binary
Scanner br = new Scanner(System.in);
System.out.println(" Input a number n");
n=br.nextInt();
System.out.println(" Input a number m");
m=br.nextInt();
}
public void calculate()
{
p=decbin(n);
q=decbin(m);
System.out.println("Binary value for " + n + " is " + p);
System.out.println("Binary value for " + m + " is " + q);
r=sumbin(m+n);
System.out.println("Sum of two binary number " + p + " and " + q + " is " + r);
}
public int decbin(int x)
{
int a,s=0, i=0;
while(x>0)
{
a=x%2;
s = s + (int)Math.pow(10,i)*a;
x=x/2;
i++;
}
return s;
}
public int sumbin(int x)
{
int a,s=0, i=0;
while(x>0)
{
a=x%2;
s = s + (int)Math.pow(10,i)*a;
x=x/2;
i++;
}
return s;
}
public static void main(String arg[])
{
BinaryAdd ob= new BinaryAdd();
ob.input();
ob.calculate();
}
}

No comments: