~ Introduction to Programming: C ~

Session 1 - A First Glimpse at the C Language

<<  Back to Contents Page

Session 1 – A First Glimpse at the C Language

Introduction to C

C is a programming language that is used widely in industry either in its original form, or more widely in the object-oriented form C++.

You will find that a lot of business programming that takes place in Unix environments involves the writing of C programs. Many modern applications have been written in C++ - it was one of the first programming languages to comprehensively employ a rich set of object-orientated features. More modern language like C# and Java however have extended this further with principles such as the Interface (which makes the impossibly complex principle of multiple inheritance redundant) and name-spaces.

In Dennis M. Ritchie's words (one of the founders of C):-

C is quirky, flawed, and an enormous success. While accidents of history surely helped, it evidently satisfied a need for a system implementation language efficient enough to displace assembly language, yet sufficiently abstract and fluent to describe algorithms and interactions in a wide variety of environments.

A Brief History of C

The C Programming language was developed by Bell Laboratories in the early seventies. It was borne from two other languages – BCPL, which was closer to Assembly Language, and B, which introduced a lot of the structures that are use in C today. C introduced such things as character types and floating point arithmetic, structures, the preprocessor, and portability.

The principle aim of the object was to devise a language that was easy enough to understand to be "high-level" – i.e. understood by humans, but low-level enough to be applicable to the writing of systems-level software – in particular, the PDP-11 based Unix operating system. In this way, both flexibility and usability could be achieved. The idea was that the language should abstract the details of how the computer achieves its tasks in such a way as to ensure that C could be portable across different types of computers, and thus the Unix operating system could be compiled on other computers with a minimum of re-writing.

C as a language was in use by 1973, although extra functionality, such as new types, were introduced up until 1980.

In 1978, Brian Kernighan and Dennis M. Ritchie wrote the seminal work The C Programming Language, which is now the standard reference book for C.

The X3J11 committee produced a formal ANS standard for C in 1989, which became the standard ISO/IEC 9899-1990.

In 1986, a descendant of C, called C++ was developed by Bjarne Stroustrup, and has now become the standard C in use in industry today. Other versions of C were also developed, such as Concurrent C [89], Objective C [86], C* [90] and most recently, Microsoft's C#.

For a more complete history, see Dennis M. Ritchie's web page at http://cm.bell-labs.com/cm/cs/who/dmr/chist.html.

C Integrated Development Environments

When writing a C program, modern versions of the language are usually accompanied with an IDE or Integrated Development Environment. These applications allow you to write the program, organize your source code, debug your programs, compile them, build them into a final executable to be distributed, and execute the programs, as well as a number of associated tasks, such as looking-up on-line help on various aspects of the language and IDE.

On this course, we will be using the Borland C++ Builder 4 compiler. Available from the SimonHuggins.com web site it the Turbo C++ Lite compiler (DOS based, but very small and fast) and the Borland C++ Builder (v1) compiler.

If you wish to purchase a more modern compiler, you can purchase an academic version of C++ Builder 5/6 Professional on the Amazon.co.uk web site, or try Borland's web site at http://shop.borland.co.uk - or the Standard edition which is fine for learning purposes for about £20 cheaper.

What is a Project?

Programs built using C++ Builder (and many modern IDEs) are organized into project.

A project will store information about the application that you are working on. Inside a project, you can store one or more source code files (i.e. the C programs you are working on). You can also store other files, such as header files, form files (if you are working with the visual form environment within C++ Builder), together with information about who is working on the project, its current version, and even what files should automatically be opened and available, and the cursor position within the last program you were editing.

Your first Project

To create a project, start up C++ Builder if you have not done so already, and click on the File menu followed by the New… menu option. In older versions of C++ Builder (e.g. v1) you will see an icon that looks something like the icon on the left. In newer versions (e.g. v4), it will look like the icon on the right. Click on whichever one you see, and click on the OK button.

On newer versions of the program, you will see the Console Wizard, which will look something like the picture to the right. Accept the default settings by clicking on the OK button.

