Jump to content


Check out our Community Blogs

kernelcoder

Member Since 06 Apr 2012
Offline Last Active Oct 02 2013 10:47 AM
*****

Topics I've Started

The Node.js

23 March 2013 - 07:54 PM

This is the index part on the series of tutorials on Node.js I started. This is about just a single post where you'll get links to all the parts on the series.

 

 

1. The Node.js -- Part1: The Basic

This part discusses about 'what is node.js', installing the necessary things to run node.js code on your machine and run the legacy hello world application.

 

 

2. The Node.js -- Part2: The Basic of HTTP Server

This part discusses about the basic of a HTTP server to implement in Node.js, reads file from OS filesystem, parsing and routing urls with an example.

 

 

 

3. The Node.js -- Part3: CouchDB Basic

It describes how to use a NoSql type database (CouchDB) in a node application, how to install a node module.

 

 

 

4. The Node.js -- Part4: Understanding Node.js Platform

It describes about Node.js's asynchronous callback system.

 

 

 

5. The Node.js -- Part5: Node Module Basic

It describes about Node's module concept.

 

 

 

6. The Node.js -- Part6: Form Programming

It describes about handling and extracting data (both POST and GET way) from a form submission to a HTTP server.

 

 

 

7. The Node.js -- Part7: Advanced HTTP Server-1

The first sub-part of a more close to complete http server that will handle all usual type of requests.


C for Beginner -- Part7: C Data Storage--Array

19 March 2013 - 01:24 AM

From this series tutorial  we had come to know about c basics , some important weapons already. Today we will learn about the most important data storage -- Array.

 

 

What is Array?

Array is simply a collection of same type variables. An array is a collection of same type of elements which are sheltered under a common name. An array can be visualized as a row in a table, whose each successive block can be thought of as memory bytes containing one element. Array holds successive memory blocks in the primary memory. The basic structure of an array declaration

<type-of-array> <name-of-array> [<number of elements in array>];

 

Lets say we have to store a name for programming purpose. We can start like this 

char a,b,c,d,e,f,g,h,i,j;
a='k';
b='e';
c='r';
d='n';
e='e';
f='l';
g='c';
h='o';
i='d';
j='e';
k='r';
printf("%c%c%c%c%c%c%c%c%c%c%c",a,b,c,d,e,f,g,h,i,j,k);//will show kernelcoder

This is not a good idea to store each character in separate variable. Thus the idea of array comes in. The name 'kernelcoder' has 11 characters. We can start storing the name kernelcoder in an array like this

char name[12] = "kernelcoder";
printf("My name is %s",name);//%s is used for string(collection of char data)

The name[12] is the declaration of an array which can hold 12 variables named name[0],name[1],.......,name[11]. Here 'name' is the array name, in the third bracket the 12 defines how many variables should the array have, this is called index of an array. See the length of 'kernelcoder' is 11 but we used 12, because for character array a null('\0') character is appended to the array thus this array has an index of 12. Basically a string is ended with a null character(\0).

Attached File  chararray.png   2.99KB   166 downloads

 

 

Types of Array

We can have all types of arrays as we knew for datatypes. So we can use character array(sometimes called as  string), integer array, floating data array etc. We just need to know how to declare and use them in our program. For an integer array roll[10], the array can hold 10 roll numbers (not 10 digits).

int roll[10];
roll[0] = 1;
roll[1] = 2;

roll[2] = 3;

roll[3] = 4;

roll[4] = 5;

roll[5] = 6;

roll[6] = 7;

roll[7] = 8;

roll[8] = 9;

roll[9] = 10;
printf("\nroll[9]=%d",roll[9]);

C for Beginner -- Part6: C Weapon logy --if/else

13 March 2013 - 02:27 AM

So far we had come to know about basic concepts of C. Today we will start learning about C weapon logy-- C control statements. 

 

 

Control Statements

