Sei sulla pagina 1di 34

KEYWORDS There are 32 words defined as keywords in C.

These have predefined uses and cann ot be used for any other purpose in a C program. They are used by the compiler a s an aid to compiling the program. They are always written in lower case. A comp lete list follows; auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while

WE NEED DATA AND A PROGRAM Any computer program has two entities to consider, the data, and the program. Th ey are highly dependent on one another and careful planning of both will lead to a well planned and well written program. Unfortunately, it is not possible to s tudy either completely without a good working knowledge of the other. For that r eason, this tutorial will jump back and forth between teaching methods of progra m writing and methods of data definition. Simply follow along and you will have a good understanding of both. Keep in mind that, even though it seems expedient to sometimes jump right into coding the program, time spent planning the data st ructures will be well spent and the quality of the final program will reflect th e original planning. HOW THIS TUTORIAL IS WRITTEN As you go through the example programs, you will find that every program is comp lete. There are no program fragments that could be confusing. This allows you to see every requirement that is needed to use any of the features of C as they ar e presented. Some tutorials I have seen give very few, and very complex examples . They really serve more to confuse the student. This tutorial is the complete o pposite because it strives to cover each new aspect of programming in as simple a context as possible. Throughout this tutorial, keywords, variable names, and function names will be g iven in boldface as an aid to clarity. These terms will be completely defined th roughout the tutorial. HOW THIS TUTORIAL IS WRITTEN As you go through the example programs, you will find that every program is comp lete. There are no program fragments that could be confusing. This allows you to see every requirement that is needed to use any of the features of C as they ar e presented. Some tutorials I have seen give very few, and very complex examples . They really serve more to confuse the student. This tutorial is the complete o pposite because it strives to cover each new aspect of programming in as simple a context as possible.

Throughout this tutorial, keywords, variable names, and function names will be g iven in boldface as an aid to clarity. These terms will be completely defined th roughout the tutorial. RESULT OF EXECUTION The result of executing each program will be given in comments at the end of the program listing after the comment is defined in about the fourth program of cha pter 2. If you feel confident that you completely understand the program, you ca n simply refer to the result of execution to see if you understand the result. I n this case, it will not be necessary for you to compile and execute every progr am. It would be a good exercise for you to compile and execute some of them howe ver, because all C compilers will not generate exactly the same results and you need to get familiar with your own compiler. Example program ------> FIRSTEX.C At this point, you should compile and execute FIRSTEX.C if you have not yet done so, to see that your C compiler is properly loaded and operating. Don't worry a bout what the program does yet. In due time you will understand it completely. Note that this program will compile and execute properly with any good compiler. A WORD ABOUT COMPILERS All of the example programs in this tutorial will compile and execute correctly with any good ANSI compatible C compiler. Some compilers have gotten extremely c omplex and hard to use for a beginning C programmer, and some only compile and b uild Microsoft Windows programs. Fortunately, most of the C compilers available have a means of compiling a standard C program which is written for the DOS envi ronment and includes none of the Windows extensions. You should check your docum entation for the capabilities and limitations of your compiler. If you have not yet purchased a C compiler, you should find one that is ANSI-C compliant, and th at also has the ability to generate a DOS executable if you are planning to use the DOS operating system. ANSWERS TO PROGRAMMING EXERCISES There are programming exercises at the end of most of the chapters. You should a ttempt to do original work on each of the exercises before referring to the answ ers in order to gain your own programming experience. These answers are given fo r your information in case you are completely stuck on how to solve a particular problem. These answers are not meant to be the only answer, since there are man y ways to program anything, but they are meant to illustrate one way to solve th e suggested programming problem. The answers are all in source files named in the format CHnn_m.C where nn is the chapter number, and m is the exercise number. If more than one answer is requir ed, an A, B, or C is included following the exercise number. PROGRAM STRUCTURE YOUR FIRST C PROGRAM Example program ------> TRIVIAL.C The best way to get started with C is to actually study a program, so load the f ile named TRIVIAL.C and display it on the monitor. You are looking at the simple st possible C program. There is no way to simplify this program or to leave anyt hing out. Unfortunately, the program doesn't do anything.

The word main is very important, and must appear once, and only once in every C program. This is the point where execution is begun when the program is run. We will see later that this does not have to be the first statement in the program but it must exist as the entry point. Following the main program name is a pair of parentheses which are an indication to the compiler that this is a function. We will cover exactly what a function is in due time. For now, I suggest that yo u simply include the pair of parentheses. The two curly brackets in lines 2 and 3, properly called braces, are used to def ine the limits of the program itself. The actual program statements go between t he two braces and in this case, there are no statements because the program does absolutely nothing. You can compile and run this program, but since it has no e xecutable statements, it does nothing. Keep in mind, however, that it is a valid C program. When you compile this program, you may get a warning. You can ignore the warning and we will discuss it later in this tutorial, or you can modify th e program so that it appears as follows; int main() { return 0; } This modified program must compile on any good C compiler since it conforms to t he ANSI-C standard. We will explain the difference in these two programs later i n this tutorial. A PROGRAM THAT DOES SOMETHING Example program ------> WRTSOME.C For a much more interesting program, load the program named WRTSOME.C and displa y it on your monitor. It is the same as the previous program except that it has one executable statement between the braces plus the obligatory return statement . The executable statement is a call to a function supplied as a part of your C li brary. Once again, we will not worry about what a function is, but only how to u se this one named printf(). In order to output text to the monitor, the desired text is put within the function parentheses and bounded by quotation marks. The end result is that whatever text is included between the quotation marks will be displayed on the monitor when the program is run. Notice the semi-colon at the end of line 5. C uses a semi-colon as a erminator, so the semi-colon is required as a signal to the compiler ine is complete. This program is also executable, so you can compile to see if it does what you think it should. It should cause the text quotation marks to appear on the monitor when you execute it. statement t that this l and run it between the

You can ignore the statements in lines 1 and 7 in this program and similar state ments in each of the remaining programs in this chapter. These will be fully des cribed later in this tutorial. We will also define why the word int is used at t he begining of line 3. We have a few preliminary topics to cover before we get t o these items. ANOTHER PROGRAM WITH MORE OUTPUT Example program ------> WRTMORE.C Load the program WRTMORE.C and display it on your monitor for an example with mo re output and another small but important concept. You will see that there are f

our executable statements in this program, each one being a call to the function printf(). The top line will be executed first, then the next, and so on, until the fourth line is complete. The statements are executed sequentially from top t o bottom. Notice the funny character near the end of the first line, namely the backslash. The backslash is used in the printf() statement to indicate that a special cont rol character is following. In this case, the "n" indicates that a newline is re quested. This is an indication to return the cursor to the left side of the moni tor and move down one line. Any place within printed text that you desire, you c an put a newline character to start a new line. You could even put it in the mid dle of a word and split the word between two lines. A complete description of this program is now possible. The first printf() outpu ts a line of text and returns the carriage. (Of course, there is no carriage, bu t the cursor is moved to the next line on the monitor. The terminology carries o ver from the days of teletypes.) The second printf() outputs a line of text but does not return the carriage so that the third line is appended to the end of th e second, then followed by two carriage returns, resulting in a blank line. Fina lly the fourth printf() outputs a line followed by a carriage return and the pro gram is complete. After compiling and executing WRTMORE.C, the following text should be displayed on your monitor; This is a line of text to output. And this is another line of text. This is a third line. Compile and execute this program to see if it gives you this output. It would be a good idea at this time for you to experiment by adding additional lines of pr intout to see if you understand how the statements really work. Add a few carria ge returns in the middle of a line to prove to yourself that it works as stated, then compile and execute the modified program. The more you modify and compile the example programs included with this tutorial, the more you will learn as you work your way through it. LET'S PRINT SOME NUMBERS Example program ------> ONEINT.C Load the file named ONEINT.C and display it on the monitor for our first example of how to work with data in a C program. The entry point main() should be clear to you by now as well as the beginning brace. The first new thing we encounter is line 5 containing int index; which is used to define an integer variable name d index. The word int is a keyword in C, and can not be used for anything else. It defines a variable that can store a whole number within a predefined range of values. We will define an actual range later. The variable name, index, can be any name that follows the rules for an identifier and is not one of the keywords for C. The final character on the line, the semi-colon, is the statement termin ator as discussed earlier. Note that, even though we have defined a variable, we have not yet assigned a va lue to it, so it contains an undefined value. We will see in a later chapter tha t additional integers could also be defined on the same line, but we will not co mplicate the present situation. Observing the main body of the program, you will notice that there are three sta tements that assign a value to the variable index, but only one at a time. The s

