Jump to content


Check out our Community Blogs

kernelcoder

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

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

Posted by kernelcoder on 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).

chararray.png

 

 

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]);

Attached Thumbnails

  • char2darray.png
  • intarray.png
  • error1.png
  • error2.png

  • 1


#653420 C for Beginner -- Part3 : C Basics -- Variable & Datatype

Posted by kernelcoder on 28 February 2013 - 11:11 PM

In this series tutorial we will cover the basics of C language, Expressions,  C Weaponology (Control statement, Operators etc), decision making, data storage, functions (structured programming), pointers, Dynamic memory allocation and so on.

We will run step by step and thoroughly. We will learn about a weapon(statement/logic) on demand that means when we need some thing to use in our program we will learn that on time. We will explain everything with descriptive examples, various ways to solve problems, thus a learner can perceive everything about C Programming, logic development , advanced programming practice etc.
Finally we will run some C projects that will make sense on how to be a master in C.
 
In the last part we had come to know how to write a Hello World program, how to build and execute the program. Today we will learn about C Variables, Datatypes and finally how to use those in a C program.
 
 
Variables
In computer programming, a variable is a storage location and an associated symbolic name(an identifier) which contains some known or unknown quantity or information, a value. The variable name is the usual way to reference the stored value, this separation of name and content allows the name to be used independently of the exact information it represents. The identifier in computer source code can be bound to a value during run time(during execution of a program), and the value of the variable may thus change during the course of program execution. Variables in programming may not directly correspond to the concept of variables in mathematics. The value of a computing variable is not necessarily part of an equation or formula as in mathematics. In computing, a variable may be employed in a repetitive process: assigned a value in one place, then used elsewhere, then reassigned a new value and used again in the same way (iteration). Variables in computer programming are frequently given long names to make them relatively descriptive of their use, whereas variables in mathematics often have terse, one- or two-character names for brevity in transcription and manipulation.
A variable storage location may be referred by several different identifiers, a situation known as aliasing. Assigning a value to the variable using one of the identifiers will change the value that can be accessed through the other identifiers.
 
 
Identifiers
Before we can do anything in any language, we must know how to name an identifier. An identifier is used for any variable, function, data definition, etc. In the C programming language, an identifier is a combination of alphanumeric characters, the first being a letter of the alphabet or an underline, and the remaining being any letter of the alphabet, any numeric digit, or the underline.Two rules must be kept in mind when naming identifiers.
  • The case of alphabetic characters is significant. Using INDEX for a variable name is not the same as using index and neither of them is the same as using InDeX for a variable name. All three refer to different variables.

  • According to the ANSI-C standard, at least 31 significant characters can be used and will be considered significant by a conforming ANSI-C compiler. If more than 31 are used, all characters beyond the 31st may be ignored by any given compiler. There are limitations when using other special characters in an identifier such as,

  •  Name of identifier includes alphabets, digit   and underscore.

            Valid name: world, addition23, sum_of_number etc.

             Invalid name: factorial#, avg value, display*number etc.

  • First character of any identifier must be either alphabets or underscor

            Valid name:  _calulate, _5,a_, __ etc.

            Invalid name: 5_, 10_function, 123 etc.

  • Name of identifier cannot be any keyword of c program.(we will learn about C keyword later on)

 
 
Datatypes
In computer programming, a data type or simply type is a classification identifying one of various types of data, such as real-valued, integer or Boolean, that determines the possible values for that type, the operations that can be done on values of that type, the meaning of the data, and the way values of that type can be stored. In C language there are 4 basic data types listed below
 
datatypes.png
 
