4. An Introduction to C Programming

4.1 Why Use C?

• ‘C’ is commonly used to produce operating systems and commercial software. Some examples of these are UNIX, Lotus-123, dBase, and some ‘C’ compilers.

• Machine Portable, which means that it requires only small changes to run on other computers.

• Very Fast, almost as fast as assembler.

• Emphasizes structured programming, by focusing on functions and subroutines.

• You may easily customize ’C’ to your own needs.

• Suited to Large and Complex Programs.

• Very Flexible, allows you to create your own functions.

• Developed at Bell Laboratories in the Early 70’s, and commercial compilers became available in the Late 70’s.Recnetly has become more popular because of its ties to UNIX. Over 90% of UNIX is written in ‘C’. AT&T originally developed ‘C’ with the intention of making it an in-house standard.

4.2 Syntax

Basic elements

/* is the start of a comment.

*/ is the end of comment.

The main program is treated like a function, and thus it has the name main().

lower/UPPER case is crucial, and can never be ignored.

Statements are separated by semi-colons ‘;’

Statements consist of one operation, or a set of statements between curly brackets {, }

There are no line numbers.

lines may be of any length.

• A very common function in ‘C’ is printf(). This function will do a formatted print. The format is the first thing which appears between the brackets. In this case the format says print an integer %d followed by a space then a ‘+’ then another space, another integer, another space, ‘=’, and another space, another integer, then a line feed ‘\n’. All variables that follow the format statement are those to be printed. x, y, and z are the three integers to be printed, in their respective orders.

• Major Data Types for variables and functions are (for IBM PC):

int (2 byte integer),

short (1 byte integer),

long (4 byte integer),

char (1 byte integer),

float (4 byte IEEE floating point standard),

double (8 byte IEEE floating point standard).

•int, short, long, char can be modified by the addition of unsigned, and register. An unsigned integer will not use 1 bit for number sign. A register variable will use a data register in the microprocessor, if possible, and it will speed things up (this is only available for integers).

 

• A function consists of a sub-routine or program, which has been assigned a name. This function is capable of accepting an argument list, and returning a single value. The function must be defined before it is called from within the program. (e.g. sin() and read()).

 

• Every variable has a scope. This determines which functions are able to use that variable. If a variable is global, then it may be used by any function. These can be modified by the addition of static, extern and auto. If a variable is defined in a function, then it will be local to that function, and is not used by any other function. If the variable needs to be initialized every time the subroutine is called, this is an auto type. static variables can be used for a variable that must keep the value it had the last time the function was called. Using extern will allow the variable types from other parts of the program to be used in a function.

 

• Other variable types of variables are union, enum, struct, etc.

• Some basic control flow statements are while(), do-while(), for(), switch(), and if(). A couple of example programs are given below which demonstrate all the ’C’ flow statements.

 

 

 

 

• #include <filename.h> will insert the file named filename.h into the program. The *.h extension is used to indicate a header file which contains ‘C’ code to define functions and constants. This almost always includes “stdio.h”. As we saw before, a function must be defined (as with the ‘add’ function). We did not define printf() before we used it, this is normally done by using #include <stdio.h> at the top of your programs. “stdio.h” contains a line which says ‘int printf();’. If we needed to use a math function like y = sin(x) we would have to also use #include <math.h>, or else the compiler would not know what type of value that sin() is supposed to return.

•#define CONSTANT TEXT will do a direct replacement of CONSTANT in the program with TEXT, before compilation. #undef CONSTANT will undefine the CONSTANT.

 

• #ifdef, #ifndef, #if, #else and #else can be used to conditionally include parts of a program. This is use for including and eliminating debugging lines in a program.

• #define, #include, #ifdef, #ifndef, #if, #else, /* and */ are all handled by the Preprocessor, before the compiler touches the program.

• Matrices are defined as shown in the example. In ‘C’ there are no limits to the matrix size, or dimensions. Arrays may be any data type. Strings are stored as arrays of characters.

• i++ is the same as i = i + 1.

 

• Pointers are a very unique feature of ‘C’. First recall that each variable uses a real location in memory. The computer remembers where the location of that variable is, this memory of location is called a pointer. This pointer is always hidden from the programmer, and uses it only in the background. In ‘C’, the pointer to a variable may be used. We may use some of the operations of ‘C’ to get the variable that the pointer, points to. This allows us to deal with variables in a very powerful way.

 

4.3 How A C Compiler Works

• A ‘C’ compiler has three basic components: Preprocessor, First and Second Pass Compiler, and Linker.

 

4.4 Structured C Code

• A key to well designed and understandable programs.

• Use indents, spaces and blank lines, to make the program look less cluttered, and give it a block style.

• Comments are essential to clarify various program parts.

• Descriptive variable names, and defined constants make the purpose of the variable obvious.

• All declarations for the program should be made at the top of the program listing.

 

4.5 Architecture of C Programs (Top Down)

4.5.1 How?

• A program should be broken into fundamental parts (using functions for each part) and then assembled using functions. Each function consists of programs written using the previous simpler functions.

 

• A Clear division should be maintained between program levels.

• Never use goto’s, they are a major source of logic errors. Functions are much easier to use, once written.

• Try to isolate machine specific commands (like graphics) into a few functions.

4.5.2 Why?

• A top-down design allows modules to be tested as they are completed. It is much easier to find an error in a few lines of code, than in a complete program.

• When programs are complete, errors tend to be associated with modules, and are thus much easier to locate.

• Updates to programs are much easier, when we only need to change one function.

• It is just as easy to change the overall flow of a program, as it is to change a function.

Application of ‘C’ to a CAD Program

4.6 Creating Top Down Programs

1. Define Objectives: Make a written description of what the program is expected to do.

2. Define Problem: Write out the relevant theory. This description should include variables, calculations and figures, which are necessary for a complete solution to the problem. From this we make a list of required data (inputs) and necessary results (output).

3. Design User Interface: The layout of the screen(s) must be done on paper. The method of data entry must also be considered. User options and help are also considered here. (There are numerous factors to be considered at this stage, as outlined in the course notes.)

4. Write Flow Program: This is the main code that decides when general operations occur. This is the most abstract part of the program, and is written calling dummy ‘program stubs’.

5. Expand Program: The dummy ‘stubs’ are now individually written as functions. These functions will call another set of dummy ‘program stubs’. This continues until all of the stubs are completed. After the completion of any new function, the program is compiled, tested and debugged.

6. Testing and Debugging- The program operation is tested, and checked to make sure that it meets the objectives. If any bugs are encountered, then the program is revised, and then retested.

7. Document: At this stage, the operation of the program is formally described. For Programmers, a top-down diagram can be drawn, and a written description of functions should also be given.

Golden Rule: If you are unsure how to proceed when writing a program, then work out the problem on paper, before you commit yourself to your programmed solution.

Note: Always consider the basic elements of Software Engineering, as outlined in the ES488 course notes.

4.7 Problems

Problem 4.1 What are the basic components of a ‘C’ compiler, and what do they do?

Problem 4.2 What are some reasons for using ‘C’ as a programming language?

Problem 4.3 Describe some of the reasons for Using Top-Down Design, and how to do it.