Control statements allow us to change the computer's control from automatically reading the next line of code to reading a different one. Computer programs are run sequentially from first line to last, the control statements allow us to control which statements should run and when.  Lets say we only want to run some code on some conditions.  For example, let's say, we are making a program for a bank. If someone wants to see his records, and gives his password, the program should check if the person is the right one. Firstly, we need to see if his password is correct. We  then need to create a control statement saying "if" the password is correct, then run the code to let him see the records. "else" run the code for people who enter the wrong password. So in computer programming we call these as weapon. There are several control statements in C,
  1. Conditional statements (if,if/else,else if, switch)
  2. Looping(for, while, do while)
  3. Labels (Goto) etc
 
The if/else Statement
The if/else statement is one of the most important weapon in programming. The if/else statement is used to choose a path from the two possible routes. The basic if/else code block should look like this
If(<condition>){
//some code will run when  the condition is true
}else {
//another code block will run when the if <condition> is false
}
In the if/else block the <condition> can be an expression, other functions or anything else, if the condition possess a value of non zero, yes, strictly non zero, its is treated as true otherwise false. So what will happen with this code?
if(100){
  printf("In if statement block.\n");//this code will always run,
}
 
if(-10000)
  printf("This printf will run because the condition is non zero.\n");
 
if(5>10)
  printf("This will not run");
printf("\nThis will always run.");
in the above code, the first if condition there 100 that is nonzero so the printf() function will always run. In the second if same case will happen, notice there is no '{}' (Curly BRACKET), this is a valid structure but not a good programming practice. See there is a '\n' at the end of the printf() argument, this is an ASCII character( ASCII Code = 10) used to go to the beginning of the next line. Showing some formatted output is a good programming practice. In the last if statement the condition is false, so the printf("This will not run"); will not run, but the next printf() will always run. Why? Because this printf() is not in the if block, so there is no condition to run this printf().  
#include<stdio.h>
#include<conio.h>
void main(){
	int a = 10;
	if(a == 10){
		printf("A is 10");
	}
	getch();
}

See the above program has an if statement or block, notice carefully the condition was ‘a == 10’. There is a ‘==’ operator, whenever we want some comparison there must be a ‘==’ operator in if condition. We can extend this program as using else statement with the if block.

#include<stdio.h>
#include<conio.h>
void main(){
	int a = 10;
	if(a == 10){
		printf("A is 10");
	}else {
		printf("A is not 10");
	}
	getch();
}

Notice that we used else statement at immediate after the if statement, otherwise compiler will throw an error. We cant use the else without the preceding if.

 
Lets think of a problem we discussed earlier, the leap year problem. We want to make a program to check whether a given year is leap year or not. Our program will take an user input for the year and will check if this is a leap year. Basic tasks to do:
  • Input year 
  • Check the year has a reminder after the operation year%4
  • Show the output
Input the year is easy as we learnt it in the previous part,
//this will wait for a real number is pressed, for simplicity we assume the user will input a legal year(an integer variable)
scanf(“%d”,&year);
Now we will use the if conditional statement to check the year is leap year or not. The logic is if the year%4 operation has a reminder 0 then the year is leap year otherwise not a leap year.
if(year%4 == 0){
	printf("The year %d is a leap year",year);
} else {
	printf("The year %d is not a leap year",year);
}

 

 

Exception
If the user doen't provide a legal year what will happen? Suppose a user inputs a year -1. our program will show the year is not a leap year, but we know the given year is not valid. So our program should have some validation control system for the user input. This is a good programming practice.
if(year<0){
	printf("%d is not a valid year. Program will terminate now.",year);
}else {
	if(year%4 == 0){
		printf("The year %d is a leap year",year);
	} else {
		printf("The year %d is not a leap year",year);
	}
}

 

 