C89 defines five foundational data types: character, integer, floating-point, double floating-point, and valueless(void). These are declared using char, int, float, double, and void, respectively. These type form the basis for several other types. The size and range of these data types may vary among processor types and compilers. However, in all cases an object of type char is 1 byte. The size of a int is usually the same as the word length of the execution environment of the program. For most 16-bit environments, such as DOS or Windows 3.1, an int is 16 bits. For most 32-bit environments such as Windows 95/98/NT/2000, an int is 32 bits. However, you cannot make assumptions about the size of an integer if you want your programs to be portable to the widest range of environments.It is important to understand that C stipulates only the minimal range of each data type, not its size in bytes.
 
 
Variable Declaration Rules
Variable declaration is to name an identifier with its datatype. In C we must declare a variable before we use it in our program. 
void main(){
int a,b,c;
}
In the above example variable a,b and c of integer type are declared on the starting of main function. And now on we can use those variables in anywhere in our program. 
#include<stdio.h>
void main(){
printf("Program started");
int a;
printf("The previous line  produces error.");
}
In the above example this program will show an error(Message shown by compiler:Declaration is not allowed here) when we compile it because we cant declare variables after the program start that means after any runnable statement. Recommendation here is  to test our program for error reporting in a old fashion c compiler named TURBO C 3.00. In this light weight compiler we can observe the errors very effectively. We knew that we can save our c program with a .c/.C extension as well as .cpp/.CPP extension. in the .cpp/.CPP extension C file, this limitation is overcame. There are other rules as well we will learn  on time.
 
 
Examples
With some examples we will learn about 4 types of data types. First come with the char.c file
#include<stdio.h>
#include<conio.h>
 
void main(){
    char a,b;
    a = 'a';
    b = 'b';
    printf("Character a: %c and b: %c",a,b );
    getch();
}
Here in the beginning of the main function there is a statement starting with char keyword(we will know about keyword later on). The a and b are the two variables that can contain a single character(a character is defined in the single quote ''). Then we assigned(the   ‘=’  operator works assigns value right to left, will know about operator later on) character ‘a’ to variable a and ‘b’ to variable b. Finally we have showed up the data/value containing variable a and b. The %c named as format specifier(see below) is used to print character in the screen in respective order.
So for integer, float and double type variable we can change the char.c program as
/***file name:int.c**/
#include<stdio.h>
#include<conio.h>
 
void main(){
    int a,b;
    a = 10;
    b = 20;
    printf("Integer a: %d and b: %d",a,b );
    getch();
}
 
 
 
/***file float.c**/
#include<stdio.h>
#include<conio.h>
 
void main(){
    float a,b;
    a = 100.25;
    b = 100;
    printf("Float a: %f and b: %f",a,b );
    getch();
}
 
 
 
/***file double.c**/
#include<stdio.h>
#include<conio.h>
 
void main(){
    double a,b;
    a = 100.25;
    b = 100;
    printf("Double a: %lf and b: %lf",a,b );
    getch();
}
 
 
 
Comments in C Language
See there is a line having /* file float.c*/ we call this comment in a source program. These code will not affect on the program execution that means these are hidden to the compiler.
 
The syntax for a comment is: -- Single Line
/* comment goes here */
or
// comment goes here
 
Syntax for Spans Multiple Lines Comments
/*
 * Author: kernelcoder
 * Purpose: To show a comment that spans multiple lines.
 * Language:  C
 */
The compiler will assume that everything after the /* symbol is a comment until it reaches the */ symbol, even if it spans multiple lines within the C program.
 
Syntax: End of Code Line
#define AGE 6    /* This constant is called AGE */
or
#define AGE 6    // This constant is called AGE
In this example, the compiler will define a constant called AGE that contains the value of 6. Then it interprets everything after the /* symbol as a comment until it reaches the */ symbol.
 
 
 
