Saturday, June 11, 2005

 

Variables

In C, a variable must be declared before it can be used. Variables can be declared at the start of any block of code, but most are found at the start of each function. Most local variables are created when the function is called, and are destroyed on return from that function.

A declaration begins with the type, followed by the name of one or more variables. For example,

int high, low, results[20];
Declarations can be spread out, allowing space for an explanatory comment. Variables can also be initialised when they are declared, this is done by adding an equals sign and the required value after the declaration.

int high = 250; /* Maximum Temperature */
int low = -40; /* Minimum Temperature */
int results[20]; /* Series of temperature readings */

C provides a wide range of types. The most common are

int An Integer
float A floating point (real) number
char A single byte of memory, enough to hold a character

There are also several variants on these types.

short An integer, possibly of reduced range
long An integer, possibly of increased range
unsigned An integer with no negative range, the spare capacity
unsigned long Like unsigned, possibly of increased range
double A double precesion floating point number

All of the integer types plus the char are called the integral types. float and double are called the real types.

Friday, June 10, 2005

 

Using C with UNIX

Writing the Program

UNIX expects you to store your program in a file whose name ends in .c This identifies it as a C program. The easiest way to enter your text is using a text editor like vi, emacs or xedit. To edit a file called testprog.c using vi type

vi testprog.c

The editor is also used to make subsequent changes to the program.

The C Compiler (cc)

The simplest method is to type

cc testprog.c

This will try to compile testprog.c, and, if successful, will produce a runnable file called a.out. If you want to give the runnable file a better name you can type

cc testprog.c -o testprog

This will compile testprog.c, creating runnable file testprog.

Make, a Program Builder

UNIX also includes a very useful program called make. Make allows very complicated programs to be compiled quickly, by reference to a configuration file (usually called Makefile). If your C program is a single file, you can usually use make by simply typing

make testprog

This will compile testprog.c and put the executable code in testprog.

Improved Type Checking Using Lint

The C compiler is rather liberal about type checking function arguments, it doesn't check bounds of array indices. There is a stricter checker called lint which won't generate any runnable code. It is a good idea to use lint to check your programs before they are completed. This is done by typing

lint testprog.c

Lint is very good at detecting errors which cause programs to crash at run time. However, lint is very fussy, and generally produces a long list of messages about minor problems with the program. Many of these will be quite harmless. Experience will teach you to distinguish the important messages from those which can be ignored.

Running the Program

To run a program under UNIX you simply type in the filename. So to run program testprog, you would type

testprog

or if this fails to work, you could type

./testprog

You will see your prompt again after the program is done.

Thursday, June 09, 2005

 

Fibonacci Series Using an Array

We have now used a variety the features of C. This final example will introduce the array. The program prints out a table of Fibonacci numbers. These are defined by a series in which any element is the sum of the previous two elements. This program stores the series in an array, and after calculating it, prints the numbers out as a table.

#include "stdio.h"

main()
{ int fib[24];
int i;

fib[0] = 0;
fib[1] = 1;

for(i = 2; i < 24; i++)
fib[i] = fib[i-1] + fib[i-2];

for (i = 0; i < 24; i++)
printf("%3d %6d\n", i, fib[i]);
}

One new construct has been introduced here.

int fib[24];
This defines an array called fib of 24 integers. In C, the array index is bounded by square brackets (this avoids confusion with a function call). Also, the first element of the array has index zero, and for this 24 element array, the last element is index 23.

Following this brief scan through the language, we shall introduce the components of C in rather more detail.

Wednesday, June 08, 2005

 

Weight Conversion with Command Line Argument

In this example, the number to be converted is supplied as part of the command to run the program. This can be a useful way of supplying a limited number of names or numbers to a program. We can run the program by typing program 1200 to convert 1200 lbs.

#include <stdio.h>
void print_converted (int pounds)
{
int stones = pounds / 14;
int uklbs = pounds % 14;
float kilos_per_pound = 0.45359;
float kilos = pounds * kilos_per_pound;

printf (" %3d %2d %2d %6.2f\n", pounds, stones, uklbs, kilos);
}

