Showing posts with label PROGRAM. Show all posts
Showing posts with label PROGRAM. Show all posts

Tuesday, 18 November 2014

CUT THE STICKS



If there are N sticks, A cut operation is performed such that length of all of them are reduced by the length of the smallest stick.
Suppose we have 6 sticks of length
5 4 4 2 2 8
then in one cut operation we make a cut of length 2 from each of the 6 sticks. For next cut operation 4 sticks are left (of non-zero length), whose length are
3 2 2 6
Above step is repeated till no sticks are left.
Input Format 
The first line contains a single integer N. 
The next line contains N integers: a
0, a1,...aN-1 separated by space, where ai represents the length of ith stick.
Output Format 
 output will be the number of sticks that are cut in separate lines

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
int findmin(int * b,int n);
int check(int *a,int n);
int main() {
int n,i,min;
 scanf("%d",&n);
    int arr[n],count=0;
    for(i=0;i<n;i++)
        {
        scanf ("%d",&arr[i]);
        }
     while(check(arr,n))
    {
         min = findmin(arr,n);
         for(i=0;i<n;i++)
             { if(arr[i]>0){
              arr[i]=arr[i]-min;
                 count++;}
              }
         printf("%d\n",count);
         count=0;
        
    }
   
    return 0;
}

  int  check(int *a,int n)
    {
    int i;
    for(i=0;i<n;i++)
        {
        if(a[i] > 0)
            {return 1;
            }
        }
       return 0;
   }
   
  int findmin(int * b,int n) 
      { int i, min=1000;
      for(i=0;i<n;i++)
          {
          if((b[i]>0) && b[i] < min)
              min=b[i];
          }
       return min;
      

      }

Monday, 17 November 2014

LONELY INTEGER

Program:to find number occurring only once

If there are integers in an array,you have to find out the numer that occurs only once

Input Format
The first line of the input indicates the number of integers. 
The next line is integers that form the array.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int lonelyinteger(int a_size, int* a) {
    int a_count[100],i,count=0,c;
   for(i=0;i< 100;i++)
       {
       a_count[i]=0;
       }
    for(i=0;i< a_size;i++)
        {c=*(a+i);
        a_count[c]=(a_count[c])+1;
        }
    for(i=0;i< 100;i++)
        {
           if(a_count[i]==1)
            {return (i); }
        }
   
   
return count;

}
int main() {
    int res;
   
    int _a_size, _a_i;
    scanf("%d", &_a_size);
    int _a[_a_size];
    for(_a_i = 0; _a_i < _a_size; _a_i++) {
        int _a_item;
        scanf("%d", &_a_item);
       
        _a[_a_i] = _a_item;
    }
   
    res = lonelyinteger(_a_size, _a);
    printf("%d", res);
   
    return 0;

}

Friday, 17 October 2014

Fibonacci program in java

/*CSEMATTER.BLOGSPOT.IN
Program-fibonacci series in java*/

import java.util.Scanner;
class fib
{
public static void main(String a[])
{
Scanner sc=new Scanner(System.in);
int prev=0,next=1,sum,num,i;
System.out.println("ENTER THE NO.");
num=sc.nextInt();
System.out.println(""+prev);
System.out.println(""+next);
for(i=2;i<num;i++)
{
sum=prev+next;
prev=next;
next=sum;
System.out.println(""+sum);
}
}
}

Saturday, 11 October 2014

FACTORIAL JAVA PROGRAM

/*CSEMATTER.BLOGSPOT.IN
Program-java program to calculate factorial*/

import java.util.Scanner;
class factorial
{
public static void main(String a[])
{
Scanner sc=new Scanner(System.in);
int i,num,f=1;
System.out.println("ENTER THE NO. TO CALCULATE FACTORIAL");
num=sc.nextInt();
for(i=1;i<num;i++)
{
f=f*i;
}
System.out.println("factorial is"+f);

}
}

Thursday, 9 October 2014

bayzentine program

/*CSEMATTER.BLOGSPOT.IN
Program-implement bayzentine program in c*/

#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>


int main()
{
int i,j,p[20][20],n,nf,cnt0=0,cnt1=1;
printf("Enter the no. of processes:");
scanf("%d",&n);
printf("Enter the process no. of faulty process:");
scanf("%d",&nf);
for(i=0;i<n;i++)
{
if(i==nf)
{
for(j=0;j<n;j++)
{
if(j!=i)
p[i][j]=random(2);
else
p[i][j]=NULL;}
}
else
{
for(j=0;j<n;j++)
{
if(j!=i)
p[i][j]=1;
else
p[i][j]=NULL;
}}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(p[i][j]==1)
++cnt1;
else if(p[i][j]==0)
++cnt0;
else
continue;
}
if(cnt1>cnt0)
continue;
else
{
printf("Processes are not synchronised \n \n");

}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d \t",p[i][j]);
}
printf("\n");
}
getch();
}

/*OUTPUT:
Enter the no. of processes:3
Enter the process no. of faulty process:2
Processes are not synchronised

    1   1
1       1
1   0          */

Wednesday, 8 October 2014

Encryption using Hashing

/* CSEMATTER.BLOGSPOT.IN
    Encryption using Hashing         */


#include <iostream>
#include<cstring>
#include<cmath>
using namespace std;
int evaluate(string str);

int myatoi(string num)
{
int temp=1,res=0,i=0;
while(num[i]!='\0')
{
res=res+temp*num[i++]-'0';
temp=temp*10;
}
return res;
}
int main()
{
string num;
getline(cin,num);
int num=myatoi(num);
cout<<"\n";
while(num>0)
{
int var;
string str1;
getline(cin,str1);
cout << str1<< "\n";
var=evaluate(str1);
--num;
}
return 0;
}

