Finite State Machine: Implementing Binary Adder in Java

import java.io.*;
class anBinaryAdder
{
public static void main(String args[])throws IOException
{
BufferedReader obj= new BufferedReader (new InputStreamReader (System.in));

int sf = 0;
int mf =0;

System.out.println(“Enter First String:”);
String a=obj.readLine();
System.out.println(“Enter Second String:”);
String b=obj.readLine();

int l1= a.length();
int res[]= new int[l1];

for (int i=l1-1;i>=0;i–)
{
char n1 = a.charAt(i);
char n2 = b.charAt(i);

System.out.println();

mf=maf(n1,n2,sf);
sf=stf(n1,n2,sf);

System.out.print(n1 +”+” + n2 +”=” + “SF”+sf + ” “+”MF” +mf);
System.out.println();

res[i]=mf;
}

System.out.println(“\nO/P :”);
for(int i=0;i<=l1-1;i++) { System.out.print(res[i]); } System.out.println("\nState :"); if (sf==0) { System.out.print("NC"); } else { System.out.print("C"); } } static char stf(char a, char b, int s) { char sf =0; if (s==0 && a=='1' && b=='1') { sf=1; } else if (s==0) { sf=0; } if (s==1 && a=='0' && b=='0') { sf=0; } else if (s==1) { sf=1; } return sf; } static char maf(char a,char b,int s) { char mf=0; if (s==0 && ((a=='0' && b=='0')||(a=='1' && b=='1')) ) { mf=0; } else if (s==0) { mf=1; } if (s==1 && ((a=='0' && b=='0')||(a=='1' && b=='1')) ) { mf=1; } else if (s==1) { mf=0; } return mf; } } /* Output Enter First String: 101011 Enter Second String: 100110 1+0=SF0 MF1 1+1=SF1 MF0 0+1=SF1 MF0 1+0=SF1 MF0 0+0=SF0 MF1 1+1=SF1 MF0 O/P : 010001 State : C */ [/java]

Leave a Reply

Your email address will not be published. Required fields are marked *