Friday, June 12, 2009

Strange Thing Happens To Me

I just resently bought ASROCK motherboard G31M-S. It has realtek 8103EL onboard LAN. Debian 5.0 just installed default r8169 driver. J2EE did not work, glass-fish v2 just went kaputt. I did not have any net connection. So :
1. I downloaded r8101 drivers using puppy Linux.
2. Extract the drivers.
3. rmmod r8169.
4. build r8101.
5. insmod r8101.ko.
6. init 6.
7. VOILA my LAN alive and kicking.
8. strangely my glass-fish running well.
9. WHY : I don't know

Bye

Thursday, May 21, 2009

Installing Apache Server in Debian 5.0 - Lenny

I need to install web server for intranet server. I have a Debian 5.0 box. Therefore it is natural to have apache server installed the newest
  • I logged in as su (Super User). BTW you need to have gcc library installed properly. It means you have to have complete library.
  • I downloaded httpd-2.2.11.tar.bz2.I moved downloaded file into /opt by typing this command : mv httpd-2.2.11.tar.bz2 /opt/. Now the file was moved to /opt.
  • I went to /opt by typing cd /opt.
  • I extract httpd-2.2.11.tar.bz2 with this command : tar xjv httpd-2.2.11.tar.bz2. Directory httpd-2.2.11 was created
  • I went in to that directory : cd /opt/httpd-2.2.11
  • Then I read INSTALL file. It says that I should use this script
$ ./configure --prefix=PREFIX
$ make
$ make install
$ PREFIX/bin/apachectl start

  • Since I wanted Apache lives inside "/usr/local/apache2" so I changed the script. The script then looked like this :
$ ./configure --prefix=/usr/local/apache2
$ make
$ make install

  • The first command that I typed was "./configure --prefix=/usr/local/apache2"
  • Next I invoke "make" to build various executables. It was about 10 minutes compilation time in my 512 MB PC.
  • Next I invoke "make install" to install the executables. Running time was about 3 minutes.
  • To start apache server I invoked "/etc/init.d/apache start"
  • I tested the installation by using firefox browser. I typed in address bar : 127.0.0.1. Then I saw the result.
  • I congratulate my self by eating salad and chicken.

Installing FIrefox 3 in Debian 5.0 - Lenny

I needed to have a browser which is familiar with me Firefox. My default Debian 5.0 Installation does not have this browser. So I downloaded from mozilla.com
  • In my computer firefox-3.0.10.tar.bz2 was downloaded into /temp. I directly downloaded it from mozilla.com
  • I moved it into /opt (Since I fell comfortable with installing new software in that directory)
  • I submitted a command like this : tar xjf firefox-3.0.10.tar.bz2. This command created a new directory : firefox
  • Then I went to /usr/bin by typing : cd /usr/bin
  • I created a softlink to /opt/firefox/firefox by typing : ln -s /opt/firefox/firefox. This action created a softlink file named firefox which linked to /opt/firefox/firefox
  • I created a menu Item Inside the Internet sub menu in my Debian 5.0

Now after installing firefox 3.0 I needed installing flash plugin.
  • I moved the downloaded file into /opt by issuing : mv install_flash_player_10_linux.tar.gz /opt/
  • I extracted the file by issuing command : tar xzf install_flash_player_10_linux.tar.gz. It created a new directory : install_flash_player_10_linux
  • I went to the directory : install_flash_player_10_linux
  • Then I issued a command inside the directory : ./flashplayer-installer
  • I was asked where is my browser installed. I answer with this : /opt/firefox. Because it is where my browser installed.
  • Then I was asked to proceed with the Installation and I said Y.
  • I tested my installation by invoking firefox : IT WAS ALIVE AND KICKING.

Sunday, April 26, 2009

6 - Stack