tatement in line 7 assigns the value of 13 to index, and its value is printed ou t by line 8. (We will see how shortly. Trust me for the time being.) Later, the value of 27 is assigned to index, and finally 10 is assigned to it, each value b eing printed out. It should be intuitively clear that index is indeed a variable and can store many different values but only one value at a time of course. Please note that many times the words "printed out" are used to mean "displayed on the monitor". You will find that in many cases experienced programmers take t his liberty, probably due to the printf() function being used for monitor displa y. HOW DO WE PRINT NUMBERS? To keep our promise, let's return to the printf() statements for a definition of how they work. Notice that they are all identical and that they all begin just like the printf() statements we have seen before. The first difference occurs wh en we come to the % character. This is a special character that signals the outp ut routine to stop copying characters to the output and do something different, usually to output the value of a variable. The % sign is used to signal the outp ut of many different types of variables, but we will restrict ourselves to only one for this example. The character following the % sign is a d, which signals t he output routine to get a decimal value and output it. Where the decimal value comes from will be covered shortly. After the d, we find the familiar \n, which is a signal to return the video "carriage", and the closing quotation mark. All of the characters between the quotation marks define the pattern of data to be output by this statement. Following the output pattern, there is a comma foll owed by the variable name index. This is where the printf() statement gets the d ecimal value which it will output because of the %d we saw earlier. The system s ubstitutes the current value of the variable named index for the %d and copies i t to the monitor. We could add more %d output field descriptors anywhere within the brackets and more variables following the description to cause more data to be printed with one statement. Keep in mind however, that the number of field de scriptors and the number of variable definitions must be the same or the runtime system will generate something we are not expecting. Much more will be covered at a later time on all aspects of input and output for matting. A reasonably good grasp of these fundamentals are necessary in order to understand the following lessons. It is not necessary to understand everything about output formatting at this time, only a fair understanding of the basics. Compile and run ONEINT.C and observe the output. Two programming exercises at th e end of this chapter are based on this program. HOW DO WE ADD COMMENTS IN C? Example program ------> COMMENTS.C Load the file named COMMENTS.C and observe it on your monitor for an example of how comments can be added to a C program. Comments are added to make a program m ore readable to you but represent nonsense to the compiler, so we must tell the compiler to ignore the comments completely by bracketing them with special chara cters. The slash star combination is used in C for comment delimiters, and are i llustrated in the program at hand. Please note that the program does not illustr ate good commenting practice, but is intended to illustrate where comments can g o in a program. It is a very sloppy looking program. The slash star combination in line 3 introduces the first comment and the star s lash at the end of that line terminates this comment. Note that this comment is prior to the beginning of the program illustrating that a comment can precede th

e program itself. Good programming practice would include a comment prior to the program with a short introductory description of the program. The comment in li ne 5 is after the main program entry point and prior to the opening brace for th e program code itself. The third comment starts after the first executable statement in line 7 and cont inues for four lines. This is perfectly legal because a comment can continue for as many lines as desired until it is terminated. Note carefully that if anythin g were included in the blank spaces to the left of the three continuation lines of the comment, it would be part of the comment and would not be compiled, but t otally ignored by the compiler. The last comment, in line 15, is located followi ng the completion of the program, illustrating that comments can go nearly anywh ere in a C program. Experiment with this program by adding comments in other places to see what will happen. Comment out one of the printf() statements by putting comment delimiter s both before and after it and see that it does not get executed and therefore d oes not produce a line of printout. Comments are very important in any programming language because you will soon fo rget what you did and why you did it. It will be much easier to modify or fix a well commented program a year from now than one with few or no comments. You wil l very quickly develop your own personal style of commenting. Some C compilers will allow you to "nest" comments which can be very handy if yo u need to "comment out" a section of code during debugging. Since nested comment s are not a part of the ANSI-C standard, none will be used in this tutorial. Che ck the documentation for your compiler to see if they are permitted with your im plementation of C. Even though they may be allowed, it is a good idea to refrain from their use, since they are rarely used by experienced C programmers, and us ing them may make it difficult to port your code to another compiler if the need should arise. GOOD FORMATTING STYLE Example program ------> GOODFORM.C Load the file GOODFORM.C and observe it on your monitor. It is an example of a w ell formatted program. Even though it is very short and therefore does very litt le, it is very easy to see at a glance what it does. With the experience you hav e already gained in this tutorial, you should be able to very quickly grasp the meaning of the program in it's entirety. Your C compiler ignores all extra space s and all carriage returns giving you considerable freedom in formatting your pr ogram. Indenting and adding spaces is entirely up to you and is a matter of pers onal taste. Compile and run the program to see if it does what you expect it to do. Example program ------> UGLYFORM.C Now load and display the program UGLYFORM.C and observe it. How long will it tak e you to figure out what this program will do? It doesn't matter to the compiler which format style you use, but it will matter to you when you try to debug you r program. Compile this program and run it. You may be surprised to find that it is the same program as the last one, except for the formatting. Don't get too w orried about formatting style yet. You will have plenty of time to develop a sty le of your own as you learn the C language. Be observant of styles as you see C programs in magazines and books. This covers some of the basic concepts of programming in C, but as there are man y other things to learn, we will forge ahead to additional program structure. It

will definitely be to your advantage to do the programming exercises at the end of each chapter. They are designed to augment your studies and teach you to use your compiler. PROGRAMMING EXERCISES * Write a program to display your name on the monitor. * Modify the program to display your address and phone number on separate li nes by adding two additional printf() statements. * Remove line 7 from ONEINT.C by commenting it out, then compile and execute the resulting program to see the value of an uninitialized variable. This can b e any value within the allowable range for that variable. If it happens to have the value of zero, that is only a coincidence, but then zero is the most probabl e value to be in an uninitialized variable because there are lots of zero values floating around in a computer's memory. It is actually legal for the program to abort if you refer to a variable that you failed to initialize, but few compile rs, if any, will actually do so. * Add the following two lines just after the last printf() of ONEINT.C to se e what it does. Study it long enough to completely understand the result. printf("Index is %d\n it still is %d\n it is %d", index, index, index); PROGRAM CONTROL THE WHILE LOOP The C programming language has several structures for looping and conditional br anching. We will cover them all in this chapter and we will begin with the while loop. The while loop continues to loop while some condition is true. When the conditio n becomes false, the looping is discontinued. It therefore does just what it say s it does, the name of the loop being very descriptive. Example program ------> WHILE.C Load the program WHILE.C and display it for an example of a while loop. We begin with a comment and the program entry point main(), then go on to define an inte ger variable named count within the body of the program. The variable is set to zero and we come to the while loop itself. The syntax of a while loop is just as shown here. The keyword while is followed by an expression of something in pare ntheses, followed by a compound statement bracketed by braces. As long as the ex pression in the parenthesis is true, all statements within the braces will be re peatedly executed. In this case, since the variable count is incremented by one every time the statements are executed, it will eventually reach 6. At that time the statement will not be executed because count is not less than 6, and the lo op will be terminated. The program control will resume at the statement followin g the statements in braces. We will cover the compare expression, the one in parentheses, in the next chapte r. Until then, simply accept the expressions for what you think they should do a nd you will be correct for these simple cases. Several things must be pointed out regarding the while loop. First, if the varia ble count were initially set to any number greater than 5, the statements within the loop would not be executed at all, so it is possible to have a while loop t hat never is executed. Secondly, if the variable were not incremented in the loo p, then in this case, the loop would never terminate, and the program would neve r complete. Finally, if there is only one statement to be executed within the lo

