Introduction To Programming

From Programming In C

Table of contents

Introduction

A computer program is an ordered set of instructions that a computer can understand, designed to make a computer perform a specific task (e.g. calculate a wage bill). Computer programming is the art of designing and writing computer programs. The noun art is used to emphasize that programming is not an exact process that can be learned by rote. It is a multi-faceted topic - part problem solving, part lingual, part logic and part mathematical. Consider the stages that are involved in writing a computer program:

  • Define the problem
  • Develop an algorithm
  • Implement the algorithm in a computer language
  • Test the program

Often several of these stages have to be repeated.

Defining the Problem

The problems set in this course should all be clear in terms of what the solution needs to be able to do. In real life this is not always true and it is worth making sure that you understand what is required before embarking on any detailed work. For example, consider being asked to produce some computer code to calculate the average of some numbers. You need to know what sort of average is required (mean, mode, or median?) If it is the mean that required, then is it an arithmetic or a geometric mean? Once you understand what is required then you can move on to the next development stage.

Develop an Algorithm

In the field of computing an algorithm is a finite set of well-defined instructions for accomplishing some task which, given an initial state, will terminate in a corresponding recognizable end-state. A good analogy is a cooking recipe. Given the start conditions (amounts of ingredients) it should be possible to follow the recipe step-by-step to the final product (cake.)

Implement the algorithm in a computer language

The processor chip in a computer works with binary numbers (machine code). In order to make the task of writing code that the computer can understand managable, various so-called "high-level" languages have been developed. There are many different high-level languages with various strengths and weaknesses. Some that you may have heard of are: C, C++ BASIC, Pascal, and FORTRAN. This course will concentrate on the language C. More on this in a moment.

Test the Program

Once written a computer program must be tested. For languages such as C this involves compiling the program to generate code that the computer understands (machine code) and then running the code to see if it works as expected. Various parts of this process may have to be repeated - during the compile stage the grammar or syntax of the program is checked and any errors will have to be corrected. Once compiled the program needs to be run and checked to see if the answer(s) is(are) as expected. If not then the algorithm and the way it has been implemented in C will need to be checked, carefully.

Compiling a Program