int evaluate(string str)
{
   // cout << "Hello World!" << endl;
   int n,i,k,l,int1,int2;
 
   //string str;
 
    // getline(cin,str);
    int arr[256]={0},arr_cpyi[256]={0},arr_cpy[256]={0};
    for(int j=0;j<str.size();j++)
    {
    ++arr[str[j]];
    ++arr_cpyi[str[j]];
    ++arr_cpy[str[j]];
    }
    // int *ini=&arr_cpy[0];
   
   
       for(k=0;k<256;k++)
    {
   
    for(l=0;l<255;l++)
    {
    if(arr_cpyi[l]>arr_cpyi[l+1])
    {
    // cout<<"*";
    int temp1=arr_cpyi[l];
    arr_cpyi[l]=arr_cpyi[l+1];
    arr_cpyi[l+1]=temp1;
    }
    }
    }
    int z=0;
    for(i=0;i<256;i++)
    {
    if(arr_cpyi[i]!=0)
    ++z;
    else
    continue;
    }
   
    int j,q,v=0;
    int y=ceil(+(z/2))+1;
    // cout<<y<<"\n";
    // int y=str.size()-2;
   
   
    //for(i=255;i>=(256-str.size());i--)
    while(y>0)
    {
    j=0;
    q=255;
    char ch1,ch2;
    // while(arr_cpyi[i]!=arr_cpy[j])
    // j++;
   
    while(arr_cpyi[256-z]!=arr_cpy[j])
    j++;
    while(arr_cpyi[255-v]!=arr_cpy[q])
    q--;
    // cout<<"j="<<j;
    // cout<<"q="<<q<<"\n";
    arr_cpy[j]=0;
    arr_cpy[q]=0;
   
   
    // cout<<"j="<<j<<"\n";
    // cout<<"q="<<q<<"\n";
   
    // ch=*temp-*ini;
    int1=&arr_cpy[j]-&arr_cpy[0];
    int2=&arr_cpy[q]-&arr_cpy[0];
    ch1=(char)int1;
    ch2=(char)int2;
    for(int x=0;x<str.size();)
    {
    if(ch1==str[x])
    {
    str[x]=ch2;
   
    ++x;
    }
    else if(ch2==str[x])
    {
    str[x]=ch1;
   
    ++x;
    }
    else
    ++x;
    }
    --z;
    ++v;
    --y;
   
   
    }
   
   
    cout<< str << endl;
   
    return 0;
}
   

Tuesday, 7 October 2014

MAEKAWA ALGORITHM DISTRIBUTED SYSTEM

/*CSEMATTER.BLOGSPOT..IN
Program name-Maekawa algorithm in distributed system*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>

void process1();
void process2();
void delay(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock());
}
int p[10],pr[10],n,i,j,count=0,ran_pr,temp,max_lmt,min_lmt;

int main()
{
    printf("Enter the no. of processses \n");
    scanf("%d",&n);
    for(i=0; i<n; i++)
        p[i]=i+1;
      do
       {
           ran_pr=random(n);
       }
       while(ran_pr!=0);
    ran_pr=3;
    printf("Control process is P%d \n",ran_pr);
    printf("Enter the priority of processes \n");
    for(i=0; i<n; i++)
    {
        printf("Priority of process P%d : \n",p[i]);
        scanf("%d",&pr[i]);
    }
    for(i=0; i<n-1; i++)
    {
        for(j=i+1; j<n; j++)
        {
            if(pr[i]>pr[j])
            {
                temp=pr[i];
                pr[i]=pr[j];
                pr[j]=temp;

                temp=p[i];
                p[i]=p[j];
                p[j]=temp;
            }
        }
    }
    for(i=0; i<n-1; i++)
    {
        if(p[i]<ran_pr)
        {
            max_lmt=ran_pr;
            process1();
        }
        else
        {
            min_lmt=ran_pr+1;
            process2();
        }
    }

    getch();
}

void process1()
{
    for(j=0; j<ran_pr; j++)
    {
        if(i!=j)
            printf("Process P%d is sending request to P%d \n",p[i],p[j]);
        else
            continue;
    }
    printf("\n");
    for(j=0; j<ran_pr; j++)
    {
        if(i!=j)
        {
            printf("Process P%d is acknowledging P%d \n",p[j],p[i]);
            count++;
        }
        else
            continue;
    }
    printf("\n");
    if(count==(ran_pr-1))
    {
        printf("Process P%d is entering CS \n",p[i]);
        delay(10000);
    }
    printf("\n");
    for(j=0; j<ran_pr; j++)
    {
        if(i!=j)
            printf("Process P%d is sending reply to P%d \n",p[i],p[j]);
        else
            continue;
    }
}

void process2()
{
    for(j=ran_pr+1; j<n; j++)
    {
        if(i!=j)
            printf("Process P%d is sending request to P%d \n",p[i],p[j]);
        else
            continue;
    }
    printf("\n");
    for(j=ran_pr+1; j<n; j++)
    {
        if(i!=j)
        {
            printf("Process P%d is acknowledging P%d \n",p[j],p[i]);
            count++;
        }
        else
            continue;
    }
    printf("\n");

    if(count==(n-ran_pr-1))
    {
        printf("Process P%d is entering CS \n",p[i]);
        delay(10000);
    }
    printf("\n");
    for(j=ran_pr+1; j<n; j++)
    {
        if(i!=j)
            printf("Process P%d is sending reply to P%d \n",p[i],p[j]);
        else
            continue;
    }
}

/*OUTPUT:
Enter the no. of processses 5
Control process is P3
Enter the priority of processes
Priority of process P1 :2
Priority of process P2 :1
Priority of process P3 :5
Priority of process P4 :3
Priority of process P5 :4

Process P2 is sending request to P1
Process P2 is sending request to P3
Process P1 is acknowledging P2
Process P3 is acknowledging P2
Process P2 is entering CS
Process P2 is sending reply to P1
Process P2 is sending reply to P3

Process P1 is sending request to P2
Process P1 is sending request to P3
Process P2 is acknowledging P1
Process P3 is acknowledging P1
Process P1 is entering CS
Process P1 is sending reply to P2
Process P1 is sending reply to P3

Process P4 is sending request to P5
Process P5 is acknowledging P4
Process P4 is entering CS
Process P4 is sending reply to P5

Process P5 is sending request to P4
Process P4 is acknowledging P5
Process P5 is entering CS
Process P5 is sending reply to P4

Process P3 is sending request to P1
Process P3 is sending request to P2
Process P1 is acknowledging P3
Process P2 is acknowledging P3
Process P5 is entering CS
Process P3 is sending reply to P1
Process P3 is sending reply to P2
*/