op, it does not need delimiting braces but can stand alone. Compile and run this program after you have studied it enough to assure yourself that you understand its operation completely. Note that the result of execution is given for this program, (and will be given for all of the remaining example programs in this tutorial) so you do not need to compile and execute every progr am to see the results. Be sure to compile and execute some of the programs howev er, to gain experience with your compiler. You should make some modifications to any programs that are not completely clear to you and compile them until you understand them completely. The best way to l earn is to try various modifications yourself. We will continue to ignore the #include statement and the return statement in th e example programs in this chapter. We will define them completely later in this tutorial. THE DO-WHILE LOOP Example program ------> DOWHILE.C A variation of the while loop is illustrated in the program DOWHILE.C, which you should load and display. This program is nearly identical to the last one excep t that the loop begins with the keyword do, followed by a compound statement in braces, then the keyword while, and finally an expression in parentheses. The st atements in the braces are executed repeatedly as long as the expression in the parentheses is true. When the expression in parentheses becomes false, execution is terminated, and control passes to the statements following this statement. Several things must be pointed out regarding the do-while loop. Since the test i s done at the end of the loop, the statements in the braces will always be execu ted at least once. Secondly, if the variable i were not changed within the loop, the loop would never terminate, and hence the program would never terminate. It should come as no surprise to you that these loops can be nested. That is, on e loop can be included within the compound statement of another loop, and the ne sting level has no limit. This will be illustrated later. Compile and run this program to see if it does what you think it should do. THE FOR LOOP Example program ------> FORLOOP.C Load and display the file named FORLOOP.C on your monitor for an example of a pr ogram with a for loop. The for loop consists of the keyword for followed by a ra ther large expression in parentheses. This expression is really composed of thre e fields separated by semi-colons. The first field contains the expression "inde x = 0" and is an initializing field. Any expressions in this field are executed prior to the first pass through the loop. There is essentially no limit as to wh at can go here, but good programming practice would require it to be kept simple . Several initializing statements can be placed in this field, separated by comm as. The second field, in this case containing "index < 6", is the test which is done at the beginning of each pass through the loop. It can be any expression which will evaluate to a true or false. (More will be said about the actual value of t rue and false in the next chapter.) The expression contained in the third field is executed each time the loop is ex

ercised but it is not executed until after those statements in the main body of the loop are executed. This field, like the first, can also be composed of sever al operations separated by commas. Following the for() expression is any single or compound statement which will be executed as the body of the loop. A compound statement is any group of valid C statements enclosed in braces. In nearly any context in C, a simple statement ca n be replaced by a compound statement that will be treated as if it were a singl e statement as far as program control goes. Compile and run this program. The while is convenient to use for a loop when you don't have any idea how many times the loop will be executed, and the for loop is usually used in those cases when you are doing a fixed number of iterations. The for loop is also convenien t because it moves all of the control information for a loop into one place, bet ween the parentheses, rather than at both ends of the code. It is your choice as to which you would rather use. Depending on how they are used, it is possible w ith each of these two loops to never execute the code within the loop at all. Th is is because the test is done at the beginning of the loop, and the test may fa il during the first iteration. The do-while loop however, due to the fact that t he code within the loop is executed prior to the test, will always execute the c ode at least once. THE IF STATEMENT Example program ------> IFELSE.C Load and display the file IFELSE.C for an example of our first conditional branc hing statement, the if. Notice first, that there is a for loop with a compound s tatement as its executable part containing two if statements. This is an example of how statements can be nested. It should be clear to you that each of the if statements will be executed 10 times. Consider the first if statement. It starts with the keyword if followed by an ex pression in parentheses. If the expression is evaluated and found to be true, th e single statement following the if is executed, and if false, the following sta tement is skipped. Here too, the single statement can be replaced by a compound statement composed of several statements bounded by braces. The expression "data == 2" is simply asking if the value of data is equal to 2. This will be explain ed in detail in the next chapter. (Simply suffice for now that if "data = 2" wer e used in this context, it would mean a completely different thing. You must use the double equal sign for comparing values.) NOW FOR THE IF-ELSE The second if is similar to the first with the addition of a new keyword, the el se in line 17. This simply says that if the expression in the parentheses evalua tes as true, the first expression is executed, otherwise the expression followin g the else is executed. Thus, one of the two expressions will always be executed , whereas in the first example the single expression was either executed or skip ped. Both will find many uses in your C programming efforts. Compile and run thi s program to see if it does what you expect. THE BREAK AND CONTINUE Example program ------> BREAKCON.C Load the file in the first 8. The break s immediately named BREAKCON.C for an example of two new statements. Notice that for loop, there is an if statement that calls a break if xx equals will jump out of the loop you are in and begin executing statement following the loop, effectively terminating the loop. This is a va

luable statement when you need to jump out of a loop depending on the value of s ome results calculated in the loop. In this case, when xx reaches the value of 8 , the loop is terminated and the last value printed will be the previous value, namely 7. The break always jumps out of the loop just past the terminating brace . The next for loop starting in line 15, contains a continue statement which does not cause termination of the loop but jumps out of the present iteration. When t he value of xx reaches 8 in this case, the program will jump to the end of the l oop and continue executing the loop, effectively eliminating the printf() statem ent during the pass through the loop when xx is eight. The continue statement al ways jumps to the end of the loop just prior to the terminating brace. At that t ime the loop is terminated or continues based on the result of the loop test. Be sure to compile and execute this program. THE SWITCH STATEMENT Example program ------> SWITCH.C Load and display the file SWITCH.C for an example of the biggest construct yet i n the C language, the switch. The switch is not difficult, so don't let it intim idate you. It begins with the keyword switch followed by a variable in parenthes es which is the switching variable, in this case truck. As many cases as needed are then enclosed within a pair of braces. The reserved word case is used to beg in each case, followed by the value of the variable for that case, then a colon, and the statements to be executed. In this example, if the variable named truck contains the value 3 during this pa ss of the switch statement, the printf() in line 13 will cause "The value is thr ee\n" to be displayed, and the break statement will cause us to jump out of the switch. The break statement here works in much the same manner as the loop, it j umps out just past the closing brace. Once an entry point is found, statements will be executed until a break is found or until the program drops through the bottom of the switch braces. If the vari able truck has the value 5, the statements will begin executing at line 17 where "case 5 :" is found, but the first statements found are where the case 8 statem ents are. These are executed and the break statement in line 21 will direct the execution out of the bottom of the switch just past the closing brace. The vario us case values can be in any order and if a value is not found, the default port ion of the switch will be executed. It should be clear that any of the above constructs can be nested within each ot her or placed in succession, depending on the needs of the particular programmin g project at hand. Note that the switch is not used as frequently as the loop an d the if statements. In fact, the switch is used infrequently but should be comp letely understood by the serious C programmer. Be sure to compile and run SWITCH .C and examine the results. THE EVIL GOTO STATEMENT Example program ------> GOTOEX.C Load and display the file GOTOEX.C for an example of a file with some goto state ments in it. To use a goto statement, you simply use the reserved word goto foll owed by the symbolic name to which you wish to jump. The name is then placed any where in the program followed by a colon. You can jump nearly anywhere within a function, but you are not permitted to jump into a loop, although you are allowe d to jump out of a loop.

This particular program is really a mess but it is a good example of why softwar e writers are trying to eliminate the use of the goto statement as much as possi ble. The only place in this program where it is reasonable to use the goto is th e one in line 23 where the program jumps out of the three nested loops in one ju mp. In this case it would be rather messy to set up a variable and jump successi vely out of each of the three nested loops but one goto statement gets you out o f all three in a very concise manner. Some persons say the goto statement should never be used under any circumstances , but this is narrow minded thinking. If there is a place where a goto will clea rly do a neater control flow than some other construct, feel free to use PARAMETER PASSING After teaching C programming for several years, I found that there are certain c oncepts that are difficult to understand and are often misunderstood by new prog rammers. This is even true of some programmers that have been using C for severa l years. This document will define how parameters are passed to functions. A det ailed knowledge of how this is done in C and C++ will allow you to write more ef ficient and more robust programs. HOW IS DATA PASSED TO A FUNCTION? Consider the very simple program given in the listing immediately below. This pr ogram makes a single call to the function named product(), and it passes two par ameters to that function. We can also see that the function returns a single val ue which is of type int. Because this is a trivial program, and we wish to keep it simple, a prototype fo r the function is not included. A real program should also do something with the returned result named area which we simply ignore in this example. int int int { int length = 12; width = 5; main() area;

area = product(length, width); /* The call to the function */ } int product(int side1, int side2) /* The function header */ { return side1 * side2; } This is a trivial program, but it will be the starting point for our study of ho w parameters are passed to a function. If we consider the two lines that are com mented on in the example code, we can extract the following two statements, whic h are executed each time the function named product() is called. int side1 = length; int side2 = width; Even though these two statements are not explicitly given in the code, they are nevertheless executed with each call to product() because of the way C is define d. The first statement is saying, "create a variable for use within the function that is of type int, named side1, and initialize it to the value of length from the calling program". Anytime we refer to the variable named side1 within the f unction, we are referring to the local copy of the variable, and if we change th e value stored in side1, we do not affect the value of length back in the callin

