~ 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

Welcome to the course in Beginner's C Programming, held at Northampton College. Your course tutor is Simon Huggins, who will be taking you through and facilitating your learning of the details of this course.

The course lasts for thirty weeks, with each session running to approximately three hours. Each session starts promptly at 6.00pm in order to prevent finishing too late. Refreshments will be available from 5.45pm, with a short break at around 7.40 for approximately twenty minutes.

Each session will start with an recap of the previous session, and overview of the topics to be covered in the coming session, and at the end, a summary of that session. Each session will be taught using a mixture of seminar-style teaching, demonstration, and a chance to try out what has been learned with a practical session.

In This Session...

In this session we will be covering the following topics:-

A bit about me

I work locally in Northampton with a company called Scottish And Newcastle Retail, which owns a few thousand pubs, restaurants, and hotel lodges. Example pubs in Northampton include the Rat & Parrot, Fish, Britannia, Greyhound, Quays and Red Lion at Brafield.

I am an Analyst / Programmer working with a system called PeopleSoft that deals with Accounts and Human Resources. It uses its own proprietary programming language designed for business working.

Having graduated from the University of Sheffield in 1995, I obtained a good knowledge of object-oriented concepts, and immediately took up a remarkable new programming language called Delphi which is still going strong today with version 7.  Based on the Pascal programming language, it took the reins from Visual Basic and introduced a visual programming environment with database facilities, and a proper structured and object-oriented programming language.

I have been programming with the C language since college days, using it regularly for 'batch' style programming in Unix - i.e. business data processing applications.

I have a web site, located at http://www.simonhuggins.com which features my main interests, including the writing of software to be distributed across the internet, mostly written in Delphi.

In case you're interested, I'm married, with two inherited children and now I'm a sort-of-grandfather! At the tender age of 30! Photos are on my web site. I also have an interest in poetry, writing fiction, and somehow fell into creating a web site for fans of the US TV Series Beauty And The Beast that was around in the late eighties / early nineties.

Just goes to prove that, even in this day and age, programmers are still often strange creatures.

Registration / Contact Details

Registration will take place at the start of this session. At the start of each subsequent session, your attendance will be marked a register to confirm your attendance.  This is used both for statistical purposes (and so I can track who has had which handouts!) and also in order to secure the appropriate funding for the course.

Later this term, you will be able to register to take the exam, which will give you one module in the City and Guilds 9531 Introductory Computer Programming programme. Details to follow.

If you will be absent for a session, please telephone the ITAS department on (01604) 734271 as soon as possible.  If you do not show up for four sessions in a row without an appropriate reason, it will be assumed that you know longer wish to continue with the course, and your name will be withdrawn from the course.

If you need to talk to somebody in the college, please contact Jonathon Halliday (my tutor) on  (01604) 734273 or by emailing him at JonathonH@northamptoncollege.ac.uk

 If you need to get in touch with me, you can contact me by emailing c@simonhuggins.com or telephoning my messaging service on 07050-618-297 or by faxing 07050-618-298.  Messages will be forwarded to me at work, so I should get any message sent up to about 4pm.

The course notes are available from my web site at http://www.simonhuggins.com/courses/cbasics/ and will be updated mostly every week during the course.  If you are absent one week, you can obtain a copy of the course notes from this location.

A printed copy of the notes will be given after any appropriate revisions are made in the week following.

Course Objectives

Upon completing this course, you should have an understanding of the following topics:-

The course looks at a variety of different types of programs that C could be used for, from arithmetic/financial/statistical computations, to a name and address book, to simple games, to working out your personal biorhythms and finding out which day you were born on!

What you WON'T get from the course:-

What is a program?

A program is a list of instructions that described a task that you wish the computer perform.

In order to specify precisely your intentions, the instructions are limited to a number of core words called keywords. For example, a common keyword is IF which is used to tell the computer you wish to do something, only if something else has happened. 

This language is not understood by the computer, which uses a very fast and simplified language designed to work well with the electronic components of your computer. This is called machine code or machine language. Few people program using this directly, unless of extreme masochistic tendency.

This means that you need something that will translate the program that you have written in to machine code. This is done using a compiler. Instead, you could just translate the program straight from the source code without converting it to machine code. This would be done by an interpreter. Java uses something in-between the two of these, called an interpiler.

Large programs can get very difficult to follow, and are thus split up into logical steps, each of which are called functions or procedures. These functions may be able to be reused in different parts of your program, thus reducing the complexity and time it takes to write your program.

Most programming languages come with a number of commonly used functions, so that a lot of the work has been done for you. These functions are packaged-up and put into a library.

A little about Object Orientation