Monday, 2 June 2014

MIN FILTER IN MATLAB


/*CSEMATTER.BLOGSPOT.IN
PROGRAM FOR MIN FILTER IN MATLAB*/

A = imread('atul1.jpg');
A=imresize(A,[300,300]);
A = rgb2gray(A)
figure,imshow(A),title('ORIGINAL IMAGE');
B=zeros(size(A));
modifyA=padarray(A,[1 1]);

        x=[1:3];
        y=[1:3];
     
for i= 1:size(modifyA,1)-2
    for j=1:size(modifyA,2)-2
     
     
       window=reshape(modifyA(i+x-1,j+y-1),[],1);
               B(i,j)=min(window);

    end
end
B=uint8(B);
figure,imshow(B),title('IMAGE AFTER MIN FILTERING');

MEDIAN FILTER IN MATLAB

/*CSEMATTER.BLOGSPOT.IN
PROGRAM FOR MEDIAN FILTER IN MATLAB*/


A = imread('atul1.jpg');
A=imresize(A,[300,300]);
 A = rgb2gray(A)
figure,imshow(A),title('ORIGINAL IMAGE');
modifyA=zeros(size(A)+2);
B=zeros(size(A));
        for x=1:size(A,1)
            for y=1:size(A,2)
                modifyA(x+1,y+1)=A(x,y);
            end
        end
    
for i= 1:size(modifyA,1)-2
    for j=1:size(modifyA,2)-2
        window=zeros(9,1);
        inc=1;
        for x=1:3
            for y=1:3
                window(inc)=modifyA(i+x-1,j+y-1);
                inc=inc+1;
            end
        end
      
        med=sort(window);
        B(i,j)=med(5);
      
    end
end
B=uint8(B);

figure,imshow(B),title('IMAGE AFTER MEDIAN FILTERING');

Wednesday, 28 May 2014

MEAN FILTER IN MATLAB PROGRAM

/*CSEMATTER.BLOGSPOT.IN
PROGRAM FOR MEAN FILTER IN MATLAB*/


A = imread('atul1.jpg');
A=imresize(A,[300,300]);
A = rgb2gray(A)
figure,imshow(A),title('ORIGINAL IMAGE');

modifyA=zeros(size(A)+2);
B=zeros(size(A));
        for x=1:size(A,1)
            for y=1:size(A,2)
                modifyA(x+1,y+1)=A(x,y);
            end
        end
   
for i= 1:size(modifyA,1)-2
    for j=1:size(modifyA,2)-2
        window=zeros(9,1);
        inc=1;
        sum=0;
        for x=1:3
            for y=1:3
                window(inc)=modifyA(i+x-1,j+y-1);
     
                sum=sum+window(inc);
                inc=inc+1;
            end
        end
       sum=sum/9;
        B(i,j)=sum;
     
    end
end
B=uint8(B);
figure,imshow(B),title('IMAGE AFTER MEAN FILTERING');


MAX FILTER MATLAB PROGRAM

/*CSEMATTER.BLOGSPOT.IN
PROGRAM FOR MAX FILTER IN MATLAB*/


A = imread('atul1.jpg');
A=imresize(A,[300,300]);
 A = rgb2gray(A)
figure,imshow(A),title('ORIGINAL IMAGE');
B=zeros(size(A));
modifyA=padarray(A,[1 1]);

        x=[1:3];
        y=[1:3];
     
for i= 1:size(modifyA,1)-2
    for j=1:size(modifyA,2)-2
       window=reshape(modifyA(i+x-1,j+y-1),[],1);
               B(i,j)=max(window);
 
    end
end
B=uint8(B);
figure,imshow(B),title('IMAGE AFTER MAX FILTERING');

LINEAR FILTER IN MATLAB PROGRAM

/*CSEMATTER.BLOGSPOT.IN
PROGRAM FOR LINEAR FILTER IN MATLAB*/


A = imread('atul1.jpg');
A=imresize(A,[300,300]);
A = rgb2gray(A)
figure,imshow(A),title('ORIGINAL IMAGE');
modifyA=zeros(size(A)+2);
B=[1,2,4;1,2,4;1,2,4];
        for x=1:size(A,1)
            for y=1:size(A,2)
                modifyA(x+1,y+1)=A(x,y);
            end
        end
   