g program because we are working only with side1. The same is true of the second parameter. We are telling the system to create a variable named side2 which is of type int, and initialize it to the value of width from the main program. When we return from the function, the two new variables are no longer needed so they are deleted. When we say they are deleted, they are not set equal to zero, or any other value, they actually cease to exist. They are deallocated by the C runtime system. A GRAPHICAL REPRESENTATION OF THIS OPERATION If you have not already done so, read the Memory Diagram document which defines some of the terms given below including the graphical diagramming conventions us ed by this author A picture is said to be worth a thousand words, so let's draw a picture. Figure 1 is a diagram of the memory space of the computer just prior to making the call to the function. (This is actually a greatly simplified diagram, but it will he lp us get started in understanding just what is happening. We will fill in more details later.) The function main() and the function product() are stored somewh ere in the global memory space of the computer, and the stack is allocated by th e C runtime system for use by our program. The two boxes represent storage for e ach of the two global variables named length and width. The storage for each of these two variables will be created just large enough to store an int type varia ble on our system. The stack is currently empty. You will notice that each of th e variables has a value as a result of the initialization in the code. (I am pur posely ignoring the variable named area for the time being. We will explain wher e it is stored later in this document.)

When the call to the function is made, the system creates a variable named side1 of type int and copies the value of length from the main program into it. This variable is created on the stack and can be used within the function. Likewise, another variable is created on the stack named side2 of type int and the value o f width is copied into it. Neither of these two variables is available for use w ithin the calling program, but are only available to the function named product( ). The memory space now looks like figure 2, and the code in the function named product() is executed with full access to the two parameters on the stack. Becau se the variables named length and width are global, they are also available for use or modification within the function named product().

When execution of the function code is complete, the value of the product of the two variables is returned to the calling program, which can do whatever it wish es to do with it. The two variables are removed from the stack and discarded or, to be a little more proper, they are deallocated. We will say more about the re turned value later in this document. When we return to the calling program, the memory space can be diagrammed as shown in figure 3. You will notice that figure 3 is identical to figure 1.

Based on what we have said so far, the following facts should be clear to you; * A copy of the input parameters is made for use within the function. This i s often referred to as pass by value. * Since the function is working with a copy of the data, it cannot change th e value of the variable passed from the calling program.

We can define a generalized assignment for each parameter that is passed to a fu nction, formal_type formal_parameter = actual_parameter; We are still not worried about the return value or the variable named area. We w ill define them completely later, but I am more interested in defining the param eter passing scheme at this time. LET'S REFINE THE MODEL SOME We will repeat the first program with a slight modification and we will be a lit tle more correct since we will not ignore any of the variables. We will move the two global variables into the main program so that they are local variables, an d if you studied C diligently, you will recall that they are also called automat ic variables. They are called automatic variables because they are automatically allocated when they are needed. If you guess that they are allocated on the sta ck, you are right. The new code is given as follows; int { int int int main() length = 12; width = 5; area;

area = product(length, width); /* The call to the function */ } int product(int side1, int side2) /* The function header */ { return side1 * side2; }

Now we have a slightly different memory layout. The automatic variables are all allocated on the stack as they are encountered in the main program, so that when we arrive at the function call in the main program, the memory layout is as dep icted in figure 4. The three variables on the stack can be accessed by the main( ) program. I promised earlier that I would show you where the variable area is s tored, and you can see that it is on the stack because it is an automatic variab le. It is a little different from the other two variables however, because it ha s not been initialized. Local variables are not automatically initialized by the system, but contain whatever bit pattern happened to be in that memory location . At this time therefore, the variable named area contains any value imaginable that is legal for an int type variable. The variables named width and length are explicitly initialized in the code.

During the call to the function, the system allocates the two parameters on the stack as it did in the last program, initializes them to the required values as illustrated above, and we have the resulting memory layout given in figure 5 jus t prior to executing the return statement. The stack now contains 5 variables. Three are available exclusively to the main( ) function, and two are available exclusively to the product() function. The wor d exclusively is essential in the preceding statement. The variables cannot be s een by any address space within the memory other than where they are defined bec ause of the way C is defined. Since we moved the two global variables into the m ain() function, they are no longer visible when we are executing code within the

product() function. Execution of the return statement in the function, causes t he two variables for the function to be deallocated from the stack, and control returns to the main() function. At this time, the memory space will look very mu ch like figure 4 again but with a meaningful value stored in area. We can make up two more rules of argument passing and stack operations; * When a function is entered, all formal parameters are created on the stack and they are initialized to the values of their corresponding actual parameters , * then all local variables within the function are created on the stack and they are initialized only if initialization values are explicitly given in the c ode. WHAT ABOUT THE ORDER OF CREATION In the case of function parameters, the default for C is to create the var iables on the stack in the reverse order from their listed order so that side2 w ould go on the stack prior to side1. We will not be concerned about this because we are only trying to understand the method of passing variables. If we were wr iting a compiler, we would be very interested in this issue, and for some kinds of advanced programming we also would need to pay attention to the creation orde r. THE WRONG NUMBER OF PARAMETERS Let's repeat the code from above but with another little change. This time we will make two calls to the function, one with too few actual parameters, and one with too many actual parameters. The new code is given as follows; int { int int int int main() length = 12; width = 5; height = 6; area;

area = product(length); /* Too few */ area = product(length, width, height); /* Too many */ } int product(int side1, int side2) /* The function header */ { return side1 * side2; } In the case of using too few parameters, we will be asking the compiler to execute the following two instructions which it cannot do because the second li ne is incomplete. int side1 = length; int side2 = ; /* error, uninitialized parameter */ If we are using prototypes, which we should be doing, the compiler will re port that there are not enough parameters during compilation, and we can very qu ickly repair the error. When providing too many parameters, there is an extra value which the syst em does not know what to do with, so it probably just ignores it. If you pass an extra value to the function, you are probably expecting the function to use the

value for something, so there is some sort of an error. Detecting and reporting these kinds of errors is what prototyping is all about. You should be very dili gent in the use of prototyping for all of your C programming. HOW IS THE DATA RETURNED? Returning data is not as easy to define since the compiler writer has a go od deal of leeway, but he must follow one rule; The returned value must be available for use long enough to permit the pro grammer to store it away in a local variable. The value returned, in this case the product of the two values passed in, may be returned on the stack or it may be returned in a register, or any other w ay that the compiler writer desires. It is up to the compiler writer to provide a means of storing the returned value in the calling program for you in a manner that corresponds with his means of returning it. Simply keep in mind that the s ystem must somehow maintain a copy of the returned value long enough for you to store a local copy of it. It must keep the value available until execution reach es a "sequence point", which in this case means the end of the statement. When y ou tell the system to assign the value to area, you are saving a copy of it. Fol lowing that, the compiler writer may delete the memory he used to return the val ue. If he returned it on the stack, it is imperative that he remove it from the stack in preparation for the next operation. But that is fine because you have t he value stored in area and you can use it in whatever way you desire. HOW DO WE PASS A POINTER? Since we are starting a whole new subject, it would be profitable to write a completely new program with a couple of pointers in it to use as our illustra tion. So, consider the following program fragment; int length = 16; int { int int int main() width = 10; *p_width = &width; area;

area = mod_product(&length, p_width) } int mod_product(int *sideA, int *sideB) { *sideA = *sideA / 2; *sideB = *sideB / 2; return *sideA * *sideB; } This is a very simple program that does nothing worthwhile except to act a s a very good example of how pointers are passed as parameters in a function cal l. We define a global variable named length and within the main() function we de fine another variable named width to give us some data to work with. Then we def ine a pointer named p_width and cause it to point to the variable named width by assigning it the address of width. Finally, we define a variable named area so we will have a place to store the result of the function call. The length and wi dth are defined in different places in this program only to illustrate two diffe rent storage means. In a meaningful program, such similar variables should be de fined together and in a similar fashion.

Just prior to making the call to the function, we have the memory layout a s depicted in figure 6. If you understand all of this article up to this point, you should be able to understand every detail of this diagram. Keep in mind that a pointer is actually another storage element, sort of like an integer, but one that stores the address of an entity rather than some actual data. CALLING THE FUNCTION WITH POINTERS When we call the function we are executing the following two statements in the manner which we defined earlier in this document. These statements create t wo new pointers on the stack and initializes them to point to two variables, one in the main program named width, and one in global memory named length; int *sideA = &length; int *sideB = p_width;