You can use the code given as a default, if you wish.

Alternatively, if you wish your program to look exactly like those that you are typing in, then follow these instructions:  Click on the Edit menu and choose the Select All option. Now press the Delete button. You are ready to type in your program from scratch.

To save the project, and any changes made to your program, click on the  button on the toolbar, or alternatively hold down the Ctrl key and press S.

You will be asked to give a name and location for your project (initially called Project1). Give it a name, ending with .mak – e.g. myproj.mak and click on Save to save the project. The C program will automatically be saved with the same name as the project, but with an ending of .cpp (for C Plus Plus). Most C programs end with .C but C++ Compilers invariably recognize C source code, so it is fine to leave this as it is.

 Having saved your file, you can now type out your program, and when you save again, the changes will automatically be saved to the files you originally chose. It's a good idea to save a blank program in advance, as it means that saving periodically whilst writing your program is easier and quicker, thus reducing the chance of losing your program if anything goes wrong.

Opening a project

 If you need to open a project up to change or run a program again, click on the File menu and click on Open Project… and select a  project name (ending with .mak) to open. Alternatively, hold down the Ctrl key and press F11 to do the same.

You can also open one of the most recently used projects by clicking on File, choosing the Recent menu item, and selecting one of the projects from the sub-menu that then appears.

Your First C Program

Create a new blank program and project as described above.

 Type out the following program:-

#include <stdio.h>

#include <conio.h>

 

void main() {

  printf("Hello World!\n");

  getch();

}

 Now compile the program to check that you have typed it in correctly (i.e. the syntax is correct). You can do this in one of three ways:-

  If you used Ctrl+F9, this will display the dialog box shown on the right, hopefully with no Warnings and no Errors. Click on the OK button when you have finished.

 To execute the application to see what it does, then do one of the following:-

 A black console window is opened displaying the words Hello World! The program then waits for you to press a key at the keyboard, after which the console window disappears.

So how does it work?  The command #include is what is known as a pre-processor command.  This means that the command gets processed prior to being compiled. In general, any commands beginning with a # occur before compilation takes place.

 In this case, the pre-processor will look for a C program in a file called stdio.h – the square brackets around the filename mean that the program will look in the same directory that the current program resides, and also on the standard search path.

This program gets inserted or included  at the point where the #include statements occur. Thus, any commands within the stdio.h program get treated as if they were part of the main program.

In this way, standard functions that are useful in lots of programs can be made available to your programs.

Note that the stdio.h library contains functions to do with general in/out processes (e.g. writing to the screen or a file), whereas conio.h contains functions to do with the black console window (e.g. clearing the screen, waiting for a key to be pressed etc.)

Compare the #include command to the uses command in Pascal.

 The next line void main() { } declares a new function called main.  All programs in C must have a function called main. This identifies the commands that will be executed when the program is run – it is rather like what appears between the begin and end. Of a Pascal program. The opening curly brace { is like the begin of a Pascal program. The closing curly brace } is like the end. of a Pascal program.

 Thus the line between these braces is the program that is to be executed:-

 printf("Hello World!\n");

 is a standard function (available from the stdio.h library) which puts something out to the console stream – i.e. writes something to the screen. As in Pascal, text string constant values start with a double-quote “ and end with another double-quote “,

The \n is another way of saying “new line” – it writes a new line – i.e. moves the cursor to the next line down and puts it at the left hand side of the screen.

 Finally, the getch() function is taken from the conio.h library, and waits for a key to be pressed, and returns the character representing the key that was pressed. In this case, the value returned is ignored, as we are just using the functions as a means to see what is on the console window before it disappears. Try removing the getch() command from the program and running it again, and you'll see why we need to do this.

Debugging

 Debugging is the act of locating and correcting errors or mistakes in your programs. Compiling your program will take some of the pain out of locating problems – it checks to see whether your program conforms with the rules for how a C program should be structured. Type in the following program exactly as shown, and try to compile it:-

#include <stdio.h>

#include <conio.h>

 