for i= 1:size(modifyA,1)-2
    for j=1:size(modifyA,2)-2
        sum=0;
            for x=1:3
               for y=1:3
                sum=sum +((modifyA(i+x-1,j+y-1))*B(x,y));
            end
        end
       sum=sum/9;
        A(i,j)=sum;
     
    end
end

figure,imshow(A),title('IMAGE AFTER LINEAR FILTERING');

HISTOGRAM EQUALIZATION IN MATLAB

/*CSEMATTER.BLOGSPOT.IN
PROGRAM FOR HISTOGRAM EQUALIZATION IN MATLAB*/


im1=imread('atul1.jpg');
im=rgb2gray(im1);
im=imresize(im,[256,256]);
numofpixels=size(im,1)*size(im,2);
figure(1);
subplot(1,2,1);
imshow(im);
subplot(1,2,2);
imhist(im);
HIm=uint8(zeros(size(im,1),size(im,2)));
freq=zeros(256,1);
probf=zeros(256,1);
probc=zeros(256,1);
cum=zeros(256,1);
output=zeros(256,1);
for i=1:size(im,1)
    for j=1:size(im,2)
        value=im(i,j);
        freq(value+1)=freq(value+1)+1;
        probf(value+1)=freq(value+1)/numofpixels;
   end
end
sum=0;
no_=255;
for i=1:size(probf)
   sum=sum+freq(i);
   cum(i)=sum;
   probc(i)=cum(i)/numofpixels;
   output(i)=round(probc(i)*no_);
end

for i=1:size(im,1)
    for j=1:size(im,2)
     HIm(i,j)=output(im(i,j)+1);
    end
end
figure(2);
subplot(1,2,1);
imshow(HIm);
subplot(1,2,2);
imhist(HIm);

OPERATIONS ON MATRIX IN MATLAB

/*CSEMATTER.BLOGSPOT.IN*/

DIGITAL IMAGE PROCESSING LAB
/*PROGRAM TO PERFORM ADDITION SUBTRACTION ETC. IN MATLAB*/

a=[1,2,3;4,5,6;7,8,9]
b=[2,4,6;1,3,5;3,4,1]
d=[1,2,3]
c=a+b;
disp('addition is ');
disp(c);
c=a-b;
disp('difference is ');
disp(c);
c=a*b;
disp('multiplication is');
disp(c);
disp('dot product');
c=a.*b;
disp(c);
disp('divison is');
c=a/d;
disp(c);
c=inv(a);
disp('inverse is');
disp(c);
disp('powerof matrix');
c=a^2;
disp(c);
disp('scalar divison');
c=a/2;
disp(c);



Tuesday, 25 March 2014

SHIFT REDUCE PARSER

/*CSEMATTER.BLOGSPOT.IN
PROGRAM-SHIFT REDUCE PARSER*/


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>

char ip_sym[15],stack[15];
int ip_ptr=0,st_ptr=0,len,i;
char temp[2],temp2[2];
char act[15];
void check();
int main()
{
printf("\n\t\t SHIFT REDUCE PARSER\n");
printf("\n GRAMMER\n");
printf("\n E->E+E\n ");
printf("\n E->E*E\n E->a");
printf("\n enter the input symbol:\t");
gets(ip_sym);
printf("\n\t stack implementation table");
printf("\n stack\t\t input symbol\t\t action");
printf("\n______\t\t ____________\t\t ______\n");
printf("\n $\t\t%s$\t\t\t--",ip_sym);
strcpy(act,"shift  ");
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
strcat(act,temp);
len=strlen(ip_sym);
for(i=0;i<=len-1;i++)
{
stack[st_ptr]=ip_sym[ip_ptr];
stack[st_ptr+1]='\0';
ip_sym[ip_ptr]=' ';
ip_ptr++;
printf("\n $%s\t\t%s$\t\t\t%s",stack,ip_sym,act);
strcpy(act,"shift ");
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
strcat(act,temp);
check();
st_ptr++;
}
st_ptr++;
check();
}
void check()
{
int flag=0;
temp2[0]=stack[st_ptr];
temp2[1]='\0';
if((!strcmpi(temp2,"a")))
{
stack[st_ptr]='E';
if(!strcmpi(temp2,"a"))
printf("\n $%s\t\t%s$\t\t\tE->a",stack, ip_sym);
flag=1;
}
if((!strcmpi(temp2,"+"))||(strcmpi(temp2,"*")))
{
flag=1;
}
if((!strcmpi(stack,"E*E"))||(!strcmpi(stack,"E+E")))
{
strcpy(stack,"E");
st_ptr=0;
if(!strcmpi(stack,"E+E"))
printf("\n $%s\t\t%s$\t\t\tE->E+E",stack,ip_sym);
if(!strcmpi(stack,"E*E"))
printf("\n $%s\t\t%s$\t\t\tE->E*E",stack,ip_sym);
flag=1;
}

if(!strcmpi(stack,"E")&& ip_ptr ==len)
{
 printf("\n $%s\t\t%s$\t\t\tACCEPT",stack,ip_sym);
getch();
 exit(0);
}
if(flag==0)
{
 printf("\n%s\t\t\t%s\t\t reject",stack,ip_sym);
 exit(0);
}
return;
}

THREE ADDRESS CODE

/*CSEMATTER.BLOGSPOT.IN
PROGRAM-TO GENERATE THREE ADDRESS CODE*/

