Saturday, August 13

Create a Pipe and print descriptive value








program


#include<stdio.h>
main()
{
int f[2];
pipe(f);
printf("Pipe Descriptive values are  %d and %d ", f[0],f[1]);
}


Create a Child process and print process-id


(i) Using one fork() system call

#include<stdio.h>
main()
{
      int f,c,p;
      f=fork();
      if(f==0)
      {
              c=getpid();
              printf("Child Process\n pid: %d",c);
              c=getppid();
              printf("\tppid :%d \n",c);
      }
      else if(f>0)
      {
           sleep(1);
           c=getpid();
           printf("\nParent Process\n pid: %d",c);
           c=getppid();
           printf("\tppid :%d\n\n",c);
      }
}
     
     
     
     

Tuesday, August 2

DEVELOP A SIMPLE ANDROID APPLICATION- Example with Code

Create a Simple Android  Application-
SIMPLE CONVERTER



"Simple converter" is the application intended to convert values from one unit to other that user can select. There are separate pages for Length, Temperature, weight.


Hi friends,

This time I would like to explain in detail how to make a simple Android application through an example - "SIMPLE CONVERTER". Here I provide the complete java code for this application. Step by Step explanation of the code is also given. "SIMPLE CONVERTER" is created in such a manner that many of the basic codes for android application development may  included. To understand them correctly, I tried to describe them stepwise.  Hope this will be useful for you.

This post includes:
  • How to make Android development platform? 
  • How to create User interface?
  • Code for basic Android application
  • Code for EditText
  • Code for Button
  • Code for Toast
  • Code for Spinner
Firstly, developing an simple Android application is  an easy job, if you know basics of java programming. Hope you are provided with eclipse to make a platform for android application development.

(I) Create application development platform

  1. To start application creation open eclipse and follow file--> New -->Project
  2. Select Android application from Android folder and "Finish".
  3. Enter necessary fields in dialog box.


 Look at the example..
  

                                  


(II) Create User Interface for Application

We need  two 'EditText 's  to enter values and two  'Button's for submitting our choices.We can include them in main.xml as follows.

Open res-->layout-->main.xml.

Edit main.xml it as:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="
http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SIMPLE CONVERTER"
android:gravity="center"
android:textSize="25sp"
/>

<EditText android:id="@+id/Value1"
android:layout_width="120sp"
android:layout_below="@+id/header"
android:hint="0.0"
android:layout_height="wrap_content">
</EditText>

<EditText
android:id="@+id/Value2"
android:layout_width="120sp"
android:hint="0.0"
android:layout_height="wrap_content"
android:layout_below="@+id/Value1">
</EditText>

<Button android:text="convert"
android:id="@+id/convert"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_below="@+id/Value2" >
</Button>

<Button android:text="Reset"
android:id="@+id/reset"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_below="@+id/convert">
</Button>

</RelativeLayout>

The output of the xml file will be as follows:







(III) Create Android Code for Application

Open the java file as src-->  <package name> -->    <filename.java>

In this example it is liengthConverter.java.
It will be like this:

package com.simpleconverter;
import android.app.Activity;
import android.os.Bundle;
public class lengthConverter extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
 {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}


Edit the java code as:


package com.simpleconverter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class lengthConverter extends Activity {

private EditText v1,v2;
private Button Convert;
private Button Reset;
private double val1=0,val2=0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

v1= ( EditText)findViewById(R.id.Value1);
v2= ( EditText)findViewById(R.id.Value2);
Convert = (Button)findViewById(R.id.convert);
Reset = (Button)findViewById(R.id.reset);
Convert.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
convertValues();
}
}
);

Reset.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
reset();
}
}
);
}