A Stack is a collection of items in which only the most recently added item may be removed. The latest added item is at the top. Basic operations are push and pop. Often top and isEmpty are available, too. Also known as "last-in, first-out" or LIFO (see NIST-DADS' definition of stack). We may think a stack is a cramp storage area, where the first item going in, will certainly last to comes out.

Basic operation of stack are :
  1. push
  2. pop
The program bellow is an example of simple stack operation :

#include "iostream"
using namespace std;

#define n 10
int Stack[n]; //declaring a stack
int Top; //declaring the Top index of a stack
int i; //general counter

void initialize(void)
{
Top = -1;
}

int stillunfilledup(void)
{
if (Top < n-1) //stack is not full yet
{
return 1;
}
else
{
return 0;
}
}

void push(int X)
{
Top =Top +1;
Stack[Top] = X;
}

int notempty(void)
{
if (Top > -1)
{
return 1;
}
else
{
return 0;
}
}

int pop()
{
int X=Stack[Top];
Top = Top -1;
return X;
}


int main(void)
{
int X;
int i;

initialize();


cin >> X;
while (X != 9999) //loop for pushing. As long as the user do not input 999, the loop runs
{
if (stillunfilledup()) //stack is not full yet
{
push(X);
}
else //stack is full
{
cout << "Stack is full";
break;
}
cin >> X;
}

cout << endl << endl << endl;
for (i = 0; i < n; i++)//loop for popping
{
if (notempty())
{
X = pop();
cout << "Pops the " << Top+1 << " th member" << X << endl;
}
else
{
cout << "empty";
}
}
}

Thursday, April 23, 2009

5 - Sorting Algorithm : Shell Sort

Another sorting algorithm is Shell Sort. It is based on insertion sort. This sorting method performs multiple passes through the array. Every time it passes the array it performs insertion sort. It divide the arry into several sets. A set grows every time the algorithm works on the array. Of course we need to understand that each members' location is not adjacent to each other (NOT CONTIGOUS). I will present two Shell sort alogoritms : one is for ascending sort and the other is for descending sort :

The first one is ascending sort :
#include "iostream"
using namespace std;

int main(void)
{
int data[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int temp;
int increment;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

increment = 3;
while (increment > 0)
{
for (i=0; i < 8; i++)
{
j = i;
temp = data[i];
while ((j >= increment) && (data[j-increment] > temp))
{
data[j] = data[j - increment];
j = j - increment;
}
data[j] = temp;
}
if (increment/2 != 0)
increment = increment/2;
else if (increment == 1)
increment = 0;
else
increment = 1;
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

return 0;
}

And here is for descending sort :
#include "iostream"
using namespace std;

int main(void)
{
int data[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int temp;
int increment;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

increment = 3;
while (increment > 0)
{
for (i=0; i < 8; i++)
{
j = i;
temp = data[i];
while ((j >= increment) && (data[j-increment] < temp))
{
data[j] = data[j - increment];
j = j - increment;
}
data[j] = temp;
}
if (increment/2 != 0)
increment = increment/2;
else if (increment == 1)
increment = 0;
else
increment = 1;
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

return 0;
}

4 - Sorting Algorithm : Insertion Sort

Another sorting algorithm that we can use is insertion sort. We can use it for doing ascending or descending sorting :
  1. If we need to do ascending sort, then we need to compare two elements : if we find an element whose value is greater than temp place its value to right.
  2. If we need to do descending sort, then we need to compare two elements : if we find an element whose value is less than temp place its value to right.
First we have a program Insertion Sort - Ascending :
#include "iostream"
using namespace std;

int main (void)
{
int data[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int k;
int temp;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

for (i = 1; i < 8; i++)
{
temp = data[i];
j = i-1;
while ((j >= 0) && (data[j] > temp))
{
data[j+1] = data[j];
j = j-1;
}
data[j+1] = temp;
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}
return 0;
}

Next we are presented with Insertion Sort - Descending :

#include "iostream"
using namespace std;

int main (void)
{
int data[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int k;
int temp;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

for (i = 1; i < 8; i++)
{
temp = data[i];
j = i-1;
while ((j >= 0) && (data[j] < temp))
{
data[j+1] = data[j];
j = j-1;
}
data[j+1] = temp;
}
cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}
return 0;
}

Next we will discuss Shell Sort

3 - Sorting Algorithm : Selection Sort

The code below is an example of Selection Sort - ascending. It ascending sorts an array :
#include "iostream"
using namespace std;

int main (void)
{
int data[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int k;
int temp;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

for (i = 0; i < 8; i++)
{
int k = i;
for (j = i + 1; j < 8; j++)
{
if (data[j] < data[k]) // Ascending Sort
{
k = j;
}
}
int t = data[i];
data[i] = data[k];
data[k] = t;
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

return 0;
}

Next we have descending sort :
#include "iostream"
using namespace std;

int main (void)
{
int data[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int k;
int temp;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

for (i = 0; i < 8; i++)
{
int k = i;
for (j = i + 1; j < 8; j++)
{
if (data[j] > data[k]) //descending sort
{
k = j;
}
}
int t = data[i];
data[i] = data[k];
data[k] = t;
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << data[i];
}

return 0;
}

Wednesday, April 22, 2009

2 - Sorting Algorithm : Bubble Sort

One of the algorithm for sorting is Bubble Sort. It is called bubble sort because the way it sorts is like bubble in a glass of soda. The smallest integer will "bubble up" after the sorting. The program bellow is an example of such algorithm. It ascending sorts the array.

#include "iostream"
using namespace std;

int main (void)
{
int arrInt[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int temp;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << arrInt[i];
}

for (j=0; j<8;j++)
{
for (i = 0; i < 7; i++)
{
if (arrInt[i] > arrInt[i+1])
{
temp = arrInt[i];
arrInt[i] = arrInt[i+1];
arrInt[i+1] = temp;
}
}
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << arrInt[i];
}
}


Next we have another example descending sort :

#include "iostream"
using namespace std;

int main (void)
{
int arrInt[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int temp;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << arrInt[i];
}

for (j=0; j<8;j++)
{
for (i = 0; i < 7; i++)
{
if (arrInt[i] < arrInt[i+1])
{
temp = arrInt[i];
arrInt[i] = arrInt[i+1];
arrInt[i+1] = temp;
}
}
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << arrInt[i];
}
}

The bubble sort algorithm is arguably one of the easiest algorithm to memorize even though it is not particularly efficient. Therefore next we are going to explore another sorting algorithm : Selection Sort for sorting an array in ascending and descending manners.

5 - Import statements generated by netbeans inside "*View.java"

These are the list of import statements generated by netbeans when we build desktop database application. These statements are placed inside *View.java (which is a user interface class) :
  1. import org.jdesktop.application.Action; Marks a method that will be used to define a Swing Action object's actionPerformed method. It also identifies the resources that will be used to initialize the Action's properties. Additional @Action parameters can be used to specify the name of the bound properties (from the same class) that indicate if the Action is to be enabled/selected, and if the GUI should be blocked while the Action's background Task is running.
  2. import org.jdesktop.application.ResourceMap; A read-only encapsulation of one or more ResourceBundles that adds automatic string conversion, support for field and Swing component property injection, string resource variable substitution, and chaining.
  3. import org.jdesktop.application.SingleFrameApplication;
  4. import org.jdesktop.application.FrameView; A View encapsulates a top-level Application GUI component, like a JFrame or an Applet, and its main GUI elements: a menu bar, tool bar, component, and a status bar. All of the elements are optional (although a View without a main component would be unusual). Views have a JRootPane, which is the root component for all of the Swing Window types as well as JApplet. Setting a View property, like menuBar or toolBar, just adds a component to the rootPane in a way that's defined by the View subclass.
  5. import org.jdesktop.application.TaskMonitor; This class is intended to serve as the model for GUI components, like status bars, that display the state of an application's background tasks. TaskMonitor provides an overview of all the ApplicationContext's Tasks, as well as the state of a single foreground Task.
  6. import org.jdesktop.application.Task; A type of SwingWorker that represents an application background task. Tasks add descriptive properties that can be shown to the user, a new set of methods for customizing task completion, support for blocking input to the GUI while the Task is executing, and a TaskListener that enables one to monitor the three key SwingWorker methods: doInBackground, process and done.
  7. import java.awt.event.ActionEvent; A semantic event which indicates that a component-defined action occurred. This high-level event is generated by a component (such as a Button) when the component-specific action occurs (such as being pressed). The event is passed to every every ActionListener object that registered to receive such events using the component's addActionListener method.
  8. import java.awt.event.ActionListener; The listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. When the action event occurs, that object's actionPerformed method is invoked.
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import javax.persistence.RollbackException; Thrown by the persistence provider when the EntityTransaction.commit() fails.
  12. import javax.swing.Timer;
  13. import javax.swing.Icon;
  14. import javax.swing.JDialog;
  15. import javax.swing.JFrame;
  16. import javax.swing.event.ListSelectionEvent;
  17. import javax.swing.event.ListSelectionListener;
  18. import org.jdesktop.beansbinding.AbstractBindingListener; An abstract subclass of BindingListener that simplifies writing BindingListeners by allowing you to extend this class and re-implement only the methods you care about.
  19. import org.jdesktop.beansbinding.Binding; A factory class for creating instances of the concrete Binding implementations provided by this package.
  20. import org.jdesktop.beansbinding.PropertyStateEvent; An event characterizing a change in a Property's state for a particular source object.

Recursion - Basic

Recursion
An algorithmic technique where a function, in order to accomplish a task, calls itself with some part of the task. To be short it is a function that calls itself. NIST-DADS states that a recursive function consists of two major parts or cases, the second part having three components.
1.base case(s), in which the problem is simple enough to be solved directly, and
2.recursive case(s). A recursive case has three components:
1.divide the problem into one or more simpler or smaller parts of the problem,
2.call the function (recursively) on each part, and
3.combine the solutions of the parts into a solution for the problem.
Depending on the problem, any of these may be trivial or complex.
To make us understand what sort of algorithm this technique is, lets have a look at the code bellow :
#include
using namespace std;
void RecursiveIncrement(int i)
{
if (i ==10) //Base case : display value of i if i == 10
{
cout << i;
}
else //Recursive case : display value of i
{
cout << i << endl;
RecursiveIncrement(++i);
}
}

int main(void)
{
RecursiveIncrement(1);
return 0;
}
The program above display integer values from 1 to 10. The base case display the value of i if its value is 10. The recursive case display the values from 1 to 9.
We have another example of such algorithm. The program work just like the previous program except that it will display the value of 10 to 1. The source code is presented below :

#include
using namespace std;

void RecursiveDecrement(int i)
{
if (i == 1)
{
cout << i;
}
else
{
cout << i << endl;
RecursiveDecrement(--i);
}
}

int main(void)
{
RecursiveDecrement(10);
return 0;
}

Those two programs are fairly simple. We are going to explore the usage of recursion to navigate several type of data list.

Friday, March 6, 2009

4 - Variable and Constant

Variable Declaration
The syntax for attribute declaration is exactly the same with what we have done when we declare methods. The syntax is like this :
[modifiers] type name_of_variable or [modifiers] type name_of_variable = [value].
  1. This form : [modifiers] type name_of_variable is only for declaring a variable without giving the the initial value of the variable.
  2. The other form is : [modifiers] type name_of_variable = [value] is for declaring a variable and GIVING it the initial value.
  3. [] (square bracket means anything inside this bracket is optional). Modifiers can be any java keywords. The most common are private, public, and static that we have encounter before.

In terms of its visibility a variable can be local if it is declared inside a method, it can only be seen inside the method where it is declared. But there is a slight difference if we compare that with the rules listed above. The syntax for declaring such variable is very short :
  1. type name_of_variable if you only want to declare a variable without initializing a value for it.
  2. type name_of_variable = valueif you need to declare an initial value.
    In fact WE ARE NOT ALLOWED to place a modifier (such as public, private, etc) when declaring a local variable.
So what is the type. Type represents the data type that can be stored in a memory are reserved for that variable. There are several types that will be of our interest :
  1. byte : the range of value is from -128 to 127 (8 bits long)
  2. short : the range of value is from -32,768 to 32,767 (16 bits long)
  3. int : the range of value is -2,147,483,648 to 2,147,483,647 (32 bits long)
  4. long : the range of value is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (64 bits long).
  5. float : 32 bits floating point or real number point number.
  6. double : 64 bits floating point or real number point number.
  7. char : 8 bits long it holds a character value. At one point of time it store one only character.
  8. boolean : a variable of type boolean can only store a logical value true or false.
Before using any variables you have to declare them, then you can assign any value that matches to their type.
  • Examples for declaration of several variables without initialization :
float floatHeight;
int intStudentNumber;
char charGrade;

  • Examples for declaration of several variables WITH initialization :float
floatWeight = 100.24F;
int intMarbleCount = 20;
char charStudentGrade = 'A';
boolean boolIStillAlive = true;

A variable can only store one value at a time, but we can change it. We can change what is stored inside a variable by assigning a legal value to it. There are 4 ways to assign a value to a variable :

  • Assigning a value directly to a variable. Suppose a Grade of a student is F (fails he never studies) : charGrade = 'F';
  • The other way is by giving a value of another variable to one variable
charStudentGrade = 'F';
charGrade = charStudentGrade;

  • We can also assign the result of an arithmetic operation to a variable :
float floatUnitPrice = 100.12F;
float floatKgOrdered = 210.01F;
float floatTotalPrice = (floatUnitPrice * floatKgOrdered);

  • We can assign the result of a function execution to a variable. WE DO NOT HAVE ANY EXAMPLE FOR THIS YET.
Constant
Do we have another type of “variable” ? Yes it is called constant. A constant represents a value in a memory area that can not be changed at all. A constant is named with capital letters. Here is an example of a constant declaration :
final char TOP_GRADE = 'A';

A constant's value can not be changed forever and ever. Its value stays happily ever after.

Heap Memory and Stack Memory
Variables that are declared inside a method, known as local variables, are stored inside stack memory area, while attributes reside inside heap memory area. Heap memory stores any information about objects while they are needed by a program, while stack memory stores memory that are suitable for a short period of time.

Saturday, February 28, 2009

3 - Class Structure

Lets begin our discussion by refreshing our memory with hello world application. A simple one class program :
public class HelloJava // The class declaration
{

public static void main(String args[]) //The main method declaration
{
System.out.println("Hello Java : a cup of arabica and robusta blend");
}

}

Inside the program we have :
1.class declaration.
2.method declaration
3.Some comments

Every class inside our application must be declared. A Declaration is like telling the world that this class exists. By convention, class names begin with a capital letter, and usually I use uppercase letter for every word that is part of a class name. Lets disect our HelloJava class :
1.syntax for class declaration is [access_modifier] class class_identifier
2.access_modifier determines the accessibility of other classes to this class. Our access modifier is public so that this class is visible and accessible to other class
3.class identifier or better known as class name is HelloJava. Our class name is HelloJava.
4.Every java program must have one main() method. Our method is declared inside HelloJava class. Our main method comprises only one statement : System.out.println("Hello Java : a cup of arabica and robusta blend"). This statement will be executed during runtime.
5.In HelloJava we haven't got any variables yet.

Comments is good for documenting our logic of programming. Comments inside a java program takes the form of :
1.//. This type of comment may spans only one line of comments
2.Traditional comment just like in c language : begin with /* end with */. This type of comments may span several lines of comments.

Until now we haven't got any variable declaration. Now lets have a look at another examples : Triangle. We have two variables, which are public. base and height are public. It means they can be accessed and manipulated by another class.

public class Triangle
{
public float base = 0;
public float height = 0;

public void showTriangle()
{
System.out.println("Base : " + base);
System.out.println("Height : " + height);
System.out.println("Area : " + base*height/2);
}

}

Another interesting declaration is the method : showTriangle. It is public but it has a key word void. It means ON COMPLETION IT DOES NOT RETURN ANY VALUE. It has 3 statements that will be executed during run time.

2 - Multiclass Java Program

Now it is time for us to write application (simple one) with more than one class. The specification for our application is that we have a class that create an instance of another class. Our main class is called TriangleCreator, and the other class is called Triangle. TriangleCreator will create an instance of a Triangle.

The scenario for building such program is that we need to have a class that will be used by another class. The first class we need to write is Triangle class, the class that creates another class is called TriangleCreator. Now we have class Triangle that is depicted bellow :

public class Triangle

{


public float base = 0;
public float height = 0;

public void showTriangle()
{
System.out.println("Base : " + base);
System.out.println("Height : " + height);
System.out.println("Area : " + base*height/2);
}

}

what you have to do is the same with the other exercises we have done before :
1.Copy the source code.
2.Paste it into your text editor.
3.Save the program as Triangle.java IN YOUR WORKING DIRECTORY.

Next we need to have TriangleCreator class.

public class TriangleCreator
{

public static void main(String args[])
{
Triangle oTriangle;
oTriangle = new Triangle();
oTriangle.base = 10;
oTriangle.height = 10;
oTriangle.showTriangle();
}

}

Here is a list of action you need to do :
1.Copy the source code.
2.Paste it into your text editor.
3.Save the program as TriangleCreator.java IN YOUR WORKING DIRECTORY.
4.Compile the program using this command :javac TriangleCreator.java
5.After completing compilation process, a bytecode is produced : TriangleCreator.class
6.You run your program by executing this command : java TriangleCreator

In the next section we are going to discuss what we have done, discussing the syntax of making class.

Tuesday, February 24, 2009

1 - Introduction to Java Programming

Java is Object Oriented Programming Language. You can find many explanation of java environment and architecture somewhere else. This page is focusing on the programming example. If you see the examples in this page you will notice that a java program at least consist of a class declaration, method declaration, comments (if required/optional), and variable declaration (usually a class has several variables).

Our first program is hello java. The source code is presented below. All you have to do is copying and pasting it into your text editor, compile, and run the program :

public class HelloJava // The class declaration
{

public static void main(String args[]) //The main method declaration
{
System.out.println("Hello Java : a cup of arabica and robusta blend");
}

}


1. Copy the source code.
2. Paste it into your text editor.
3. Save the program as HelloJava.java IN YOUR WORKING DIRECTORY.
4. Compile the program using this command :javac HelloJava.java
5. After completing compilation process, a bytecode is produced : HelloJava.class
6. You run your program by executing this command : java HelloJava

We have more programming work to do. We are going to have another program that will print multiple lines of output. The source code is presented below. In case you are wondering what kopi luwak is Kopi luwak is coffe beans fermented inside the digestion system of a weasel like animal called luwak.

public class HelloKopiLuwak
{

public static void main(String args[])
{
System.out.println("Kopi Luwak : Exquisite Coffe produced by digestive system of ");
System.out.println("Paradoxurus hermaphroditusa, raccon-like animal." );
System.out.println("Perhaps it costs 300 or 400 dollars per kilo ");
}

}

1. Copy the source code.
2. Paste it into your text editor.
3. Save the program as HelloKopiLuwak.java IN YOUR WORKING DIRECTORY.
4. Compile the program using this command :javac HelloKopiLuwak.java
5. After completing compilation process, a bytecode is produced : HelloJavaKopiLuwak.class
6. You run the program by executing this command : java HelloKopiLuwak

We can also modify the program so that instead of having 3 println statements. We only need one.

public class HelloKopiLuwakModified
{

public static void main(String args[])
{
System.out.println("Kopi Luwak : Exquisite Coffe produced by digestive system of\nParadoxurus hermaphroditusa, raccon-like animal\nPerhaps it costs 300 or 400 dollars per kilo ");
}

}

Then what you have to do is :
1. Copy the source code.
2. Paste it into your text editor.
3. Save the program as HelloKopiLuwakModified.java IN YOUR WORKING DIRECTORY.
4. Compile the program using this command :javac HelloKopiLuwakModified.java
5. After completing compilation process, a bytecode is produced : HelloKopiLuwakModified.class
6. You run the program by executing this command : java HelloKopiLuwakModified

Until now, we only have one class. A one class program is fine inside classroom. But in actual world you need to have several classes. How to make such construct will be discussed on the next section of Java Programming.

Sunday, February 8, 2009

Serial Port Programming : Sender and Receiver

The required equipment required consists of :
1. DB-9 null modem. The null modem that you need to use is loop type null modem.
2. USB to serial port converter.

Now we are going to write a program that act as a data sender. Data is sent through the serial port. Basically program consists of several activities :
1.turning on a null modem.
2.setting up program's action on incoming package.
3.setting up program's output mode.
4.setting up program's connection control flag :
1.Baudrate is 4800 BPS (B4800) .
2.Enable RTS/CTS (hardware) flow control (CRTSCTS) .
3.Ignore modem control lines (CLOCAL) .
4.Character size mask is 8 (CS8).
5.flushing the modem line.
6.initiating the modem.
7.sending data through the modem line. the data is system's time.

Of course you need to have a receiver. wich is also a program. What makes the receiver different from the sender is the loop that reads data input :
for(;;)
{
read(fd,&c,1); /* reads the null modem */
write(1, &c,1); /* prints input to the screen */
}

before running any program you really need to alter the status of your null modem device (after you plug in it)), so that it can be read and written on. REMEMBER ALL SERIAL COMMUNICATION DEVICES IS TREATED AS FILE. You have to make it readable and writable. Beside that you need to have a null modem :
1. For changing the permission of ttyS0 you need to execute : #sudo chmod 777 /dev/ttyS0
2. For changing the permission of ttyUSB0 you need to execute : #sudo chmod 777 /dev/ttyUSB0

Now first we have a sender's source code. We assume program below uses Serial Port 0.

#include "termios.h" /*this file contains declaration of required functions and types*/
#include "stdio.h" /*you know what this is*/
#include "fcntl.h" /*this file constains declaration for O_RDWR and O_NOCTTY)*/
#include "time.h" /*this file contains time's operatives*/


int main(void)
{
int i, j, s;
char t[9];
time_t ttrs;
struct tm *ti;
int fd; /*variable of type integer used as descriptor to a serial port*/
char c;
struct termios termiosA; /*declaring a variable of type termios*/
/* Turn on the null modem */
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY); /* I have done : sudo chmod 777 /dev/ttyS0 */


/* We don't care about incoming bytes with parity on data input */
termiosA.c_iflag = IGNPAR;

/*
Raw output.
*/
termiosA.c_oflag = CR0; /* output modes */

/*
we are going to set a connection with serial port to the receiver (this computer is a sender)
1. Baudrate is 4800 BPS (B9600)
2. Enable RTS/CTS (hardware) flow control (CRTSCTS)
3. Ignore modem control lines (CLOCAL)
4. Character size mask is 8 (CS8)
*/
termiosA.c_cflag = B4800 | CRTSCTS | CLOCAL | CS8; /* control flags */


/* flush the modem line */
tcflush(fd, TCIFLUSH);

/* initiate the modem */
tcsetattr(fd,TCSANOW,&termiosA);

/* Now its time to send something. */
i = 0;
for (;;)
{
time(&ttrs);
ti=localtime(&ttrs);
if (s != ti->tm_sec)
{
printf("Sending time data : %s", t);
sprintf(t, "%d:%d:%d\n", ti->tm_hour, ti->tm_min, ti->tm_sec);
s = ti->tm_sec;
for (j = 0; j < 9;j++)
{
write(fd, t[j], 1);
}
return 0;
}

Next we have a receiver program. The receiver uses USB port 0. :

#include "termios.h" /*this file contains declaration of required functions and types*/
#include "stdio.h" /*you know what this is*/
#include "fcntl.h" /*this file constains declaration for O_RDWR and O_NOCTTY)*/

int main()
{
int fd; /*variable of type integer used as descriptor to a serial port*/
char c;
struct termios termiosA; /*declaring a variable of type termios*/
/* Turn on the null modem */
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY); /* I have done : sudo chmod 777 /dev/ttyUSB0 */


/* We don't care about incoming bytes with parity on data input */
termiosA.c_iflag = IGNPAR;

/*
Raw output.
*/
termiosA.c_oflag = CR0; /* output modes */

/*
we are going to set a connection with serial port to the sender (this computer is a receiver)
1. Baudrate is 4800 BPS (B4800)
2. Enable RTS/CTS (hardware) flow control (CRTSCTS)
3. Ignore modem control lines (CLOCAL)
4. Character size mask is 8 (CS8)
*/

termiosA.c_cflag = B4800 | CRTSCTS | CLOCAL | CS8; /* control flags */

/*The change to the line's state takes effect straight away*/
/* flush the modem line and initiate the modem */
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&termiosA);
/* input is handled by the loop below */

for(;;)
{
read(fd,&c,1); /* reads the null modem */
write(1, &c,1); /* prints input to the screen */
}

}

Now what you need to do is to compile and run each program and see the result. Good luck

Wednesday, January 21, 2009

errno : C Error Handling

Whatever programming you are doing. It's nice to have a feedback if something goes wrong in your program. Basically a c program would capture error message value generated by system's environment. Bellow is a rudimentary function that capture error handling.
#include "error.h"
#include "errno.h"
#include "stdio.h"

void errordisplay(int error)
{
switch (error)
{
case E2BIG : printf("E2BIG");break;
case EACCES : printf("EACCES");break;
case EADDRINUSE : printf("EADDRINUSE");break;
case EADDRNOTAVAIL : printf("EADDRNOTAVAIL");break;
case EAFNOSUPPORT : printf("EAFNOSUPPORT");break;
/*case EAGAIN : printf("EAGAIN");break;*/
case EALREADY : printf("EALREADY");break;
case EBADE : printf("EBADE");break;
case EBADF : printf("EBADF");break;
case EBADFD : printf("EBADFD");break;
case EBADMSG : printf("EBADMSG");break;
case EBADR : printf("EBADR");break;
case EBADRQC : printf("EBADRQC");break;
case EBADSLT : printf("EBADSLT");break;
case EBUSY : printf("EBUSY");break;
case ECANCELED : printf("ECANCELED");break;
case ECHILD : printf("ECHILD");break;
case ECHRNG : printf("ECHRNG");break;
case ECOMM : printf("ECOMM");break;
case ECONNABORTED : printf("ECONNABORTED");break;
case ECONNREFUSED : printf("ECONNREFUSED");break;
case ECONNRESET : printf("ECONNRESET");break;
/*case EDEADLK : printf("EDEADLK");break;*/
case EDEADLOCK : printf("EDEADLOCK");break;
case EDESTADDRREQ : printf("EDESTADDRREQ");break;
case EDOM : printf("EDOM");break;
case EDQUOT : printf("EDQUOT");break;
case EEXIST : printf("EEXIST");break;
case EFAULT : printf("EFAULT");break;
case EFBIG : printf("EFBIG");break;
case EHOSTDOWN : printf("EHOSTDOWN");break;
case EHOSTUNREACH : printf("EHOSTUNREACH");break;
case EIDRM : printf("EIDRM");break;
case EILSEQ : printf("EILSEQ");break;
case EINPROGRESS : printf("EINPROGRESS");break;
case EINTR : printf("EINTR");break;
case EINVAL : printf("EINVAL");break;
case EIO : printf("EIO");break;
case EISCONN : printf("EISCONN");break;
case EISDIR : printf("EISDIR");break;
case EISNAM : printf("EISNAM");break;
case EKEYEXPIRED : printf("EKEYEXPIRED");break;
case EKEYREJECTED : printf("EKEYREJECTED");break;
case EKEYREVOKED : printf("EKEYREVOKED");break;
case EL2HLT : printf("EL2HLT");break;
case EL2NSYNC : printf("EL2NSYNC");break;
case EL3HLT : printf("EL3HLT");break;
case EL3RST : printf("EL3RST");break;
case ELIBACC : printf("ELIBACC");break;
case ELIBBAD : printf("ELIBBAD");break;
case ELIBMAX : printf("ELIBMAX");break;
case ELIBSCN : printf("ELIBSCN");break;
case ELIBEXEC : printf("ELIBEXEC");break;
case ELOOP : printf("ELOOP");break;
case EMEDIUMTYPE : printf("EMEDIUMTYPE");break;
case EMFILE : printf("EMFILE");break;
case EMLINK : printf("EMLINK");break;
case EMSGSIZE : printf("EMSGSIZE");break;
case EMULTIHOP : printf("EMULTIHOP");break;
case ENAMETOOLONG : printf("ENAMETOOLONG");break;
case ENETDOWN : printf("ENETDOWN");break;
case ENETRESET : printf("ENETRESET");break;
case ENETUNREACH : printf("ENETUNREACH");break;
case ENFILE : printf("ENFILE");break;
case ENOBUFS : printf("ENOBUFS");break;
case ENODATA : printf("ENODATA");break;
case ENODEV : printf("ENODEV");break;
case ENOENT : printf("ENOENT");break;
case ENOEXEC : printf("ENOEXEC");break;
case ENOKEY : printf("ENOKEY");break;
case ENOLCK : printf("ENOLCK");break;
case ENOLINK : printf("ENOLINK");break;
case ENOMEDIUM : printf("ENOMEDIUM");break;
case ENOMEM : printf("ENOMEM");break;
case ENOMSG : printf("ENOMSG");break;
case ENONET : printf("ENONET");break;
case ENOPKG : printf("ENOPKG");break;
case ENOPROTOOPT : printf("ENOPROTOOPT");break;
case ENOSPC : printf("ENOSPC");break;
case ENOSR : printf("ENOSR");break;
case ENOSTR : printf("ENOSTR");break;
case ENOSYS : printf("ENOSYS");break;
case ENOTBLK : printf("ENOTBLK");break;
case ENOTCONN : printf("ENOTCONN");break;
case ENOTDIR : printf("ENOTDIR");break;
case ENOTEMPTY : printf("ENOTEMPTY");break;
case ENOTSOCK : printf("ENOTSOCK");break;
/*case ENOTSUP : printf("ENOTSUP");break;*/
case ENOTTY : printf("ENOTTY");break;
case ENOTUNIQ : printf("ENOTUNIQ");break;
case ENXIO : printf("ENXIO");break;
case EOPNOTSUPP : printf("EOPNOTSUPP");break;
case EOVERFLOW : printf("EOVERFLOW");break;
case EPERM : printf("EPERM");break;
case EPFNOSUPPORT : printf("EPFNOSUPPORT");break;
case EPIPE : printf("EPIPE");break;
case EPROTO : printf("EPROTO");break;
case EPROTONOSUPPORT : printf("EPROTONOSUPPORT");break;
case EPROTOTYPE : printf("EPROTOTYPE");break;
case ERANGE : printf("ERANGE");break;
case EREMCHG : printf("EREMCHG");break;
case EREMOTE : printf("EREMOTE");break;
case EREMOTEIO : printf("EREMOTEIO");break;
case ERESTART : printf("ERESTART");break;
case EROFS : printf("EROFS");break;
case ESHUTDOWN : printf("ESHUTDOWN");break;
case ESPIPE : printf("ESPIPE");break;
case ESOCKTNOSUPPORT : printf("ESOCKTNOSUPPORT");break;
case ESRCH : printf("ESRCH");break;
case ESTALE : printf("ESTALE");break;
case ESTRPIPE : printf("ESTRPIPE");break;
case ETIME : printf("ETIME");break;
case ETIMEDOUT : printf("ETIMEDOUT");break;
case ETXTBSY : printf("ETXTBSY");break;
case EUCLEAN : printf("EUCLEAN");break;
case EUNATCH : printf("EUNATCH");break;
case EUSERS : printf("EUSERS");break;
case EWOULDBLOCK : printf("EWOULDBLOCK");break;
case EXDEV : printf("EXDEV");break;
case EXFULL : printf("EXFULL");break;
}
}

int main(void)
{
int err;
FILE *fp = NULL;
if (fp=fopen("SSS","r")==NULL)
{
err = errno;
}
errordisplay(err);
return 0;
}

After compiling and running this program you notice that it will display the error message, wich is originally is an integer value. I copied, pasted and edited that error messages from errno.h header file (/usr/include/errno.h) :

browse@joko-desktop:~/Desktop$ gcc -o errprog.o errprog.c
errprog.c: In function ‘main’:
errprog.c:135: warning: assignment makes pointer from integer without a cast
browse@joko-desktop:~/Desktop$ ./errprog.o
ENOENTbrowse@joko-desktop:~/Desktop$

Hopefully this will help you in catching logical error in long programs that have many interfaces to another entities. WISH YOU LUCK

Tuesday, January 20, 2009

termios : a prelude to serial port programming

If you like to make a serial port program, you need to use functions and structures declared inside /usr/include/termios.h (be aware it uses another header file /usr/include/bits/termios.h). The first thing that you need to understand is a data structure declared inside /usr/include/bits/termios.h :
struct termios
{
tcflag_t c_iflag; /* input mode flags */
tcflag_t c_oflag; /* output mode flags */
tcflag_t c_cflag; /* control mode flags */
tcflag_t c_lflag; /* local mode flags */
cc_t c_line; /* line discipline */
cc_t c_cc[NCCS]; /* control characters */
speed_t c_ispeed; /* input speed */
speed_t c_ospeed; /* output speed */
#define _HAVE_STRUCT_TERMIOS_C_ISPEED 1
#define _HAVE_STRUCT_TERMIOS_C_OSPEED 1
};

Inside that structure we see the names of other types : tcflag_t, cc_t, and speed_t. What they really are of type char and unsigned int :
1.typedef unsigned char cc_t;
2.typedef unsigned int speed_t;
3.typedef unsigned int tcflag_t;

Now lets disect what are inside the termios (These values are declared inside /usr/include/bits/termios.h) :
1. The posibble values for c_iflag
/* c_iflag bits */
#define IGNBRK 0000001
#define BRKINT 0000002
#define IGNPAR 0000004
#define PARMRK 0000010
#define INPCK 0000020
#define ISTRIP 0000040
#define INLCR 0000100
#define IGNCR 0000200
#define ICRNL 0000400
#define IUCLC 0001000
#define IXON 0002000
#define IXANY 0004000
#define IXOFF 0010000
#define IMAXBEL 0020000
#define IUTF8 0040000

2. The possible values for c_oflag :
/* c_oflag bits */
#define OPOST 0000001
#define OLCUC 0000002
#define ONLCR 0000004
#define OCRNL 0000010
#define ONOCR 0000020
#define ONLRET 0000040
#define OFILL 0000100
#define OFDEL 0000200
#if defined __USE_MISC || defined __USE_XOPEN
# define NLDLY 0000400
# define NL0 0000000
# define NL1 0000400
# define CRDLY 0003000
# define CR0 0000000
# define CR1 0001000
# define CR2 0002000
# define CR3 0003000
# define TABDLY 0014000
# define TAB0 0000000
# define TAB1 0004000
# define TAB2 0010000
# define TAB3 0014000
# define BSDLY 0020000
# define BS0 0000000
# define BS1 0020000
# define FFDLY 0100000
# define FF0 0000000
# define FF1 0100000
#endif
#define VTDLY 0040000
#define VT0 0000000
#define VT1 0040000
#ifdef __USE_MISC
# define XTABS 0014000
#endif

3. The possible values for c_cflag :
/* c_cflag bit meaning */
#ifdef __USE_MISC
# define CBAUD 0010017
#endif
#define B0 0000000 /* hang up */
#define B50 0000001
#define B75 0000002
#define B110 0000003
#define B134 0000004
#define B150 0000005
#define B200 0000006
#define B300 0000007
#define B600 0000010
#define B1200 0000011
#define B1800 0000012
#define B2400 0000013
#define B4800 0000014
#define B9600 0000015
#define B19200 0000016
#define B38400 0000017
#ifdef __USE_MISC
# define EXTA B19200
# define EXTB B38400
#endif
#define CSIZE 0000060
#define CS5 0000000
#define CS6 0000020
#define CS7 0000040
#define CS8 0000060
#define CSTOPB 0000100
#define CREAD 0000200
#define PARENB 0000400
#define PARODD 0001000
#define HUPCL 0002000
#define CLOCAL 0004000
#ifdef __USE_MISC
# define CBAUDEX 0010000
#endif
#define B57600 0010001
#define B115200 0010002
#define B230400 0010003
#define B460800 0010004
#define B500000 0010005
#define B576000 0010006
#define B921600 0010007
#define B1000000 0010010
#define B1152000 0010011
#define B1500000 0010012
#define B2000000 0010013
#define B2500000 0010014
#define B3000000 0010015
#define B3500000 0010016
#define B4000000 0010017
#define __MAX_BAUD B4000000
#ifdef __USE_MISC
# define CIBAUD 002003600000 /* input baud rate (not used) */
# define CMSPAR 010000000000 /* mark or space (stick) parity */
# define CRTSCTS 020000000000 /* flow control */
#endif


4. The possible values for c_lflag :
/* c_lflag bits */
#define ISIG 0000001
#define ICANON 0000002
#if defined __USE_MISC || defined __USE_XOPEN
# define XCASE 0000004
#endif
#define ECHO 0000010
#define ECHOE 0000020
#define ECHOK 0000040
#define ECHONL 0000100
#define NOFLSH 0000200
#define TOSTOP 0000400
#ifdef __USE_MISC
# define ECHOCTL 0001000
# define ECHOPRT 0002000
# define ECHOKE 0004000
# define FLUSHO 0010000
# define PENDIN 0040000
#endif
#define IEXTEN 0100000

Saturday, January 17, 2009

gmtime and localtime (time.h)

We need to use structure for displaying local time (one time only). The program bellow uses predefined structure from “time.h”. The structure tm (which is defined in ) as follows:
#ifdef _TIME_H
__BEGIN_NAMESPACE_STD
/* Used by other time functions. */
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/

#ifdef __USE_BSD
long int tm_gmtoff; /* Seconds east of UTC. */
__const char *tm_zone; /* Timezone abbreviation. */
#else
long int __tm_gmtoff; /* Seconds east of UTC. */
__const char *__tm_zone; /* Timezone abbreviation. */
#endif
};

the structure can be read inside the manual for gcc library. Another declarations inside time.h that are interesting are :

__BEGIN_NAMESPACE_STD
/* Return the `struct tm' representation of *TIMER
in Universal Coordinated Time (aka Greenwich Mean Time). */
extern struct tm *gmtime (__const time_t *__timer) __THROW;

/* Return the `struct tm' representation
of *TIMER in the local timezone. */
extern struct tm *localtime (__const time_t *__timer) __THROW;

__END_NAMESPACE_STD

The program bellow uses gmtime(). According to gcc manual it is a functions that converts the calendar time timep (time protocol) to broken-down time representation, expressed in Coordinated Universal Time (UTC) or GMT.

#include "stdio.h"
#include "time.h"
int main()
{
time_t ttrs;
struct tm *ptrti;
time(&ttrs);
ptrti=gmtime(&ttrs);
printf("%d %d %d", ptrti->tm_hour, ptrti->tm_min, ptrti->tm_sec);
return 0;
}

The program above displays local time once. If you need to capture and display time once every second the you will need a loop. Inside this program we use localtime(). According to gcc manual, it is a function that converts the calendar time timep (time protocol) to broken time representation, expressed relative to the user’s specified time zone or local time zone.
#include "time.h"
#include "stdio.h"
int main()
{
int sh;
time_t rt;
struct tm * ti;
while(1)
{
time(&rt);
ti = localtime(&rt);
if (sh != ti->tm_sec) printf("%d %d %d\n", ti->tm_hour, ti->tm_min, ti->tm_sec);
sh = ti->tm_sec;
}
}

Structure

Structure is a bunch of variables bundled together and then is named according to the proper abstraction of the creator. Therefore the name of a structure depends on the creator. Of course the name should be meaningful. The variables may be of the different type. In another languange a structure may be called a record. In my opinion, the most important aspect of structure is for abstraction. Compiling attributes that are important for current activities, and forget about the unimportant things. For example I need to model a student, and what matters to me for deciding his final mark are : StudentId, First Name, Last Name, Assignment, MidExam, and FinalExam. In this example the weight for final mark calculation is 30% of assignment, 30% of MidExam, and 40% of FinalExam. The name of the structure is Student. See the example bellow :
#include "stdio.h"

#include "stdlib.h"

typedef struct

{

char StudentId[5];

char FirstName[20];

char LastName[20];

float Assignment;

float MidExam;

float FinalExam;

} Student;

int main(void)

{

Student os;

float final;

printf("Student Id : ");

scanf("%s", os.StudentId);

printf("First Name : ");

scanf("%s", os.FirstName);

printf("Last Name : ");

scanf("%s", os.LastName);

printf("Assignment : ");

scanf("%f", &os.Assignment);

printf("Mid Term Exam : ");

scanf("%f", &os.MidExam);

printf("Final Exam : ");

scanf("%f", &os.FinalExam);

final = 0.3*os.Assignment+ 0.3*os.MidExam+ 0.4*os.FinalExam;

printf("The Grade for : %s %s %s is %f", os.StudentId, os.FirstName, os.LastName, final);

}

Tuesday, January 13, 2009

Basic Structure of a Program : Iteration

Iteration

The last important construct is itteration. It executes a set of programming statements several times until certain condition is reached. The sentinel condition is usually evaluated by using pre increment and post increment Operation. Lets have a look at the example bellow. It shows the post increment operation in a simple sequential program :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int i = 10;
system("clear");
printf("%d", i++); /*The output of this operation is 10, since the variable is used first and then the value is incremented */
}

Now we are going to have a pre increment operation :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int i = 10;
system("clear");
printf("%d", ++i); /*The output of this operation is 11, since the variable is incremented first and then the value is displayed */
}

Now lets use this operation for controlling a for loop. Example below is post increment :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int j;
system("clear");
for (j=0;j<10;)
{
printf("%d \n", j++);
}
}

The output of the program is : 0 1 2 3 4 5 6 7 8 9. What would happened if the sentinel is pre increment
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int j;
system("clear");
for (j=0;j<10;)
{
printf("%d \n", ++j);
}
}
The output will decidedly different : 1 2 3 4 5 6 7 8 9 10.

Now its time for use to move to the nitty gritty of C programming.

Friday, January 9, 2009

Basic Structure of a Program : Selection

Basic Structure of a Program : Selection
Selection construct in any programming language is for controlling the execution of certain part of an algorithm when certain condition occurs. In C/C++ language this structure is implemented with if/if-else if-else and switch-case statements. For example we decide not to drink tea when it is hot, we eats when we feel hungry, A lecturer decides that a student passes an exam if his mark is more or equal to 60. Bellow is an example of if construct :

First Example : if
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
float floatGrade; /*Declaring a variable for storing a student's grade*/
system("clear");
printf("Student's Mark : -->");
scanf("%f", &floatGrade);
if (floatGrade >= 60.00)
{
printf("Passes\n");
}
else
{
printf("Fails\n");
}
return 0;
}

Second Example : if/else-if/else
In the next example we specify that a student get :
1.Grade C if his mark is more or equal 60 and less than 70
2.Grade B if his mark is more or equal 70 and less than 80
3.Grade A if his mark is more or equal 80 and less or equal than 100
4.Fails if his mark is more or equal 0 and less than 60
5.The program will say that the value is not legal if it is not in the range between 0 and 100.
The sorce code is :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
float floatGrade; /*Declaring a variable for storing a student's grade*/
system("clear");
printf("Student's Mark : -->");
scanf("%f", &floatGrade);
if (floatGrade >= 60.00 && floatGrade < 70) /*Condition for grade C*/
{
printf("Passes with grade C\n");
}
else if (floatGrade >= 70.00 && floatGrade < 80) /*Condition for grade B*/
{
printf("Passes with grade B\n");
}
else if (floatGrade >= 80.00 && floatGrade <= 100) /*Condition for grade A*/
{
printf("Passes with grade A\n");
}
else if (floatGrade >= 0.00 && floatGrade < 60) /*Condition for Fail*/
{
printf("Fails \n");
}
else /*Specifying that another value outside the range of 0 to 100 is not legal*/
{
printf("Value is not legal\n");
}
return 0;
}