#include<stdio.h>
#include<string.h>
void pm();
void plus();
void div();
int i,ch,j,l,addr=100;
char ex[10],exp[10],exp1[10],exp2[10],id1[5],op[5],id2[5];
void main()
{
clrscr();
while(1)
{
printf("\n1.assignment\n2.arithmetic\n3.relational\n4.Exit\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the expression with assignment operator:");
scanf("%s",exp);
l=strlen(exp);
exp2[0]='\0';
i=0;
while(exp[i]!='=')
{
i++;
}
strncat(exp2,exp,i);
strrev(exp);
exp1[0]='\0';
strncat(exp1,exp,l-(i+1));
strrev(exp1);
printf("Three address code:\ntemp=%s\n%s=temp\n",exp1,exp2);
break;

case 2:
printf("\nEnter the expression with arithmetic operator:");
scanf("%s",ex);
strcpy(exp,ex);
l=strlen(exp);
exp1[0]='\0';

for(i=0;i<l;i++)
{
if(exp[i]=='+'||exp[i]=='-')
{
if(exp[i+2]=='/'||exp[i+2]=='*')
{
pm();
break;
}
else
{
plus();
break;
}
}
else if(exp[i]=='/'||exp[i]=='*')
{
div();
break;
}
}
break;

case 3:
printf("Enter the expression with relational operator");
scanf("%s%s%s",&id1,&op,&id2);
if(((strcmp(op,"<")==0)||(strcmp(op,">")==0)||(strcmp(op,"<=")==0)||(strcmp(op,">=")==0)||(strcmp(op,"==")==0)||(strcmp(op,"!=")==0))==0)
printf("Expression is error");
else
{
printf("\n%d\tif %s%s%s goto %d",addr,id1,op,id2,addr+3);
addr++;
printf("\n%d\t T:=0",addr);
addr++;
printf("\n%d\t goto %d",addr,addr+2);
addr++;
printf("\n%d\t T:=1",addr);
}
break;
case 4:
exit(0);
}
}
}
void pm()
{
strrev(exp);
j=l-i-1;
strncat(exp1,exp,j);
strrev(exp1);
printf("Three address code:\ntemp=%s\ntemp1=%c%ctemp\n",exp1,exp[j+1],exp[j]);
}
void div()
{
strncat(exp1,exp,i+2);
printf("Three address code:\ntemp=%s\ntemp1=temp%c%c\n",exp1,exp[i+2],exp[i+3]);
}
void plus()
{
strncat(exp1,exp,i+2);
printf("Three address code:\ntemp=%s\ntemp1=temp%c%c\n",exp1,exp[i+2],exp[i+3]);
}


/*OUTPUT
Example Generation of Three Address Project Output Result

1. assignment
2. arithmetic
3. relational
4. Exit
Enter the choice:1
Enter the expression with assignment operator:
a=b
Three address code:
temp=b
a=temp

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a+b-c
Three address code:
temp=a+b
temp1=temp-c

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a-b/c
Three address code:
temp=b/c
temp1=a-temp

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a*b-c
Three address code:
temp=a*b
temp1=temp-c

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:a/b*c
Three address code:
temp=a/b
temp1=temp*c
1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:3
Enter the expression with relational operator
a
<=
b

100 if a<=b goto 103
101 T:=0
102 goto 104
103 T:=1

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:4

*/

Sunday, 23 March 2014

PREDICTIVE PARSER PROGRAM

/*CSEMATTER.BLOGSPOT.IN
PROGRAM NAME-STACK IMPLEMENTATION OF PREDICTIVE PARSER*/

#include<ctype.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define non_term_count 5
#define term_count 6
#define rightHandMarker term_count-1
#define no_of_production 8

char nt[]={'E','A','T','B','F'},ter[]={'i','+','*','(',')','$'};
char arr[20][20][20]={
   {"TA","","","TA","",""},
    {"","+TA","","","@","@"},
    {"FB","","","FB","",""},
    {"","@","*FB","","@","@"},
    {"i","","","(E)","",""}
};
char ipstr[20];
char stack[40],prod[10];
int i=0,top=1,ia,ix;

struct predictive_table
{
 char prod[10];
}table[non_term_count][term_count]={"\0"};

struct
{
 int isNull;
 char term[10];
}first[non_term_count]={{0,"(i"},{1,"+"},{0,"(i"},{1,"*"},{0,"(i"}};
struct
{
 int isMarker;
 char term[10];
}follow[non_term_count]={{1,")"},{1,")"},{1,"+)"},{1,"+)"},{1,"+*)"}};
char terminals[term_count-1][2]={"i","+","*","(",")"};
char nonTerminals[non_term_count][3]={"E","A","T","B","F"};
char grammar[no_of_production][10]={"E T A","A + T A","A @","T F B","B * F B","B @","F ( E )","F i"};
char pgrammar[no_of_production][10]={"E->TA","A->+TA","A->@","T->FB","B->*FB","B->@","F->(E)","F->i"};

int matchTerminals(char term[])
{
 int i=-1;
 for(i=0; i<term_count-1; i++)
if(!strcmp(term,terminals[i]))
break;
 return i;
}

void copy_follow(int index,int loc)
{
 char term[2];
 int j,ind;
 if(follow[index].isMarker==1)
 {
  if(strlen(table[index][rightHandMarker].prod)==0)
   strcpy(table[index][rightHandMarker].prod,pgrammar[loc]);
  else
   printf("\nGiven Grammar is not LL(1)");
 }
 j=0;

 while(follow[index].term[j]!='\0')
 {
  term[0]=follow[index].term[j];
  term[1]='\0';
  ind = matchTerminals(term);
  if(strlen(table[index][ind].prod)==0)
   strcpy(table[index][ind].prod,pgrammar[loc]);
  else
   printf("\nGiven Grammar is not LL(1)");
  j++;
 }
}