void convertValues()
{
if (v1.getText().length() > 0)
{
val1=Double.parseDouble(v1.getText().toString());
val2=InchToCm(val1);
}
else if(v2.getText().length() > 0)
{
val2=Double.parseDouble(v2.getText().toString());
val1=CmToInch(val2);
}
else
Toast.makeText(this,"please enter a value",Toast.LENGTH_LONG).show();
v1. setText(Double.toString(val1));
v2. setText(Double.toString(val2));

}
double InchToCm(double val)
{return(val*2.54);}
double CmToInch(double val)
{return(val/2.54);}


void reset()
{
v1.setText("");
v2.setText("");
}
}

This code converts centimeter value entered  in EditText _1 to Inch value and display it  in EditText _2.








Let us have  a detailed look on the code:

(IV) CODE EXPLANATION

I would like to describe each code segment separately , rather than explaining all in a while.

**How EditText works??

 Include this code in xml file. 

<EditText<Spinner
android:id="@+id/Value2"
android:layout_width="120sp"
android:hint="0.0"
android:layout_height="wrap_content"
android:layout_below="@+id/Value1">
</EditText>

Points to note:-
  • id   :: unique identifier for being accessed in java code.
  • hint:: hint displayed in EditText field.
  • text:: default text displayed in EditText field.


To access EditText in java, code as
v1= ( EditText)findViewById(R.id.Value1);

To check the no. of characters in text Field
int count=myEditText.getText().length();

To read a string
String val=myEditText.getText().toString();

To read a number
Double =val=Double.parseDouble(myEditText.getText().toString());


**How Button works??

To include a button ,code xml as:

<Button android:text="ButtonName"
 android:id="@+id/Button_id"
 android:layout_width="fill_parent" android:layout_height="wrap_content"
>
</Button>

To access button in java code:
private MyButton = (Button)findViewById(R.id.ButtonNmae);

To recognize Button click,
MyButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
..........
}
}
);


**How Toast works??

Toast displays a tiny message for a short time and then disappears.

Code for Toast is
Toast.makeText(this,"my Toast...",Toast.LENGTH_SHORT).show();

parameter 1: context
parameter 2:Text to display.
parameter 2:duration of display; LENGTH_SHORT,LENGTH_LONG are available


(V)Modify the code

Current code has the only ability to convert from inch to centimeter and viceversa. We can improve it by including a Spinner with more unit conversion options.


** How to code Spinner??

Edit xml code as:

android:id="@+id/unit1"
android:gravity="center"
android:layout_height="wrap_content" android:layout_below="@+id/Value1" android:layout_width="fill_parent">
</Spinner>

To include options with spinner:

String[] items = new String[] {"inch<-->Centimeter",
 "Foot<-->Metre",
"Mile<-->Kilometre",
"Yard<-->Metre"};

ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_item, items);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

mySpinner.setAdapter(adapter);

To get the selection by Spinner, use the funtion:
int select=mySpinner.get SelectedItemPosition();

 We have now familiarized  with all necessary codings to deal with simple application, To improve functionality, edit  java code as,


void convertValues()
{
int u1= unit1.getSelectedItemPosition();
if (v1.getText().length() > 0)
{
val1=Double.parseDouble(v1.getText().toString());
val2=findValue1(val1,u1);
}
else if(v2.getText().length() > 0)
{
val2=Double.parseDouble(v2.getText().toString());
val1=findValue2(val2,u1);
}
else
Toast.makeText(this,"please enter a value",Toast.LENGTH_LONG).show();
v1. setText(Double.toString(val1));
v2. setText(Double.toString(val2));

}

double findValue1(double val,int unit)
{
double retval=0.0;
switch(unit)
{
case 0:retval= InchToCm(val);break;
case 1:retval= FootToMetre(val);break;
case 2:retval=MileToKm(val);break;
case 3:retval=YardToMetre(val);break;
}
return(retval);
}

double findValue2 (double val,int unit)
{
double retval=0.0;
switch(unit)
{
case 0:retval= CmToInch(val);break;
case 1:retval= MetreToFoot(val);break;
case 2:retval=KmToMile(val);break;
case 3:retval=MetreToYard(val);break;
}
return(retval);
}

