Load the file named tempconv.c for an example of a useful, even though somewhat limited
program. This is a program that generates a list of centigrade and Fahrenheit temperatures and
prints a message out at the freezing point of water and another at the boiling point of water.
/***********************************************************/
/* This is a temperature conversion program written in */
/* the C programming language. This program generates */
/* and displays a table of farenheit and centigrade */
/* temperatures, and lists the freezing and boiling */
/* of water */
/**********************************************************/
main( )
{
int count; /* a loop control variable */
int farenheit; /* the temperature in farenheit degrees */
int centigrade; /* the temperature in centigrade degrees */
printf("Centigrade to farenheit temperature table\n\n");
for(count = -2;count <= 12;count = count + 1 ){
centigrade = 10 * count;
farenheit = 32 + (centigrade * 9)/5;
printf(" C =%4d F =%4d ",centigrade,farenheit);
if (centigrade == 0)
printf(" Freezing point of water");
if (centigrade == 100)
printf(" Boiling point of water");
printf("\n");
} /* end of for loop */
}
Of particular importance is the formatting. The header is simply several lines of comments
describing what the program does in a manner the catches the readers attention and is still
pleasing to the eye. You will eventually develop your own formatting style, but this is a good
way to start.
Also if you observe the for loop, you will notice that all of the contents of the compound statement are indented a few spaces to the right of the "for" reserved word, and the closing brace is lined up under the "f" in "for". This makes debugging a bit easier because the construction becomes very obvious.
You will also notice that the "printf" statements that are in the "if" statements within the big
"for" loop are indented three additional spaces because they are part of another construct. This
is the first program in which we used more than one variable. The three variables are simply
defined on three different lines and are used in the same manner as a single variable was used
in previous programs. By defining them on different lines, we have opportunity to define each
with a comment.
Friday, January 16, 2009
The Goto Statement
Load and display the file gotoex.c for an example of a file with some "goto" statements in
main()
{
int dog,cat,pig;
goto real_start;
some_where:
printf("This is another line of the mess.\n");
goto stop_it;
/* the following section is the only section with a useable goto */
real_start:
for(dog = 1;dog < 6;dog++) {
for(cat = 1;cat < 6;cat++) {
for(pig = 1;pig < 4;pig++) {
printf("Dog = %d Cat = %d Pig = %d\n",dog,cat,pig);
if ((dog + cat + pig) > 8 ) goto enough;
};
};
};
enough: printf("Those are enough animals for now.\n");
/* this is the end of the section with a useable goto statement */
printf("\nThis is the first line out of the spaghetti code.\n");
goto there;
where:
printf("This is the third line of the spaghetti code.\n");
goto some_where;
there:
printf("this is the second line of the spaghetti code.\n");
goto where;
stop_it:
printf("This is the last line of the mess.\n");
}
To use a "goto" statement, you simply use the reserved word "goto", followed by the symbolic
name to which you wish to jump. The name is then placed anywhere in the program followed
by a colon. You are not allowed to jump into any loop, but you are allowed to jump out of a
loop. Also, you are not allowed to jump out of any function into another. These attempts will
be flagged by your compiler as an error if you attempt any of them.
This particular program is really a mess but it is a good example of why software writers are
trying to eliminate the use of the "goto" statement as much as possible. The only place in this
program where it is reasonable to use the "goto" is the one in line 17 where the program jumps
out of the three nested loops in one jump. In this case it would be rather messy to set up a
variable and jump successively out of all three loops but one "goto" statement gets you out of
all three.
Some persons say the "goto" statement should never be used under any circumstances but this
is rather narrow minded thinking. If there is a place where a "goto" will be best, feel free to use
it. It should not be abused however, as it is in the rest of the program on your monitor.
main()
{
int dog,cat,pig;
goto real_start;
some_where:
printf("This is another line of the mess.\n");
goto stop_it;
/* the following section is the only section with a useable goto */
real_start:
for(dog = 1;dog < 6;dog++) {
for(cat = 1;cat < 6;cat++) {
for(pig = 1;pig < 4;pig++) {
printf("Dog = %d Cat = %d Pig = %d\n",dog,cat,pig);
if ((dog + cat + pig) > 8 ) goto enough;
};
};
};
enough: printf("Those are enough animals for now.\n");
/* this is the end of the section with a useable goto statement */
printf("\nThis is the first line out of the spaghetti code.\n");
goto there;
where:
printf("This is the third line of the spaghetti code.\n");
goto some_where;
there:
printf("this is the second line of the spaghetti code.\n");
goto where;
stop_it:
printf("This is the last line of the mess.\n");
}
To use a "goto" statement, you simply use the reserved word "goto", followed by the symbolic
name to which you wish to jump. The name is then placed anywhere in the program followed
by a colon. You are not allowed to jump into any loop, but you are allowed to jump out of a
loop. Also, you are not allowed to jump out of any function into another. These attempts will
be flagged by your compiler as an error if you attempt any of them.
This particular program is really a mess but it is a good example of why software writers are
trying to eliminate the use of the "goto" statement as much as possible. The only place in this
program where it is reasonable to use the "goto" is the one in line 17 where the program jumps
out of the three nested loops in one jump. In this case it would be rather messy to set up a
variable and jump successively out of all three loops but one "goto" statement gets you out of
all three.
Some persons say the "goto" statement should never be used under any circumstances but this
is rather narrow minded thinking. If there is a place where a "goto" will be best, feel free to use
it. It should not be abused however, as it is in the rest of the program on your monitor.
The Switch Statement
Load and display the file switch.c for an example of the biggest construct yet in the C
language, the switch.
{
int truck;
for (truck = 3;truck < 13;truck = truck + 1) {
switch (truck) {
case 3 : printf("The value is three\n");
break;
case 4 : printf("The value is four\n");
break;
case 5 :
case 6 :
case 7 :
case 8 : printf("The value is between 5 and 8\n");
break;
case 11 : printf("The value is eleven\n");
break;
default : printf("It is one of the undefined values\n");
break;
} /* end of switch */
} /* end of the loop */
}
The switch is not difficult, so don’t let it intimidate you. It begins with the keyword "switch"
followed by a variable in parentheses which is the switching variable, in this case "truck". As
many cases as desired are then enclosed within a pair of braces. The reserved word "case" is
used to begin each case entered followed by the value of the variable, then a colon, and the
statements to be executed.
In this example, if the variable "truck" contains the value 8 during this pass of the switch
statement, the printf will cause "The value is three" to be displayed, and the "break" statement
will cause us to jump out of the switch.
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 variable has the value 5, the
statements will begin executing where "case 5 :" is found, but the first statements found are
where the case 8 statements are. These are executed and the break statement in the "case 8"
portion will direct the execution out the bottom of the switch. The various case values can be
in any order and if a value is not found, the default portion of the switch will be executed.
It should be clear that any of the above constructs can be nested within each other or placed in
succession, depending on the needs of the particular programming project at hand.
Compile and run switch.c to see if it does what you expect it to after this discussion.
language, the switch.
{
int truck;
for (truck = 3;truck < 13;truck = truck + 1) {
switch (truck) {
case 3 : printf("The value is three\n");
break;
case 4 : printf("The value is four\n");
break;
case 5 :
case 6 :
case 7 :
case 8 : printf("The value is between 5 and 8\n");
break;
case 11 : printf("The value is eleven\n");
break;
default : printf("It is one of the undefined values\n");
break;
} /* end of switch */
} /* end of the loop */
}
The switch is not difficult, so don’t let it intimidate you. It begins with the keyword "switch"
followed by a variable in parentheses which is the switching variable, in this case "truck". As
many cases as desired are then enclosed within a pair of braces. The reserved word "case" is
used to begin each case entered followed by the value of the variable, then a colon, and the
statements to be executed.
In this example, if the variable "truck" contains the value 8 during this pass of the switch
statement, the printf will cause "The value is three" to be displayed, and the "break" statement
will cause us to jump out of the switch.
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 variable has the value 5, the
statements will begin executing where "case 5 :" is found, but the first statements found are
where the case 8 statements are. These are executed and the break statement in the "case 8"
portion will direct the execution out the bottom of the switch. The various case values can be
in any order and if a value is not found, the default portion of the switch will be executed.
It should be clear that any of the above constructs can be nested within each other or placed in
succession, depending on the needs of the particular programming project at hand.
Compile and run switch.c to see if it does what you expect it to after this discussion.
The If Statement
Loadand display the fileifelse.cfor an example of our first conditional branching statement,
the "if".
/* This is an example of the if and if-else statements */
main()
{
int data;
for(data = 0;data < 10;data = data + 1) {
if (data == 2)
printf("Data is now equal to %d\n",data);
if (data < 5)
printf("Data is now %d, which is less than 5\n",data);
else
printf("Data is now %d, which is greater than 4\n",data);
} /* end of for loop */
}
Notice first, that there is a "for" loop with a compound statement as its executable part containing two "if" statements. This is an example of how statement can be nested. It should be clear to " statements will be executed 10 times.
Consider the first "if" statement. It starts with the keyword "if" followed by an expression in
parentheses. If the expression is evaluated and found to be true, the single statement following
the "if" is executed. If false, the following statement 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
explained in detail in the next chapter. (Simply suffice for now that if "data = 2" were used in
this context, it would mean a completely different thing.)
Now For The If-Else
The second "if" is similar to the first, with the addition of a new reserved word, the "else",
following the first printf statement. This simply says that, if the expression in the parentheses
evaluates as true, the first expression is executed, otherwise the expression following 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 skipped. Both will find many uses in your
C programming efforts. Compile and run this program to see if it does what you expect.
The Break And Continue
Load the file named breakcon.c for an example of two new statements.
main( )
{
int xx;
for(xx = 5;xx < 15;xx = xx + 1){
if (xx == 8)
break;
printf("in the break loop, xx is now %d\n",xx);
}
for(xx = 5;xx < 15;xx = xx + 1){
if (xx == 8)
continue;
printf("In the continue loop, xx is the now %d\n",xx);
}
}
Notice that in the first "for" there is an if statement that calls a break if xx equals 8. The break
will jump out of the loop you are in and begin executing the statements following the loop,
effectively terminating the loop. This is a valuable statement when you need to jump out of a
loop depending on the value of some results calculated in the loop. In this case, when xx reaches
8, the loop is terminated and the last value printed will be the previous value, namely 7.
The next "for" loop, contains a continue statement which does not cause termination of the loop
but jumps out of the present iteration. When the value of xx reaches 8 in this case, the program
will jump to the end of the loop and continue executing the loop, effectively eliminating the
printf statement during the pass through the loop when xx is eight. Compile and run the program to see if it does what you expect.
the "if".
/* This is an example of the if and if-else statements */
main()
{
int data;
for(data = 0;data < 10;data = data + 1) {
if (data == 2)
printf("Data is now equal to %d\n",data);
if (data < 5)
printf("Data is now %d, which is less than 5\n",data);
else
printf("Data is now %d, which is greater than 4\n",data);
} /* end of for loop */
}
Notice first, that there is a "for" loop with a compound statement as its executable part containing two "if" statements. This is an example of how statement can be nested. It should be clear to " statements will be executed 10 times.
Consider the first "if" statement. It starts with the keyword "if" followed by an expression in
parentheses. If the expression is evaluated and found to be true, the single statement following
the "if" is executed. If false, the following statement 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
explained in detail in the next chapter. (Simply suffice for now that if "data = 2" were used in
this context, it would mean a completely different thing.)
Now For The If-Else
The second "if" is similar to the first, with the addition of a new reserved word, the "else",
following the first printf statement. This simply says that, if the expression in the parentheses
evaluates as true, the first expression is executed, otherwise the expression following 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 skipped. Both will find many uses in your
C programming efforts. Compile and run this program to see if it does what you expect.
The Break And Continue
Load the file named breakcon.c for an example of two new statements.
main( )
{
int xx;
for(xx = 5;xx < 15;xx = xx + 1){
if (xx == 8)
break;
printf("in the break loop, xx is now %d\n",xx);
}
for(xx = 5;xx < 15;xx = xx + 1){
if (xx == 8)
continue;
printf("In the continue loop, xx is the now %d\n",xx);
}
}
Notice that in the first "for" there is an if statement that calls a break if xx equals 8. The break
will jump out of the loop you are in and begin executing the statements following the loop,
effectively terminating the loop. This is a valuable statement when you need to jump out of a
loop depending on the value of some results calculated in the loop. In this case, when xx reaches
8, the loop is terminated and the last value printed will be the previous value, namely 7.
The next "for" loop, contains a continue statement which does not cause termination of the loop
but jumps out of the present iteration. When the value of xx reaches 8 in this case, the program
will jump to the end of the loop and continue executing the loop, effectively eliminating the
printf statement during the pass through the loop when xx is eight. Compile and run the program to see if it does what you expect.
The For Loop
The "for" loop is really nothing new, it is simply a new way of describe the "while" loop. Load
and edit the file named forloop.c for an example of a program with a "for" loop.
/* This is an example of a for loop */
main( )
{
int index;
for(index = 0;index < 6;index = index + 1)
printf("The value of the index is %d\n",index);
}
The "for" loop consists of the reserved word "for" followed by a rather large expression in
parentheses. This expression is really composed of three fields separated by semi-colons. The
first field contains the expression "index = 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 what 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 commas.
The second field, in this case containing "index < 6", is the test which is done at the beginning
of each loop through the program. It can be any expression which will evaluate to a true or
false. (More will be said about the actual value of true and false in the next chapter.)
The expression contained in the third field is executed each time the loop is executed 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 several 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 can be replaced by a compound statement
that will be treated as if it were a single statement as far as program control goes. Compile and
run this program.
and edit the file named forloop.c for an example of a program with a "for" loop.
/* This is an example of a for loop */
main( )
{
int index;
for(index = 0;index < 6;index = index + 1)
printf("The value of the index is %d\n",index);
}
The "for" loop consists of the reserved word "for" followed by a rather large expression in
parentheses. This expression is really composed of three fields separated by semi-colons. The
first field contains the expression "index = 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 what 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 commas.
The second field, in this case containing "index < 6", is the test which is done at the beginning
of each loop through the program. It can be any expression which will evaluate to a true or
false. (More will be said about the actual value of true and false in the next chapter.)
The expression contained in the third field is executed each time the loop is executed 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 several 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 can be replaced by a compound statement
that will be treated as if it were a single statement as far as program control goes. Compile and
run this program.
The Do-While Loop
Avariation of the while loop is illustrated in the program dowhile.c, which you should load
and display.
/* This is an example of a do-while loop */
main( )
{
int i;
i = 0;
do {
printf("the value of i is now %d\n",i);
i = i + 1;
} while (i < 5);
}
This program is nearly identical to the last one except that the loop begins with the reserved
word "do", followed by a compound statement in braces, then the reserved word "while", and
finally an expression in parentheses. The statements in the braces are executed repeatedly as
long as the expression in 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 this statement. Since the test is done at the end of
the loop, the statements in the braces will always be executed at least once. Secondly, if "i",
were not changed within the loop, the loop would never terminate, and hence the program would
never terminate. Finally, just like the while loop, if only one statement will be executed within
the loop, no braces are required. Compile and run this program to see if it does what you think
it should do.
It should come as no surprise to you that these loops can be nested. That is, one loop can be
included within the compound statement of another loop, and the nesting level has no limit.
and display.
/* This is an example of a do-while loop */
main( )
{
int i;
i = 0;
do {
printf("the value of i is now %d\n",i);
i = i + 1;
} while (i < 5);
}
This program is nearly identical to the last one except that the loop begins with the reserved
word "do", followed by a compound statement in braces, then the reserved word "while", and
finally an expression in parentheses. The statements in the braces are executed repeatedly as
long as the expression in 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 this statement. Since the test is done at the end of
the loop, the statements in the braces will always be executed at least once. Secondly, if "i",
were not changed within the loop, the loop would never terminate, and hence the program would
never terminate. Finally, just like the while loop, if only one statement will be executed within
the loop, no braces are required. Compile and run this program to see if it does what you think
it should do.
It should come as no surprise to you that these loops can be nested. That is, one loop can be
included within the compound statement of another loop, and the nesting level has no limit.
Program Control
The While Loop
The C programming language has several structures for looping and conditional branching. 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 condition becomes false, the looping
is discontinued. It therefore does just what it says it does, the name of the loop being very
descriptive.
Load the program while.c and display it for an example of a while loop.
/* This is an example of a "while" loop */
main( )
{
int count;
count = 0;
while (count < 6) {
printf("The value of count is %d\n",count);
count = count + 1;
}
}
Webegin with a comment and the program name, then go on to define an integer variable "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 parentheses, followed by a compound statement bracketed by braces. As long as the expression in parentheses is true, all statements within the braces will be executed. In this case, since the variable count is incremented byone every time the statements are executed, and the loop will be terminated. The program control will resume at the statement following the statements in braces.
We will cover the compare expression, the one in parentheses, in the next chapter. Until then,
simply accept the expressions for what you think they should do and you will probably be correct.
Several things must be pointed out regarding the while loop. First, if the variable 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 that never is executed. Secondly, if the variable were
not incremented in the loop, then in this case, the loop would never terminate, and the program
would never complete. Finally, if there is only one statement to be executed within the loop, it
does not need braces but can stand alone.
Compile and run this program.
The C programming language has several structures for looping and conditional branching. 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 condition becomes false, the looping
is discontinued. It therefore does just what it says it does, the name of the loop being very
descriptive.
Load the program while.c and display it for an example of a while loop.
/* This is an example of a "while" loop */
main( )
{
int count;
count = 0;
while (count < 6) {
printf("The value of count is %d\n",count);
count = count + 1;
}
}
Webegin with a comment and the program name, then go on to define an integer variable "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 parentheses, followed by a compound statement bracketed by braces. As long as the expression in parentheses is true, all statements within the braces will be executed. In this case, since the variable count is incremented byone every time the statements are executed, and the loop will be terminated. The program control will resume at the statement following the statements in braces.
We will cover the compare expression, the one in parentheses, in the next chapter. Until then,
simply accept the expressions for what you think they should do and you will probably be correct.
Several things must be pointed out regarding the while loop. First, if the variable 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 that never is executed. Secondly, if the variable were
not incremented in the loop, then in this case, the loop would never terminate, and the program
would never complete. Finally, if there is only one statement to be executed within the loop, it
does not need braces but can stand alone.
Compile and run this program.
Good Formatting Style
Load the file goodform.c and observe it on your monitor.
main() /* Main program starts here */
{
printf("Good form ");
printf ("can aid in ");
printf ("understanding a program.\n");
printf("And bad form ");
printf ("can make a program ");
printf ("unreadable.\n");
}
It is an example of a well formatted program. Even though it is very short and therefore does
very little, it is very easy to see at a glance what it does. With the experience you have 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 spaces and all carriage returns giving you
considerable freedom concerning how you format your program. Indenting and adding spaces
is entirely up to you and is a matter of personal taste. Compile and run the program to see if it
does what you expect it to do.
Now load and display the program uglyform.c and observe it.
main( ) /* Main program starts here */{printf("Good form ");printf
("can aid in ");printf(" understanding a program.\n")
;printf("And bad form ");printf("can make a program ");
printf("unreadable.\n");}
How long will it take 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 your
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 worried about formatting style
yet. You will have plenty of time to develop a style of your own as you learn the language. Be
observant of styles as you see C programs in magazines, books, and other publications.
This should pretty well cover the basic concepts of programming in C, but as there are many
other things to learn, we will forge ahead to additional program structure
main() /* Main program starts here */
{
printf("Good form ");
printf ("can aid in ");
printf ("understanding a program.\n");
printf("And bad form ");
printf ("can make a program ");
printf ("unreadable.\n");
}
It is an example of a well formatted program. Even though it is very short and therefore does
very little, it is very easy to see at a glance what it does. With the experience you have 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 spaces and all carriage returns giving you
considerable freedom concerning how you format your program. Indenting and adding spaces
is entirely up to you and is a matter of personal taste. Compile and run the program to see if it
does what you expect it to do.
Now load and display the program uglyform.c and observe it.
main( ) /* Main program starts here */{printf("Good form ");printf
("can aid in ");printf(" understanding a program.\n")
;printf("And bad form ");printf("can make a program ");
printf("unreadable.\n");}
How long will it take 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 your
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 worried about formatting style
yet. You will have plenty of time to develop a style of your own as you learn the language. Be
observant of styles as you see C programs in magazines, books, and other publications.
This should pretty well cover the basic concepts of programming in C, but as there are many
other things to learn, we will forge ahead to additional program structure
How Do We Add Comments In C
can be added to a C program.
/* This is a comment ignored by the compiler */
main( ) /* This is another comment ignored by the compiler */
{
printf("We are looking at how comments are "); /* A comment is
allowed to be
continued on
another line */
printf("used in C.\n");
}
/* One more comment for effect */
Comments are added to make a program more readable to you but the compiler must ignore the
comments. The slash star combination is used inC for comment delimiters. They are illustrated
in the program at hand. Please note that the program does not illustrate good commenting
practice, but is intended to illustrate where comments can go in a program. It is a very sloppy
looking program.
The first slash star combination introduces the first comment and the star at the end of the first
line terminates this comment. Note that this comment is prior to the beginning of the program
illustrating that a comment can precede the program itself. Good programming practice would
include a comment prior to the program with a short introductory description of the program.
The next comment is after the "main( )" program entry point and prior to the opening brace for
the program code itself
The third comment starts after the first executable statement and continue 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 anything 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. The last comment is located following the completion of the program, illustrating that comments can go nearly anywhere in a C program.
Experiment with this program be adding comments in other places to see what will happen.
Comment out one of the printf statements by putting comment delimiters both before and after
it and see that it does not get printed out.
Comments are very important in any programming language because you will soon forget 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 will very quickly develop your own
personal style of commenting.
Somecompilers allow you to "nest" comments which can be very handy if you need to "comment
out" a section of code during debugging. Check your compiler documentation for the availability
of this feature with your particular compiler. Compile and run comments.c at this time.
/* This is a comment ignored by the compiler */
main( ) /* This is another comment ignored by the compiler */
{
printf("We are looking at how comments are "); /* A comment is
allowed to be
continued on
another line */
printf("used in C.\n");
}
/* One more comment for effect */
Comments are added to make a program more readable to you but the compiler must ignore the
comments. The slash star combination is used inC for comment delimiters. They are illustrated
in the program at hand. Please note that the program does not illustrate good commenting
practice, but is intended to illustrate where comments can go in a program. It is a very sloppy
looking program.
The first slash star combination introduces the first comment and the star at the end of the first
line terminates this comment. Note that this comment is prior to the beginning of the program
illustrating that a comment can precede the program itself. Good programming practice would
include a comment prior to the program with a short introductory description of the program.
The next comment is after the "main( )" program entry point and prior to the opening brace for
the program code itself
The third comment starts after the first executable statement and continue 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 anything 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. The last comment is located following the completion of the program, illustrating that comments can go nearly anywhere in a C program.
Experiment with this program be adding comments in other places to see what will happen.
Comment out one of the printf statements by putting comment delimiters both before and after
it and see that it does not get printed out.
Comments are very important in any programming language because you will soon forget 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 will very quickly develop your own
personal style of commenting.
Somecompilers allow you to "nest" comments which can be very handy if you need to "comment
out" a section of code during debugging. Check your compiler documentation for the availability
of this feature with your particular compiler. Compile and run comments.c at this time.
How Do We Print Numbers
To keep our promises, 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 when we come to the % character. This is a special
character that signals the output routine to stop copying characters to the output and do something
different, namely output a variable. The % sign is used to signal the start 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 the 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, and after the pattern, there is a comma followed by the variable name "index". This
is where the "printf" statement gets the decimal value which it will output because of the "%d"
we saw earlier. We could add more "%d" output field descriptors within the brackets and more
variables following the description to cause more data to be printed with one statement. Keep
in mind however, that it is important that the number of field descriptors and the number of
variable definitions must be the same or the runtime system will get confused and probably quit
with a runtime error.
Much more will be covered at a later time on all aspects of input and output formatting. A
reasonably good grasp of this topic is necessary in order 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.
Notice that they are all identical and that they all begin just like the "printf" statements we have
seen before. The first difference occurs when we come to the % character. This is a special
character that signals the output routine to stop copying characters to the output and do something
different, namely output a variable. The % sign is used to signal the start 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 the 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, and after the pattern, there is a comma followed by the variable name "index". This
is where the "printf" statement gets the decimal value which it will output because of the "%d"
we saw earlier. We could add more "%d" output field descriptors within the brackets and more
variables following the description to cause more data to be printed with one statement. Keep
in mind however, that it is important that the number of field descriptors and the number of
variable definitions must be the same or the runtime system will get confused and probably quit
with a runtime error.
Much more will be covered at a later time on all aspects of input and output formatting. A
reasonably good grasp of this topic is necessary in order 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.
To Print Some Numbers
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.
main( )
{
int index;
index = 13;
printf("The value of the index is %d\n",index);
index = 27;
printf("The valve of the index = %d\n",index);
index = 10;
printf("The value of the index = %d\n",index);
}
The entry point "main" should be clear to you by now as well as the beginning brace. The first
new thing we encounter is the line containing "int index;", which is used to define an integer
variable named "index". The "int" is a reserved word in C, and can therefore not be used for
anything else. It defines a variable that can have a value from -32768 to 32767 on most MS-DOS
microcomputer implementations of C. It defines a variable with a value from -2147483648 to
2147483647 in HiTech C. Consult your compiler users manual for the exact definition for your
compiler. The variable name, "index", can be any name that follows the rules for an identifier and is not one of the reserved words for C. Consult your manual for an exact definition of an
identifier for your compiler. In HiTech C, the construction of identifier names is the same as
in UNIX, however 31 characters and both cases are significant. The compiler prepends an
underscore to external references in the assembler pass. The final character on the line, the
semi-colon, is the statement terminator used in C.
We will see in a later chapter that additional integers could also be defined on the same line,
but we will not complicate the present situation.
Observing the main body of the program, you will notice that there are three statements that
assign a value to the variable "index", but only one at a time. The first one assigns the value of
13 to "index", and its value is printed out. (We will see how shortly.) Later, the value 27 is
assigned to "index", and finally 10 is assigned to it, each value being printed out. It should be
intuitively clear that "index" is indeed a variable and can store many different values. 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 this liberty, probably due to the
"printf" function being used for monitor display.
work with data in a C program.
main( )
{
int index;
index = 13;
printf("The value of the index is %d\n",index);
index = 27;
printf("The valve of the index = %d\n",index);
index = 10;
printf("The value of the index = %d\n",index);
}
The entry point "main" should be clear to you by now as well as the beginning brace. The first
new thing we encounter is the line containing "int index;", which is used to define an integer
variable named "index". The "int" is a reserved word in C, and can therefore not be used for
anything else. It defines a variable that can have a value from -32768 to 32767 on most MS-DOS
microcomputer implementations of C. It defines a variable with a value from -2147483648 to
2147483647 in HiTech C. Consult your compiler users manual for the exact definition for your
compiler. The variable name, "index", can be any name that follows the rules for an identifier and is not one of the reserved words for C. Consult your manual for an exact definition of an
identifier for your compiler. In HiTech C, the construction of identifier names is the same as
in UNIX, however 31 characters and both cases are significant. The compiler prepends an
underscore to external references in the assembler pass. The final character on the line, the
semi-colon, is the statement terminator used in C.
We will see in a later chapter that additional integers could also be defined on the same line,
but we will not complicate the present situation.
Observing the main body of the program, you will notice that there are three statements that
assign a value to the variable "index", but only one at a time. The first one assigns the value of
13 to "index", and its value is printed out. (We will see how shortly.) Later, the value 27 is
assigned to "index", and finally 10 is assigned to it, each value being printed out. It should be
intuitively clear that "index" is indeed a variable and can store many different values. 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 this liberty, probably due to the
"printf" function being used for monitor display.
Another Program With More Output
Load the program wrtmore.c and display it on your monitor for an example of more output
and another small but important concept. You will see that there are four program statements
in this program, each one being a "printf" function statement. The top line will be executed first
then the next, and so on, until the fourth line is complete. The statements are executed in order
from top to bottom.
main( )
{
printf("This is a line of text to output.\n");
printf("And this is another ");
printf("line of text.\n\n");
printf("This is the third line.\n");
}
Notice the funny character near the end of the first line, namely the backslash. The backslash
is used in the printf statement to indicate a special control character is following. In this case,
the "n" indicates that a "newline" is requested. This is an indication to return the cursor to the
left side of the monitor and move down one line. It is commonly referred to as a carriage
return/line feed. Any place within text that you desire, you can put a newline character and start
a new line. You could even put it in the middle of a word and split the word between two lines.
The C compiler considers the combination of the backslash and letter n as one character. The
exact characters used to indicate a newlin and carriage return are operating system specific.
MS-DOS, Unix, 1616/OS and Macintosh may vary one from the other.
A complete description of this program is now possible. The first printf outputs a line of text
and returns the carriage. The second printf outputs a line but does not return the carriage so the
third line is appended to that of the second, then followed by two carriage returns, resulting in
a blank line. Finally the fourth printf outputs a line followed by a carriage return and the program is complete.
Compile and run this program to see if it does what you expect it to do. It would be a good idea
at this time for you to experiment by adding additional lines of printout to see if you understand
how the statements really work.
and another small but important concept. You will see that there are four program statements
in this program, each one being a "printf" function statement. The top line will be executed first
then the next, and so on, until the fourth line is complete. The statements are executed in order
from top to bottom.
main( )
{
printf("This is a line of text to output.\n");
printf("And this is another ");
printf("line of text.\n\n");
printf("This is the third line.\n");
}
Notice the funny character near the end of the first line, namely the backslash. The backslash
is used in the printf statement to indicate a special control character is following. In this case,
the "n" indicates that a "newline" is requested. This is an indication to return the cursor to the
left side of the monitor and move down one line. It is commonly referred to as a carriage
return/line feed. Any place within text that you desire, you can put a newline character and start
a new line. You could even put it in the middle of a word and split the word between two lines.
The C compiler considers the combination of the backslash and letter n as one character. The
exact characters used to indicate a newlin and carriage return are operating system specific.
MS-DOS, Unix, 1616/OS and Macintosh may vary one from the other.
A complete description of this program is now possible. The first printf outputs a line of text
and returns the carriage. The second printf outputs a line but does not return the carriage so the
third line is appended to that of the second, then followed by two carriage returns, resulting in
a blank line. Finally the fourth printf outputs a line followed by a carriage return and the program is complete.
Compile and run this program to see if it does what you expect it to do. It would be a good idea
at this time for you to experiment by adding additional lines of printout to see if you understand
how the statements really work.
A Program That Does Something
For a much more interesting program, load the program named wrtsome.c and display it on
your monitor. It is the same as the previous program except that it has one executable statement
between the braces.
main( )
{
printf("This is a line of text to output.");
}
The executable statement is another function. Once again, we will not worry about what a
function is, but only how to use this one. In order to output text to the monitor, it is put within
the function parentheses and bounded by quotation marks. The end result is that whatever 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 the line. C uses a semi-colon as a statement terminator,
so the semi-colon is required as a signal to the compiler that this line is complete. This program
is also executable, so you can compile and run it to see if it does what you think it should. With
some compilers, you may get an error message while compiling, indicating the printf() should
have been declared as an integer. Ignore this for the moment.
your monitor. It is the same as the previous program except that it has one executable statement
between the braces.
main( )
{
printf("This is a line of text to output.");
}
The executable statement is another function. Once again, we will not worry about what a
function is, but only how to use this one. In order to output text to the monitor, it is put within
the function parentheses and bounded by quotation marks. The end result is that whatever 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 the line. C uses a semi-colon as a statement terminator,
so the semi-colon is required as a signal to the compiler that this line is complete. This program
is also executable, so you can compile and run it to see if it does what you think it should. With
some compilers, you may get an error message while compiling, indicating the printf() should
have been declared as an integer. Ignore this for the moment.
Getting started in C
The best way to get started with C is to actually look at a program, so load the file named
trivial.c into edit and display it on the monito
Your First C Program
You are looking at the simplest possible C program. There is no way to simplify this program,
or to leave anything out. Unfortunately, the program doesn’t do anything.
main()
{
}
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 you simply include the pair of parentheses.
The two curly brackets { }, properly called braces, are used to define the limits of the program
itself. The actual program statements go between the two braces and in this case, there are no
statements because the program does absolutely nothing. Youcan compile and run this program,
but since it has no executable statements, it does nothing. Keep in mind however, that it is a
valid C program.
trivial.c into edit and display it on the monito
Your First C Program
You are looking at the simplest possible C program. There is no way to simplify this program,
or to leave anything out. Unfortunately, the program doesn’t do anything.
main()
{
}
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 you simply include the pair of parentheses.
The two curly brackets { }, properly called braces, are used to define the limits of the program
itself. The actual program statements go between the two braces and in this case, there are no
statements because the program does absolutely nothing. Youcan compile and run this program,
but since it has no executable statements, it does nothing. Keep in mind however, that it is a
valid C program.
What Is An Identifier?
Before you can do anything in any language, you must at least know how you name an identifier.
An indentifier is used for any variable, function, data definition, etc. In the programming language
C, an identifier is a combination of alphanumeric characters, the first being a letter of the
alphabet or an underline, and the remaining being any letter of the alphabet, any numeric digit,
or the underline. Two rules must be kept in mind when naming identifiers.
1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not
the same as using "index" and neither of them is the same as using "InDex" for a variable. All
three refer to different variables.
2. As C is defined, up to eight significant characters can be used and will be considered
significant. If more than eight are used, they may be ignored by the compiler. This may or may
not be true of your compiler. You should check your reference manual to find out how many
characters are significant for your compiler. The HiTech C compiler used with the Applix 1616
allows 31 significant characters, and prepends an underscore (_)
It should be pointed out that some C compilers allow use of a dollar sign in an identifier name,
but since it is not universal, it will not be used anywhere in this tutorial. Check your documentation to see if it is permissible for your particular compiler.
An indentifier is used for any variable, function, data definition, etc. In the programming language
C, an identifier is a combination of alphanumeric characters, the first being a letter of the
alphabet or an underline, and the remaining being any letter of the alphabet, any numeric digit,
or the underline. Two rules must be kept in mind when naming identifiers.
1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not
the same as using "index" and neither of them is the same as using "InDex" for a variable. All
three refer to different variables.
2. As C is defined, up to eight significant characters can be used and will be considered
significant. If more than eight are used, they may be ignored by the compiler. This may or may
not be true of your compiler. You should check your reference manual to find out how many
characters are significant for your compiler. The HiTech C compiler used with the Applix 1616
allows 31 significant characters, and prepends an underscore (_)
It should be pointed out that some C compilers allow use of a dollar sign in an identifier name,
but since it is not universal, it will not be used anywhere in this tutorial. Check your documentation to see if it is permissible for your particular compiler.
C Boot Disk
Make a new, bootable copy of your 1616 User disk, following the directions in your Users
Manual. To ensure sufficient space, delete any obviously unwanted files you notice on the copy.
Copy the contents of your HiTech C distribution disk to the new disk, keeping the subdirectories
the same as on the HiTech disk.
If you have received any updated C header files or other updates, copy these also to their
respective subdirectories on your new disk.
Using edit, alter the xpath and assign commands in your autoexec.shell file in the
root directory of your new disk.
Your xpath should include /F0/bin (if it is not already included) Add the following lines to your autoexec.shell, to recreate the environment used by Tim Ward when originally running these programs.
assign /hitech /f0/bin
assign /sys /f0/include
assign /temp /rd
This will allow code to be written without regard to where you actually put your files. If you
are using a second drive, or a hard disk, simply change the assign to point /hitech to the
correct drive. Ctends to use temporary files extensively. If you have sufficientmemory available
on your ram disk, use /rd for temporary files. If not, use the current drive and directory, as
indicated by the assign /temp .
Make sure you copy the new C preprocessor relcc.xrel from the user disk into the /bin
subdirectory of your new C disk.
Note that relccexpects by default to find itsClibrary files on the current drive in the /hitech
directory. It also expects to find its include files on the current drive in the /hitech/include
directory. Wewill explain what this means later, and there is a detailed discussion of the HiTech
C compiler at the end of the tutorial.
If all is correct, you can now compile a C file by typing
relcc -v file.c
The -v flag is to invoke the verbose mode, which produces the maximum information from the
compiler.
If you are experimenting, you may prefer to capture any errors encountered in a file, for later
study. If so, use
relcc -v file.c } errorfile
Manual. To ensure sufficient space, delete any obviously unwanted files you notice on the copy.
Copy the contents of your HiTech C distribution disk to the new disk, keeping the subdirectories
the same as on the HiTech disk.
If you have received any updated C header files or other updates, copy these also to their
respective subdirectories on your new disk.
Using edit, alter the xpath and assign commands in your autoexec.shell file in the
root directory of your new disk.
Your xpath should include /F0/bin (if it is not already included) Add the following lines to your autoexec.shell, to recreate the environment used by Tim Ward when originally running these programs.
assign /hitech /f0/bin
assign /sys /f0/include
assign /temp /rd
This will allow code to be written without regard to where you actually put your files. If you
are using a second drive, or a hard disk, simply change the assign to point /hitech to the
correct drive. Ctends to use temporary files extensively. If you have sufficientmemory available
on your ram disk, use /rd for temporary files. If not, use the current drive and directory, as
indicated by the assign /temp .
Make sure you copy the new C preprocessor relcc.xrel from the user disk into the /bin
subdirectory of your new C disk.
Note that relccexpects by default to find itsClibrary files on the current drive in the /hitech
directory. It also expects to find its include files on the current drive in the /hitech/include
directory. Wewill explain what this means later, and there is a detailed discussion of the HiTech
C compiler at the end of the tutorial.
If all is correct, you can now compile a C file by typing
relcc -v file.c
The -v flag is to invoke the verbose mode, which produces the maximum information from the
compiler.
If you are experimenting, you may prefer to capture any errors encountered in a file, for later
study. If so, use
relcc -v file.c } errorfile
Introduction
TheC programming language was originally developed by Dennis Ritchie of Bell Laboratories,
and was designed to run on a PDP-11 with a UNIX operating system. Although it was originally
intended to run under UNIX, there was a great interest in running it on the IBM PC and compatibles, and other systems. C is excellent for actually writing system level programs, and the entire Applix 1616/OS operating system is written in C (except for a few assembler routines). It is an excellent language for this environment because of the simplicity of expression, the compactness of the code, and the wide range of applicability.
It is not a good "beginning" language because it is somewhat cryptic in nature. It allows the programmer a wide range of operations from high level down to a very low level approaching the level of assembly language. There seems to be no limit to the flexibility available. One experienced C programmer made the statement, "You can program anything in C", and the statement is well supported by my own experience with the language. Along with the resulting freedom however, you take on a great deal of responsibility. It is very easy to write a program that destroys itself due to the silly little errors that, say, a Pascal compiler will flag and call a fatal error. In C, you are very much on your own, as you will soon find.
Since C is not a beginners language, I will assume you are not a beginning programmer, and I
will not attempt to bore you by defining a constant and a variable. You will be expected to
know these basic concepts. You will, however, not be expected to know anything of the C
programming language. I will begin with the highest level of C programming, including the
usually intimidating concepts of pointers, structures, and dynamic allocation. To fully understand
these concepts, it will take a good bit of time and work on your part, because they not
particularly easy to grasp, but they are very powerful tools. Enough said about that, you will
see their power when we get there, just don’t allow yourself to worry about them yet.
and was designed to run on a PDP-11 with a UNIX operating system. Although it was originally
intended to run under UNIX, there was a great interest in running it on the IBM PC and compatibles, and other systems. C is excellent for actually writing system level programs, and the entire Applix 1616/OS operating system is written in C (except for a few assembler routines). It is an excellent language for this environment because of the simplicity of expression, the compactness of the code, and the wide range of applicability.
It is not a good "beginning" language because it is somewhat cryptic in nature. It allows the programmer a wide range of operations from high level down to a very low level approaching the level of assembly language. There seems to be no limit to the flexibility available. One experienced C programmer made the statement, "You can program anything in C", and the statement is well supported by my own experience with the language. Along with the resulting freedom however, you take on a great deal of responsibility. It is very easy to write a program that destroys itself due to the silly little errors that, say, a Pascal compiler will flag and call a fatal error. In C, you are very much on your own, as you will soon find.
Since C is not a beginners language, I will assume you are not a beginning programmer, and I
will not attempt to bore you by defining a constant and a variable. You will be expected to
know these basic concepts. You will, however, not be expected to know anything of the C
programming language. I will begin with the highest level of C programming, including the
usually intimidating concepts of pointers, structures, and dynamic allocation. To fully understand
these concepts, it will take a good bit of time and work on your part, because they not
particularly easy to grasp, but they are very powerful tools. Enough said about that, you will
see their power when we get there, just don’t allow yourself to worry about them yet.
Subscribe to:
Comments (Atom)
Google Search
Custom Search