int matchNonTerminals(char non_term[])
{
 int i=-1;
 for(i=0; i<non_term_count; i++)
if(!strcmp(non_term,nonTerminals[i]))
break;
 return i;
}



void show_table()
{
 int k,i,j;
 printf("\n\t\t\tPredictive Parser Table \n\n");
 printf("   |");
 for(i=0; i<term_count-1; i++)
  printf("    %s    |",terminals[i]);
 printf("    $    |");
 for(i=0; i<non_term_count; i++)
 {
  printf("\n----------------------------------------------------------------");
  printf("\n%s",nonTerminals[i]);
  for(k=strlen(nonTerminals[i]); k<3; k++)
   printf(" ");
  printf("|");
  for(j=0; j<term_count; j++)
  {
    printf(" %s",table[i][j].prod);
    for(k=strlen(table[i][j].prod); k<8; k++)
     printf(" ");
    printf("|");
  }
 }
}
void fun();
int main()
{
 int i,k,j,t,flag=0,indexTerm,indexNonTerm,index;
 char nextChar[10]="\0",nonterm[10]="\0",term[10]="\0";
 for(i=0; i<no_of_production; i++)
 {
  t=0;
  j=0;
  flag=0;
  while(grammar[i][j]!=' '&&grammar[i][j]!='\0')
   nonterm[t++]=grammar[i][j++];
  nonterm[t]='\0';
  indexNonTerm=matchNonTerminals(nonterm);
X:  j++;
  t=0;
  while(grammar[i][j]!=' '&&grammar[i][j]!='\0')
   nextChar[t++]=grammar[i][j++];
  nextChar[t]='\0';
  if(!strcmp(nextChar,"@"))
   copy_follow(indexNonTerm,i);
  else
  {
   index=matchTerminals(nextChar);
   if(index!=term_count-1)
   {
    if(strlen(table[indexNonTerm][index].prod)==0)
     strcpy(table[indexNonTerm][index].prod,pgrammar[i]);
    else
    {
      printf("\nGiven Grammar is not LL(1)");
      break;
    }
   }
   else
   {
    index=matchNonTerminals(nextChar);
    if(index!=non_term_count)
    {
     k=0;
     while(first[index].term[k]!='\0')
     {
       term[0]=first[index].term[k];
       term[1]='\0';
       indexTerm=matchTerminals(term);
       if(strlen(table[indexNonTerm][indexTerm].prod)==0)
strcpy(table[indexNonTerm][indexTerm].prod,pgrammar[i]);
       else
       {
printf("\n Given Grammar is not LL(1) ");
break;
       }
       k++;
     } //end while
     if(first[index].isNull==1)
     {
       flag=1;
       goto X;
     }
     else
      flag=0;
    }
   }
  }
  if(flag==1)
   copy_follow(indexNonTerm,i);
 }
 show_table();
 fun();
 getch();
}


void fun()
{

       void pop();
void push(char);
int resolve_nt(char);
int resolve_t(char);
void advance();
char a,x;
int len,k;
stack[0]='$';
stack[1]='E';
printf("\nenter the input string:\n");
scanf("%s",ipstr);
printf("I/p string\t\tStack\t\tProduction Used\n");
while(1)
{
a=ipstr[i];
x=stack[top];
for(k=i;ipstr[k]!='$';k++)
printf("%c",ipstr[k]);
printf("$\t\t");
if(x==a)
{
if(x=='$')
{
printf("input is accepted");
break;
}
else
{
pop();
advance();
}
}
else if(isupper(x))
{
ix=resolve_nt(x);
ia=resolve_t(a);
strcpy(prod,arr[ix][ia]);
len=strlen(prod);
pop();
for(k=1;k<=len;k++)
push(prod[len-k]);
if(stack[top]=='@')
pop();
}
else
{
printf("error");
break;
}
for(k=0;k<=top;k++)
printf("%c",stack[k]);
printf("\t\t\t%s\n",prod);
}
}

void push(char t)
{
top+=1;
stack[top]=t;
}
void pop()
{
top--;
}
void advance()
{
i++;
}
int resolve_nt(char t)
{
int k,index;
for(k=0;k<5;k++)
{
if(t==nt[k])
{
index=k;
break;
}
}
return index;
}

int resolve_t(char t)
{
int k,index;
for(k=0;k<6;k++)
{
if(t==ter[k])
{
index=k;
break;
}
}
return index;
}

/*OUTPUT


                        Predictive Parser Table

   |    i    |    +    |    *    |    (    |    )    |    $    |
----------------------------------------------------------------
E  | E->TA   |         |         | E->TA   |         |         |
----------------------------------------------------------------
A  |         | A->+TA  |         |         | A->@    | A->@    |
----------------------------------------------------------------
T  | T->FB   |         |         | T->FB   |         |         |
----------------------------------------------------------------
B  |         | B->@    | B->*FB  |         | B->@    | B->@    |
----------------------------------------------------------------
F  | F->i    |         |         | F->(E)  |         |         |
enter the input string:
i+i*i$
I/p string              Stack           Production Used
i+i*i$          $AT                     TA
i+i*i$          $ABF                    FB
i+i*i$          $ABi                    i
i+i*i$          $AB                     i
+i*i$           $A                      @
+i*i$           $AT+                    +TA
+i*i$           $AT                     +TA
i*i$            $ABF                    FB
i*i$            $ABi                    i
i*i$            $AB                     i
*i$             $ABF*                   *FB
*i$             $ABF                    *FB
i$              $ABi                    i
i$              $AB                     i
$               $A                      @
$               $                       @
$               input is accepted

*/