Once again, two different methods of passing a pointer to a function are u sed for illustration. In the first case we take the address of the actual parame ter right in the function call and pass the resulting pointer to the function. I n the second case we pass a pointer's value. A well planned program should pass both parameters in the same manner in order to make the program easier to unders tand. You should be able to clearly see that the reason these two pointers are p ointing to variables in the other parts of the program is because we passed poin ters to those other variables. Following execution of the function call, we are in the function and the memory layout is depicted in figure 7.

Following execution of the three statements within the function but prior to the return to the main program, we have the memory layout as depicted in figu re 8. You will notice that the system has modified the two variables named lengt h and width which are elements of the calling program. It has calculated the ret urn value but we have no way to depict where it is stored since each compiler ca n use any method it desires. Suffice it to say that somewhere the system has the value of 40 stored away for return. Following return, the value of 40 is stored in the variable named area and the program terminates. This program should have clearly depicted how the pointers are used to pro vide access to the actual values in the calling program. You should notice also that copies of the pointers were passed to the function in this program which sa ys that the first rule, given at the beginning of this document, is not violated . PASSING AN ARRAY TO A FUNCTION The name of an array is actually a pointer which is pointing to the first element in the array, with the added caveat that it cannot be changed. It is act ually a constant pointer. Therefore when we pass the name of the array to a func tion we are passing a pointer to the first element and we make a copy of that po inter for use within the function. For more details on arrays, see the document entitled Arrays and Pointers in this group of documents. Study the following program fragment for a few minutes and we will make a few comments on it.

#define ELEMENTS 10 double my_array[ELEMENTS]; int main() { int index; int sum; for (index = 0 ; index < ELEMENTS ; index++) { my_array[index] = (double)(index * 2); } sum = sum_array(ELEMENTS, my_array); } double sum_array(int size, double in_array[]) { int index; double total = 0.0; for (index = 0 ; index < size ; index++) { total = total + in_array[index]; } return total; }

A graphical representation of the address space just prior to executing th e for loop in the function is given in Figure 9. You will notice that we did not pass the entire array to the function, we only passed the address of the first element which we stored in the variable in_array. This gives us access to the en tire array for either reading or modification. Note that the pointer in_array is not a constant but is a variable and can be changed because of the way we defined it. A VERY IMPORTANT DEFINITION The diligent student will notice that we did not say, "an array is a point er", because that is definitely not true. We can say, "the name of an array is a constant pointer to the first element of the array." Be sure you understand tha t statement completely because it could save you a lot of grief some time in you r programming future. This is carefully defined in the document entitled Arrays and Pointers in this group of documents. PASSING A STRUCTURE TO A FUNCTION We finally come to the big one, passing a structure to a function. We begin as usual, by defining a very simple program containing the construct urrent interest. In this case we declare a trivial structure that can store of the elements of a date, and write a program that passes a date variable function and passes a pointer to the date structure to another function. struct date { int month; int day; will of c each to a

int year; }; int main() { struct date birthday; birthday.month = 7; birthday.day = 4; birthday.year = 1776; use_struct(birthday); /* Pass the full date */ use_point(&birthday); /* Pass a pointer to the date */ } void use_struct(struct date in_date) { /* Use the date passed in */ } void use_point(struct date *in_date) { /* Use the date pointer passed in */ } The first thing you should notice is that the entire date structure named birthday is stored on the stack because it is defined locally. A lot of large st ructures defined in this way will use up the stack very quickly. This should enc ourage you to use dynamically allocated memory as often as possible for large en tities. The heap is much larger than the stack on most systems.

When we execute the use_struct() function, the entire date structure is pa ssed into the function. A structure is allocated on the stack with storage space for each of the three variables, and the three values from birthday are copied into their respective spaces. The function then has access to each of the three variables which it can read or modify, and the structure is removed from the sta ck when control returns to the calling program. It should be apparent that this could be very inefficient for a large structure since it could take a relatively long time to build the structure and copy the data from the actual parameter. F igure 10 gives a graphical representation of the memory space of the computer wh en we have just entered the function use_struct(), but before we have changed an y of the values of the date structure on the stack.

Calling use_point() with a pointer to the structure is very similar to the previous example program, so very little needs to be said about it except to ex amine figure 11 for a graphical representation of the memory space just after en tering the function. Note that the pointer named in_date is actually pointing to the entire structure that was already on the stack so a new structure does not have to be built and initialized. It looks like it is pointing to only the month variable, but it is actually pointing to all three components of the date struc ture. This is a weakness with this particular graphical notation.

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&HTML&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

BEGINNING HTML (Warming Up) Most of GUI-based web page authoring tools have their own fancy ways of generati ng the HTML code, and by the time they are through, you have a page three times the size of what you would have had, had you simply written the HTML commands. M athematically, if you generate a page through FrontPage2000, for instance, and i t's size is 30 units [bytes, kilobytes], you can have the SAME look by hand-codi ng, and the size will be 9-10 units. Yes, this is the amount of junk code genera ted. On the Net, size does matter. When for the first time I saw the source-code of an HTML page, I got so scared t hat I quickly closed the window. Then gradually, my web developer friends talked me into learning the ropes line by line, and within a week, I felt like an HTML dude. I'm not exaggerating. It really is so easy. So if you are psychologically ready, and would like to give it a try, follow the se steps and in about 10 minutes, you'll have your first [if you have never done it before] hand-coded HTML page. Don't get disheartened with the look, I unders tand you could be used to the fancy-frills of your tool. Just remember one thing , an HTML page is mostly made of tags. There is a beginning tag: , and an ending tag. Note the forward slash in the ending tag. In this first article, we'll be discussing the basic tags. In the proceeding articles, we'll go deeper and deepe r. Anoter thing before we progress: get hold of HomeSite, if you can. It's a very n eat HTML coder - very humble. It let's you run amuck with your hand-coding, but now and then, provides help in the form of drop-down menus, so that you do not h ave to memorize all those spooky options associated with HTML tags. It automatic ally pops out the closing tag so you don't miss it. == Step 1: == Create a separate directory where you are going to store your file(s). == Step 2: == Open your favorite text editor. I would suggest for this first file, use NOTEPAD because it loads very fast, and no matter how many copies you open, it doesn't act fussy. == Step 3: == Write these two lines first, as they are visible here: <HTML>

</HTML> Your entire web page is going to exist within the confines of these two tags. I suggest you write the closing tag as soon as you write the opening tag so that l ater on, when there are too many tags, you don't get mixed up. At this moment, you can save the file in the new directory you just created. Rem ember while saving, if you are using NotePad, that while writing the name of the file, for instance, firstpage.html, you have to enclose it within quotes in ord er to save it as an HTML page: "firstpage.html". NOTE: Due to character per line limitations, some of the HTML text may appear br oken, but when you are typing in your text editor, press enter only when you hav e typed the closing tag, for instance, </P>. In the following two sections, you get to get your hands dirty with pure viscera of HTML. ELEMEMTARY HTML TAGS We had concluded the previous section with the all pervasive tag: <HTML> </HTML> . This tag informs the reader (a browser or a word-processor, or anything that r eads HTML) that the file being considered is a web page. Let's see what step 4 has in store. == Step 4: == Within <HTML> </HTML> tags, insert another tag so that your lines look like: <HTML> <HEAD> </HEAD> </HTML> Within the head tag, we store all the information that we want the browser to re ad first before proceeding to read the rest of the stuff, for instance, the titl e of the page, information about the author, meta tags (some of the meta tags ca uses your page to be found when the user tries to find a page like yours, throug h his/her preferred search engine or directory, for instance, "Description" and "Keywords" meta tags), etc. For the time being, we'll have just the Title tag he re, as right now we are in no hurry to be found by all and sundry. Although it is not within the scope of this article to tutor you on how to be se arch engine friendly, it is recommended you choose the words of your title after careful scrutiny. Try to include in it the words that you think the surfer migh t type at the search engine prompt. The search engine guys recommend that if it is your company page, then put the name of your company there. <HTML> <HEAD> <TITLE>This is my first, hand-coded HTML page</TITLE> </HEAD> </HTML> If a tag is not going to contain many lines of code, we can have the opening and closing tags in the same line, for instance, <TITLE>.....</TITLE>

