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.!!!!