FIRST AND FOLLOW PROGRAM

/*CSEMATTER.BLOGSPOT.IN
PROGRAM-TO FIND FIRST AND FOLLOW*/

#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<conio.h>

void follow(char c);
void first_1(char c);
void FIRST(char );

int n,m=0,p,i=0,j=0;
char a[10][10],f[10];
int count,n1=0;
char  first[10];

int main()
{
 int i,z,choice;
 char c,ch;
 printf("Enter the no.of productions:");
 scanf("%d",&n);
 printf("Enter the productions(epsilon=$):\n");
 for(i=0;i<n;i++)
  scanf("%s%c",a[i],&ch);
count=n;

do
{
n1=0;
printf("Element :");
scanf("%c",&c);
FIRST(c);
printf("\n FIRST(%c)= { ",c);
for(i=0;i<n1;i++)
printf("%c ",first[i]);
printf("}\n");

printf("press 1 to continue : ");
scanf("%d%c",&choice,&ch);
}
while(choice==1);

 do
 {
  m=0;
  printf("Enter the element whose FOLLOW is to be found:");

  scanf("%c",&c);
  follow(c);
    printf("FOLLOW(%c) = { ",c);
  for(i=0;i<m;i++)
   printf("%c ",f[i]);
  printf(" }\n");
    printf("Do you want to continue(0/1)?");
  scanf("%d%c",&z,&ch);
 }
 while(z==1);
}

void follow(char c)
{

 if(a[0][0]==c)
 f[m++]='$';
 for(i=0;i<n;i++)
 {
  for(j=2;j<strlen(a[i]);j++)
  {
   if(a[i][j]==c)
   {
    if(a[i][j+1]!='\0')
     first_1(a[i][j+1]);

    if(a[i][j+1]=='\0'&&c!=a[i][0])
     follow(a[i][0]);

   }
  }
 }
}
void first_1(char c)
{
      int k;
                 if(!(isupper(c)))
                 f[m++]=c;

                 for(k=0;k<n;k++)
                 {
                 if(a[k][0]==c)
                 {
                 if(a[k][2]=='$')
                  follow(a[i][0]);
                 else if(islower(a[k][2]))
                 f[m++]=a[k][2];

                 else
                  first_1(a[k][2]);
                 }
                 }

}



void FIRST(char c)
{
int j;
if(!(isupper(c)))first[n1++]=c;
for(j=0;j<count;j++)
{
if(a[j][0]==c)
{
if(a[j][2]=='$') first[n1++]='$';
else if(islower(a[j][2]))first[n1++]=a[j][2];
else FIRST(a[j][2]);
}
}
}

/*OUTPUT

Enter the no.of productions:8
Enter the productions(epsilon=$):
E=TD
D=+TD
D=$
T=FS
S=*FS
S=$
F=(E)
F=a
Element :E
FIRST(E)= { ( a }
press 1 to continue : 1

Element :D
FIRST(D)= { + $ }
press 1 to continue : 1

Element :T
FIRST(T)= { ( a }
press 1 to continue : 1

Element :S
FIRST(S)= { * $ }
press 1 to continue : 1

Element :F
FIRST(F)= { ( a }
press 1 to continue : 0

Enter the element whose FOLLOW is to be found:E
FOLLOW(E) = { $ )  }
Do you want to continue(0/1)?1

Enter the element whose FOLLOW is to be found:D
FOLLOW(D) = { $ )  }
Do you want to continue(0/1)?1

Enter the element whose FOLLOW is to be found:T
FOLLOW(T) = { + $ )  }
Do you want to continue(0/1)?1

Enter the element whose FOLLOW is to be found:S
FOLLOW(S) = { + $ )  }
Do you want to continue(0/1)?1

Enter the element whose FOLLOW is to be found:F
FOLLOW(F) = { * + $ )  }
Do you want to continue(0/1)?0 */

Friday, 21 March 2014

LEXICAL TOOL PROGRAM IN C

/*CSEMATTER.BLOGSPOT.IN
PROGRAM-LEXICAL ANALYSIS PROGRAM IN C*/

/*4 FILES ARE NEEDED FOR THIS PROGRAM
1.LEX.C
2.INTER.C-automatically generated on running
3.OPER.C-contains opeartors
4.KEY.C-contains keyword
and one file to perform lexical analysis
NOTE-PUT ALL THREE C FILES IN A SAME FOLDER AND ON RUNNING THE PROGRAM ENTER ANY FILE NAME,THAT SHOULD BE PRESENT IN SAME FOLDER*/

*/


1 LEX.C

#include"stdio.h"
#include"conio.h"
#include<string.h>
#include<ctype.h>

