home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
ftp.whtech.com
/
ftp.whtech.com.tar
/
ftp.whtech.com
/
Geneve
/
9640news
/
CAT12
/
CTUTORL.ARK
< prev
next >
Wrap
Text File
|
2006-10-19
|
21KB
|
400 lines
?
--- c99 ---
A Tutorial Introduction for Dartmouth TIBBS;
by Scott Flinn
_______________
The 'C' programming language, like many I have had the occasion to use in
anything less than a trivial way, is very subtle in its appeal, to the extent
that I am now completely incapable of explaining what it is about the language
that attracts me so strongly to it. My first dabblings in C led to a well
developed monolog on its indispensable attributes, and a full week of work
completed my metamorphosis into a veritable C freak, destroying forever any
chance I may have had to explain in a rational way why it might be a good idea
to have a look at it. For this reason, I will make no attempt to convince you
that you are, in fact, in much greater danger of having disaster befall you if
you choose to ignore c99. This is quite probably a fact, but I will still make
no attempt to convince you of it. Instead, I will make the assumption that,
since you have persisted to this point through a tedious paragraph of turgid
rubbish, you have already found sufficient reason to give the language some
attention and probably already realize that it is the only realistic
alternative to Forth for those desiring more speed or power than Basic can
offer.
This tutorial will make a typical assumption, and so begins with the
standard disclaimer that it makes no effort to introduce proper programming
technique or methodology. It is assumed from this point on that the reader is
familiar with TI Basic at least to the extent that useful (though perhaps
simple) programs can be produced. The similarities (as well as some of the
outrageous differences) will be pointed out, and a simple method for producing
equally simple programs will be presented. This first tutorial article is
geared toward the basic mechanics of writing, compiling, loading, and running a
c99 program on the TI-99/4A. Not in this article, but to be included in later
tutorials will be discussions on function use, character strings, and some of
the more useful features of c99 not found in Basic.
For those uninitiated to compiler languages, the sight of a C program
listing will make Basic look extremely appealing. The first task, which many
find to be the most formidable, is that of realizing that the strange
appearance of a C program, and the seemingly inhuman procedure required to
produce one are really just elaborate illusions generated by a small handful of
arbitrary rules who, not wanting to be broken and violated, make a valiant
attempt to drive away the faint at heart. You must see these rules for what
they are - selfish, inconsiderate, but very harmless and almost trivial to
master. Let's start with the most unusual of these.
There are four aspects of any C program which are not present in
Basic. Namely: 1) declared variables
2) program and function names
3) semicolons to end statements
4) source files vs. compiled files
Without a doubt, the most despised aspect of compiled languages is the
need to declare all variables used in the program before they are actually
referenced in that program. The last straw for many people is that the place
in the program in which these variables are declared determines what parts of
the program can refer to them (ie. use them). The first hurdle to get over is
to notice that variables used in C programs are no different than those used in
Basic. If you have been using the variable A for example, and want to add 1 to
it, you would use A = A + 1. (There are actually betters ways of doing this in
C, but A = A + 1 is FINE for now). The only difference is that before you can
do this, or anything involving the variable A for that matter (eg. A = 6, or B
= A / 2), you must tell the program that you want to be able to use that
variable. Telling the program about variables that you want to be able to use
it what is meant by 'variable declarations'. Since this is the most hated
aspect of compiled languages, particularly by those new to them, I thought I
should at least mention it here, to give you plenty of warning. I will return
to them later, but first you must know how to write programs of any kind,
preferably starting with those that don't use things as complicated as
variables.
Following is a listing of your very first c99 program. If you have
already successfully written programs in c99, you may skip this part - you have
my permission to do that! If not, then this is a great starting point:
main()
{ puts("Hello world\n\n");
}
That's it...that's all you need. Type it in EXACTLY like that and it will
work. Type it in where? Ah...well, let's begin with a detailed description of
the steps required t{_o write, compile, load, and run a c99 program. Once you
have successfully run the program above, then you will know how to run any c99
program, and a knowledge of c99 will then be the last step.
The program source code (ie. the stuff above that begins with 'main()' and
ends with '}') can be typed in using any program that produces a D/V 80 text
file. The best one to use is the Editor/Assembler (henceforth to be abreviated
E/A) editor. The TI Writer editor is also fine, as long as the file is saved
using the PRINT option rather than SAVE (to avoid a line of tab data being
saved at the end). Now, once you have the above text typed into a file, you
are ready to start compiling. The compiler is called 'C99C' and also requires
the files 'C99D' and 'C99E'. This can be loaded either from E/A Option 5, or
from any E/A simulator (such as Funlwriter). When the program is loaded it
will begin execution automatically, and will start asking questions
immediately. DO NOT PANIC. Depending on the version of the compiler you have,
there are a number of different questions you can be asked. Following is a
list of possibilities along with the correct responses for the above program:
1) Include c-text? N or n
2) Inline push code? N or n
3) Main program? Y or y (only in older versions of c99)
4) Input filename? DSKn.whatever-you-called-the-program-file
5) Output filename? DSKn.a-new-filename
And at this point compilation will begin. BE SURE to put the disk with
the program on it back in the drive if you removed it to load the compiler.
Since it is a very short program, the compilation should be fairly quick. If
you have not properly entered the program, then (depending on the version of
c99 you are using) it will either tell you when it has finished that it has
found errors, or it will show you the errors as it encounters them,}i and will
wait for you to hit the spacebar to continue. In either case, get out of the
compiler in any way you like and find the discrepancy between your program file
and the program listed above. Then try it again.
If compilation is successful, however, the message 'COMPILATION COMPLETE'
will be issued, and you will be asked if you want to RERUN? Respond with N or
n, and you will be returned to either E/A or the color bar screen. You have
now compiled your program! (You are now roughly half done!) The next step is to
assemble your compiled program. The output file that you specified to the
compiler should now contain the compiler's output - namely a TMS9900 assembly
program that can be assembled with the TI assembler (either with E/A or
Funlwriter). To do this, load the assembler (by selecting the assembler option
in either case). The input file for the assembler is the OUTPUT file from the
c99 compiler. The new output file is any, as yet unused filename. After
providing this information to the compiler program, you will be asked for a
list filename. Respond with a carriage return. You will then be prompted to
specify some options. Again respond with a carriage return, and assembly
should commence. Again, if errors are encountered, you will be informed, and
you should start again. If not, you will now have a program that can be run
and are ready for the last step (exciting, isn't it). Exit the assembler. At
this point, I do not know how to avoid using either E/A or Mini Memory. If you
have one of these cartridges, however, then select the 'LOAD AND RUN' option.
The first file you must load is CSUP (which is on the c99 release diskette).
This file must ALWAYS be loaded before c99 programs will run. Next load the
file produced by the assembler (the one you specified for output). Pressing
enter will produce the 'PROGRAM NAME' prompt to which you must respond START.
Sit back and watch the fun. If the words 'Hello world' do not appear on your
screen, carefully retrace your steps.
Congratulations. You have just plowed you way through the exceedingly
bizarre sequence of steps required to compile and run c99 programs. Now do it
again. That's right, do it AGAIN! It's the only way you'll get the hang of it.
Try changing the message in quotation marks next time (eg. "Hello Fred\n\n"
might be nice). In particular, see if you can figure out what the characters
'\n' in the message do. Add a couple more \n's - try taking them all out. The
important part is that you feel comfortable with the compilation steps. To
make it a little easier, here is a very brief summary of the steps that must be
followed. First, however, an IMPORTANT word about file names. With C, you
tend to use a lot of different files, and it is sometimes hard to remember all
the names you use. A very good suggestion (if you don't mind me saying so) is
to pick ONE name for all of the steps (eg. FRED might be nice), and distinguish
between the different intermediate steps using the last two characters. Like
so:
DSK1.FRED;C ;C indicates that this file contains the c99
program
DSK1.FRED;A ;A indicates that this is the output of the
compiler. It is the file that you must
now assemble, hence the A
DSK1.FRED;R ;R indicates that this file is ready to (load
and) run
Now for the advertised list of compilation steps:
1) Write or modify the program with a D/V 80 editor
2) Save the file, and load the c99 compiler
3) Answer the questions as described above (or as described in the
c99 user's manual, which is really very good and is something you
should probably read)
4) input filename = file;C
output filename = file;A
5) Load the assembler, and assemble file;A to produce file;R - no list file,
no options
6) Load CSUP from LOAD AND RUN option
7) Load file;R and push enter
8) Respond to PROGRAM NAME with START
9) Observe results. If not as desired, curse vigorously.
If you have made it this far, then the fourth problem in the list above
has been solved. We still have three to go, so let's tackle them bodily. The
next thing to consider is the program name 'main'. In C, every program must
have this name, which must be followed by (), indicating that there are no
parameters to be passed to it. Actually, most C programs eventually have many
distinct blocks of program statements, each of which is labeled. Execution of
the program begins with the block labeled 'main()', so it must always be
present. The idea of separate blocks of statements in C is identical to that
of user defined subprograms in Extended Basic. If a block of lines is to be
used more than once, it is often convenient to put these together into a
subroutine (called 'functions' in C) which can be called simply by using its
name with the appropriate parameters. The idea of functions has been
introduced here at the outset because, while it is possible to write programs
without functions, it is deemed VERY bad programming practice. It is therefore
a very good idea to get over the shock of having to use them before you lose
your nerve.
The last problem to be introduced is that, rather arbitrarily, every
single statement must end in a semicolon. This actually makes the compiler's
task easier and, in many cases, makes the resulting C code easier to read
(believe it or not!) For those of you familiar with Pascal, the semicolon in C
is actually part of the statement, not merely a statement separator. So, for
example, the statement immediately before an 'else' statement must have a
semicolon just as every other line must.
The last part of this extremely brief introduction will be the much
dreaded return to the topic of variable declarations. In c99, there are two
different data types corresponding very roughly to the types numeric and string
in Basic. Specifically, c99 uses integer or character variables. An integer
variable can hold any integer in the range -32768 to 32767. c99 does not
support floating point numbers directly, so the range can be no bigger than
this. In addition, there is no way to represent fractional parts. So the
statement A = 1/2 will set A to 0, since 0.5 cannot be represented in integer
form. Similarly, A = 5/3 would give A the value of 1, which is the integer
part of 5/3 = 1.667. Character variables are very nearly the same, although
they serve an entirely different purpose. For the technically inclined,
integer variables are 16 bit and character variables are 8 bit (for the even
more technically inclined, all arithmetic involving BOTH types of data are done
using 16 bit operands, all the character data being extended logically to 16
bits before being combined. So mixing the data types is usually legal,
although very much frowned upon).
An additional word must be said about character variables. These
variables are rarely used alone since most functions almost always deal with
integer data. The most common use for character variables is in arrays. C has
no string manipulation facilities. Unlike basic, it is not possible to have a
string variable that can be easily manipulated; instead, arrays of characters
must be used, and string manipulations involve manipulating each character
variable in the array. Actually, the manipulation of string data (ie. arrays
or characters involves one of the trickier aspects of C and should be left
until some of the other aspects are mastered. DO NOT let this deter you. The
next tutorial article in this series will contain a complete description of
character strings, the various ways of representing and manipulating them, and
several very useful functions which perform more common manipulations on them.
In the meantime, a small number of examples of slightly easier uses of strings
can be found in the examples which follow.
So what about the actual declaration of these things...I've been stalling,
haven't I? Well, it is actually pretty easy. Any block of program lines
enclosed within {braces} is treated as a single statement, making it possible
to do a large number of things in IF-THEN-ELSE statements, for example. In
particular, the main program is a block of statements which must be separated
from other functions. Surrounding all of the lines in 'main()' with {} ensures
that it will be treated as one block before any other lines in the program file
are considered. Now, any variables used with a block of lines surrounded by {}
must be declared immediately following the opening brace {. If the variable is
going to be used to store integer data, then it must be declared using the
statement 'int var-name', and must then be restricted to integer data.
Similarly, character variables used withing a block must be declared as 'char
var-name'. Note that, unlike string variables in Basic, no $ is required for
character variable names. In fact, there is no distinction at all between
integer and variable names.
Now for the tricky part. A variable can only be used in the block of
lines in which it has been declared, which includes blocks of lines within that
block. The usual practice is to declare all of the variables used in a
function, including the main program function 'main()', immediately after the
opening brace for that function. They can then be referenced from anywhere
within that function.
That is more than enough for now. The next thing on the agenda is LOTS of
practice. The following programs illustrate most of the things outlined above.
Try compiling them. Make small changes to see what happens. Do whatever you
like with them, but whatever else, do compile and run them. A few hours spent
now in frustration will pay endless rewards through the truly unbelievable
power that you will 6quickly become easier than Basic ever was.
The next section, incidentally, contains lots of exciting information about
functions and things. This is where the power of C really begins to show. Even
if you intend to stop here for now, you should at least look at the sample
program at the start of the next section to see what you are missing.
SAMPLE PROGRAMS:
/******************************************************************************/
/* comments are a very important part of C programs, much more than in basic
in C, when a slash-asterisk pair is encountered, everything that follows is
interpreted as a comment until an asterisk-slash pair is found */
main() /* begins EVERY c99 program */
{ int i; /* i is a variable we want to use. Note the semicolon */
for (i=32; i<= 126; i=i+1) /* the for statement is just a bit different */
{ putchar(i); /* puts character whose ascii value is i on the screen */
putchar(10); /* ASCII 10 is a linefeed - this skips to a new line */
} /* this ends the block of lines executed every time the for loop repeats
you can think of it as replacing the NEXT from Basic */
}
/******************************************************************************/
/* the same program without the comments is, for clarity: */
main()
{ int i;
for (i = 32; i <= 126; i = i + 1)
{ putchar(i);
putchar(10);
}
}
/* fiddle with the limits in the for statement and see what happens */
/******************************************************************************/
main()
{ int i;
char *c, *d;
c = "string";
d = c;
for (i = 0; i < 6; i++) /* i++ means i=i+1 */
{ puts("Character ");
putchar(i+48);
puts(" of the string is ");
putchar(*d++);
putchar(10);
}
puts("\n\nThe whole string is ");
puts(c);
}
/******************************************************************************/
extern printf(); /* printf is an external function, and requires this before it
can be referenced. Don't worry about it. Just remember,
any program that uses printf must have this statement in it.
Also, the file PRINTF from the c99 release diskette must be
loaded along with CSUP and your own file */
main()
{ int i;
for (i = 0; i < 100; i++)
prizTCHsquared is %d\n", i, i*i);
}
/* play with printf, particularly the %d things, and see if you can figure it
out */
/******************************************************************************/
This next program is a good deal more complicated and should give you
something to chew on until I get around to writing the next tutorial. A
reference book on C (such as "The C Programming Language" by Kernighan and
Ritchie, available at the Dalhousie Book Store) is highly recommended. In
addition, if you understand the programs above, a thorough reading of the c99
user's manual would now be a good idea.
extern printf();
#define FALSE 0 /* all occurrences of FALSE are replaced with 0 */
#define TRUE -1 /* all occurrences of TRUE are replaced with -1 */
main()
{ int n, test, prime, key;
tscrn(2, 8); /* change screen color */
locate(1, 15);
puts("Factor Finder");
for (n = 1; n < 32767; n = n + 2)
{ prime = TRUE; /* see #define above */
test = 2;
locate(8, 4);
printf("Testing %d ->", n);
while ((test < n/2) & (prime == TRUE))
{ key = poll(1);
if ((n % test) == 0) /* n % test is remainder when test divides n */
{ prime = FALSE;
locate(10, 5);
printf("%6d divides %6d", test, n);
}
else
test++; /* same as test = test + 1 */
}
}
}
/******************************************************************************/
)3=GUUUUUUUU
Download complete. Turn off Capture File.