double InchToCm(double val){return(val*2.54);}
double CmToInch(double val){return(val/2.54);}
double MetreToFoot (double val){return(val*3.28084);}
double FootToMetre (double val){return(val/3.28084);}
double MileToKm (double val){return(val*1.60934);}
double KmToMile (double val){return(val/1.60934);}
double MetreToYard(double val){return(val*1.09361);}
double YardToMetre(double val){return(val/1.09361);}


Now, our Simple converter is able to convert values on these units.


inch<-->Centimeter
Foot<-->Metre
Mile<-->Kilometre
Yard<-->Metre
   

Is Android programming funny now.??   :)
Your valuable suggestions are welcomed.!!
  



FOR MORE TRICKS ABOUT ANDROID PROGRAMMING WITH COMPLETE CODE AND EXPLANATION , CLICK HERE..!!!! :) :)



Monday, August 1

C program to implement DFA

//updated on 11/03/2015

Hello friends,


               This post describes how a Deterministic Finte Automata (DFA) can be implemented using C. Do you know, associated with every programming language compiler there is a program named  recognizer that takes a string , say string S, as input and answers "YES" if S is a sentence of the language and  " NO " otherwise..!! To accomplish this , we have to train recognizer about the syntactic structure of intended language ( done with regular expressions). For this purpose, we construct a transition diagram called a "finite automation". In a Deterministic Finite Automation, only one transition out of state is possible on the same input symbol. On the other hand, in NonDeterministic Finite Automata more than one transitions may possible for same input symbol.


  . Some interesting implementations using DFA are:
  • whether DFA accepts all strings.
  • whether DFA accepts any string
  • whether two DFAs recognize the same language
  • DFA with a minimum number of states for a particular regular language



Illustartion


Consider the DFA represented in this transition diagram.



   
                         


Here is a sample DFA with starting state " 0 ", and accepting state " 1" .  "a" and "b" are the input symbols.
This DFA will accept any string containing 'a's and 'b' and last symbol should be 'a'.


CODE:


#include <stdio.h>
#define TOTAL_STATES 2
#define FINAL_STATES 1
#define ALPHABET_CHARCTERS 2
#define UNKNOWN_SYMBOL_ERR 0
#define NOT_REACHED_FINAL_STATE 1
#define REACHED_FINAL_STATE 2
enum DFA_STATES{q0,q1};
enum input{a,b};
int Accepted_states[FINAL_STATES]={q1};
char alphabet[ALPHABET_CHARCTERS]={'a','b'};
int Transition_Table[TOTAL_STATES][ALPHABET_CHARCTERS];
int Current_state=q0;
void DefineDFA()
{
    Transition_Table[q0][a] = q1;
    Transition_Table[q0][b] = q0;
    Transition_Table[q1][a] = q1;
    Transition_Table[q1][b] = q0;
}
int DFA(char current_symbol)
{
int i,pos;
    for(pos=0;pos<ALPHABET_CHARCTERS; pos++)
        if(current_symbol==alphabet[pos])   
            break;//stops if any character other than a or b
    if(pos==ALPHABET_CHARCTERS)
         return UNKNOWN_SYMBOL_ERR;
    for(i=0;i<FINAL_STATES;i++)
 if((Current_state=Transition_Table[Current_state][pos])
==Accepted_states[i])
            return REACHED_FINAL_STATE;
    return NOT_REACHED_FINAL_STATE;
}
int main(void)
{
    char current_symbol;
    int result;
 
    DefineDFA();    //Fill transition table
 
    printf("Enter a string with 'a' s and 'b's:\n
                Press Enter Key to stop\n");
 
 
    while((current_symbol=getchar())!= '\n')
        if((result= DFA(current_symbol))==UNKNOWN_SYMBOL_ERR)
            break;
    switch (result) {
    case UNKNOWN_SYMBOL_ERR:printf("Unknown Symbol %c",
  current_symbol); 
 break;
    case NOT_REACHED_FINAL_STATE:printf("Not accepted"); break;
    case REACHED_FINAL_STATE:printf("Accepted");break;
    default: printf("Unknown Error");
    }
    printf("\n\n\n");
    return 0;
}


OUTPUT
========

String with only "a"s and "b"s and last symbol is "a".     ACCEPTED..!!



String with only "a"s and "b"s but  last symbol is not  "a".     REJECTED..!!



Unknown symbol "y" in input. REJECTED.!!!!



Sunday, July 31

C PROGRAM TO DISPLAY TYPE OF A FILE






Hi Friends,

This is my C program to check the type of a file in UNIX system. Before going to program, have a look on what actually a 'type' means in UNIX system. A file may be one of the  following types :
  1. Regular File  : It may be either a text file or a binary file.
  2. Directory File : These are the files that can store other files (like file folder we use) so that users can organise their files into some hierarchical manner.!!)
  3. Character Device File : It refers to a physical device that transmits data in a character-based manner. (like printer, modems, consoles),
  4. Block Device File : Similar to character device file, but it can transmit a block  of data at a time.
  5. FIFO FILE : A special pipe device file which furnishes a temporary buffer for 2 or more processes to communicate (by writing to / reading data from buffer).