void main()
{
FILE *fi,*fo,*fop,*fk;
int flag=0,i=1;
char c,t,a[15],ch[15],file[20];
clrscr();
printf("Enter the file name : ");
scanf("%s",file);
fi=fopen(file,"r");
fo=fopen("inter.c","w");
fop=fopen("oper.c","r");
fk=fopen("key.c","r");
c=getc(fi);
while(!feof(fi))
{
if(isalpha(c)||isdigit(c)||(c=='['||c==']'||c=='.'==1))
fputc(c,fo);
else
{
if(c=='\n')
fprintf(fo,"\t$\t");
else
fprintf(fo,"\t%c\t",c);
}
c=getc(fi);
}
fclose(fi);
fclose(fo);
fi=fopen("inter.c","r");
printf("\t\tLEXICAL ANALYSIS \n");
fscanf(fi,"%s",a);
printf("\nline : %d\n",i++);
while(!feof(fi))
{
if((strcmp(a,"$")==0))
{
printf("\nline : %d\n",i++);
fscanf(fi,"%s",a);
}
fscanf(fop,"%s",ch);
while(!feof(fop))
{
if(strcmp(ch,a)==0)
{
fscanf(fop,"%s",ch);
printf("\t\t%s\t:\t%s\n",a,ch);
flag=1;
}
fscanf(fop,"%s",ch);
}
rewind(fop);
fscanf(fk,"%s",ch);
while(!feof(fk))
{
if(strcmp(ch,a)==0)
{
fscanf(fk,"%s",ch);
printf("\t\t%s\t:\tkeyword\n",a);
flag=1;
}
fscanf(fk,"%s",ch);
}
rewind(fk);
if(flag==0)
{
if(isdigit(a[0]))
printf("\t\t%s\t:\tconstant\n",a);
else
printf("\t\t%s\t:\tidentifier\n",a);

}
flag=0;
fscanf(fi,"%s",a);
}
getch();
}

------------------------------------------------------------------------------------------------------------

2.key.c

int
void
main
char
if
for
while
else
printf
scanf
FILE
include
stdio.h
conio.h
iostream.h

------------------------------------------------------------------------------------------------------------

3.oper.c

( openpara
) closepara
{ openbrace
} closebrace
<     lesser
> greater
" doublequote
' singlequote
: colon
; semicolon
# preprocessor
= equal
== assign
% percentage
^ bitwise
& reference
* star
+ add
- sub
\ backslash
/ slash


------------------------------------------------------------------------------------------------------------
/*sample file is cd4.c

#include<stdio.h>
#include<conio.h>

int main()
{
int a;
printf("hello");
if(a==1)
{
printf("ok");
}
else
{
printf("notok");
}
}
*/

/*output-

Enter the file name : cd4.c
                LEXICAL ANALYSIS

line : 1
                #       :       preprocessor
                include :       keyword
                <       :       lesser
                stdio.h :       keyword
                >       :       greater

line : 2
                #       :       preprocessor
                include :       keyword
                <       :       lesser
                conio.h :       keyword
                >       :       greater

line : 3
                $       :       identifier
                int     :       keyword
                main    :       keyword
                (       :       openpara
                )       :       closepara

line : 4
                {       :       openbrace

line : 5
                int     :       keyword
                a       :       identifier
                ;       :       semicolon

line : 6
                printf  :       keyword
                (       :       openpara
                "       :       doublequote
                hello   :       identifier
                "       :       doublequote
                )       :       closepara
                ;       :       semicolon

line : 7
                if      :       keyword
                (       :       openpara
                a       :       identifier
                =       :       equal
                =       :       equal
                1       :       constant
                )       :       closepara

line : 8
                {       :       openbrace

line : 9
                printf  :       keyword
                (       :       openpara
                "       :       doublequote
                ok      :       identifier
                "       :       doublequote
                )       :       closepara
                ;       :       semicolon

line : 10
                }       :       closebrace

line : 11
                else    :       keyword

line : 12
                {       :       openbrace

line : 13
                printf  :       keyword
                (       :       openpara
                "       :       doublequote
                notok   :       identifier
                "       :       doublequote
                )       :       closepara
                ;       :       semicolon

line : 14
                }       :       closebrace

line : 15
                }       :       closebrace

line : 16
                $       :       identifier
*/

INFIX TO POSTFIX PROGRAM IN C

/*CSEMATTER.BLOGSPOT.IN
PROGRAM-INFIX TO POSTFIX PROGRAM IN C*/


#include<stdio.h>
#include<conio.h>
#include<string.h>
#define size 10

char stack[size];
int tos=0,element;
void push(int element);
char pop();
void show();
int isempty();
int isfull();
char infix[30],output[30];
int prec(char);

int main()
{
        int i=0,j=0,k=0,length;
        char temp;
        printf("enter the infix expression\n");
        scanf("%s",infix);
        length=strlen(infix);
  for(i=0;i<length;i++)
  {
  if(infix[i]!='+' && infix[i]!='-' && infix[i]!='*' && infix[i]!='/' && infix[i]!='^' && infix[i]!=')' && infix[i]!='(' )
    {
   output[j++]=infix[i];
    }
   else
    {
    if(tos==0)
    {
    push(infix[i]);
    }
    else
    {
    if(infix[i]!=')' && infix[i]!='(')
    {
    if( prec(infix[i]) <= prec(stack[tos-1])  )
    {
    output[j++]=pop();
    push(infix[i]);
    }
    else
    {
    push(infix[i]);
    } }
    else
    {
    if(infix[i]=='(')
    {push(infix[i]);}
    if(infix[i]==')')
    {
    temp=pop();
    while(temp!='(')
    {output[j++]=temp;
    temp=pop();}
    }}}}}
    while(tos!=0)
    {
    output[j++]=pop();
    }
 printf("the postfix expression is: %s\n",output);}

void push(int element)
{
    stack[tos]=element;
    tos++;
}
char pop()
{
    tos--;
    return(stack[tos]);
}

int prec(char symbol)
{
if(symbol== '(')
return 0;
if(symbol== ')')
return 0;
if(symbol=='+' || symbol=='-')
return 1;
if(symbol=='*' || symbol=='/')
return 2;
if(symbol=='^')
return 3;
return 0;
}