Don't Wait,Do it yourself.

Latest courses

CFG java programming S->aSb | bSa | epsilon | equal number of a's and b's

PROGRAM:- 1

Note:- this program is based on the following  cfg production rules.

---------------------------------------------------------------------------------------------------------
Q 1. write a java program for the cfg having equal number of a's and b's
    production rule                                                                 //file 1 readable (to be read)
      S -> aSb
      S -> bSa
      S -> ~ ( epsilon)    // the symbol  "~" denote the  epsilon
---------------------------------------------------------------------------------------------------------


---------------------------------------------------------------------------------------------------------
file two= (where code of the cfg written)

code
import java.io.*;
import java.util.Scanner;

class Cfg
{
    public static void main(String args []) throws IOException
    {
        Scanner r=new Scanner(System.in);
        File file=new File("/home/rajeevkumarmahato/CG/C.java");     //first file location  
        BufferedReader br=new BufferedReader(new FileReader(file));
        String t="";
        while((t=br.readLine())!=null)
            System.out.println(t);

        System.out.println("enter the string");
        String input=r.next();
        if(input.length()%2==0)
        {
            int lastpointer=input.length()-1;
            for(int i=0;i<input.length()/2;i++)
            {
                if(input.charAt(i)=='a' && input.charAt(lastpointer)=='b')
                {
                    System.out.println("aSb");
                    lastpointer--;
                }
                else if(input.charAt(i)=='b' && input.charAt(lastpointer)=='a')
                {
                    System.out.println("bSa");
                    lastpointer--;
                }
                else
                {
                    System.out.println("not in the cfg"); 
                     break;

                }

            }
        }
        else
        {

            System.out.println("Not belongs to the cfg");
        }

    }

}

Example;-
1.
CFG java example





















2.



cgf java programming





































1 comment:

  1. nice
    can you provide me the c program code ?
    what is the first file c.java ?

    ReplyDelete

Please do not enter any spam link in the comment Box