instead of <TITLE> ..... </TITLE> This applies to all the tags. Clear till here? Now if you want to see how your page looks on your browser, loa d your browser, and in the URL window, type the complete path of your file, like c:\newfolder\firstpage.html and press Enter. See nothing? Don't get alarmed, and don't think you've goofed up big somewhere. We haven't yet put anything in the code that should come up in the browser. Yes, on the browser's window title bar, you can view the text that you've put within <TITLE> </TITLE>. From now onwards, leave your browser open, and keep pressing the Refresh or Relo ad button to see the changes, when you make them. Just remember to save the modi fied file [File -> Save: In the text editor] before refreshing. == Step 5: == Now we come to the body of the page. Modify your page so that it looks like: <HTML> <HEAD> <TITLE>This is my first, hand-coded HTML page</TITLE> </HEAD> <BODY> </BODY> </HTML> <BODY> tag tells the browser that from now onwards, the actual content of the pa ge will come into the picture. We leave this section here because the last stage of our First Page course shoul dn't have an abrupt break. In the concluding section we shall see how we can dis play simple text, hyperlinks and graphic files on our web page. TEXT AND HYPERLINKS In the preceding section, we had left the discussion at the <BODY> </BODY> tag, so let us continue from here. For showing simple text, we use the <P> tag in such a manner: <P>Ah! This is for the first time I'm writing my own HTML. The world is so diffe rent out here. Marvelous!</P> You can consider <P></P> to be a paragraph. OK, now the page should look like: <HTML>

<HEAD> <TITLE>This is my first, hand-coded HTML page</TITLE> </HEAD> <BODY> <P>Ah! This is for the first time I'm writing my own HTML. The world is so diffe rent out here. Marvelous!</P> </BODY> </HTML> Refresh the page. See something? If you want to highlight a section, for instance, "Marvelous!", you can do it li ke this: <P>Ah! This is for the first time I'm writing my own HTML. The world is so diffe rent out here. <B>Marvelous!</B></P> Refresh the page. See something? The use of some of the tags have been discontinued by some of the newer browsers , but we'll handle those complexities when we cover style sheets. At the moment, these should work. The browser will show the text in the default font. If you want to use your own font, size and color, you'll have to use the font size for a particular portion of the text like this: <P>Ah! This is for the first time <FONT SIZE="10pt" FACE="Verdana" COLOR="Red">I 'm writing my own HTML</FONT>. The world is so different out here. <B>Marvelous! </B></P> If you find it confusing, just type it as it is, save the file, and refresh the page in the browser, and you'll understand what I'm trying to say. Notice the opening and closing tags everywhere? SIZE, FACE and COLOR are the mai n basic attributes of the <FONT> </FONT> tag. == Step 6: == Let us now create a k is the fancy text ses into a pointing her web-destination hyper-link too, but hyperlink and get over with the current article. A hyper lin over which when you hover your cursor, the cursor metamorpho finger, indicating that you are going to be taken to some ot upon clicking the left mouse button. A graphic can act as a we'll come to that later.

Suppose you want to add the following lines to the page: <P>For more cool content, go to Bytesworth.com.</P> So that the page looks like now: <HTML> <HEAD> <TITLE>This is my first, hand-coded HTML page</TITLE> </HEAD> <BODY> <P>Ah! This is for the first time <FONT SIZE="10pt" FACE="Verdana" COLOR="Red">I

'm writing my own HTML</FONT>. The world is so different out here. <B>Marvelous! </B></P> <P>For more cool content, go to Bytesworth.com.</P> </BODY> </HTML> Save and refresh the page. </P> also acts as a line break, so the next text appe ars like a new paragraph. You want the message in such a way, that when someone clicks on Bytesworth.com, the person is taken to http://www.bytesworth.com. To accomplish this, you'll hav e to re-write the second paragraph like this: <P>For more cool content, go to <A HREF="http://www.bytesworth.com"> Bytesworth. com </A>.</P> exactly like this. Don't worry if the lines appear broken, you should write the entire thing in one line, as it is. The latest page now is: <HTML> <HEAD> <TITLE>This is my first, hand-coded HTML page</TITLE> </HEAD> <BODY> <P>Ah! This is for the first time <FONT SIZE="10pt" FACE="Verdana" COLOR="Red">I 'm writing my own HTML</FONT>. The world is so different out here. <B>Marvelous! </B></P> <P>For more cool content, go to <A HREF="http://www.bytesworth.com"> By tesworth.com </A>.</P> </BODY> </HTML> Save it, and refresh it. Bytesworth.com should appear as a hyperlink. Don't get distraught by the drab look. If you follow all the articles, you'll be able to make the coolest pages possible in HTML/JavaScripts. So this is your first, basic page. Using the given tags, you can keep adding fur ther content according to how creative you feel. In the next article, we'll be d iscussing general layout, tables, and a couple of more tags. IMAGES AS HYPERLINKS In the preceding sections, you learnt how to come up with an elementary HTML pag e. You learnt the tags that are the backbone of an average HTML page, namely, <H TML> </HTML>, <HEAD> </HEAD>, <TITLE> </TITLE>, <BODY> </BODY>, <P> </P> and <A> </A>. Assuming you could assimilate the gushing fountain of wisdom in the previous art icles, we move onto the streams of more evolved tags. Let's start with graphics. Graphics enhance the look of a page, they make it more informative [One picture is worth a thousand words, etc.], and they give your page an identity. But don't go over board - the total size of one page should not, ideally, exceed 25 KB. T here are many other issues involved with web-based graphics, but at this moment, we are just covering the HTMLization of graphic files.

== Step 7: == To include graphics, we use the <IMG> tag in this manner: <IMG SRC="picture.gif"> Where "picture.gif" is some graphic file that you already have in the same folde r. If the graphic file is not present in the same folder as your HTML page, then you have to specify the entire path of the file being used. For example, if you r HTML file is in the root directory, and "picture.gif" is in a sub-directory graphics - of your root-directory, the syntax turns out to be: <IMG SRC="graphics/picture.gif"> "/" (forward slash) is for servers. For your local hard-drive, you should use "\ " (back slash). SRC is an attribute of <IMG> and it stands for "source". There are primarily two graphic file formats prevalent on the web, namely, GIF a nd JPG. GIF files use lesser colors, and hence are smaller in size and load quic ker, and further, animated graphics can be created out of GIF files. JPG files a re more refined, and we use them to display graphics that require clarity and gr eater pixel density, for instance, a photograph. More efficacious formats are be ing developed in the meantime to suit Internet compatibility. In some tags, you don't have to use the closing tag. We don't use </IMG> with <I MG>, but with the advent of XML, closing tags are going to be compulsary. Let us borrow the HTML code of our existing page, and in that, include the <IMG> tag too. <HTML> <HEAD> <TITLE>This is my first, hand-coded HTML page</TITLE> </HEAD> <BODY> <IMG SRC ="picture.gif"> <P>Ah! This is for the first time <FONT SIZE="10pt" FACE="Verdana" COLOR="Red">I 'm writing my own HTML</FONT>. The world is so different out here. <B>Marvelous! </B></P> <P>For more cool content, go to <A HREF="http://www.bytesworth.com"> By tesworth.com </A>.</P> </BODY> </HTML> Save and refresh your page. You might have observed that on many web pages, they use fancy graphics to show various links, as you can see the fancy gray buttons on this web site. We perfor m this by <A HREF = "morelinks.html"><IMG SRC = "morelinks.gif"></A> We have inserted the <IMG> tag between <A> </A>, so instead of the text link, no w we have a graphic link. Our modified HTML source page, looks like this (repetitive code has been replace

d by dots):

<IMG SRC ="picture.gif">

<A HREF ="morelinks.html"><IMG SRC ="morelinks.gif"></A> You can explore the <IMG> tag further on your own, but there is another crucial attribute of this tag that we are going to cover before moving on to the next se ction - the ALT attribute - alternative. We use the ALT attribute inside <IMG> to insert text that gets displayed or soun ded when the cursor is hovered over the image, or while the image is being loade d, or when the graphics display has been disabled in the browser, or when your s ite is being viewed on a non-graphics browser, or when visually challenged peopl e are browsing on a voice-enabled browser.

<IMG SRC ="picture.gif" ALT ="Your Title in Text">