Format Specifier
We have  used %c format specifier in the char.c program. These are used to print formatted output to the screen. The % specifiers that  can be used in ANSI C are:
%c -- single character
%d -- integer
%e -- float or double exponential format
%f, %lf  -- float or double signed decimal
%g -- (%G) float or double use %f or %e as required
%o -- int unsigned octal value
%p -- pointer address stored in pointer
%s -- array of char sequence of characters, string
%u -- int unsigned decimal
%x -- (%X) int unsigned hex value etc
 
 
The ASCII Code
The American Standard Code for Information Interchange (ASCII, pronunciation: /ˈæski/ **-kee) is a character-encoding scheme originally based on the English alphabet. ASCII codes represent text in computers, communications equipment, and other devices that use text. Most modern character-encoding schemes are based on ASCII, though they support many additional characters. Each character we are using for programming purpose has an ASCII code. 
#include<stdio.h>
#include<conio.h>
void main(){
    char a='a',B='B';
    printf("The Ascii code of a:%d and B:%d",a,B );
    getch();
}
See the program will show the ASCII code of the two characters a and B, also notice that there %d is used to print the integer value of the ASCII codes of that two characters.

  • 1


#653180 C for Beginner -- part2 : How to Write a Hello World Program in C Language

Posted by kernelcoder on 26 February 2013 - 02:35 AM

In the first part of this series tutorial we had come to know about computer programming, how to design a program, how to implement an algorithm etc. Today we will know about C language, various types of programming language, C compilers and finally how to write a hello world program in C language.

 

 

C Language

The programming language C was originally developed by Dennis Ritchie of Bell Laboratories and was designed to run on a PDP-11with a UNIX operating system. Although it was originally intended to run under UNIX, there has been a great interest in running it under the MS-DOS operating system on the IBM PC and compatibles. It is an excellent language for this environment because of the simplicity of expression, the compactness of the code, and the wide range of applicability. Also, due to the simplicity and ease of writing a C compiler, it is usually the first high level language available on any new computer, including microcomputers, minicomputers, and mainframes.

One experienced C programmer made the statement, "You can program anything in C, and the statement is well supported by my own experience with the language. Along with the resulting freedom however, you take on a great deal of responsibility because it is very easy to write a program that can destroy itself due to the silly little errors".
 
 
Compilers
A compiler reads the entire program(source code) and converts it into object code, which is a translation of the  program's source code into a form that the computer can execute directly. Object code is also  referred to as binary code or machine code. Once the program is compiled, a line of source code is no longer meaningful in the execution of your program.
 
Interpreter does also same thing as compiler does. In general, an interpreted program runs slower than a compiled program. Remember, a compiler converts a program's source code into object code that a computer can execute directly. Therefore, compilation is a one-time cost, while interpretation incurs an overhead each time a program is run. 
C was created, influenced, and field-tested by working programmers. The end result is that C gives the programmer what the programmer wants: few restrictions, few complaints, block structure, stand-alone functions, and a compact set of keywords. By using C, we can nearly achieve the efficiency of assembly code combined with the structure of Pascal or Modula-2. It is no wonder that C has become the universal language of programmers around the world. Here's some example of programming languages by their level of human perception type.
 
High level (Human Perception Higher) 
  •     Ada
  •     Modula-2 
  •     Pascal 
  •     COBOL 
  •     FORTRAN 
  •     BASIC
Middle level Java  
  •     C++ 
  •     
  •     FORTH 
  •     Macro-assembler
Low level
  •     Assembler
 
Compilation Procedures of a C Program
Creating an executable form of a C program consists of these three steps:
  1.  Creating the program
  2.  Compiling the program
  3.  Linking the program with whatever functions are needed from the library
Today, most compilers supply integrated programming environments that include an editor. Most  also include stand-alone compilers. For stand-alone versions, we must have a separate editor to create your program. In either case, be careful: Compilers only accept standard text files for input. 
For example, the compilers will not accept files created by certain word processors because they contain control codes and non printing characters.The exact method you use to compile your program will depend upon what compiler you are using. Also, how linking is accomplished will vary between compilers and environments; for example, it  may be included as part of the compiler or as a stand-alone application.
 

 

 

Popular C Compilers

In this tutorial we are going to use the Microsoft Visual Studio 10 IDE and its integrated compiler.
 
 
Setting Up The Environment
Download the Microsoft Visual Studio 10 from Microsoft site then install it. Run the Microsoft Visual Studio 10 program and create a project.
  • Create a new project by clicking File->New->Project.
  • From Installed Template choose other language
  • Choose language Visual C++
  • In Visual C++ choose tab Win32
  • Choose project type Win32 Console Application

