ForumHelpMembers

Board Navigation
Forum
microShit - programming forum
Memberlist
Register

Quick register
Username:
Password: Confirm password:
Email:
      

Welcome Guest
The time now is 2008-09-05, 6:23 pm

Nakarm glodne dziecko - wejdz na strone www.Pajacyk.pl
Oficjalny serwis aukcyjny wo¶p 2008. Kup lub sprzedaj cokolwiek - tak te¿ mo¿esz pomóc



!Hello!
Author: mepomiaskitte @ 2008-02-24, 4:00 pm
Good
site.

Comments: 0 :: View Comments (Post your comment)

urgent!!!! i need code of Chat server in c
Author: ndurjoy3002 @ 2008-01-24, 8:31 pm
i am new to this forum...i need a help from you.....i need a chat server written in c....where 2 or multiple client can communicate by login in chat server (at least 2 clients).the message must not be sent by using broadcasting.

i need this code very urgent..please help me...please..

regards
ndurjoy3002

N.B: java code is also accepted.

Comments: 1 :: View Comments (Post your comment)

Hello.! Happy New Year 2008.!Ïðèâåò.! Ñ íîâûì ãîäîì2008.!Bon
Author: AngelaBridget @ 2008-01-11, 2:30 am
Bonjour. ! Bonne annee 2008.!

Comments: 0 :: View Comments (Post your comment)

Program porownujacy 5 algorytmow sortowania
Author: simmon @ 2008-01-05, 10:01 am
Kompilacja, linkowanie pod Linuksem:
$gcc -c main.c fukcje.c

$gcc -o main main.o funcje.o


Plik main.c :
#include <stdio.h> //zalaczenie biblioteki wejscia-wyjscia
#include <stdlib.h> //zalaczenie standardowej biblioteki
#include <time.h> //zalaczenie biblioteki zawierajacej funkcje time()
#include "typy.h"
#include "funkcje.h"

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