<A HREF ="morelinks.html"><IMG SRC ="morelinks.gif" ALT ="More Links"></A> This sums up the <IMG> tag. It's an important tag, and hence, has taken up an en tire chapter. You'll find yourself implementing it again and again, but please d on't over-do it. We move on to tables now. HTML TABLES Tables are used to display information in an orderly manner. Incidentally, here we are not talking furniture. A table means tabular representation of certain da ta on your computer screen or in printed form. Ideally, a table consists of rows and columns. Mathematically, every table has a t least one row, and at least one column. In an empty square box, even if you don't see multiple vertical and horizontal l ines, there is at least one row and at least one column. So when we are defining a table, there are three tags that are deeply involved i n the entire tabular configuration. The chief tag <TABLE> </TABLE> kindles the i nitiation. Then we have the child tag, namely, <TR> </TR> which brings on the ro w, and the last, but not the least, we have a grandchild tag here, <TD> </TD> wh ich originates a column. The legal sequence of these three tags goes like this: <TABLE WIDTH="n%" BGCOLOR="some color" BORDER="n"> <TR> <TD> The information you want to show off about. </TD>

</TR> </TABLE> Where n can be any positive number. Within every <TABLE> </TABLE>, there can be n numbers of <TR> </TR>, and within every <TR> </TR>, there can be n numbers of <TD> </TD>. Then you can have nested tables. For instance, within a single cell of nth row and mth column, you can have more tables. Note: If the upper row has a single column, and the preceding one has multiple c olumns, its better to define the single-columned row in a separate table. Let's promenade through a day-to-day example. Let us create a tiny table display ing your marks in English, Mathematics and Philosophy, in two semesters and see how it fairs on your upcoming web page. Don't get intimidated by so many tags an d their attributes - once you are able to create and apprehend the architecture of one table, you'll be able to create any kind of table. Note: Within <!-- and --> we can insert comments so that we can keep account of complex HTML coding. Literally, you insert the comments like this - Less-than si gn, exclamation mark, dash dash, space, you comment, space, dash dash, greater-t han sign. The code: <!-- The title table --> <TABLE WIDTH="100%" BORDER="1"> <!-- The row begins here --> <TR BGCOLOR="black"> <!-- Column --> <TD WIDTH="100%" ALIGN="center"> <P><FONT COLOR="white"><B>My Marks</B></FONT></ P> </TD> <!-- Column ends --> </TR> <!-- Row ends --> </TABLE> <!-- The title table ends --> <!-- The rest of the table starts here --> <TABLE WIDTH="100%" BORDER="1"> <!-- First row --> <TR BGCOLOR="silver"> <!-- First column --> <TD WIDTH="25%"> </TD> <!-- First column ends --> <!-- Second column --> <TD WIDTH="25%" ALIGN="center"> <FONT COLOR="black"><B>English</B></FONT> </TD> <!-- Second column ends --> <!-- And so on --> <TD WIDTH="25%" ALIGN="center"> <FONT COLOR="black"><B>Mathematics</B></FONT> </ TD> <TD WIDTH="25%" ALIGN="center"> <FONT COLOR="black"><B>Philosophy</B></FONT> </T

D> </TR> <TR BGCOLOR="white"> <TD WIDTH="25%"> <FONT COLOR="black"><B>SEM1</B></FONT> </TD> <TD WIDTH="25%" ALIGN="center"> <FONT COLOR="black"><B>72%</B></FONT> </TD> <TD WIDTH="25%" ALIGN="center"> <FONT COLOR="black"><B>82%</B></FONT> </TD> <TD WIDTH="25%" ALIGN="center"> <FONT COLOR="black"><B>60%</B></FONT> </TD> </TR> <TR BGCOLOR="white"> <TD WIDTH="25%"> <FONT COLOR="black"><B>SEM2</B></FONT> </TD> <TD WIDTH="25%" ALIGN="center"> <FONT COLOR="black"><B>75%</B></FONT> </TD> <TD WIDTH="25%" ALIGN="center"> <FONT COLOR="black"><B>78%</B></FONT> </TD> <TD WIDTH="25%" ALIGN="center"> <FONT COLOR="black"><B>65%</B></FONT> </TD> </TR> </TABLE> If you want to discern what these lines do, save, and refresh your page. WIDTH="100%" means a particular table should cover the entire width of your comp uter screen, and a particular column should cover the entire width of the table containing it. <TD WIDTH="25%"> means the column is covering only 25% space of t he stipulated table. This raps up the table business. Make as many tables as you can as an exercise. The next section tells you something about the Style sheets and Server Side Incl udes. CASCADING STYLE SHEETS A few sections back, I had mentioned somewhere that some of the older HTML tags have been deprecated. This means the newer browsers refuse to recognize them. If you use these tags, the new browsers can mutilate your design in retaliation. These tags have been deprecated to accommodate more devises that are vying to gi ve net access to their users, for instance, WAP devices, televisions, etc. One of the deprecated tags is, <FONT> </FONT>. We no longer use it. Another one I can remember is, <CENTER> </CENTER>. Both of them generate protests by advance d HTML editors. So to render effects that were provided by such tags in the past, we have to use Cascading Style Sheets (CSS). A popular usage of Cascading Style Sheets is to g ive a consistent design look to a web site. Once you've designed certain styles, you can apply them on any part of your web site with just one tag. For example, supposing you have developed hundreds of pages using a particular CSS definitio n for a particular section, and all of a sudden you want to change the look of t

hat section, you just have to redefine your CSS, and lo!, your entire web site g ets upgraded. A typical CSS definition is: <STYLE type="text/css"> A {TEXT-DECORATION: none} A:hover {TEXT-DECORATION: underline} P {font: 10 pt Arial; color: black; line-height: 12 pt; align: left} </STYLE> This definition appears in the <HEAD> </HEAD> section of the page where it is be ing applied. For instance, in our First HTML page, this style would appear like this: <HTML> <HEAD> <TITLE>This is my first, hand-coded HTML page</TITLE> <STYLE type="text/css"> A {TEXT-DECORATION: none} A:hover {TEXT-DECORATION: underline} P {font: 10 pt Arial; color: black; line-height: 12 pt; align: left} </STYLE> </HEAD> <BODY> You must be familiar with <A> </A> and <P> </P> tags. When we were investigating <A> </A>, we saw that the text that appears as a link in your browser is blue, and underlined. But, if now we type <P>For more cool content, go to <A HREF="http://www.bytesworth.com">Bytesworth.c om</A>.</P> The attribute A {TEXT-DECORATION: none} makes sure that you don't see that under line under "Bytesworth.com", and A:hover {TEXT-DECORATION: underline} makes the underline appear when you hover the cursor over this text. If you want to define a paragraph-heading, do it like this: <STYLE type="text/css"> H1 {14 pt Verdana; color: maroon; text-decoration: underline; font-weight: bold} </STYLE> So now if you type: <H1>Our monthly output</H1>

A CSS can be defined on the page itself, or that you define a Cascading Style Sheet as are lengthy and you are going to apply them st have to mention the name of the CSS file ry page.

as an on in

an external file. It is preferred external file if the definitions more than 10 pages so that you ju the <HEAD> </HEAD> section of eve

To define an external CSS file, open a new file in your text editor, and type P { font-size : 10 pt; font-family : Arial; line-height : 12 pt; } A { font-size : 10 pt; font-family : Arial; font-weight : bold; color : Maroon; text-decoration : none; } A:hover { font-size : 10 pt; font-family : Arial; font-weight : bold; color : Red; text-decoration : underline; } Save the file as "mystyle.css". Remember to give a css extension. Then within <HEAD> </HEAD> of the HTML page where you want the CSS to be applied , type this: <LINK REL = STYLESHEET Type = "text/css" HREF = "mystyle.css"> Supply the complete path if the css file resides in some other folder. Save the HTML page and Refresh it. This covers the basic concept behind Cascading Style Sheets. There is a dilemma though. What if you want to have different CSS styles for the same tag for different sections? We'll ponder over it in the next section. And we'll cover some more formatting issues. NAVIGATION BARS AND BULLETED LISTS Highlight: Next, we are going to learn to make a navigation bar so that the Web site becomes "navigable", and then we learn to present point-wise information in the form of "Bulleted Lists". A proper navigation is the backbone of your Web site's success on the Net. If yo u want the visitors to be able to access all the information you want them to be able to access, you got to provide them with a consistent modus operandi for do ing it. And that modus operandi has to be present throughout the web site. A navigation bar can be on the top, at the bottom, on the left, on the right, or in the middle, in whichever way it suits the look of your entire design.