Nested if/else
See the above code block, there is if/else statement in another else block. We can place if/else statements into another if or else  statement block like that. This is called nesting of a statement. Basic block of nesting of if/else statement should look like this,
If(<condition>){
   If(<some other condition>){
      //some other codes if the <some other condition> is true
   }else {
      //else some other codes 
   }
}else {
   //code will execute if the <condition> is false
}
We can use multilevel nesting as we need in our program. Lets think a program, we have three numbers and this program will find which one is the biggest.
#include<stdio.h>
#include<conio.h>
void main(){
	int a = 10, b = 20 , c = 5;
	if(a>b){
		if(a>c){
			printf("a(%d) is the biggest among-st %d %d %d ",a,a,b,c);
		}else {
			printf("c(%d) is the biggest among-st %d %d %d ",c,a,b,c);
		}
	}else {
		if(b>c){ 
			printf("b(%d) is the biggest among-st %d %d %d ",b,a,b,c);
		}else {
			printf("c(%d) is the biggest among-st %d %d %d ",c,a,b,c);
		}	
	}
getch();
}

So this program is able to find out the biggest number among three numbers. But we some time need this process done among thousands of numbers! How? We will see this in the next part.  

 

 

Tasks

  • Input a number and find out the number is even or odd.
  • Input two numbers and make a swap program(interchanging the value of two variables)
  • Test various exceptions, Check the errors occur for misplacing the if and else block in a program, Check for a number bigger than the range of integer
  • What will happen when a user inputs a character for the leap year program?  

The Node.js -- Part7: Advanced HTTP Server-1

07 March 2013 - 02:40 AM

We had come to know about basic http server that was able to server files requested by the client. Today we will start learning how to make an advanced http server which is able to handle various types of requests from client side. In this part of this advanced server we will start designing an application that has single html page with some links. Our http server will handle all the requests from that page. Thus we will complete our advanced server.

 

The Goal

Our goal is to create the final http server application that can handle all http requests from client side. We will use some modules/platforms like flatiron for this purpose. Our application will have some html pages with lots of links/requests, forms etc. We will create an html page home.html. We will send this page on client request and we will use this as our application starter page.
 
Basic HTTP Server
Our basic http server that we created earlier: 
var http = require('http');
var server = http.createServer(function(req,res){
    //request handler code here
    console.log('Request found.');
    res.end('Hello world');
});
server.listen('8080');
console.log('Server is running.');
This was our basic http server that can send a message on client request. If we want to process requests from client side we need to parse the url got and then need to make the handler for some requests. Here we will implement an easy solution for all requests part by part.
 

 

The Application using flatiron

We will use a node module named flatiron which is used for various purpose. Flatiron is a platform that run on node, we can tell flatiron as node framework.  Flatiron gives us a commandline tool that can generate several application boilerplates. Installing flatiron is easy. Just run this in node commandline
npm install flatiron -g
This command will install flatiron framework glabally that means you can use this in anywhere in all your applications.  Flatiron gives us a good commandline tool and we can use this by ‘flatiron’ command in node commandline. Now we will create our application by this command
flatiron create httpserver
There will be some prompt that will ask for some initial information about the author description of the app etc. After providing all those flatiron  will create our application in the httpserver(name of the app) folder in current working directory with some files and by default on http://localhost:3000. Directory structure of the newly created application:
Attached File  createserver.png   9.36KB   179 downloads
Our application starter file is app.js, package.json contains the information about the application, config folder has a config/config.json file that can be edited to configure our application with some default parameters/values, the lib and test initially don't have any file. 
Well now we are set to run our application by the command, reaching in the httpserver directory:
node app.js
 
This will show an error like node module not found with some helpful messages, we have to install all the dependencies for this application by this command
npm install
This command will install all the dependencies into our application httpserver folder. Now we are set to see what we created. After running the app, when we hit http://localhost:3000 we will see a message {"hello":"world"} in the browser. The request handler looks like:

app.router.get('/', function () {
  this.res.json({ 'hello': 'world' });//sending  json data
});

From now on we will work in the app.js file. Now we set the home.html for our starter application page.

app.router.get('/', function () {//default request handler, for start point of our app, finally here will be login form
var data = fs.readFileSync('./html/home.html');

console.log('Sending read file: home.html');
this.res.end(data);
});
 