int main() {

  for(int i=1;i<=10;i++)

    printf('i is %d',i+++);

  getch();

}

 The program is intended to count from 1 to 10 and display the count on the screen, one line at a time.

 You will get an error message saying that “Character constant must be one or two characters long”. This appears at the bottom of your listing in a separate box.

 You also get another error message saying "Expression Syntax" immediately beneath it. Try double-clicking on this. Notice that the cursor is placed at the end of the line, just after where the compiler thinks the problem might be. Try double-clicking on the first error message again. The cursor goes back to just after the opening quote. You can skip from one error to another in this manner so that you can cure as many bugs as possible without having to compile again. Sometimes one errors causes many other errors. In this case, look only at the first error, and try compiling again.

 The first error (Character constant must be one or two characters long) indicates (rather indirectly) that the use of the single-quotes is probably incorrect – they are used with single-character constants. We should have used double-quotes. So replace the single-quotes with double-quotes, and try compiling again.

This time you see the second error message, saying “Expression syntax” – not very helpful, but at least we can see that the problem towards the end of line 6. If we look carefully, we can see that there are three +s after the i rather than two. So delete the third + and compile again.

This time, we get no error messages.

 Click on the  button to run (execute) the program. The results are as follows:-

 

 We can see two problems here. The program is counting every second number, and it is not putting each count on a separate line.

 To put the number on each line, we would alter the program to add a \n to the end of the text as follows:-

 printf("i is %d\n",i++);

 Make this change, and try Compiling and running the program again. Results should be as follows:-

 

 There is still the problem of the number having 2 added to it each time around the loop. Let’s investigate to see what is happening.

 Click on the line where the printf statement appears. Now set a breakpoint by using one of these three methods:-

This highlights the line in red to indicate that execution of the program will be suspended at that point for you to see what is happening. Now try running the program again.

 The program runs, and execution stops, with an arrow appearing to the left of the line of code where execution is currently paused.

 If you want to see what the value of the i variable is at this point as a one-off, hold down the Ctrl button and press F7.

If you type in the expression as being i, and click on the Evaluate button, the value of the expression will be calculated (1 to start with). You could choose a new value for i at this point, if you thought it would help, by placing a different value in the New value box and clicking on the Modify button.

 The result is 1, so before the highlighted command gets runs, the value of i is 1. So i must be being changed after the text gets displayed.

 Click on the Close button to close the expression evaluator.

 If you wish to see how the value of i is changing each time the program stops at the breakpoint, then it may be better to use a watchpoint. Press Ctrl+F5. Enter i in the expression box and click on the OK button. The value of i gets displayed in a floating box. Now each time you click on the run ( ) button to resume the program, it will continue, and stop again at the breakpoint, showing the new value of i. Unfortunately, the window gets placed behind the code window each time you click on the run button, so you will need to click on the watch window to bring it back to the top again.

 If we look carefully, i++ happens twice each loop. If we take the second ++ away as follows, the problem should disappear:-

printf("i is %d\n",i);

 You may wish to take the breakpoint off now that you have located the problem. To do this, ensure you are clicked onto the line with the breakpoint on (i.e. highlighted in red) and press the F5 button once again to take the red highlighting and thus the breakpoint off. Alternatively, just click to the left of the line again, and that will also take the breakpoint off.

 The results should now be as follows when you compile and run the program:-

 

 That's better!

The listing now looks like this after our various debugging attempts:-

#include <stdio.h>

#include <conio.h>

 

void main() {

  for(int i=1;i<=10;i++)

      printf("i is %d\n",i);

  getch();

}

 Don't worry if this loses you a bit as to what each statement does in the program – the important thing is to understand the process we go through in order to debug the program. You will be applying this later when you write programs of your own.