int main(void) //rozpoczecie programu glownego
{
FILE *plik; //deklaracja wskaznika do pliku
char nazwa[20]; //deklaracja 20 elementowej tablicy w ktorej znajduja sie obiekty typu char
struct dane s_babelkowe, s_shell, s_przez_wstawianie, s_przez_wybieranie, s_grzebieniowe; //deklaracja zmiennych struktury
int i, jak, typ, w, ww, q, jjak[5], jsort[5]; //deklaracja obiektow int sluzacych do wczytywania i zapisywania danych wprowadzanych w menu
long int ile_liczb, czas_insertionsort, czas_selectionsort, czas_b_sort, czas_grzebieniowe, ile_1;//deklaraja elementow typu long int sluzacych do przechowywania czasu operacji sortowan
void *tablica; //deklaracja wskaznika do tablicy

do
{
etykieta_poczatek: //nadanie nazwy etykiecie do kotrej powraca program w razie wystapienia bledow przy wyborze odpowiednich wariantow w menu
printf(" WYBIERZ METODE POSORTOWANIA WPISUJAC ODPOWIEDNIA CYFRE?\n\n 1 - Program pozwalajacy na wybor sortowan\n 2 - Progran porownujacy wszystkie sortowania\n"); //wybor metody wsyswietlenia menu
scanf("%d",&w); //zapisanie wartosci do obiektu typu int
if((w!=1)&&(w!=2)) { printf("\nUWAGA!! BLEDNY WYBOR! POWROT DO POCZATKU PROGRAMU! \n\n"); goto etykieta_poczatek;}//Wyswietlenie komunikatu w razie blednego wyboru sposrod menu>> Za pomoca komendy idz do... uzytkownik zostaje przeniesiony do poczatku programu

if(w==1) //jesli zadeklarowana zostala chec porownania wydajnosci z mozliwym wyborem metod sortowania to wykona sie ten blok
{
printf("\n WYBIERZ TYP DANYCH\n\n 1 - CHAR\n 4 - INT\n 8 - FLOAT\n"); //wybieranie typu danych na jakich beda operowac funkcje sortowania
scanf("%d", &typ); //zapisanie wartosci 1,4 lub 8 pod zmienna typ;
if((typ!=1)&&(typ!=4)&&(typ!=8)) { printf("\nUWAGA!! BLEDNY WYBOR! POWROT DO POCZATKU PROGRAMU! \n\n"); goto etykieta_poczatek;}//Wyswietlenie komunikatu w razie blednego wyboru sposrod menu>> Za pomoca komendy idz do... uzytkownik zostaje przeniesiony do poczatku programu
if (jak!=5) //jesli wybrana liczba byla rozna od np.5
{
printf("\n PODAJ ILOSC LICZB DO POSORTOWANIA:"); //podanie ilosci danych do posortowania
scanf("%ld",&ile_liczb); //zapis...

[ Read Full ]
Comments: 1 :: View Comments (Post your comment)

Learning C / Pointers and arrays
Author: simmon @ 2007-12-09, 1:16 pm
Arrays & Strings

Arrays in C act to store related data under a single variable name with an index, also known as a subscript. It is easiest to think of an array as simply a list or ordered grouping of variables. As such, arrays often help a programmer organize collections of data efficiently and intuitively.

Later we will consider the concept of a pointer, fundamental to C, which extends the nature of the array. For now, we will consider just their declaration and their use.

Arrays

If we want an array of six integers , called "numbers", we write in C

int numbers[6];

For a character array called letters,

char letters[6];

and so on.

If we wish to initialize as we declare, we write

int point[6]={0,0,1,0,0,0};

If we want to access a variable stored in an array, for example with the above declaration, the following code will store a 1 in the variable x

int x;
x = point[2];

Arrays in C are indexed starting at 0, as opposed to starting at 1. The first element of the array above is point[0]. The index to the last value in the array is the array size minus one. In the example above the subscripts run from 0 through 5. C does not guarantee bounds checking on array accesses. The compiler may not complain about the following (though the best compilers do):

char y;
int z = 9;
char point[6] = { 1, 2, 3, 4, 5, 6 };
//examples of accessing outside the array. A compile error is not always raised
y = point[15];
y = point[-4];
y = point[z];

During program execution, an out of bounds array access does not always cause a run time error. Your program may happily continue after retrieving a value from point[-1]. To alleviate indexing problems, the sizeof() expression is commonly used when coding loops that process arrays.

int ix;
short anArray[]= { 3, 6, 9, 12, 15 };

for (ix=0; ix< (sizeof(anArray)/sizeof(short)); ++ix) {
DoSomethingWith( anArray[ix] );
}

Notice in the above example, the size of the array was not explicitly specified. The compiler knows to size it at 5 because of the five values in the initializer list. Adding an additional value to the list will cause it to be sized to six, and because of the sizeof expression in the for loop, the code automatically adjusts to this change. Good programming practice is declare a variable size and store the size of the array.

size = sizeof(anArray)/sizeof(short)

C also supports multi dimensional arrays (or, rather, arrays of arrays). The simplest type is a two dimensional array. This creates a rectangular array - each row has the same number of columns. To get a char array with 3 rows and 5 columns we write in C

char two_d[3][5];

To access/modify a value in this array we need two subscripts:

char ch;
ch = two_d[2][4];

or

two_d[0][0] = 'x';

Similarly, a multi-dimensional array can be initialized like this:

int two_d[2][3] = {{ 5, 2, 1 },
{ 6, 7, 8 }};

There are also weird notations possible:

int a[100];
int i = 0;
if (a[i]==i[a])
{
printf("Hello World!\n");
}

a[i] and i[a] refer to the same location. (This is explained later in the next Chapter.)

Strings
String "Merkkijono" stored in memory
String "Merkkijono" stored in memory

C has no string handling facilities built in; consequently, strings are defined as arrays of characters.

char string[30];

However, there is a useful library of string handling routines which you can use by including another header file.

#include <stdio.h>
#include <string.h> //new header file

int main(void) {
...
...

[ Read Full ]
Comments: 0 :: View Comments (Post your comment)

Learning C / File IO
Author: simmon @ 2007-12-09, 12:47 pm
Introduction

The stdio.h header declares a broad assortment of functions that perform input and output to files and devices such as the console. It was one of the earliest headers to appear in the C library. It declares more functions than any other standard header and also requires more explanation because of the complex machinery that underlies the functions.

The device-independent model of input and output has seen dramatic improvement over the years and has received little recognition for its success. FORTRAN II was touted as a machine-independent language in the 1960s, yet it was essentially impossible to move a FORTRAN program between architectures without some change. In FORTRAN II, you named the device you were talking to right in the FORTRAN statement in the middle of your FORTRAN code. So, you said READ INPUT TAPE 5 on a tape-oriented IBM 7090 but READ CARD to read a card image on other machines. FORTRAN IV had more generic READ and WRITE statements, specifying a logical unit number (LUN) instead of the device name. The era of device-independent I/O had dawned.

Peripheral devices such as printers still had fairly strong notions about what they were asked to do. And then, peripheral interchange utilities were invented to handle bizarre devices. When cathode-ray tubes came onto the scene, each manufacturer of consoles solved problems such as console cursor movement in an independent manner, causing further headaches.

It was into this atmosphere that Unix was born. Ken Thompson and Dennis Ritchie, the developers of Unix, deserve credit for packing any number of bright ideas into the operating system. Their approach to device independence was one of the brightest.

The ANSI C <stdio.h> library is based on the original Unix file I/O primitives but casts a wider net to accommodate the least-common denominator across varied systems.

Streams

Input and output, whether to or from physical devices such as terminals and tape drives, or whether to or from files supported on structured storage devices, are mapped into logical data streams, whose properties are more uniform than their various inputs and outputs. Two forms of mapping are supported: text streams and binary streams.

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if the data consist only of printable characters and the control characters horizontal tab and new-line, no new-line character is immediately preceded by space characters, and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

Unix adopted a standard internal format for all text streams. Each line of text is terminated by a new-line character. That's what any program expects when it reads text, and that's what any program produces when it writes text. If such a convention doesn't meet the needs of a text-oriented peripheral attached to a Unix machine, then the fixup occurs out at the edges of the system. None of the code in the middle needs to change.

A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream shall compare equal to the data that were earlier written out to that stream under the same implementation. Such a stream may, however, have an implementation-defined number of null characters appended to the end of the stream.

Nothing in Unix prevents the...

[ Read Full ]
Comments: 0 :: View Comments (Post your comment)

Learning C / Procedures and functions
Author: simmon @ 2007-12-09, 12:40 pm
Procedures and Functions

A function is a section of code that has some separate functionality or does something that will be done over and over again.

As a basic example, you are writing code to print out the first 5 squares of numbers, then the first 5 cubes, then the next 5 squares again. We could write it like this:

for(i=1; i <= 5; i++)
{
printf("%d ", i*i);
}
for(i=1; i <= 5; i++)
{
printf("%d ", i*i*i);
}
for(i=1; i <= 5; i++)
{
printf("%d ", i*i);
}


We have to write the same loop twice. We may want to somehow put this code in a separate place and simply jump to this code when we want to use it.

This is what precisely functions are for.

More on functions

A function is like a black box. It takes in input, does something with it, then spits out an answer.

Note that a function may not take any inputs at all, or it may not return anything at all. In the above example, if we were to make a function of that loop, we may not need any inputs, and we aren't returning anything at all (Text output doesn't count - when we speak of returning we mean to say meaningful data that the program can use).

We have some terminology to refer to functions:

* A function, call it f, that uses another function g, is said to call g. For example, f calls g to print the squares of ten numbers.
* A function's inputs are known as its arguments
* A function that wants to give f back some data that g calculated is said to return that data. For example, g returns the sum of its arguments.

Writing functions in C

It's always good to learn by example. Let's write a function that will return the square of a number.

int square(int x)
{
int square_of_x;
square_of_x = x * x;
return square_of_x;
}

To understand how to write such a function like this, it may help to look at what this function does as a whole. It takes in an int, x, and squares it, storing it in the variable square_of_x. Now this value is returned.

The first int at the beginning of the function declaration is the type of data that the function returns. In this case when we square an integer we get an integer, and we are returning this integer, and so we write int as the return type.

Next is the name of the function. It is good practice to use meaningful and descriptive names for functions you may write. It may help to name the function after what it is written to do. In this case we name the function "square", because that's what it does - it squares a number.

Next is the function's first and only argument, an int, which will be referred to in the function as x. This is the function's input.

Inbetween the braces is the actual guts of the function. It declares an integer variable called square_of_x that will be used to hold the value of the square of x. Note that the variable square_of_x can only be used within this function, and not outside. We'll learn more about this sort of thing later, and we will see that this property is very useful.

We then assign x multiplied by x, or x squared, to the variable square_of_x, which is what this function is all about. Following this is a return statement. We want to return the value of the square of x, so we must say that this function returns the contents of the variable square_of_x.

Our brace to close, and we have finished the declaration.

Note this should look familiar - you have been writing functions already, in fact - main is a function that is always written.

In general

In general, if we want to declare a function, we write

type name(type1 arg1, type2 arg2, ...)
{
/* code */
}

We've previously said that a function can take no arguments, or can return nothing, or both. What do we write if we want the function to return nothing? We use C's ...

[ Read Full ]
Comments: 0 :: View Comments (Post your comment)

Learning C / Control
Author: simmon @ 2007-12-09, 11:50 am
Control

Very few C programs follow exactly one control path and have each instruction stated explicitly. In order to program effectively, it is necessary to understand how one can alter the steps taken by a program due to user input or other conditions, how some steps can be executed many times with few lines of code, and how programs can appear to demonstrate a rudimentary grasp of logic. C constructs known as conditionals and loops grant this power.

From this point forward, it is necessary to understand what is usually meant by the word block. A block is a group of code statements that are associated and intended to be executed as a unit. In C, the beginning of a block of code is denoted with { (left curly), and the end of a block is denoted with }. It is not necessary to place a semicolon after the end of a block. Blocks can be empty, as in {}. Blocks can also be nested; i.e. there can be blocks of code within larger blocks.

Conditionals

There is likely no meaningful program written in which a computer does not demonstrate basic decision-making skills. It can actually be argued that there is no meaningful human activity in which some sort of decision-making, instinctual or otherwise, does not take place. For example, when driving a car and approaching a traffic light, one does not think, "I will continue driving through the intersection." Rather, one thinks, "I will stop if the light is red, go if the light is green, and if yellow go only if I am traveling at a certain speed a certain distance from the intersection." These kinds of processes can be simulated in C using conditionals.

A conditional is a statement that instructs the computer to execute a certain block of code or alter certain data only if a specific condition has been met. The most common conditional is the If-Else statement, with conditional expressions and Switch-Case statements typically used as more shorthanded methods.

Before one can understand conditional statements, it is first necessary to understand how C expresses logical relations. C treats logic as being arithmetic. The value 0 (zero) represents false, and all other values represent true. If you chose some particular value to represent true and then compare values against it, sooner or later your code will fail when your assumed value (often 1) turns out to be incorrect. Code written by people uncomfortable with the C language can often be identified by the usage of #define to make a "TRUE" value.

Because logic is arithmetic in C, arithmetic operators and logical operators are one and the same. Nevertheless, there are a number of operators that are typically associated with logic:

Relational and Equivalence Expressions:

a < b
1 if a is less than b, 0 otherwise.
a > b
1 if a is greater than b, 0 otherwise.
a <= b
1 if a is less than or equal to b, 0 otherwise.
a >= b
1 if a is greater than or equal to b, 0 otherwise.
a == b
1 if a is equal to b, 0 otherwise.
a != b
1 if a is not equal to b, 0 otherwise

New programmers should take special note of the fact that the "equal to" operator is ==, not =. This is the cause of numerous coding mistakes and is often a difficult-to-find bug, as the statement (a = b) sets a equal to b and subsequently evaluates to b, while (a == b), which is usually intended, checks if a is equal to b. It needs to be pointed out that, if you confuse = with ==, your mistake will often not be brought to your attention by the compiler. A statement such as if ( c = 20) { is considered perfectly valid by the language, but will always assign 20 to c and evaluate as true. A simple technique to avoid this kind of bug (in many, not all cases) is to put the constant first. This will cause the compiler to issue an error, if == got mispelled with =.

Note that C does not have a dedicated boolean type as many other languages do. 0 means false and anything else true. So ...

[ Read Full ]
Comments: 0 :: View Comments (Post your comment)

Learning C / Math
Author: simmon @ 2007-12-09, 11:40 am
Operators and Assignments

In C, simple math is very easy to handle. The following operators exist: + (addition), - (subtraction), * (multiplication), / (division), and % (modulus); You likely know all of them from your math classes - except, perhaps, modulus. It returns the remainder of a division (e.g. 5 % 2 = 1).

Care must be taken with the modulus, because it's not the equivalent of the mathematical modulus: (-5) % 2 is not 1, but -1. Division of integers will return an integer, and the division of a negative integer by a positive integer will round towards zero instead of rounding down (e.g. (-5) / 3 = -1 instead of -2).

There is no inline operator to do the power (e.g. 5 ^ 2 is not 25, and 5 ** 2 is an error), but there is a power function.

The mathematical order of operations does apply. For example (2 + 3) * 2 = 10 while 2 + 3 * 2 = 8. The order of precedence in C is BFDMAS: Brackets, Functions, Division or Multiplication (from left to right, whichever comes first), Addition or Subtraction (also from left to right, whichever comes first).

Assignment in C is simple. You declare the type of variable, the name of the variable and what it's equal to. For example, int x = 0; double y = 0.0; char z = 'a';

Code:
#include <stdio.h>
 
int main()
{
    int i = 0, j = 0;
 
    /* while i is less than 5 AND j is less than 5, loop */
    while( (i < 5) && (j < 5) )
    {
        /* postfix increment, i++
         *     the value of i is read and then incremented
         */
        printf("i: %d\t", i++);
 
        /*
         * prefix increment, ++j
         *     the value of j is incremented and then read
         */
        printf("j: %d\n", ++j);
    }
 
    printf("At the end they have both equal values:\ni: %d\tj: %d\n", i, j);
 
    return 0;
}


will display the following:

Code:
i: 0    j: 1
i: 1    j: 2
i: 2    j: 3
i: 3    j: 4
i: 4    j: 5
At the end they have both equal values:
i: 5    j: 5


(Source: WikiBooks, licence: GNU FDL, Authors)

Comments: 0 :: View Comments (Post your comment)

Learning C / Simple Input and Output
Author: simmon @ 2007-12-09, 10:41 am
Simple Input and Output

When you take time to consider it, a computer would be pretty useless without some way to talk to the people who use it. Just like we need information in order to accomplish tasks, so do computers. And just as we supply information to others so that they can do tasks, so do computers.

These supplies and returns of information to a computer are called input and output. 'Input' is information supplied to a computer or program. 'Output' is information provided by a computer or program. Frequently, computer programmers will lump the discussion in the more general term input/output or simply, I/O.

In C, there are many different ways for a program to communicate with the user. Amazingly, the most simple methods usually taught to beginning programmers may also be the most powerful. In the "Hello, World" example at the beginning of this text, we were introduced to a Standard Library file stdio.h, and one of its functions, printf(). Here we discuss more of the functions that stdio.h gives us.

Output using printf()

Recall from the beginning of this text the demonstration program duplicated below:

#include <stdio.h>

int main(void)
{
printf("Hello, world!\n");
return 0;
}

If you compile and run this program, you will see the sentence below show up on your screen:

Hello, world!

This amazing accomplishment was achieved by using the function printf(). A function is like a "black box" that does something for you without exposing the internals inside. We can write functions ourselves in C, but we will cover that later.

You have seen that to use printf() one puts text, surrounded by quotes, in between the brackets. We call the text surrounded by quotes a literal string (or just a string), and we call that string an argument to printf.

As a note of explanation, it is sometimes convenient to include the open and closing parentheses after a function name to remind us that it is, indeed, a function. However usually when the name of the function we are talking about is understood, it is not necessary.

As you can see in the example above, using printf() can be as simple as typing in some text, surrounded by double quotes (note that these are double quotes and not two single quotes). So, for example, you can print any string by placing it as an argument to the printf() function:

printf("This sentence will print out exactly as you see it...");

And once it is contained in a proper main() function, it will show:

This sentence will print out exactly as you see it...

Printing numbers and escape sequences

Placeholder codes

The printf function is a powerful function, and is probably the most-used function in C programs.

For example, let us look at a problem. Say we don't know what 1905 + 31214 is. Let's use C to get the answer.

We start writing

#include <stdio.h> /* this is important, since printf
* can't be used without this line */

(For more information about the line above, see The Preprocessor).

int main(void)
{
printf("1905+31214 is");
return 0;
}

but here we are stuck! printf only prints strings! Thankfully, printf has methods for printing numbers. What we do is put a placeholder format code in the string. We write:

printf("1905+31214 is %d", 1905+31214);

The placeholder %d literally "holds the place" for the actual number that is the result of adding 1905 to 31214.

These placeholders are called format specifiers. Many other format specifiers work with printf. If we have a floating-point number, we can use %f to print out a floating-point number, decimal point and all. An incomplete list is:

* %i and %d - int
* %f - float
* %lf - double
* %s - string
* %x - hexadecimal

A more complete list is in the File I/O section.

Tab...

[ Read Full ]
Comments: 0 :: View Comments (Post your comment)

Learning C / Variables
Author: simmon @ 2007-12-08, 1:43 pm
Variables

Like most programming languages, C is able to use and process named variables and their contents. Variables are simply names used to refer to some location in memory - a location that holds a value with which we are working.

It may help to think of variables as a placeholder for a value. You can think of a variable as being equivalent to its assigned value. So, if you have a variable i that is initialized (set equal) to 4, then it follows that i+1 will equal 5.

Since C is a relatively low-level programming language, before a C program can utilize memory to store a variable it must claim the memory needed to store the values for a variable . This is done by declaring variables. Declaring variables is the way in which a C program shows the number of variables it needs, what they are going to be named, and how much memory they will need.

Within the C programming language, when managing and working with variables, it is important to know the type of variables and the size of these types. Since C is a fairly low-level programming language, these aspects of its working can be hardware specific - that is, how the language is made to work on one type of machine can be different from how it is made to work on another.

All variables in C are "typed". That is, every variable declared must be assigned as a certain type of variable.

Declaring, Initializing, and Assigning Variables

Here is an example of declaring an integer, which we've called some_number. (Note the semicolon at the end of the line; that is how your compiler separates one program statement from another.)

int some_number;

This statement means we're declaring some space for a variable called some_number, which will be used to store integer data. Note that we must specify the type of data that a variable will store. There are specific keywords to do this - we'll look at them in the next section.

Multiple variables can be declared with one statement, like this:

int anumber, anothernumber, yetanothernumber;

We can also declare and assign some content to a variable at the same time. This is called initialization because it is the "initial" time a value has been assigned to the variable:

int some_number=3;

In C, all variable declarations (except for globals) should be done at the beginning of a block. Some compilers do not let you declare your variables, insert some other statements, and then declare more variables. Variable declarations (if there are any) should always be the first part of any block.

After declaring variables, you can assign a value to a variable later on using a statement like this:

some_number=3;

You can also assign a variable the value of another variable, like so:

anumber = anothernumber;

Or assign multiple variables the same value with one statement:

anumber = anothernumber = yetanothernumber = 3;

This is because the assignment ( x = y) returns the value of the assignment. x = y = z is really shorthand for x = (y = z).

Naming Variables

(Note: Several words in this section should be made into links.)

Variable names in C are made up of letters (upper and lower case) and digits. The underscore character ("_") is also permitted. Names must not begin with a digit. Unlike some languages (such as Perl and some BASIC dialects), C does not use any special prefix characters on variable names.

Some examples of valid (but not very descriptive) C variable names:

foo
Bar
BAZ
foo_bar
_foo42
_
QuUx

Some examples of invalid C variable names:

2foo (must not begin with a digit)
my foo (spaces not allowed in names)
$foo ($ not allowed -- only letters, digits, and _)
while (language keywords cannot be used as names)

As the last example suggests, certain words are reserved as keywords in the language, and these cannot be used as variable names.

In addition there are certain ...

[ Read Full ]
Comments: 0 :: View Comments (Post your comment)

Learning C / Structure and style
Author: simmon @ 2007-12-08, 1:20 pm
C Structure and Style

This is a basic introduction to producing effective code structure in the C Programming Language. It is designed to provide information on how to effectively use indentations, comments, and other elements that will make your C code more readable. It is not a tutorial on actually programming in C.

New programmers will often not see the point of creating structure in their programs' code, because they often think that code is designed purely for a compiler to read. This is often not the case, because well-written code that follows a well-designed structure is usually much easier for programmers (who haven't worked on the code for months) to read, and edit.

In the following sections, we will attempt to explain good programming techniques that will in turn make your programs more effective.

Introduction

The following two blocks of code are essentially the same: Both of them contain exactly the same code, and will compile and execute with the same result; however there is one essential difference.

Which of the following programs do you think is easier to read?



#include <stdio.h>
int main(void) {printf("Hello, World!\n");return 0;}

or

#include <stdio.h>

int main(void)
{
printf("Hello, World!\n");
return 0;
}

The simple use of indents and line breaks can greatly improve the readability of the code; without making any impact whatsoever on how the code performs. By having readable code, it is much easier to see where functions and procedures end, and which lines are part of which loops and procedures.

This book is going to focus on the above piece of code, and how to improve it. Please note that during the course of the tutorial, there will be many (apparently) redundant pieces of code added. These are only added to provide examples of techniques that we will be explaining, without breaking the overall flow of code that the program achieves.

Line Breaks and Indentation

The addition of white space inside your code is arguably the most important part of good code structure. Effective use of it can create a visual gauge of how your code flows, which can be very important when returning to your code when you want to maintain it.

Line Breaks

Line breaks should be used in three main parts of your code

* After precompiler declarations.
* After new variables are declared.
* Between new paths of code. (i.e. Before the declaration of the function or loop, and after the closing '}' bracket).

The following lines of code have line breaks between functions, but not any indention. Note that we have added line numbers to the start of the lines. Using these in actual code will make your compiler fail, they are only there for reference in this book.

10 #include <stdio.h>
20 int main(void)
30 {
40 int i=0;
50 printf("Hello, World!");
60 for (i=0; i<1; i++)
70 {
80 printf("\n");
90 break;
100 }
110 return 0;
120 }
130

Based on the rules we established earlier, there should now be four line breaks added.

* Between lines 10 and 20, as line 10 is a precompiler declaration
* Between lines 40 and 50, as the block above it contains variable declarations
* Between lines 50 and 60, as it is the beginning of a new path (the 'for' loop)
* Between lines 100 and 110, as it is the end of a path of code

This will make the code much more readable than it was before:

10 #include <stdio.h>
11
20 int main(void)
30 {
40 int i=0;
41
50 printf("Hello, World!");
51
60 for (i=0; i<1; i++)
70 {
80 printf("\n");
90 break;
100 }
101
110 return 0;
120 }


But this still isn't as readable as it can be.

Inde...

[ Read Full ]
Comments: 0 :: View Comments (Post your comment)

Log in
Username:
Password:
Remember me 
I forgot my password
Register

Recent topics
» X Rumer is the BEST!!!
» !Hello!
» Software Development Company
» Photoshop Tutorials site
» Borland JBuilder 2007 Enterprise

Statistics
Users write 40 posts, 29 topics
We have 5063 registered users
The newest registered user is Playdaypeakspxz


Powered by phpBB modified by Przemo © 2003 phpBB Group
microShit |Sanory Directory | Katalog stron | Katalog stron WWW
Page generated in 0.3 second. SQL queries: 13