new_project.png

 

From the dialog box click on Next button.

 

new_project2.png

 

In the W32 Application Wizard please ensure the application type is console application and in the additional options uncheck the precompiled header then click finish.

 

new_project3.png

 

 

The Hello World C Program

To start programming, right click on Source Files and add a new item. You need to make sure below two points,

  • Select C++ File to add 
  • Name the file with extension to .c, default is .cpp. To work with C language program source file name should be with extension .c In this case I am giving source file name as hello_world.c
new_file.png

 

So now we are set to write our first C program. The basic structure of a C program should be

#include header files
The main function(){
        Code in the main function
}

Each C program must follow this structure. There are lots of header files come with the c compilers. We can use this header files in our program by just the include() preprocessor. Just like

#include<stdio.h>
#include<conio.h>

Here we included stdio.h file to use its build in functions like printf(), scanf() etc. This is the most used header file we generally use in a c program. The purpose of using conio.h will be described in time.

So the main block will be

void main(){
      printf(“Hello!. This is our first c program.”);
      getch();
}

The main() function is the starting point in a C program and there must be one main function in a c program. C compilers execute a c program from top to bottom starting from the first instruction in the main function. Each function must have a return type in c language,  here void is the return type of the main function that returns nothing. The printf() function shows generally the message it  argument-ed. So our program should show the message "Hello! This is our first c program" . The getch() is a build in function from header file conio.h that waits until a key is pressed when the output is showing in the console. To compile and execute the program press F5 and we will see(if everything is okay that means there is no error in our program)

execute.png

 

 


  • 1


#652787 C for Beginner -- part1 : Computer Programming Basics

Posted by kernelcoder on 19 February 2013 - 11:57 PM

Hello everyone!

This series of tutorials are for those who  are beginner and want to learn C programming. If someone knows about computer programming that's good but if not, this tutorial will guide you to learn about computer programming and then we will start learning C programming.

 

 

Computer Programming

Computer doesn't know  English or other languages but there are many languages computer can understand : known as programming language. Example: C, C++, Java, PHP etc. Well, Computer (actually the processor) don't even understand them but only machine/binary code/language. But its tedious tasks for human to write program in binary/machine code. So there are some intermediate or high level languages (C, C++, Java and others) which are for human to write code. There are some programs which translates code from those intermediate languages to machine/binary code. We call this programs compiler or interpreter. By the programming languages we generally give instructions to computer  to perform some specific tasks, these instructions are combinedly called as 'Program' or 'Computer Program' and the instructions are called as 'Code'. So computer programming is to write instructions for computer in any programming language. These instructions can be written by following the structure of that programming language.

 

So the basic need to write a computer program is to decide what is the task. Then writing the code. When we run the program only then computer can get those instructions and will perform the task if everything goes fine. So a new thing comes up "running the program". Running the program is the process to execute the compiled Code. Compilation is the process to find out whether the instructions are syntactically okay and follow the standard and structure of the language. We will cover these terms in our next part of this tutorial.

 

 

A Simple Computer Program

Let us think a problem: We want our computer can add two numbers. Generally there are programs come with operating system named as calculator that can do this simple task but we want to make a computer program that can add two numbers. Firstly, our program needs these two numbers we want to add. When these numbers are supplied to our program the instruction of addition will add the numbers and finally shows us the sum. The algorithm for this task is

algorithm.png

Algorithm is the step by step solution of a problem(Here addition of two numbers). The picture shows  the flow chart(graphical representation of an algorithm) of addition of two numbers.

Let the numbers be 15 and 7. So the addition of these two numbers will be 15+7=22. Our task is to write the instruction of addition of two numbers. The addition instruction in C language

sum = number1 + number2;

