Wednesday 4 December 2013

C program to demonstrate working of Turing Machine

Leave a Comment
        Turing machine is a imaginary device with infinite tape which manipulates the symbols on tape to get required result on the basis of specified rule. Instead of going in a theoretical detail we will concentrate on practical implementation of it.
        Here we are going to demonstrate "n mod 2" implementation using Turing machine. In this example we take input from user (number 'n') and then create an array with size 'n+2' containing "NULL" followed by all 1s followed by "NULL". At first pointer is pointing to the left most element of array which is initial of array. Then by traversing right go to the element of array which is "NULL" and stop at that point as shown in the figure below. Then traverse left. If '1' comes while traversing left, replace '1' with "NULL" and alter the flag between 0 and 1. At last if you get flag as '1' then it can be considered as ODD number otherwise (flag=0 i.e. remain as it is) it is EVEN number.
       Download program NMOD2.c.


#include"stdio.h"
#include"stdlib.h"
int main()
{
 int i,n,flag=0;
 char *ptr;
 printf("\n Enter number\n");
 scanf("%d",&n);
 ptr= (char *)malloc((n+2)*sizeof(char));

 for(i = 0; i < n+2; i++)
 {
  if(i == 0 || i == n+1)
  {
   ptr[i]='\0';
  }
  else
  {
   ptr[i]='1';
  }
 }

 ptr=ptr+1;
 while(*ptr != '\0')
 {
  ptr = ptr+1;
 }
 ptr = ptr-1;

 while(*ptr != '\0')
 {
  if(*ptr == '1')
  *ptr='\0';

  if(flag == 0)
  {
   flag = 1;
  }

  else if(flag == 1)
  {
   flag = 0;
  }
  else
  {
  }
  ptr=ptr-1;
 }
 
 if(flag == 1)
  printf("This is ODD Number\n");
 else
  printf("This is EVEN Number\n" );
 return 0;
}


0 comments:

Post a Comment