The app object is the current application object is used to do everything in server purpose. The router object is used to route a request path to some specified callback function.
See we placed the html file in html folder in the httpserver. We read the file on http://localhost:3000('/') request and its readFileSync() that reads file synchronously. Then the data is sent back to the client side. Thus we initialize our application. Now its easy to make some other request handlers(append this after the previous block of code) 

app.router.get('about', function () {
    var data = fs.readFileSync('./html/about.html');
    console.log('sending read file: about.html');
    this.res.end(data);
});

In the homepage there is a link/request for 'about', when a user clicks on that this router will send the about.html back to the client side. Our first part of this advanced httpserver application completed. Will come soon with the next part.
 
Recommended Reading

C for Beginner -- Part5: Basics of IO

06 March 2013 - 02:08 AM

Today we are going to learn about the most important part of programming --input/output. Here we will discuss about input from standard input device(the keyboard). This part of this tutorial will explain how to take input from user from the standard input device -- the keyboard.

 

 

Build-in Functions 

Functions are snippet of codes that performs some specific tasks on some given data. Built-in functions are similar to operational codes, they perform operations on given data. Those functions can be used in expressions. The syntax of built-in functions is:

return_type function-name ( argument{:argument...}){
//codes to do something on the data found in argument
}
Arguments for the function may be variables, constants, expressions, a prototyped procedure, or other functions. An expression argument can include a built-in function. In C language there are lots of built in functions located in various header files , we call those as library function. In C each function must return a value, if there is nothing to return then it will return void. The printf() returns void, the main returns void as we used void main so far. Simple calling to a function in a program:
printf(arguments);//printf as a built-in function
 
 
Input Characters
The standard library provides several functions for reading or writing one character at  a time, of which getchar and putchar are  the simplest. Each time it is called, getchar reads the  input character from a standard input device and returns its value.  The characters normally come from the keyboard. As we knew earlier a character can be shown in screen by %c in the printf() function. The function  getchar() waits until a character is pressed by the user.

char a;
printf(“Please Enter a charecter:”);
a = getchar();//try with pressing many characters but this will store only the first one
printf(“\n You have pressed character a :  %c”,a);

Here we used getchar() to take a character input. When the program starts running, the printf() shows  the message: “Please Enter a character:”  then getchar() waits until a key is pressed (will terminate taking input when the 'Enter' key is pressed) when a key is pressed it stores the character to the variable a. Finally we just printed the character in the screen. Showing some messages like those is a good programming practice. We have printed the character got from the getchar() function, we can also see the ASCII code of that character by printing the character as integer

printf(“\n You have pressed character a :  %c and ASCII Code is : %d”,a,a);

A character is nothing but an integer that represents the ASCII code of that character. For example see the program

int a = 65;
putchar(a);//same as printf("%c",a); notice that a is integer type

See the output of this program will show the character 'A' in the screen. The function putchar() prints a character each time it is called,  prints the contents of the  variable a as a character, usually on the screen. Calls to putchar and  printf may be interleaved,  the output will appear in the order in which the calls are made.

 
 
The scanf() Build-in Function
The scanf() is a build in function from header file stdio.h and is mostly used for user input. scanf( ) is the general -purpose console input routine. It can read all the built-in data types and automatically convert numbers into the proper internal format. It is much like the reverse of printf( ). The format for scanf( ) is
int  scanf(const  char  *control_string,  .  .  .  );
The scanf( ) function returns the number of data items successfully assigned a value. If an error occurs, scanf( ) returns EOF(ends of file). The control_string determines how values are read into the variables pointed to in the argument list.
The control string consists of three classifications of characters(same as format specifiers):
  •  Format specifiers, White-space characters & Non-white-space characters
The input format specifiers are preceded by a % sign and tell scanf( ) what type of data is to be read. The format specifiers are matched, in order from left to right, with the arguments in the argument list. Here's  some examples to take various types of input.
int a;
scanf("%d",&a);
printf("\n the data you given : %d",a);
Please run this program several  times and input different types of data each time. Notice that this scanf waits until a 'Enter' key is pressed, when you input a character(=that means not a number type) the printf will show a garbage data(an undefined, not meaningful data). The scanf( ) function stops reading a number when the first non-numeric character is encountered.
To read an integer, we use either the %d or %i specifier. To read a floating-point number represented in either standard or scientific notation, we use %e, %f, or %g. (C99 also includes %a, which reads a  floating-point number.)
 