N.b. this section is background, and not required knowledge for this course.

Finally, most modern languages are in some way object-oriented. The principles of this are quite simple - imagine an object (e.g. a bicycle). It is an object. It can do various things - e.g. go, brake, accelerate and change gears. Each of these is a procedure that can be performed with the bicycle. But associated with the bicycle is various information - e.g. the make, model, current acceleration, colour, etc. These are known as attributes.

Now, let's say you wish to design a souped-up version of the sample bike - more gears, different colour, and with a bell!!! With object-orientation, rather than redoing everything again, you would borrow the design of the old bike, and just add to and replace various aspects of the object - e.g. a new attribute called bell and a new procedure called ring. Saves a lot of time. This principle is known as inheritance.

Finally, lets says we have a new object called shop. This has 50 spaces for bicycles, but until they are bought, who knows what they will be? So, we define 50 spaces that can hold a bike object (all of which share similar basic attributes and procedures) and pop different types of bikes into and out of those spaces as they are needed. In this way, we may not know in advance that the bike has a bell, but we know it can go, break, accelerate, and change gears! This principle is known as polymorphism - just to make it sound clever!

This is the basics of object-oriented programming. You build programs to reflect 'things' or objects that exist in the task or tasks you are trying to achieve.

We will not be looking at object orientation on this course, although these facilities are available in C++ which is the object-oriented version of C (i.e. C plus a lot more!)

A brief history of computer languages

N.b. this section is background, and not required knowledge for this course.

In that late 1940's, a German engineer called Konrad Zuse sought a better way to program computers. He developed a system of symbols that could be used to solve problems step-by-step, called Plankalkul.

Alan Turing wrote a shorthand code for writing programs on the Mark I computer - but still pretty indecipherable to the untrained.

John Mauchly then developed Short Code which allowed equations to be entered using a special code.

Grace Hopper, inspired by this, became the first real advocate of High Level Languages - languages that are closer to language that humans might use to describe tasks.

One of the first widely-used languages was IBM Fortran, developed in the 1950's, working with mathematical data. The language ALGOL was developed in 1958, but was never as well accepted as Fortran. 

COBOL (Common Business Oriented Language) was created in 1960, to serve mainly large businesses and governmental institutes. COBOL is still widely used in industry today, especially on large mainframe computers.

In 1964, BASIC (Beginners All-Purpose Symbolic Instruction Code) was released, making programming accessible to many more people. Variants are still in wide use today - e.g. Microsoft Visual Basic.

In 1965, a language called PL/1 was introduced to be a 'cure-all' language. Being overly complex, it met with only limited success.

Simula I and 67 had little impact at the time, but introduced the early concepts of object-oriented programming that underpins most languages, including C++, used today.

In 1971, a Swiss professor called Niklaus Wirth introduced a teaching language called Pascal, which introduced important concepts in structured programming to reduce errors and increase readability.

C was created in 1972, intended as a middle-level language for writing operating systems for different computers, although its uptake has been far more universal than anticipated.

Smalltalk, designed in the late 1970's, was the biggest breakthrough in many years, being both graphical and object-oriented. The concepts developed in Smalltalk contribute largely to modern languages such as C++, Java and C#.

ADA is used by the US Department of Defense, and was released in the early 1980's - it is large and very complex, and bears similarities with another release of that time, Modula-2 - a teaching language based on Pascal.

C++ was released in the mid-1980's to extend the popular C language to include object-oriented concepts.

Java was released in the mid-1990's to an enthusiastic audience, and Microsoft's .Net framework has as its flagship language, C# which is very similar to both Java and C++.

Introduction to C

C is a middle-level programming language that is used widely in industry either in its original form, or more widely in the object-oriented form C++.  Middle-level implies that it is neither high level (i.e. using easy to use English words and structures that are hard to understand by the machine but easy to understand by the programmer) nor low level (i.e. using obscure assembly language that describes how the computer does its processing at the hardware [chip] level, but works very fast due to it being written using a language the machine understands more readily than humans writing programs).