Exercises

  1. Try closing down the C IDE and open it up again. Try finding and opening the project you were working on, compile it, and run it again.
  2. Create a new program that prints out to the screen the text "Hello everybody" and then on the next line down (remember that \n within text means a new line), the text "This is my program."  Compile and run it. Save it as hello.mak for the project and hello.cpp for the program, in the c:\temp directory.
  3. Open the COUNT.C program again, and alter it to count from 10 down to 1 by changing the line containing the for as follows:

  for(int i=10;i>=1;i--)

  1. If you have some time, try running and saving the following program. It shows how you can do some clever programming in C with just a few programming statements. However, it also shows how difficult to decipher C can be:-

#include <stdio.h>

#include <stdlib.h>

#include <conio.h>

#include <ctype.h>

void main() { char user,computer; clrscr(); randomize();

  printf("Stone Knife Paper Game\n----------------------\n\n");

  printf("Press S for stone, K for Knife, or P for Paper: ");

  printf("%c\nComputer Chose %c\n\n",

    user=toupper(getch()),computer="SKP"[rand()%3]);

  printf("%s Won.\n\nPress a key to finish. ",

      "Nobody\0You\0Computer\0"+(user==computer ? 0 :

      (((user=='S')&&(computer=='K'))||((user=='K')&&(computer=='P'))||

      ((user=='P')&&(computer=='S')) ? 7 : 11))); getch(); }

 It is a version of the "Scissors Knife Paper" game.

 Over the page is a more understandable, if little more verbose example, that does exactly the same job:-

 Stone Knife Paper Program – Better-Structured Version

/*

** Stone Knife Paper Game

** by Simon Huggins - 5th February 2002

*/

 

#include <stdio.h>

#include <stdlib.h>

#include <conio.h>

#include <ctype.h>

#include <string.h>

 

void main() {

 

  /* User / Computer store the User's and Computer's choices */

  char user,computer;

  /* i is a temporary variable to store a random number from 0 to 2 */

  int i;

  /* str stores a string of chracters to show who won */

  char str[10];

 

  /* Clear the screen and randomize numbers */

  clrscr(); randomize();

 

  /* Print the title and prompt */

  printf("Stone Knife Paper Game\n");

  printf("----------------------\n\n");

  printf("Press S for stone, K for Knife, or P for Paper: ");

  user=toupper(getch());

 

  /* Show User's choice */

  printf("%c\n",user);

 

  /* Choose S, K or P at random for the computer */

  i=rand()%3;

  switch(i) {

    case 0 : computer = 'S'; break;

    case 1 : computer = 'K'; break;

    default  : computer = 'P';

  }

 

  /* Show the computer's choice */

  printf("Computer Chose %c\n\n",computer);

 

  /* Determine and show who won */

  if (user==computer)

    strcpy(str,"Nobody");

  else if (((user=='S')&&(computer=='K'))||

          ((user=='K')&&(computer=='P'))||

          ((user=='P')&&(computer=='S')))

    strcpy(str,"You");

  else

    strcpy(str,"Computer");

  printf("%s Won.\n\n",str);

 

  /* Closing message and await a keypress */

  printf("Press a key to finish. ");

  getch();

 

}

 As it is, we have not yet learned the basic syntax to say how this all fits together. However, you should be able to see certain similarities with Pascal – e.g. begin and end are replaced with { and }, the write and  writeln statements are replaced with printf, variable assignments use = instead of :=, comments start with a /* and end with a */ instead of pascal which start with a { and end with a }.  The if statement is very much the same, except the command before an else is terminated with a ; whereas the ; would be omitted with Pascal, and also the condition that is tested must be enclosed in brackets ( and ). The condition to see if two variables or values are the same is a double-equals too, instead of a single-equals.

 We'll get used to these differences as we work our way through the course, but for the moment this gives you a flavour of what is to come.

Next Session

We will be looking a little more closely at the structure of a C program. We will be looking at libraries and includes (what they are) and looking a little more into the C pre-processor and what it does. We will be covering some programming fundamentals such as the use of variables, constants, and the different data types involved. We will look at how to convert between the different data types, and at arithmetic in C, and precedence rules. We will also look at how to comment your program to make it easier to follow.

Finally, we'll take a first look at printf, to show data on the screen.