Here's some lists of specifiers
%a Reads a floating -point value (C99 only).
%c Reads a single character.
%d Reads a decimal integer.
%i Reads an integer in either decimal, octal, or hexadecimal format.
%e Reads a floating -point number.
%f Reads a floating -point number.
%g Reads a floating -point number.
%o Reads an octal number.
%s Reads a string.
%x Reads a hexadecimal number.
%p Reads a pointer.
%n Receives an integer value equal to the number of characters read so far.
%u Reads an unsigned decimal integer.
%[ ] Scans for a set of characters.
%% Reads a percent sign.
 

To read an individual character we used getchar( ), we can use scanf( ) for this purpose if we use the %c format specifier. However, like most implementations of getchar( ), scanf( ) will generally line-buffer input when the %c specifier is used. This makes it somewhat troublesome in an interactive environment.

Although spaces, tabs, and newlines are used as field separators when reading other types of data, 

when reading a single character, white-space characters are read like any other character. For 

example, with an input of "a b" this code fragment

scanf("%c%c%c", &a, &b, &c);//a='a' b='space character' c='b'

 

  • Thus the scanf( ) function can be used to read a string(sequence of characters) from the input stream using the %s format specifier. Using %s causes scanf( )  to read characters until it encounters a white-space character(Space/Tab/Enter). The characters that are read are put into the character array(we will learn about array later on) pointed to by the corresponding argument, and the result is null(=a character: ASCII code is 0, represented as '\0') terminated. As it applies to scanf( ), a white-space character is either a space, a newline, a tab, a vertical tab, or a formfeed.
  char str[30];//str is a character type variable that has 30 consecutive  variables in it
  printf("Enter a string: "); 
  scanf(''%s", str);//notice there is no '&' 
  printf("Here's your string: %s", str);
 
The program responds with only the "hello" portion of the string input "hello there"
 
  • A non-white-space character in the control string causes scanf( ) to read and discard matching characters in the input stream. For example, ''%d,%d" causes scanf( ) to read an integer, read and discard a comma, and then read another integer. If the specified character is not found, scanf( ) terminates. If you want to read and discard a percent sign, use %% in the control string.Strings will be read into character arrays, and the array name, without any index, is the address of the first element of the array. So, to read a string into the character array str, you would use scanf("%s", str). In this case, str is already a pointer and need not be preceded by the & operator.
  • All the variables used to receive values through scanf( )  must be passed by their addresses. This means that all arguments must be pointers. Recall that this is how C creates a call by reference, which allows a function to alter the contents of an argument. For example, to read an integer into the variable count , you would use the following scanf( ) call:

scanf("%d", &count);
 
 
The getch()
As we used this funtion in each of our program. This function simply waits until a key is pressed but it returns void and dont stores the key pressed even it doesn't show what key is pressed,  that we used to show the output until user wanted to close it.
 
Displaying an Address
When we declare a variable, a segment of the system memory is supplied to store the value of the variable. The size of the block depends on the variable type. Sometimes we need to display  address of a variable, we can use %p. This format specifier causes printf( ) to display a  machine address in a format compatible with the type of addressing used by the computer. The next program displays the address of sample:
#include <stdio.h> 
void main(){ 
int sample;
  printf(''%p", &sample); 
}
See there is a '&' before the sample variable in the printf function. This notation is generally used to display addresses and for other types of notation we will learn later on. After learning the above tutorial a learner should be able to take floating point, double type data input, if further explanation needed feel free to ask. From today on we will have some tasks basis of the tutorial part.
 
 
Tasks
  • Various types data input by scanf() and output by printf()
  • Taking multiple inputs in one scanf()
  • Testing the errors may occur regarding scanf()
  • Testing by wrong data input
  • Finding out the situation when input is failed using scanf() etc

 

 


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download