As mentioned above, a program written in a high level language needs to be converted into machine code that the computer can run. This is a multistage process:

  • First the source file (http://en.wikipedia.org/wiki/Source_code) is processed by a compiler to produce an object file.
  • Next the object file (http://en.wikipedia.org/wiki/Object_code) is processed by a [Linker (http://en.wikipedia.org/wiki/Linker)] to produce an "executable program" (http://en.wikipedia.org/wiki/Executable) (sometimes called an executable image or binary image. The linker inserts links from the compiled code to code in other files that are necessary for the executable program to interact with the operating system of the computer and other files that may contain precompiled routines written by other people for general use. Such routines are usually stored in a library that which contains one or more pre-compiled routines.

Note: The source code is transferrable between different types of computer whilst in general the executable is not.

Interactive Development Environment

During this course we will be using a so called Interactive Development Environment or IDE called Dev-C++ (http://www.bloodshed.net/devcpp.html) from Bloodshed Software. As well as providing an editor for writing C programs, the IDE automatically performs a lot of the processes that need to be gone through in order to produce an executable. This software package has been chosen because it is the only freely available IDE for the C programming language that works on the Windows operating system. Students can download it free of charge from the web site linked above.

Writing and Compiling a program with DevC++

Compiling a program with Dev-C++ is a fairly straightforward process and is very similar to that used by other IDEs that you may have used in the past such as Microsoft Visual Studio. Dev-C++ optionally organizes programs into projects where all the files associated with a given program are members of a project. In this course, the projects will contain one source file and so we will not be using this feature, complex projects however can contain thousands of files.

The following describes the steps to be taken to open the Dev-C++ compiler, type a program and compile it:

First open the Dev-C++ compiler application via the instructions in the [[devc++ for Windows]] link in the left hand menu bar.

Next select the File menu and choose the New option, selecting Source File

A new, untitled, file will appear in the large area on the right hand side of the window. Type your program into this file. Notice how the program changes the colour of different parts of the program - this is called syntax highlighting and can make the program much more readable. When you are finished, save your program. You should save your program on your U: drive and preferably in a separate folder. AVOID USING LONG FILENAMES AND FILENAMES WITH SPACES IN THEM. In the save dialog box you must select C source files (*.c) in the Save as type option.

Next you can compile and run (execute) your code. It is possible to run the Compile and Run steps separately or together (in which case the Run step will not happen if the program doesn't successfully compile. There are a number of ways of doing this, including:

  1. Using the options under the Execute menu
  2. Using the coloured buttons to the top left of the menu bar
  3. Using the function keys: Compile=CTRL+F9; Run=CTRL+F10, Compile+Run=F9

If all goes well, after selecting Run via one of these methods from you will see your program working in a separate window, e.g.: Example output

If your code does not compile you will be presented with a list of compilation errors. Note that double clicking on any error will highlight the line in your source code which produced the error.

A Simple C Program

Traditionally a computer course begins with the "Hello, world!" (http://en.wikipedia.org/wiki/Hello_world) program. This is a very simple program that outputs the words "Hello, world!" on a computer's display device (usually a screen).

 #include<stdio.h>
 #include<stdlib.h>

 int main(void)
 {
    printf("Hello, world!\n");

    system("pause");
    return 0;
 }

The first 2 lines are known as preprocessor directives (http://en.wikipedia.org/wiki/Preprocessing_directive). The first line accesses the standard C library. The second line must always appear at the beginning of any program that inputs (from the keyboard) or outputs (to the screen) any information.

The next line indicates that a function called main is being declared. The function main has a special role in the C language. In any C program the function main is the first part of the program to be run. The keyword int indicates that the main function will return a value that is an integer (more about this later), void indicates that the function requires no parameters or arguments passing to it.

The code that defines, or makes up, the main function is contained within a set of curly braces { }, this is known as a code block. In this case there are three lines of code:

 printf("Hello, world!\n");

This line calls the function printf, which is declared in the file stdio.h. The single string "Hello, world!\n" is passed to the function. printf outputs this string onto the screen. The \n tells the program to print a new line at the end of the line. printf is dealt with in more detail below.

 system("pause");

This line is not strictly necessary. When you run a program compiled using Dev-C++ a DOS window will be opened on the computer screen and all the output from the program will go there. At the end of the program, this window will disappear. The system("Pause") command makes the program wait until a key is pressed.

 return 0;

Recall that the function main() was declared as returning a value of type int. This line returns a value of zero and terminates the function and in doing so stops the program running. The value returned by main is usually ignored by the computer operating system.

Syntax of a C Program

A natural language such as English allows for great flexibility in terms of grammar. The speech style of character Yoda in the Star Wars films is a good example of what can be tolerated. Computer languages are not so forgiving. Strict rules are placed on what words can be used, the arrangement of expressions and the usage of parameters. These rules define what is known as the syntax of the language. A brief overview of the rules for C is given below. More details will be given as the course progresses.

Layout

Expressions in C are terminated by semicolons (;). The "Hello, world!" program above is formatted so as to make it easier for humans to read (the lines inside the curly braces are indented with spaces). The compiler ignores the extra spaces and it reads the program as:

 #include<stdlib.h>
 #include<stdio.h>
 int main(void){printf("Hello, world!\n");system("pause");return(0);}

Note that each preprocessor directive is ignored by the compiler so it MUST appear on a separate line.

The ability to change the layout of the program with spaces makes C an example of a free-form programming language. Some other languages (e.g. FORTRAN77) have very strict rules about how a program is laid out.

Keywords

A core set of special words, keywords, is defined for C. These are words that cannot be used for any other purpose other than the one defined in the language definition. The set of keywords for C is one of the smallest for any high level language. C has 32 keywords which is less than half the number that C++ has (74). This does not mean that C can do less than half that C++ can. The keywords for C are shown in the table below. The use of most, but not all, of these will be covered in this course.

auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

Variables

Most computer programs will need to store information for later use. This is achieved by reserving space in the computer's memory. The location of this storage space is represented in a computer program as a variable. The information stored at the location is known as the "value" of the variable. C is very strict about the type of data that can be stored in a variable. For example, if a variable is declared to be for integer type data and an attempt is made to store the value 12.3 in this variable then only the integer part of the number (i.e. 12) will be stored. Data types will be studied in detail in topic 2.

The program below gives a brief demonstration of how variables are used

 #include<stdio.h>
 #include<stdlib.h>
 int main(void)
 {
    int x;
    int y;
    int z;

    x=3;
    y=2;
    z=x+y;

    printf("x+y=%d\n",z);
    system("pause");
    return 0;
  }

The first couple of lines of code are the same as for the "Hello, world!" program. The code that defines the main function is a little different. It is divided into 3 blocks of code. The first block declares three variables x,y and z. They are all of type int(i.e. they are treated as integers). The syntax for declaring a variable is:

 variable_type variable_name;

Do not forget the semicolon.

The next block shows how to assign values to the variables. Notice that the syntax is very like that used in mathematics the = and + symbols act as you would expect. It is important to note that the direction of the expressions is important. The lines

 2=y;
 x+y=z;

will not work. The syntax for assigning values to variables is

 variable = expression;

Hopefully you should be able to see that the last two lines of code are used to output the value of z to the screen and to end the program. Notice that there are now two parameters sent to the printf function(command). First there is the string "x+y=%d\n" and then there is the variable z. The "%d" tells the printf function that it is going to output an integer at this point. The variable z tells it which variable to write out.

In a program of this size the names used for the variables are fine and easy to keep track of. In more complex programs a good choice of variable name can make the code significantly easier to read and to follow. C is pretty flexible in terms of allowed variable names. The restrictions are:

  • Must start with a letter.
  • Can only contain letters, numbers and the underscore.
  • May not be one of the C keywords listed above.

C is sensitive to upper and lower cases and and so the following two statements are not the same and create separate variables:

 int Gnome;
 int gnome;

Commenting

Computer programs rapidly become very difficult to follow as they increase in length. C allows programs to be annotated so that the programmer can make it clear what each part of the program does. This annotation is achieved through comments and is ignored by the compiler. A comment is started with the delimiter /* and ended with the delimiter */. Modern C compilers allow a second type of comment, one borrowed from the C++ language. C++ style comments are begun with the delimiter // and terminate at the end of the line. In contrast C style comments can spread across many lines. The code snippet below demonstrates both types of comment.

 /*************************************************
 *                                                *
 *         Program to demonstrate comments        *
 *                                                *
 *   Inputs 2 numbers, outputs the sum of them    *
 *                                                *
 *************************************************/
 #include <stdio.h>
 #include<stdlib.h>

 int main(void)
 {
    int x; // store an integer
    int y; // store an integer

   // first get the 2 integers
    printf("Input first integer\n"); // prompt for first number
    scanf("%d",&x); // get first number, store in x

    printf("Input second integer\n"); // prompt for second number
    scanf("%d",&y); // get second number, store in y

   // Now output result

    printf("The sum of %d and %d is %d\n",x,y,x+y);

    system("pause");
    return 0; // that's it, end now!
 }

You have not been introduced to the scanf command yet, but hopefully you can see from the comments that it is used to input a number from the keyboard.

The usefulness of comments cannot be emphasized enough. They make programs much easier to read. This is useful if your computer code is to be used by other people and it is also useful for yourself because although your code may seem obvious to you at the time of writing it, a couple of days later it could easily seem unintelligible. Comments have no effect on the size or efficiency of the final executable code so put in as many comments as you can. In this course there are occasions when you will reuse old pieces of code that you have written earlier in the course. You are also able to take old programs and modify them during assessments, therefore if your code is well commented it will be easier to reuse it in the future.

Further Reading

A Book on C Kelley and Pohl :

  • Section 1.2 "Program output" pages 6 - 10
  • Section 2.4 "Keywords" page 77
  • Section 1.3 " Variables, Expressions, and Assignment" pages 10 - 13
  • Section 2.3 "Comments" pages 75 - 76.


http://en.wikibooks.org/wiki/Programming:C_Preliminaries


Return to the course summary

phy225: Course Details

general


compilers


2011-12 assessments


past exam papers

  • 2008-9 (http://physics-database.group.shef.ac.uk/exampapers/2008-09/PHY225%20LT.pdf)
  • 2009-10 (http://physics-database.group.shef.ac.uk/exampapers/2009-10/PHY225%20Exam%20Sem%201%202009-10.pdf)
  • 2010-11 (http://physics-database.group.shef.ac.uk/exampapers/2010-11/PHY225_10_11.pdf)