Third Example : switch-case
Another selection type is using switch-case. A switch-case construct consists of :
1.switch key word accompanied by the variable that will be evaluated to determine which program statement that will be executed.
2.program statements inside the switch-case nest.
The example of this statement is that a student will be awarded a sum of money, so that he can go to the movie.
#include "stdio.h"
#include "stdlib.h"
#include "ctype.h" /*We use toupper to convert the lowercase input to uppercase*/
int main()
{
char chrGrade;

system("clear");
printf("Student Grade :---> ");
scanf("%c", &chrGrade);
chrGrade=toupper(chrGrade);
switch(chrGrade)
{
case 'A' : printf("You are awarded $100");break;
case 'B' : printf("You are awarded $50");break;
case 'C' : printf("You are awarded $25");break;
case 'D' : printf("You are awarded $0");break;
default : printf("Wrong Grade");break;
}
return 0;
}

Now you have already learn how to create a selection construct.

Basic Structure of a Program : Sequence

Basically a program(algorithm) have three basic structures : sequence, selection, and repetition. We are going to discussed these basic structures by using examples. So that you will have basic and hopefully thorough knowledge of each structure.

Sequence
A Sequence consists of several instructions. Each instruction is executed according to its writing order. Instruction sequence determines the result of an algorithm. This is a sample of simple algorithm :
1.Put the pan on the stove
2.Turn on the stove
3.Put the butter into the pan
4.Pour in egg
5.Let it fried for a minute
6.Put the egg on a plate
Now you can have a plate of EATABLE fried egg. What would happen if you change the order. for example :
1.Put the pan on the stove
2.Turn on the stove
3.Pour in egg
4.Let it fried for a minute
5.Put the butter into the pan
6.Put the egg on a plate.
What do we have know ? BURNT UNEATABLE BITTER UGLY fried egg. Now lets have a simple program that can be compiled by using gcc compiler.