main (int argc, char *argv[])
{
int pounds;
if (argc !=2)
{
printf("Usage: convert weight_in_pounds \n");
exit(1);
}
sscanf(argv[1], "%d", £s);
printf(" pounds stones uklbs kilos\n");
print_converted(pounds);
}

The main function definition has changed so that it takes two arguments, argc is a count of the number of arguments, and argv is an array of strings containing each of the arguments. The system creates these when the program is run.

Some other new concepts are introduced here.

if(argc != 2) Checks that the typed command has two elements, the command name and the weight in pounds.

exit(1); Leave the program. The argument 1 is a way of telling the operating system that an error has occurred. A 0 would be used for a successful exit.

sscanf(argv[1], "%d", £s) Converts a string like "100" into an integer value stored in pounds. The argument is stored in argv[1] as a string. sscanf works like scanf, but reads from a string instead of from the terminal.

 

Weight Conversion with a Prompt

To illustrate this, our next program will re-use the function from 2.3. The program is similar to the last one, but instead of printing a table of weights, the user enters a weight, and this value is converted. Such a program requires user input. This can be done in two ways, both of which will be shown.

The simpler implementation is to prompt for a weight, and then read the user's keyboard input. This would be done as follows

#include

void print_converted(int pounds)
/* Convert U.S. Weight to Imperial and International
Units. Print the results */
{ int stones = pounds / 14;
int uklbs = pounds % 14;
float kilos_per_pound = 0.45359;
float kilos = pounds * kilos_per_pound;

printf(" %3d %2d %2d %6.2f\n",
pounds, stones, uklbs, kilos);
}

main()
{ int us_pounds;

printf("Give an integer weight in Pounds : ");
scanf("%d", &us_pounds);

printf(" US lbs UK st. lbs INT Kg\n");
print_converted(us_pounds);
}

A printf statement is used to prompt for input. scanf is an equivalent input statement, note that the variable to be read us_pounds is written as &us_pounds here. This is very important and it will be explained later.

Tuesday, June 07, 2005

 

Weight Conversion Table Using a Function

The previous program could be better structured by defining a function to convert the weights and print out their values. It will then look like this.

#include

void print_converted(int pounds)
/* Convert U.S. Weight to Imperial and International
Units. Print the results */
{
int stones = pounds / 14;
int uklbs = pounds % 14;
float kilos_per_pound = 0.45359;
float kilos = pounds * kilos_per_pound;
printf(" %3d %2d %2d %6.2f\n",pounds, stones, uklbs, kilos);

}

main()
{ int us_pounds;

printf(" US lbs UK st. lbs INT Kg\n");

for(us_pounds=10; us_pounds < 250; us_pounds+=10)
print_converted(us_pounds);
}


void print_converted(int pounds) is the beginning of the function definition. The line within the loop reading print_converted(us_pounds) is a call to that function. When execution of the main function reaches that call, print_converted is executed, after which control returns to main.

The text enclosed by symbols /* and */ is a comment. These are C's way of separating plain text comments from the body of the program. It is usually good practice to have a short comment to explain the purpose of each function.

Defining a function has made this program larger, but what have we gained? The structure has been improved. This may make little difference to the readability of such a small program. In a larger program, such structuring makes the program shorter, easier to read, and simplifies future maintenance of the program. Another benefit of defining a function, is that the function can easily be re-used as part of another program.

 

A Weight Conversion Program

#include
#define KILOS_PER_POUND .45359
main()
{ int pounds;

printf(" US lbs UK st. lbs INT Kg\n");

for(pounds=10; pounds < 250; pounds+=10)
{ int stones = pounds / 14;
int uklbs = pounds % 14;
float kilos = pounds * KILOS_PER_POUND;
printf(" %d %d %d %f\n",
pounds, stones, uklbs, kilos);
}
}

Again notice that the only function is called main.

int pounds; Creates a variable of integer type called pounds.

float kilos; Creates a floating point variable (real number) called kilos.

#define KILOS_PER_POUND .45359
defines a constant called KILOS_PER_POUND. This definition will be true throughout the program. It is customary to use capital letters for the names of constants, since they are implemented by the C preprocessor.

for(pounds=10; pounds < 250; pounds+=10)
This is the start of the loop. All statements enclosed in the following curly brackets will be repeated. The loop definition contains three parts separated by semi-colons.