See the instruction is ended with a semicolon, we call this complete instruction as statement. So this simple statement can produce the summation of number1(=15) and number2(=7) as sum(=22). When the sum is produced we will simply write a statement that will show the sum in the computer window. So we have the idea of a computer program. 

Computer programs have zero or more inputs and zero or more outputs. The inputs can be various type, for the addition program input was two numbers and output was the sum. 

 

In our next tutorial  will learn about "C Programming Language" with an example of Hello World program.

Attached Files


  • 2


#651759 The Node.js -- Part2: The Basic of HTTP Server

Posted by kernelcoder on 06 February 2013 - 03:42 AM

In the first tutorial of this series we have learnt how to write a basic node application and there we came to the hello world app. In this part, we will learn the concept of HTTP server -- how to write a HTTP server application which responds to the corresponding client request. 
 
 
The HTTP Server
The HTTP server generally serves the requested files or data. So there are some server side scripts that grab the requests and send the requested files/data. Here we will implement a simple HTTP server that serves files/data as the request. 
 
 
Creating the HTTP Server
We will need some internal modules like http, fs (File System), url etc. Its easy to use these modules in anywhere in the node application. So in our code file we'll start by requiring the modules. Here we will use require() function to use modules. Then we will create server by createServer() method.
 
 
var http = require('http'), url  = require(‘url’), fs = require('fs');
 
http.createServer ( function ( req, res ) {
   res.end("Hello world");
}).listen(8080, 'localhost');

console.log('Server running.');
 
This was the simple Hello World app we created first part. Simply if the client hits http://localhost:8080 and will get the "Hello World" message. We will extend this application and make it a client server application where client will make request to server and server will respond based on the request. Now client will hit with some parameters such as file name like index.html. So the request will look like  http://localhost:8080/index.html. The request has two parts -- i) first one is the host part ‘http://localhost:8080’, and, ii)  path-name ‘/index.html’.
 
 
 
var url_parts = url.parse(req.url);
 
//testing what request found by url GET request 
console.log(url_parts);

//pathName / means there is just host part in the requested url
 if(url_parts.pathname != '/') {  
      // requested file serving
      fs.readFile( '.'+url_parts.pathname, function(err, data) {
         res.end(data);//just sending the read data from the file
      });

  } else {
   // just respond with a confirmation message that the server is running when the request is http://localhost:8080
   res.end("Hi, Server is running. This is Hello World. Thanks!");
}

 
 
 
So when the requested url  has a pathname just like the 'hostName:port/pathName'  the server will find out the file named as the
pathName. The file can be located in the inner directory or upper directory. If the file found, server will send response with the read file data otherwise server will send file not found message. When the request  is just 'hostName:port' server will send response as “the server is running” as a confirmation message. But if the requested file is not found, it sends a file not found error message.
 
 
 
fs.readFile('.' + url_parts.pathname, function(err, data) {

//if file not found error occured 
if(err) {
   res.end("<h1align='center' style='color:red'>I am sorry. File Not Found.</h1>");
}
else {
         res.end(data);
}
});
 
 
The readFile() is an asynchronous function that takes the file name as first argument to read data and when reading is done the callback function is called. The callback has two parameters -- error and data. On success, the data event is occurred, otherwise the file not found event occurred.
 
 
Client side file index.html file is shown here
 
<!DOCTYPE html>
<html>
<head>      
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <link rel="stylesheet" href="styles/style.css" />
</head>
<body>
       <div align="center"><h1>Hi This is index.html page.You are done.Good job.</h1></div>
</body>
</html>
See the html has a CSS stylesheet file linked and the browser will request for the css file automatically. So when the client again requests for this file the same thing happens as the request for index.html file and after the css file is available on client side the css styles are applied to the index.html page and it is shown to the browser.
 
The css file look like this --
 
 
root { 
    display: block;
}
div{
background: activeborder;
margin: 100px auto;
color:brown;
}
This functionality of a sever is called routing. For advance purpose we can use something like Flatiron module. For more info about Flatiron module please visit https://github.com/flatiron/flatiron site.  We will see the flatiron tutorial next time.