First Example : HELLO World
The example will produce simple executable binary file. Now we have a file named hello.c :

#include "stdio.h"

int main()
{
printf("Hello World");
return 0;
}

Then we need to do a compilation with statement like this :
#gcc -o hello.out hello.c

The output of this statement is hello.out, We can execute this executable by issuing this command :
#./hello.out

Afterwards the output "Hello World" will be displayed

More example
Lets make another simple program that will takes user input for calculating the area of a triangle. The source code is listed bellow :

#include "stdio.h"
#include "stdlib.h"
int main(void)
{
float floatHeight = 0, floatWidth = 0;
system("clear"); /* This statement calls system's command : “clear” */
printf("\nWidth : --> ");
scanf("%f", &floatHeight);
printf("\nHeight : --> ");
scanf("%f", &floatWidth);
printf("\nArea : --> %f", floatHeight*floatWidth/2);
return 0;
}

Another example will be nice to enhance our "felling" for writing a program in sequential construct. The program is about calculating the area of a circle :
#include "stdlib.h"
#include "stdio.h"
#define PI 3.1416
int main()
{
float rad;
float area;
system("clear");
printf("Enter radius :-> ");
scanf("%f", &rad);
area = PI * rad * rad;
printf("Area :---------> %f", area);
printf("\nBye...");
return 0;
}

Another example is calculating the area of a rectangle :
#include "stdio.h"
#include "stdlib.h"
int main()
{
float width,length;
float area;
system("clear");
printf("Length :-> ");
scanf("%f", &length);
printf("Width :-> ");
scanf("%f", &width);
printf("Area :-> %f\n", length*width);
return 0;
}

We are going to have another simple example of sequence. See the source code bellow for the calculation of a volume of a cylinder :
#include "stdio.h"
#include "stdlib.h"
#include "math.h" /*contains prototype of pow (power) */
int main(void)
{
float floatHeight = 0, floatRadius = 0;
system("clear");
printf("\nHeight : --> ");
scanf("%f", &floatHeight);
printf("\nRadius : --> ");
scanf("%f", &floatRadius);
printf("\nVolume : --> %f", floatHeight*pow(floatRadius,2)*22/7);
return 0;
}
So, business as usual, compile and run it !!!