The first is used to initialise variables when the loop is entered.
The second is a check, when it proves false, the loop is exited.
The third is a statement used to modify loop counters on each loop iteration after the first.
The effect of pounds += 10 is to add 10 to the value of the variable pounds. This is a shorthand way of writing pounds = pounds + 10.

The printf statement now contains the symbols %d and %f. These are instructions to print out a decimal (integer) or floating (real) value. The values to be printed are listed after the closing quote of the printf statement. Note also that the printf statement has been split over 2 lines so it can fit onto our page. The computer can recognise this because all C statements end with a semicolon.

 

A Very Simple Program

This program will print out the message "This is a C program"

#include
main()
{
printf("This is a C program\n");
}

Though the program is very simple, a few points are worthy of note.

Every C program contains a function called main. This is the start point of the program.

#include allows the program to interact with the screen, keyboard and filesystem of your computer. You will find it at the beginning of almost every C program.

main() declares the start of the function, while the two curly brackets show the start and finish of the function. Curly brackets in C are used to group statements together as in a function, or in the body of a loop. Such a grouping is known as a compound statement or a block.

printf("This is a C program\n"); prints the words on the screen. The text to be printed is enclosed in double quotes. The \n at the end of the text tells the program to print a newline as part of the output.

Most C programs are in lower case letters. You will usually find upper case letters used in preprocessor definitions (which will be discussed later) or inside quotes as parts of character strings. C is case sensitive, that is, it recognises a lower case letter and it's upper case equivalent as being different.

While useful for teaching, such a simple program has few practical uses. Let us consider something rather more practical. The following program will print a conversion table for weight in pounds (U.S.A. Measurement) to pounds and stones (Imperial Measurement) or Kilograms (International).

Sunday, June 05, 2005

 

Dialects of C

Common C
Until recently there was one dominant form of the C language. This was the native UNIX form, which for historical reasons is known as either Bell Labs C, after the most popular compiler, or K. &R. C, after the authors of the most popular textbook on the language. It is now often called "Classic C"

ANSI C
The American National Standards Institute defined a standard for C, eliminating much uncertainty about the exact syntax of the language. This newcomer, called ANSI C, proclaims itself the standard version of the language. As such it will inevitably overtake, and eventually replace common C.

ANSI C does incorporate a few improvements over the old common C. The main difference is in the grammar of the language. The form of function declarations has been changed making them rather more like Pascal procedures.

This course introduces ANSI C since it is supported by the SUN workstation compilers. Most C programming texts are now available in ANSI editions.

 

C and Unix

This course teaches C under the UNIX operating system. C programs will look similar under any other system (such as VMS or DOS), some other features will differ from system to system. In particular the method of compiling a program to produce a file of runnable code will be different on each system.

The UNIX system is itself written in C. In fact C was invented specifically to implement UNIX. All of the UNIX commands which you type, plus the other system facilities such as password checking, lineprinter queues or magnetic tape controllers are written in C.

In the course of the development of UNIX, hundreds of functions were written to give access to various facets of the system. These functions are available to the programmer in libraries. By writing in C and using the UNIX system libraries, very powerful system programs can be created. These libraries are less easy to access using other programming languages. C is therefore the natural language for writing UNIX system programs.

 

About C Language

As a programming language, C is rather like Pascal or Fortran. Values are stored in variables. Programs are structured by defining and calling functions. Program flow is controlled using loops, if statements and function calls. Input and output can be directed to the terminal or to files. Related data can be stored together in arrays or structures.

Of the three languages, C allows the most precise control of input and output. C is also rather more terse than Fortran or Pascal. This can result in short efficient programs, where the programmer has made wise use of C's range of powerful operators. It also allows the programmer to produce programs which are impossible to understand.

Programmers who are familiar with the use of pointers (or indirect addressing, to use the correct term) will welcome the ease of use compared with some other languages. Undisciplined use of pointers can lead to errors which are very hard to trace. This course only deals with the simplest applications of pointers.

It is hoped that newcomers will find C a useful and friendly language. Care must be taken in using C. Many of the extra facilities which it offers can lead to extra types of programming error. You will have to learn to deal with these to successfully make the transition to being a C programmer.

This page is powered by Blogger. Isn't yours?