Note: A single device can have both block and character device files representing them for different access methods.Consider F be a character device file on its creation. But F can be used by a hard disk to bulk/ non-blocking data transfer between a process and the disk.


         Here is the complete program. . .

TYPECHECK.C 


 /*
PROGRAM NAME: TYPECHECK.C
AIM : TO READ A FILE NAME AND DISPLAY IT'S TYPE
DATE : 07/31/2011
*/

  #include<stdio.h>                                                                           
  #include<sys/stat.h>                                          
                                                                             
  main ()
 {   
    char file_name[20];
    struct stat p;
    printf("\nEnter filename :  ");
    scanf("%s",file_name);
    stat(file_name,&p);
    printf("\a\n%s is a ",file_name); 
    if(S_ISREG(p.st_mode))
    printf("regular file");
     else if(S_ISDIR(p.st_mode))
     printf("directory file");
     else if(S_ISCHR(p.st_mode))
     printf("character file");
     else if(S_ISBLK(p.st_mode))
     printf("block file");
      else if(S_ISFIFO(p.st_mode))
      printf("FIFO file");
      
else
      printf("Unknown type file or not found..!!");
      getch();
     
 }                   





Saturday, July 30

C PROGRAM TO IMPLEMENT MACRO PROCESSOR

 Here is my C program implementing a Macro Processor. We know that Macro is a single line abbreviation for a group of statements. We should define that sentence - cluster before using them in actual program. Macro processor will analyse the program and on encountering  macro variable, it will replace that 'Macro invocation' to corresponding Macro definition. It should also take care the number  and position of arguments used in Macro invocation.



ALGORITHM

MACROPROCESSOR
  • EXPANDING=FALSE.
  • Read each line and call GETLINE() and PROCESSLINE() until END encounters.

PROCESSLINE ( )
  • If OPCODE is a macroname then EXPAND ( ).
  • Else if OPCODE is MACRO ,then DEFINE ( ).
  • Else write line to expanded file as such.
DEFINE( )
  • Enter Macro name into NMATAB.
  • Enter macro prototype into DEFTAB.
  • Set LEVEL=1.
  • Substitute parameters with positional notations and enter to DEFTAB.
  • If OPCODE=MACRO, LEVEL++;
  • If OPCODE=MEND, LEVEL--;
  • Continue this until LEVEL=0
  • Store beginning and end of definition as pointers within NAMTAB