The ideal is, either on the top, or on the left hand side. What we generally do is, after inserting the logo etc. at the top, we define a t able of two columns. <table width="100%" border="0" cellspacing="3"> <tr> <!-- Left hand side navigation section --> <!-- This section generally remains the same for the entire --> <!-- Web site. --> <td width="20%" align="left" valign="top"> <!--#include file="leftnav.inc" --> </td> <!-- Below is the portion that has content unique to the particular <!-- page. -> <td width="80%" align="left" valign="top> </td> </tr> </table> The above portion should be saved as a template file, so that you make the desir ed changes in the template, keep the common code intact, and save the modified f ile as your own file. Make ample use of the comment tag <!-- Comment --> so that you know where you are putting what, especially if you are working with multiple table and column defi nitions. "leftnav.inc" can be the included file that has the following HTML code: <a href="index.shtml">Home Page</a> <a href="profile.shtml">My Profile</a> <a href="contact.shtml">Contact Me</a> You can have as many links as the number of pages you want to be seen. You don't need to use the Server Side Includes if your Web site consists of mere ly 6-7 pages because then you can just keep on copying and pasting the navigatio n bar code at: <td width="20%" align="left" valign="top"> <!--#include file="leftnav.inc" --> < /td> in this way: <td width="20%" align="left" valign="top"> <a href="index.shtml">Home Page</a> <a href="profile.shtml">My Profile</a> <a href="contact.shtml">Contact Me</a> </td> Bulleted Lists:There is a special tag used to achieve a mesmeric feat. In fact, there are two tags, namely, <ol> </ol> and <ul> </ul>.

<ul> is for a bulleted list, and <ol> is for a numbered list. You do this in the following manner: <p>We provide the following services:</p> <ul type="disk"> <li>Woodwork</li> <li>Oil Painting</li> <li>Furnishing</li> <li>Fitting</li> </ul> <li> </li> is for individual bulleted components. The type attribute of <ul> tag decides what sort of bullet is going to be visibl e. Generally, there is this disk, a circle, and a square. You can define the tag in your Cascading Style Sheet so that whenever you display the bulleted list , it appears in the same manner. This is it for now. The next section is going to teach you how to make a User Fe edback form, which is very essential to make your Web site interactive. USER FEEDBACK HTML FORM Highlight: Finally we come to Forms. After going through this celestial section you'll be able to make your own HTML feedback forms so that the visitors can sen d you feelers about what are their intentions vis--vis you and your Web site, and other sundry things that may or may not concern you. As usual we have a tag called, illuminatingly, <form> </form>. Whatever lies wit hin belongs to this tag and is going to be a part of its definition as a whole. The basic infrastructure of a user feedback form manifests itself like this: <form name="myform" method="post" action="process_form.pl"> <input type="hidden" name="email_ad" value="your email id goes here."> <input type="hidden" name="subject" value="put your subject here."> <input type="hidden" name="redirect_page" value="thankyou.html"> <p>Please enter your name: <input type="Text" name="Vname" size="25"> <br> <p>Please enter your email: <input type="Text" name="Vemail" size="25"> <br> <p>Please enter your comments: <textarea cols="25" rows="5" name="Comms"></texta rea> <br> <input type="submit" name="S1" value="Submit"> <input type="reset" name="R1" value="Reset"> </form> Good! Now let us take the bull by its horns, and ponder over the individual part s one-by-one in a scholarly manner. An average <form> has the method, name, and action attributes. There might be more tags, but in this nascent stage of Form l earning, let's stick to these three attributes. A method can have the value "pos t" or "get". "Post" is used when we are just "submitting" the information, but, "get" is used when we are retrieving information according to the information "s ubmitted". A good example of "get" is the search engine box, where you enter the word to be searched, and then the program displays the information retrieved. The attribute name is not vital to the existence of a form, but later on, in a S

CRIPT, if you desiderate to access the individual components of a form (for exam ple, validating the user input), then you need it. Action is where all the action is. This attribute holds the name of the file tha t is going to do something to the fields entered by the user. It holds the funct ions, and the "hidden" fields definitions in order to perform some task. The abo ve file, process_form.pl (a PERL file), we assume, emails you the details entere d by the user. This file mostly lurks in the CGI-BIN folder of your server, and if you are hosting your Web site on a commercial server, the host company provid es this sort of file. Ok now, hidden fields. Generally what conspires is, the PERL file needs an email address so that the entered information can be dispatched to that address. Then it might sound decent to give a subject to that future email, so that wherever it goes, the recipient can make out what sort of email it is. It would look extr emely impolite if you do not appreciate all the pain taken by the visitor - henc e, it calls for a thank you page redirection. In this manner, there could be tens of "hidden" field definitions. <input type="Text" name="Vname" size="25"> displays an empty field box of size 25 characters. And so on "Submit" tells the browser to invoke the file "process_form.pl" ies all the fields in case you want to re-enter all the values. explore other means to manipulate the "submit" field so that we at the person entering the information into the fields is not a and "Reset" empt Later on, we'll can make sure th complete dud.

A radio button is a GUI component that lets the user select one, and only one op tion from a given list of options. <p>Would you like to receive promotional emails from me? Yes <input type="radio" name="yesno" value="Yes"> No <input type="radio" name="yesno" value="No"> Both the input definitions have the same name because in a particular set of mul tiple radio buttons, only one choice can be made. You can have as many radio but tons as you want by giving them single name but varied values. The following portion lets the user choose an option from a drop down list: <p>Your profession is: <select size="1" name="profession"> <option value="Engineer">Engineer</option> <option value="Doctor">Doctor</option> <option value="Swindler">Swindler</option> <option value="Lawyer">Lawyer</option> </select> Saying in the clichd manner, last, but not the least, is a check box which is dis played by the following code: <p>Acceptable <input type="checkbox" name="checky"> Please remember that all this paraphernalia comes within <form> </form>. In the next section, we'll wrap up HTML and dive into the depths of JAVASCRIPTS and VBSCRIPTS. We'll also learn how to make the above partaken form cooler by in corporating SCRIPTS. Till then, Ciao! SOME TAGS / ATTRIBUTES THAT MAKE WEB PAGES LOOK COOLER

Before we move on to Scripting, let's go through some tags and attributes of HTM L that enhance the look and functionality of our pages. We are going to wrap up our HTML promenade after we are through with this section. Page Background: You can give your HTML page a background, using an image, by th e following attribute of the <body> tag: <body background="background.gif"> where "background.gif" is the file you want to make your background. This background scrolls up and down when you scroll your page. What if you want an image in the background that should not scroll, but remain fixed? You can do it like this: <body background="background.gif" bgproperties="fixed"> Individual cells of a table can too be given separate backgrounds using the abov e attributes inside the <td> tag. Frames: <br> This quote is used to insert a break, or a line break. For instance: <a href="url1.html">URL 1</a> <br> <a href="url2.html">URL 2</a> makes sure that URL 1 and URL 2 appear on separate lines. Every self-respecting web site developer wants his/her web site to be indexed by all those famous search engines and indexes like Lycos, Yahoo!, Excite, AltaVis ta, etc. Although this process takes ages to materialize, initialize, you can co ncentrate on incorporating certain keywords into your pages so that they get fou nd. Content of your page: Search engines generally read the first 250 or so words of your page while searching it. Try to include all the crucial words in this area . But take care that they have to make sense. Don't spam your web page with word s. The more you narrow down, greater is the chance of being indexed. Title: Whatever you write within <title> </title> sometimes helps the search eng ines. Meta tags: There are two crucial meta tags, viz., Description and Keywords. Thes e two tags are used with <head> </head> of your HTML page in the following style : <head> <meta name="Description" content="A perfect source to begin learning basic HTML" > <meta name="Keywords" content="tutorials, articles, profile, profession"> <title> </title> </head> Alt Text of your image file: Remember <img src="title.gif" alt="The logo of Gold en Words"> sort of composition? The search engines also look for the searched te xt in the Alt attributes of your various graphics file. Always use them, copious ly, but not unnecessarily.< /FONT>

<h1>, <h2>, <h6>:... Some search engines love words trapped within <h> </h> tag. <h> tags are used for inserting section, paragraph headings, for instance: <h1>Main Heading</h1> <h2>Sub Heading</h2> <h3>Sub-sub Heading</h3> You can define these headings in your Cascading Style Sheets according to your o wn preferences; otherwise, they have their default settings.

Potrebbero piacerti anche