So our final router should look like this
 
var http = require('http'),
url = require('url'),  
fs = require('fs');
  
http.createServer(function (req, res) {
// parse URL
var url_parts = url.parse(req.url);
console.log(url_parts+" query "+url_parts.query);
  
if(url_parts.pathname != '/') {
      // file serving
      fs.readFile('.'+url_parts.pathname,
function(err, data) {
         if(err) {res.end("<h1 align='center'>I am sorry. File Not Found.</h1>");}
         res.end(data);
      });
}
else {
          res.end("Hi,Server is running.This is Hello World.Thanks");
}
}).listen(8080, 'localhost');

console.log('Server running at
localhost:8080');
 
 
 
The zip attachment contains the code file, html and css file.

Check out our other node.js content!

Attached Files


  • 1


#651545 The Node.js -- Part1: The Basic

Posted by kernelcoder on 03 February 2013 - 03:21 AM

Recently I started learning Node.js and I'm thinking about writing a series of articles on Node.js. Today, we'll learn the basics of Node.js.
 
 
What is Node.js?
Node.js is an I/O driven application platform which consist of the V8 javascript engine which uses the google chrome browser engine, a library/framework and code is written in javascript. Its fast and used for creating scalable network based system. Node.js generally processes each operation asynchronously and it is event driven but we can adapt it for synchronous processing that means we can make a process synchronous as well as asynchronous as our need.


Why Node.js?

Node.js has some excellent advantages
  • node has non-blocking io,that means each io event must have at least one callback function which runs after the operation finished at that time other codes are running.
  • has support of mostly used protocol like http, dns, ssl etc
  • node is low level and it streams everything, its always streams the data but never forces data to be buffered.
Node is all over event driven io framework that lives with javascript events.
 
Setting Up Development Environment
Firstly we have to download node from here and install it.Then you are set to write node application. You will need an IDE or code editor like Netbeans IDE, notepad etc to write code. Node applications need some internal and external modules. Internal modules are come with node installation like http, fs (File System), url etc which is part of the Node.js platform. To run an application, as example written in a HelloWord.js file, open the command prompt on your system (better open Node.js provided command line which get installed with Node.js) and type node HelloWord.js.

Check out our other node.js content!

The Legacy Hello World Application
Node.js app is simply javascipt code snippets. Open the node.js command line interface to run code. Lets start checking our node environment by
 
//server.js 
console.log("Hi,The node server is running and up.");
So create a javascript file, namely server.js, in the current working directory with the code above.To run the code go to node provided CLI (command line interface) and run with node command
 
>node server.js
Which will show in the next line "Hi,The node server is running and up."
 
So our node environment is ready and you are set to develop your node application. Lets create our first http server. Node lives with node modules, to create http server we need the http modules. Modules are simply some collection of node functions created and exported for some specific purpose. We can use node modules by simply require() function.
 
//server.js file
var http = require('http');
http.createServer(function(request,response){
});
http.listen(8080);
console.log('Server in running..');
Run this by
 
>node server.js
Now our server created and ready to run and get requests from client side. Here by require() we imported the http module functions and here we used two of them createServer() and listen().
createServer() function takes a callback function as argument which takes two arguments request and response. We can process the request and response in the callback function as we want. The listen() function here takes the port number to accept connection to the client with the server address to 127.0.0.1 or localhost/ . Now if we hit http://localhost:8080 from browser the node server will start responding.
Here we just want to see the hello world so add the code in the callback function
 
//simple response to the request from the client
response.end("Hi,The Node server is running and up.");
So now if we hit http://localhost:8080 we can see "Hi,The Node server is running and up.". So our first step in node is at end.
 
 
Recommended Reading
There are lots of resources in the net. The http://nodejs.org  has the excellent documentation,the excellent http://www.nodebeginner.org/ and the http://book.mixu.net are enough to start.
 
Be back soon with the next one.
 
EDIT: Click me to go to second part of this series.
  • 4


#640336 HTML $ DATABASE

Posted by kernelcoder on 30 September 2012 - 07:44 PM

The answer is no. HTML runs on client's browser. So the traditional logic is user have to send request from browser to server and server will handle the request and can access database through server side scripting languages like PHP, Perl, Python, Ruby, C#, C/C++ (as CGI) etc and send a response (HTML) back to client (browser).

However, HTML5 provides some database API through which you can connect to SQLite database (as far as I know) which is managed by browser. You can read about HTML5 on WIKI and see example here.
  • 1


#640275 A simple application in C# to create a diamond using asterisks

Posted by kernelcoder on 29 September 2012 - 09:03 PM

I tried your suggestions and my code completely went nuts. First it gave a blank console with no text. Then after entering 1 it went into an infinite loop that ran so fast I could barely make out what it said.

Did you see the sample code segment about the 'while' loop in my last comment? Attachment is the modified code I said about.

Attached Files


  • 1


#640271 A simple application in C# to create a diamond using asterisks

Posted by kernelcoder on 29 September 2012 - 08:08 PM

You need to take care of few things --
  • Put the 'Enter 1 for diamond, or for inverted triangle. Enter -1 to quit' text inside the while loop (as the first line in while loop)
  • You don't need to put break statement in the 'while' loop after calling the DrawDiamond or DrawTriangle. A 'break' statement execution in a loop (for, while, foreach) causes breaking its execution and jump at after the loop body statement.
  • There are two lines at the end of both methods DrawTriangle and DrawDiamond. Those two lines are
    Console.Write("Press any key to quit. "); // prompt user
    Console.ReadKey();
    . That Console.ReadKey is eating the user choice input and that's why 'while' loop is exiting after only first execution.
Here is the sample while loop --
int choice = 0;
while (choice != -1)
{
    Console.Write("Enter 1 for diamond, or for inverted triangle. Enter -1 to quit. "); // prompt user
    choice = Convert.ToInt32(Console.ReadLine());
if (choice == 1)
{
    Shapes.DrawDiamond(5);                      
}  //end if
else if (choice == 2)
{ //triangle
    Triangle.DrawTriangle(10);
}
} // end Main
Now you just need to replace the 'if/else' part with 'switch' clause.

Another thing: You don't need to put a 'return' statement at the end of 'void' return type methods like you did for DrawDiamond and DrawTriangle method in Shapes.cs file.
  • 1


#640183 Creating a Class for Enums

Posted by kernelcoder on 28 September 2012 - 09:51 PM

The explanation ---

10: Look, ColorEnum is a enumeration which is declared inside the Colors class. So, in C++, to access a type which is declared in another type (called nested type), we need to use the scope resolution operator {::} in between the outer type (Colors) and inner type(ColorEnum) -- that's why in this case, to access ColorEnum, we need follow the Colors::ColorEnum way. And this type is take as an argument to the constructor of Colors class. The constructor method is only declared at line 10 but later defined at line 17

11: Same reason as the above -- AsString is just a member function of Colors class. But it is declared only on line 11 but later defined on line 22.


I think declaring the class functions in another place (usually in a header file) and the definitions in another file is the reason of most of your confusion. Do you understand the following code? I placed all the function only in once place. That is I declared and defined the functions on the same place.
#include <iostream>

#include <string>

using namespace std;

class Colors
{
public:
/* An enumeration */
enum ColorEnum {blue, red, green, yellow, black};

/* Constructor of Color class which takes an argument of enumeration of type ColorEnum */
Colors(Colors::ColorEnum value)
{
value = initvalue;
}

/* a member fuction which returns the name of the color provided as enumeration in the constructor of the class*/
string AsString()
{
switch (value)
{
case blue:
return "blue";
case red:
return "red";
case green:
return "green";
case yellow:
return "yellow";
case black:
return "black";
default:
return "Not Found";
}
}

protected:
/* the member variable which holds the enumeration provided by user of this class.*/
ColorEnum value;
};

int main()
{
Colors InkColor = Colors::red;
/* The above lines is actually is Colors InkColor(Colors::red);*/

cout << InkColor.AsString() << endl; // this is where the AsString method of Colors class is called and printing.
return 0;
}

  • 1


#640038 A simple application in C# to create a diamond using asterisks

Posted by kernelcoder on 27 September 2012 - 04:55 PM

Your understanding is ok. The printing of the spaces at the first part of each segment are causing the asterisk to be centered.
  • 1


#640032 XAML -> Failed to work with instance of the class

Posted by kernelcoder on 27 September 2012 - 04:32 PM

Perhaps the IntelliSense of VS-2012 is in 'bored' mood with you because you named that variable with non english word! -- Just kidding :D

Looking at your XAML file I see that your page class name is 'MainPage' which is in 'App4' namespace. But the code you have shown is from your application class. What I'm saying is that the code file you have shown is not the code-behind file for your XAML file and that's why you found the IntelliSense is not showing its talent! Find the code file that has the 'MainPage' class and type in there and I hope you will see it working.
  • 1


#639752 Trigger to increment a column everytime another column is updated

Posted by kernelcoder on 24 September 2012 - 09:14 PM

So your suggestion would be to not use a trigger at all?

Well, solution1 is manual and 2 is automatic. But note that there are other columns on the same table (in your actual table). Now if you use trigger and update other columns (not the total_time but another one) onto the music table, the 'samples' column will also be increased automatically which I bet you don't want, right? So, yes, my suggestion is go for the first solution for this simple problem scenario.
  • 1


#639744 Understanding memory leaks and crashes in C++

Posted by kernelcoder on 24 September 2012 - 08:03 PM

It stops existing as soon as the 'return' is executed, since its scope is local to that function. So 'return' is returning a 'variable' that doesn't exist.

Well, the variable 'temp' will not exist after the return statement in method 'function' but the memory that is created in that function which is referenced in the 'temp' variable will exist because the memory is created on the heap. Note that Heap memory does not get deleted/freed until you call 'delete' or 'free' on it.

So, what I'm saying is that the following code is bad as the memory for local variable 'temp' is created on stack --
char* danger( char* c)
{
char temp[100]; // This is real bad as the memory is created on the STACK
strcpy ( temp, c );
return temp;
}

void test()
{
char data[10] = "fewchars";
char* refPtr = danger(data);
cout << refPtr;
}



But in this following code, the memory is created on HEAP. So the memory will not free until you free the memory blocks with delete operator.
char* noDanger( char* c)
{
char* temp = new char [ strlen (c) + 1 ]; // Look, memory is creating on HEAP
strcpy ( temp, c );
return temp;
}

void test()
{
char data[10] = "fewchars";
char* refPtr = noDanger(data);
cout << refPtr; // This is OK
}

  • 1


#639723 [SOLVED][Qt]Project help - displaying doc file.

Posted by kernelcoder on 24 September 2012 - 04:51 PM

kernelcoder, thanks for Qt-apps.org I'll surely find there some useful code :)

After few hours of intense searching / reading / googling I think the main problem is that QTextBrowser is only plain text / html aware... soo Firstly I will need to convert .doc files to html(?) Any Idea how to display .doc files ?
The idea of writing own converter is making me creeps :/

Well, not only QTextBrowser is plain-text/html aware but also QEdit and QLabel as well.

However, just to say about Qt, if you want to go for any document editing system, you need to work with QTextDocument, QTextEdit.

We are talking about MSWORD doc files ,right? Well, MSWORD has its own rules/protocol for the doc format and those metadata does also there in a doc file. So to be able to work with doc file you need to understand all the formats the document has. Well, as of me, that's not an easy task!, but yes, if someone can convert the document to an html file, you can use it easily with QTextEdit/QTextDocument to show and to even edit. There even some online tools for the doc-html conversion. What about that? Have you tried yet?
  • 1




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