EXPAND ( )
  • EXPANDING = TRUE
  • Set up arguments from macro invocation in ARGTAB.
  • Write macro invocation statement to expanded file  as a comment line.
  • Call GETLINE() and PROCESSLINE() till macro definition ends.
  • Set EXPANDING=FALSE.


GETLINE ( )
  • If EXPANDING is TRUE, read from DEFTAB (data structure where macro body is stored) and substitute arguments for positional notations.
  • If  EXPANDING is FALSE , read next line from input file.




MACROPROCESSOR.C

 /*
PROGRAM NAME:MACRO.C
AIM: TO IMPLEMENT MACRO PROCESSOR.
INPUT : "INPUT.TXT"
OUTPUT: "EXPANDED.TXT"
DATE: 07/28/2011
*/


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

void GETLINE();
void PROCESSLINE();
void DEFINE();
void EXPAND();


 FILE *expanded;
 FILE *input;

 char label[10],opcode[10],operand[25];
 char line[20];
 int namcount=0, defcount=0;
 int EXPANDING;
 int curr;



 struct namtab
 {
 char name[10];
 int start,end;
}mynamtab[15];
     
 struct deftab
 {
        char macroline[25];
  }mydeftab[25];

struct argtab
{
       char arg[3][9];
 }myargtab;
///MACRO MAIN
int main()

{
    EXPANDING=0;

    input =fopen("input.txt","r");                          
 expanded=fopen("expanded.txt","w");
GETLINE();
 
     while(strcmp(opcode,"END")!=0)
{  

     PROCESSLINE();
       GETLINE();
 }
              fprintf(expanded,"%s",line);
      getch();
     return 1;
  }
                            


//   GETLINE
     void GETLINE()
     {    char word1[10],word2[10],word3[10],buff[10];
int count=0,i,j=0;
if(EXPANDING)strcpy(line,mydeftab[curr++].macroline);
 else fgets(line,20,input);
        opcode[0]='\0';label[0]='\0';operand[0]='\0';word1[0]='\0';word2[0]='\0';word3[0]='\0';
        
                      for(i=0;line[i]!='\0';i++)
                      {
                                        
                                                if(line[i]!=' ')
                                                buff[j++]=line[i];
                    
                                                 else
                      {
                                                   
                      buff[j]='\0';
                 
                   
                      strcpy(word3,word2);
                      strcpy(word2,word1);
                       strcpy(word1,buff);
                     j=0;count++;
                      }
                    
                    
                      }

                       buff[j-1]='\0';
                      strcpy(word3,word2);
                      strcpy(word2,word1);
                       strcpy(word1,buff);
                   
   
      switch(count)
                       {
                                    case 0:strcpy(opcode,word1);break;
                                    case 1:{strcpy(opcode,word2);strcpy(operand,word1);}break;
                                    case 2:{strcpy(label,word3);strcpy(opcode,word2);strcpy(operand,word1);}break;
                       }
                   
                     
                       }
                   