You will find that a lot of business programming that takes place in Unix environments (e.g.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 that C++ employs, 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 rough translation is: C is not always logical or sensible, which is probably why many 'traditional' programmers love it. Somebody wanted to build a portable operating system, and so C was born to be low-level enough for operating system stuff, but high-level enough for humans to be able  to follow reasonably well and relate to real work in some way.

A Brief History of C

N.b. this section is background, and not required knowledge for this course.

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 objective 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 ANSI 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.

Compilers

When you write your list of instructions for the computer to perform a task, called a program (or source code), you can write it using one of the many available programming languages available today - Java, C, C++, Pascal, Perl, BASIC etc. etc.

Once you have created your instructions, you will need to start a program called a compiler, which will take your instructions (the source code), and translate them into a form understood by the computer that the program is being created on - effectively, it translates a language you can understand reasonably well to a language the computer can understand.

Many compilers have an in-between stage, where the original program (source code) is converted to something called object code - this is often used to package up procedures into libraries, so that they can be distributed to other programmers, without them being able to see (and thus copy) the original source code. It also tends to be a lot smaller in size than the original source code, and can also be scrambled for extra security.

This object code can then be converted into machine code, which is the language that your computer understands inside its circuitry (i.e. central processing unit, or CPU).  This is also known as an executable file.

On your computer, C source code files can be identified by their ending - they end with .c or .cpp (for C or C++). Note that C programs will generally be understood by a C++ compiler (C++ being the next generation of C). 

Object code files tend to end with .obj, and executable files (the files that the computer understands, and that you will use to execute or run your programs) tend to end with .exe

The diagram below shows this process.

From Source Code to Executable Code: Compile & Build Process

 

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 (i.e. locate and correct mistakes), compile them, build them into a final executable to be distributed, and execute the programs (use them), 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 is the Turbo C++ Lite compiler (DOS based, but very small and fast) and the Borland C++ Builder (v1) compiler, which operates similarly but not identically to the v4 compiler.

If you wish to use 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. If you want to pay even less, you may like to try looking for the product on an auction site such as http://www.ebay.co.uk

What is a Project?

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

A project will store information about the application that you are working on.

Inside a project, you can (amongst other things) :-

Starting C++ Builder

To start C++ Builder, double-click on the icon on the desktop marked C++ Builder, or navigate to it from the Start button on the bottom-left hand side of your Windows desktop (typically found in Start > Programs > Borland C++ Builder > C++ Builder).

You should see a screen that looks something like the image below

The bottom two elements are used when building up visual windows-based applications, which we do not cover on this course, so are for our purposes, irrelevant.

The important section is at the top, where you can perform various functions - the menu, and the toolbar. These will be used extensively in this course.

To close the application again, just click on the little cross at the top-right hand corner of the title-bar on the menu/toolbar box.  If you have made any changes to your project (or programs in the project), you will be asked whether you wish to save the changes. You would generally answer by clickin on the Yes button.

Your first Project

The process of creating a new project depends on the version of C++ Builder that you use.  We need to create what is known as a console application - meaning an application that uses text and no graphics in a black box. This is ideal for seeing quick results when learning to program.

We are using Version 6 of C++ Builder this year. To create a new console application under v6:-

In older versions, you will not need to click the Other menu, and the icon may be called Console App. Also, the dialog box may be different (in which case, accept the default settings).

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 Reopen 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 in the above section.

 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?  Well, we'll go into the specifics in upcoming weeks, but for the more technically minded, here we go...

#include <stdio.h>

#include <conio.h>

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.)

void main() {  

...

}  

 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. The curly braces identify the start and end of the function, or (in the case of main) the program.

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

  printf("Hello World!\n");

 printf("Hello World!\n");

printf 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.

  getch();

 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.

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 (use File/Save As... menus) hello.mak for the project and hello.cpp for the program, in the c:\temp directory.
    Note - this means that printf("Hello World!\n"); should be replaced with something like printf("Hello everybody\nThis is my program.\n");  
  1. If you have some spare time (or wish to try something else at home), 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, where Stone blunts Knife, Knife cuts Paper, and Paper wraps Stone. You play against the computer.

Following below 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 (i.e. language rules) to say how this all fits together. The meanings will become clear as the course progresses.

What have we covered?

In this session we have looked at:-

Other resources about C Programming 

A good web site to look on for a tutorial on how to use C can be found at http://www.cs.cf.ac.uk/Dave/C/CE.html  
Another one can be found at http://www.hull.ac.uk/Hull/CC_Web/docs/cnotes/contents.html

The C Programming Language by Kernighan and Ritchie is the classic text describing the C programming language in detail. The authors are the original designers of the language, so it can be a bit high-browed at time!

 If you look on http://www.amazon.co.uk, drill down the subjects as follows: Books > Computers & Internet > Programming > Languages & Tools > Languages > C & C++ > Introductory C  -- You’ll see a variety of relevant books – for example : -

In the Next Session...

In the next session we will be covering the following topics:-

(c) Copyright 2002-4 Simon Huggins.   All Rights Reserved.
If you have any issues or questions regarding the content of this web site, please contact the author by clicking here.
Alternatively, you can leave a voice message on 00 44 (0)7050-618-297 or fax on 00 44 (0)7050-618-298

This Page was last updated: 29 January 2004 13:06