//     PROCESSLINE
                       void PROCESSLINE()
                       {
                            int i;
                        for(    i=0;i<namcount;i++)
                      
                                if(!strcmp(opcode,mynamtab[i].name))
                                {
                                                               
                                                                  EXPAND();return;
                                                          
                                                        
                                                             
                                                                  }
                                                           
                                                               { 
                                                                  if(!strcmp(opcode,"MACRO"))
                                                                
                                                                 DEFINE();
                                                               
                                                                 else fprintf(expanded,"%s",line);
                                                                   }
                                                                   }
   
   
     void DEFINE()
     {
          int LEVEL,i=0,j=0,k=0;
       char param[5][9];
       char s[3];
      strcpy(s,"123");
 
          strcpy(mynamtab[namcount].name,label);
          mynamtab[namcount].start=defcount;
          strcpy(mydeftab[defcount].macroline,line);
      
       
          while(operand[i]!='\0')
          {
                                if(operand[i]!=',')
                                param[j][k++]=operand[i];
                                else
                                {
                                    param[j++][k]='\0';
                                
                                    k=0;
                                    }
                              
                               i++;
                                }
                                param[j][k]='\0';
                             
        
          LEVEL=1;
     
        while(LEVEL>0)
          {
                   
            GETLINE();
           
              if(operand[0]!='\0')
             {
            for(i=0;i<3;i++)
            {
            if(!strcmp(operand,param[i]))
            {

            operand[0]='?';
            operand[1]=s[i];
            operand[2]='\0';
             }
             }
             }
           if(!strcmp(opcode,"MACRO"))
            LEVEL++;
           else if(!strcmp(opcode,"MEND"))
            LEVEL--;

            strcpy(mydeftab[defcount].macroline,opcode);
            if(operand[0]!='\0')
            {
            strcat(mydeftab[defcount].macroline," ");
            strcat(mydeftab[defcount].macroline,operand);
            strcat(mydeftab[defcount].macroline,"\n");
            }
            strcat(mydeftab[defcount++].macroline,"\n");

                        }
                        mynamtab[namcount++].end=defcount;
                   
                    
                        }
                      
         

//Expand
        
    void EXPAND()
                        {
                             int i,end=0,j=0,k=0;
                             EXPANDING=1;
                             int arg=0;
                      
                         fprintf(expanded,"//%s",line);
                             for(i=0;i<namcount;i++)
                             {
                             if(!strcmp(opcode,mynamtab[i].name))
                             {
                                                             
                             curr=mynamtab[i].start;
                             end=mynamtab[i].end;
                          
                           
                                   while(operand[i]!='\0')
                                {
                                if(operand[i]!=',')
                                myargtab.arg[j][k++]=operand[i];
                                else
                                {
                                    myargtab.arg[j++][k]='\n';
                                
                                    k=0;
                                    }
                              
                               i++;
                                }                              
                                 myargtab.arg[j][k]='\n';
                           
                        
                             }
                             }
                           
                             while(curr<(end-1))
                             {
                                              GETLINE();
                           if(operand[0]=='?')
                                         
                          strcpy(operand,myargtab.arg[operand[1]-'0'-1]);

                           fprintf(expanded,"%s %s %s",label,opcode,operand);
                        
                             }
                             EXPANDING=0;
                           
                           
                         }



/*************************************************************************************/


  Let us have a look on what will be the output of the program for a sample input.


input.txt



COPY START 1000

RDBUFF MACRO P,Q,R
CLEAR A
CLEAR S
CLEAR X
+LDT #4096
TD P
JEQ *-3
RD P
STCH Q
JLT *-19
LDA R
COMP #0
STX R
MEND

//main program





FIRST STL RETADR
RDBUFF F1,BUFF1,L1
CLEAR X
RDBUFF F2,BUFF2,L2
RDBUFF F3,BUFF3,L3
JLT *-19
STA
END



The output produced will be,

expanded.txt

COPY START 1000
//main program
FIRST STL RETADR
//RDBUFF F1,BUFF1,L1
 CLEAR A
 CLEAR S
 CLEAR X
 +LDT #4096
 TD F1
 JEQ *-3
 RD F1
 STCH BUFF1
 JLT *-19
 LDA L1
 COMP #0
 STX L1
CLEAR X
//RDBUFF F2,BUFF2,L2
 CLEAR A
 CLEAR S
 CLEAR X
 +LDT #4096
 TD F2
 JEQ *-3
 RD F2
 STCH BUFF2
 JLT *-19
 LDA L2
 COMP #0
 STX L2
//RDBUFF F3,BUFF3,L3
 CLEAR A
 CLEAR S
 CLEAR X
 +LDT #4096
 TD F3
 JEQ *-3
 RD F3
 STCH BUFF3
 JLT *-19
 LDA L3
 COMP #0
 STX L3
JLT *-19
STA
END