Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: C Programming Tutorials
Description: Every program is limited by the language which is used to write it. C is a programmer's language. Unlike BASIC or Pascal, C was not written as a teaching aid, but as an implementation language. C is a computer language and a programming tool which has grown popular because programmers like it! It is a tricky language but a masterful one. Sceptics have said that it is a language in which everything which can go wrong does go wrong. True, it does not do much hand holding, but also it does not hold anything back. If you have come to C in the hope of finding a powerful language for writing everyday computer programs, then you will not be disappointed. C is ideally suited to modern computers and modern programming.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


C Programming Tutorial

Node:Top, Next:Preface, Previous:(dir), Up:(dir)

C Programming Tutorial (K&R version 4)
This is a C Programming Tutorial for people who have a little experience with an interpreted programming language,
such as Emacs Lisp or a GNU shell
...
02
Copyright © 1987,1999 Mark Burgess
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this
permission notice are preserved on all copies
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Node:Preface, Next:Introduction, Previous:Top, Up:Top

Preface
Every program is limited by the language which is used to write it
...
Unlike BASIC or
Pascal, C was not written as a teaching aid, but as an implementation language
...

Sceptics have said that it is a language in which everything which can go wrong does go wrong
...
If you have come to C in the hope of finding a powerful
language for writing everyday computer programs, then you will not be disappointed
...

This book is a tutorial
...
It presumes that you have some previous aquaintance with programming -- you need to know what a
variable is and what a function is -- but you do not need much experience
...
When it comes down to it, most languages have
basically the same kinds of features: variables, ways of making loops, ways of making decisions, ways of accessing
files etc
...
You will most likely find all of those things and more, as you work though the chapters
...
In places these examples make use of
features before they have properly been explained
...


Mark Burgess
...
The book was originally
published by Dabs Press
...
This new edition is written in Texinfo, which is a documentation system that
uses a single source file to produce both on-line information and printed output
...

Node:Introduction, Next:Reserved words & example, Previous:Preface, Up:Top

Introduction
What is C? What is it for? Why is it special?
Levels:
Basic ideas:
The compiler:
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
A computer falls definitely into the category of complex objects and it
can be thought of as working at many different levels
...
Low level is perhaps the easiest to understand: it describes a level of
detail which is buried down amongst the working parts of the machine: the low level is the level at which the
computer seems most primitive and machine-like
...

Imagine stepping back from the complexity of the machine level pieces and grouping together parts which work
together, then covering up all the details
...
) At a high level a computer becomes a group of black boxes which can then
be thought of as the basic components of the computer
...
The aim of any high level computer language is to provide an easy and
natural way of giving a programme of instructions to a computer (a computer program)
...
As you might expect, the action which results from a single
machine code instruction is very primitive and many thousands of them are required to make a program which does
anything substantial
...

C is one of a large number of high level languages which can be used for general purpose programming, that is,
anything from writing small programs for personal amusement to writing complex applications
...
Before C, high level languages were criticized by machine code programmers because they shielded the user
from the working details of the computer, with their black box approach, to such an extent that the languages become
inflexible: in other words, they did not not allow programmers to use all the facilities which the machine has to offer
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

They are not merely monologues to the machine, they are a way to express ideas and a way to solve problems
...
This is
vitally important for writing lengthy programs because complex problems are only manageable with a clear
organization and program structure
...
These provide an excellent basis for controlling the

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

Another unusual feature of C is the way it can express ideas concisely
...
C gives us the apparatus to build neat and compact programs
...
Its conciseness can be a mixed blessing: the aim is to try to seek a balance between
the often conflicting interests of readability of programs and their conciseness
...

C allows things which are disallowed in other languages: this is no defect, but a very powerful freedom which, when
used with caution, opens up possibilities enormously
...
The programmer carries an extra responsibility to write a careful and
thoughtful program
...

C tries to make the best of a computer by linking as closely as possible to the local environment
...
Above all it is flexible
...

The aim of this book is to convey some of the C philosophy in a practical way and to provide a comprehensive
introduction to the language by appealing to a number of examples and by sticking to a strict structuring scheme
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

hoped that this will give a flavour of the kind of programming which C encourages
...
What can go wrong
...
It differs in a
number of ways
...
This form of the
program is called the source program
...

Secondly, the completed source file is passed to a compiler--a program which generates a new file containing a
machine code translation of the source text
...
The executable
file is said to have been compiled from the source text
...
You use a screen editor to create the words of a program (program text) and run the final program
in its compiled form usually by simply typing the name of the executable file
...
A compiler usually operates in two or more phases (and each phase may have stages
within it)
...
As we shall see later, this approach provides a flexible

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

A two-phase compiler works in the following way:
Phase 1 scans a source program, perhaps generating an intermediate code (quadruples or pcode) which helps to
simplify the grammar of the language for subsequent processing
...
A separate object file is built for each separate
source file
...
o files
...
This program appends standard library code to the object file so that the code is complete
and can "stand alone"
...
Even at this stage, the compiler can fail, if it finds that it has a reference to a function which
does not exist
...

To avoid the irritation of typing two or three separate commands (which are often cumbersome) you will normally find
a simple interface for executing compiler
...
out
...
c , write
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
c

Node:Errors, Next:Use of Upper and Lower Case, Previous:The compiler, Up:Introduction

Errors
Errors are mistakes which we the programmers make
...
They are listed all in one go, with the line number, in the text file, at which the error occurred
and a message to say what was wrong
...
Upon compilation, you would see this error message:
eg
...
c:12: parse error before `y'

(If you compile the program in Emacs, you can jump directly to the error
...
However, a compiler will usually not stop at the first error it encounters but will
attempt to continue checking the syntax of a program right to the last line before aborting, and it is common to
submit a program for compilation only to receive a long and ungratifying list of errors from the compiler
...
The situation thus
looks much worse than it really is
...

As a rule, look for the first error, fix that, and then recompile
...
But at the beginning, just look for and fix the first error
...
You intend to send a letter to all drivers whose licenses will expire soon; instead, you send a letter
to all drivers whose licenses will expire sometime
...
This file will contain machine code which can
be executed according to the rules of the computer's local operating system
...

Node:Use of Upper and Lower Case, Next:Questions 1, Previous:Errors, Up:Introduction

Use of Upper and Lower Case
One of the reasons why the compiler can fail to produce the executable file for a program is you have mistyped
something, even through the careless use of upper and lower case characters
...

Unlike languages such as Pascal and some versions of BASIC, the C compiler distinguishes between small letters and
capital letters
...
If a letter is typed in the
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...


Declarations
Compiler languages require us to make a list of the names and types of all variables which are going to be used in a
program and provide information about where they are going to be used
...
It serves
two purposes: firstly, it provides the compiler with a definitive list of the variables, enabling it to cross check for
errors, and secondly, it informs the compiler how much space must be reserved for each variable when the program is
run
...
Consequently, the type of a variable is of great importance to the compiler
...

Node:Questions 1, Previous:Use of Upper and Lower Case, Up:Introduction

Questions
1
...

3
...

5
...
The basic instructions are built up using a reserved set of words, such as main , for , if,while ,
default , double, extern, for , and int , to name just a few
...
You cannot use default, for example, as
the name of a variable
...

See All the Reserved Words, for a complete list of the reserverd words
...
If you use a word which has already been adopted in a
library, there will be a conflict between your choice and the library
...
For example, the stdio library, which is part of the C library, provides
standard facilities for input to and output from a program
...
While the features provided by libraries are not strictly a part of the C language itself, they are
essential and you will never find a version of C without them
...

printf:
Example 1:
Output 1:
Questions 2:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
It provides
an superbly versatile way of printing text
...
some string
...
These can be inserted into a text string
by using a `control sequence' inside the quotes and listing the variables after the string which get inserted into the
string in place of the control sequence
...
The printf function is described in full detail in the relevant
chapter, but we'll need it in many places before that
...
If you are
reading this in Info, you can copy this to a file, compile and execute it
...
h>
/***********************************************************/
main ()
{
printf
printf
printf
printf
printf
printf
printf
printf
printf
printf
printf
printf
}

/* Poem */

("Astronomy is %dderful \n",1);
("And interesting %d \n",2);
("The ear%d volves around the sun \n",3);
("And makes a year %d you \n",4);
("The moon affects the sur %d heard \n",5);
("By law of phy%d great \n",6);
("It %d when the the stars so bright \n",7);
("Do nightly scintill%d \n",8);
("If watchful providence be%d \n",9);
("With good intentions fraught \n");
("Should not keep up her watch divine \n");
("We soon should come to %d \n",0);

Node:Output 1, Next:Questions 2, Previous:Example 1, Up:Reserved words & example

Output
Astronomy is 1derful \n"
And interesting 2
The ear3 volves around the sun
And makes a year 4 you
The moon affects the sur 5 heard
By law of phy6d great
It 7 when the the stars so bright
Do nightly scintill8
If watchful providence be9
With good intentions fraught
Should not keep up her watch divine

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

2
...

4
...

Write a command to print out the number 22?
Write two commands to print out "The 3 Wise Men" two different ways
...
This is a layer of software which drives the hardware
and provides users with a comfortable environment in which to work
...
The operating system
is the route to all input and output, whether it be to a screen or to files on a disk
...
In C the link between these two is very efficient
...

Recently the tendency has been to try to eliminate typing completely by providing graphical user interfaces (GUIs) for
every purpose
...
For that one needs a command language
...
On microcomputers
command languages are usually very similar in concept, though more primitive, with only slightly different words for
essentially the same commands
...

When most compiler languages were developed, they were intended to be run on large mainframe computers which
operated on a multi-user, time-sharing principle and were incapable of interactive communication with the user
...
Input and output are not actually defined as a fixed, unchanging part of the C language
...
This file is called a standard C library
...
) The library is standard in the sense that C has developed a set of functions which all
computers and operating systems must implement, but which are specially adapted to your system
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Files and Devices
The filing system is also a part of input/output
...
C does this implicitly
(it comes from Unix)
...
The corresponding route for output is called "stdout" or standard output file and is usually a
monitor screen
...
The keyboard and the monitor screen are not
really files, of course, they are `devices', (it is not possible to re-read what has been sent to the monitor", or write to
the keyboard
...
The advantage of treating devices like this is that it is not necessary to know how
a particular device works, only that it exists somewhere, connected to the computer, and can be written to or read
from
...
This is a
great simplification of input/output! The filenames of devices (often given the lofty title `pseudo device names')
depend upon your particular operating system
...
You might
have to open it explicitly as a file
...

Node:Filenames, Next:Command languages, Previous:Files devices, Up:Operating systems

Filenames
The compiler uses a special convention for the file names, so that we do not confuse their contents
...
c
...
o, as yet unlinked
...
EXE on Windows derived systems
...
a or liblibraryname
...
Header files are always called libname
...

The endings `dot something' (called file extensions) identify the contents of files for the compiler
...
The quad file and the object file are only working files and should be deleted by the compiler at the end of
compilation
...
c suffix is to tell the compiler that the file contains a C source program and similarly the other
letters indicate non-source files in a convenient way
...
c

Node:Command languages, Next:Questions 3, Previous:Filenames, Up:Operating systems

Command Languages and Consoles
In order to do anything with a compiler or an editor you need to know a little about the command language of the
operating system
...
e
...

ls -l
less filename
emacs filename

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Fortunately it is possible to get by with knowing just handful of the most common ones and having the
system manual around to leaf through when necessary
...
Every system will have its own way of
halting or terminating the operation of a program or the execution of a command
...
In GNU/Linux, CTRL-C is used
...

2
...

4
...


What is an operating system for?
What is a pseudo-device name?
If you had a C source program which you wanted to call `accounts' what name would you save it under?
What would be the name of the file produced by the compiler of the program in 3?
How would this program be run?

Node:Libraries, Next:Programming style, Previous:Operating systems, Up:Top

Libraries
Plug-in C expansions
...

The core of the C language is small and simple
...
This is what makes C so portable
...
You can also make your own, but to do so you need to know
how your operating system builds libraries
...

Libraries are files of ready-compiled code which we can merge with a C program at compilation time
...
For example, there are
libraries of mathematical functions, string handling functions and input/output functions and graphics libraries
...
For example, to merge with the math library libm
...
c -lm

when you compile the program
...
If we wanted to add in the socket library libsocket
...
c -lm -lsocket

and so on
...
When library functions are used in programs, the appropriate
library code is included by the compiler, making the resulting object code often much longer
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

conjunction with the libraries
...
You cannot then use the names of functions or macros which have already been
defined in libraries or header files to mean anything other than what the library specifies
...
h
...
The math
...
a
...
h

at the top of a program file
...
h"

includes a personal header file which is in the current directory
...
h>

includes a file which lies in a standard directory like /usr/include
...

Some functions can be used without having to include library files or special libraries explicitly since every program is
always merged with the standard C library, which is called libc
...
h>
main ()
{
printf ("C standard I/O file is included\n");
printf ("Hello world!");
}

A program wishing to use a mathematical function such as cos would need to include a mathematics library header
file
...
h>
#include ...
These details will be found in the local manual for a particular
C compiler or operating system
...
Libraries also add
to the time it takes to compile a program
...
Others have to load in everything before they can run a program
at all, so many libraries would slow them down
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

To know what names libraries have in a particular operating system you have to search through its documentation
...

Questions 4:
Node:Questions 4, Previous:Libraries, Up:Libraries

Questions
1
...

3
...


How is a library file incorporated into a C program?
Name the most common library file in C
...

C is actually a free format language
...
This has both advantages and dangers
...

The disadvantage is that, unless a strict style is adopted, very sloppy programs can be the result
...

Programs are only understandable if care is taken in choosing the names of variables and functions
...
Such a scheme becomes
increasingly difficult to achieve with the size and complexity of the problem
...
In the end, experience and
good judgement are the factors which decide whether a program is written well or poorly written
...
Previously restrictions of memory size, power and of particular compilers often forced
restrictions upon style, making programs clustered and difficult
...

Node:Form of a C program, Next:Comments, Previous:Programming style, Up:Top

The form of a C program
What goes into a C program? What will it look like?
C is made up entirely of building blocks which have a particular `shape' or form
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

program, whether it is the form of the main program or of a subroutine
...

The basic building block in a C program is the function
...
One and only one of these functions in the program must have the name main()
...
This is how C distinguishes functions from ordinary variables
...
It
always starts where main() is
...

Only the operating system can call the function main(): this is how a C program is started
...

/******************************************************/
/*
*/
/* Program : do nothing
*/
/*
*/
/******************************************************/
main()

/* Main program */

{
do_nothing();
}
/******************************************************/
do_nothing()

/* Function called */

{

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
There are several new things to notice
about this program
...
This is all that is required to transfer control to the new function
...
No such thing is needed in C
...

All instructions in C must end with a semi-colon
...
This helps the compiler
diagnose errors
...
When the program meets the
closing brace } it then transfers back to main() where it meets another } brace and the program ends
...
All functions have the same status as far as a program is
concerned
...
When a program is compiled, each function is
compiled as a separate entity and then at the end the linker phase in the compiler attempts to sew them all together
...
Here are some
more basic elements which we shall cover
...
The following
chapters will then expand upon this as a kind of basic plan
...
h>
#include ...

}
/****************************************************/
function2 (a,b)

/* Purpose */

int a,b;
{

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

}

Question 5:
Neither comments nor preprocessor commands have a special place in this list: they do not have to be in any one
particular place within the program
...

2
...

4
...


What is a block?
Name the six basic things which make up a C program
...

Comments are a way of inserting remarks and reminders into a program without affecting its content
...
Programs can contain any number of comments without losing speed
...

Comments are marked out or delimited by the following pairs of characters:
/*
...
*/

Because a comment is skipped over as though it were a single space, it can be placed anywhere where spaces are valid
characters, even in the middle of a statement, though this is not to be encouraged
...
If there are too many comments
you obscure your code and it is the code which is the main message in a program
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

{
/* This little line
/* This little line
/* This little line
to the next line
/* And so on
...
h>

/* header file */

#define

0

NOTFINISHED

/**********************************************/
/* A bar like the one above can be used to */
/* separate functions visibly in a program */
main ()
{ int i;

/* declarations */

do
{
/* Nothing !!! */
}
while (NOTFINISHED);
}

Node:Question 7, Previous:Example comment 2, Up:Comments

Question
1
...
to start but forgets the
...
Solving problems
...

A function is a module or block of program code which deals with a particular task
...
Functions serve two purposes
...

Functions help us to organize a program in a simple way; in Kernighan & Ritchie C they are always written in the
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
)
types of parameters
{ variable declarations
statements
...


...

Each function has a name or identifier by which is used to refer to it in a program
...
The declarations and `type of parameter'
statements are formalities which will be described in good time
...
The name of a function must begin
with an alphabetic letter or the underscore _ character but the other characters in the name can be chosen from the
following groups:
a
...
Z

(any letter from A to Z)
0
...
Here is a real
example function which adds together two integer numbers a and b and prints the result c
...

Add_Two_Numbers (a,b)

/* Add a and b */

int a,b;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The details are
quickly learned with practice and experience
...
It has to be called from somewhere
...
e
...
Here is a simple
program which makes use of some functions in a playful way
...
The idea is to illustrate the way in which the functions connect together:
Structure diagram:
Program listing:
Functions with values:
Breaking out early:
The exit function:
Functions and types:
Questions 6:
Node:Structure diagram, Next:Program listing, Previous:Functions, Up:Functions

Structure diagram
Level 0:

main ()
|

Level 1:

DownOne ()
/
/

Level 2:

DownLeft()

\
\
DownRight()

Note: not all functions fit into a tidy hierarchy like these
...
Where would you place the printf function in this hierarchy?
Node:Program listing, Next:Functions with values, Previous:Structure diagram, Up:Functions

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h>
/***********************************************/
/* Level 0
*/
/***********************************************/
main ()
{
printf ("This is level 0: the main program\n");
printf ("About to go down a level
\n");
DownOne ();
printf ("Back at the end of the start!!\n");
}
/************************************************/
/* Level 1
*/
/************************************************/
DownOne ()

/* Branch out! */

{
printf ("Down here at level 1, all is well\n");
DownLeft (2);
printf ("Through level 1
...

That is, the whole function is thought of as having a value
...
It is possible to make a function hand back a value to the place at which it was called
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

following example:
bill = CalculateBill(data
...
This statement makes it look as though CalculateBill() is a number
...
The value of the function is assigned to "bill" and the program continues
...

In C, returning a value is a simple matter
...

If there were no return statement the program could not know which value it should associate with the name
CalculateBill and so it would not be meaningful to speak of the function as having one value
...
For instance if CalculateBill had just been:
CalculateBill (starter,main,dessert)

/* WRONG! */

int starter,main,dessert;
{ int total;
total = starter + main + dessert;
}

then the value bill would just be garbage (no predictable value), presuming that the compiler allowed this to be
written at all
...
This is usually what is done with the input
output functions printf() and scanf() which actually return values
...

NOTE : Functions do not have to return integers: you can decide whether they should return a different data type, or
even no value at all
...
This is where the beauty of the
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The program can simply call return(value) anywhere in the function and control
will jump out of any number of loops or whatever and pass the value back to the calling statement without having to
finish the function up to the closing brace }
...
The function is entered with some values for a and b and, assuming that a is less than b, it
starts to execute one of C's loops called while
...
If a becomes bigger than b at any point the return(b) statement gets executed and the function
myfunction quits, without having to arrive at the end brace }, and passes the value of b back to the place it was called
...
This is called with a return code, like this:
#define CODE

0

exit (CODE);

This function also calls a number of other functions which perform tidy-up duties such as closing open files etc
...
But what happens if a function is required to return a
different kind of value such as a character? A statement like:
bill = CalculateBill (a,b,c);

can only make sense if the variable bill and the value of the function CalculateBill() are the same kind of object:
in other words if CalculatBill() returns a floating point number, then bill cannot be a character! Both sides of an
assignment must match
...
So far no declarations have been needed
because C assumes that all values are integers unless you specifically choose something different
...

Node:Questions 6, Previous:Functions and types, Up:Functions

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

2
...

4
...


Write a function which takes two values a and b and returns the value of (a*b)
...
Descriminating types
...

A variable is a seqeuence of program code with a name (also called its identifier)
...
The name of a variable must begin with an alphabetic letter or the underscore _
character but the other characters in the name can be chosen from the following groups:
a
...
Z

(any letter from A to Z)
0
...


In C variables do not only have names: they also have types
...
In BASIC and in some older, largely obsolete languages, like PL/1, a special naming
convention is used to determine the sort of data which can be held in particular variables
...
g
...
No such convention exists in C
...
This serves two
purposes:
It gives a compiler precise information about the amount of memory that will have to be given over to a variable
when a program is finally run and what sort of arithmetic will have to be used on it (e
...
integer only or floating
point or none)
...

There is a lot of different possible types in C
...
The names of these types are all
reserved words in C and they are summarized as follows:
char

A single ASCII character
short

A short integer (usually 16-bits)
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

enum

Discussed in a later chapter
...

There is some repetition in these words
...
Unsigned means that only positive or zero values can be used
...
e
...
The
advantage of using this kind of variable is that storing a minus sign takes up some memory, so that if no minus sign is
present, larger numbers can be stored in the same kind of variable
...
On some systems variables are signed by
default, whereas on others they are not
...
,variablenameN;

For example:
int i,j;
char ch;
double x,y,z,fred;
unsigned long int Name_of_Variable;

Failing to declare a variable is more risky than passing through customs and failing to declare your six tonnes of Swiss
chocolate
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

and will terminate a compiling session whilst complaining bitterly, often with a host of messages, one for each use of
the undeclared variable
...
For now it will do to simply state what
these places are
...
One place is outside all of the functions
...
(After the #include
lines, for example
...
There are also called static and external
variables in special cases
...
h>
int globalinteger;

/* Here! outside {} */

float global_floating_point;
main ()
{
}

2
...
Any block will
do, as long as the declaration follows immediately after the opening brace
...
Another name for them is automatic variables
...
*/
while (i < 10)
{ char ch;
int g;
/*
...
This is no more efficient than doing it in two stages, but it is sometimes tidier
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

int i = 0;
char ch = 'a';

are equivalent to the more longwinded
int i;
char ch;
i = 0;
ch = 'a';

This is called initialization of the variables
...
If there are just one or two declarations then this initialization method can
make a program neat and tidy
...
A lot
means when it starts to look as though there are too many
...
It is only for tidiness that this is allowed
...
Groups of char form strings
...
g
...
g
...
The same effect can also be achieved by writing:
char ch = 'a';

A character can be any ASCII character, printable or not printable from values -128 to 127
...
) Control characters i
...
non printable characters are put into programs by using a backslash \ and a special
character or number
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

horizontal tab HT
\v

vertical tab (not all versions)
\"

double quotes (not all versions)
\'

single quote character '
\\

backslash character \
\ddd

character ddd where ddd is an ASCII code given in octal or base 8, See Character Conversion Table
...

Node:Example special chars, Next:integers, Previous:char, Up:Types

Listing
/***************************************************/
/*
*/
/* Special Characters
*/
/*
*/
/***************************************************/
#include ...
It is also possible to have the type:
unsigned char

This admits ASCII values from 0 to 255, rather than -128 to 127
...
The difference between
these is the size of the integer which either can hold and the amount of storage required for them
...
Even different flavours of Unix can have varying sizes for
these objects
...
int means a `normal' integer and short means a
`short' one, not that that tells us much
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

short
16
unsigned short 16

-32768 to 32767
0 to 65535

int
long
unsigned int
long long

-2147483648 to 2147483647
(ditto)
0 to 4294967295
-9e18 to + 8e18

32
32
32
64

Increasingly though, 64 bit operating systems are appearing and long integers are 64 bits long
...
Some mainframe operating systems are completely 64 bit, e
...
Unicos has no 32 bit values
...
All the mathematical functions which C can use require
double or long float arguments so it is common to use the type float for storage only of small floating point
numbers and to use double elsewhere
...
) On a typical 32 bit implementation the different types would be organized as follows:
Type

Bits

Possible Values

float
double
long float
long double

32
64
32
???

+/- 10E-37 to +/- 10E38
+/- 10E-307 to +/- 10E308
(ditto)

Typical declarations:
float x,y,z;
x = 0
...
456E5
z = 0;
double bignum,smallnum;
bignum = 2
...
2E-300;

Node:Choosing Variables, Next:Assigning variables to one another, Previous:Types, Up:Variables

Choosing Variables
The sort of procedure that you would adopt when choosing variable names is something like the following:
Decide what a variable is for and what type it needs to be
...

Decide where the variable is allowed to exist
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
It is common to give these short
names (single characters)
...
A
common one, for instance is to use the letters:
int i,j,k;

to be integer type variables used for counting
...
) Other integer values should have more meaningful names
...

Node:Assigning variables to one another, Next:Types and The Cast Operator, Previous:Choosing Variables,
Up:Variables

Assigning variables to one another
Variables can be assigned to numbers:
var = 10;

and assigned to each other:
var1 = var2;

In either case the objects on either side of the = symbol must be of the same type
...
So
int a, b = 1;
a = b;

is a valid statement, and:
float x = 1
...
This is a questionable practice though
...
Numerical values and characters will interconvert because characters are
stored by their ASCII codes (which are integers!) Thus the following will work:
int i;
char ch = 'A';
i = ch;
printf ("The ASCII code of %c is %d",ch,i);

The result of this would be:
The ASCII code of A is 65

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
For instance it would convert a character into an integer:
int i;
char ch = '\n';
i = (int) ch;

The value of the integer would be the ASCII code of the character
...
Similarly floating point and integer types can be interconverted:
float x = 3
...

There is no such problem the other way around
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

The general form of the cast operator is therefore:
(type) variable

It does not always make sense to convert types
...

Cast operators crop up in many areas of C
...

/***************************************************/
/*
*/
/* Demo of Cast operator
*/
/*
*/
/***************************************************/
#include ...
345;
i = (int) x;
ch = (char) x;
printf ("From float x =%f i =%d ch =%c\n",x,i,ch);
i = 45;
x = (float) i;
ch = (char) i;
printf ("From int i=%d x=%f ch=%c\n",i,x,ch);
ch = '*';
i = (int) ch;
x = (float) ch;
printf ("From char ch=%c i=%d x=%f\n",ch,i,x);
}

Node:Storage class register static and extern, Next:Functions types, Previous:Types and The Cast Operator,
Up:Variables

Storage class static and extern
Sometimes C programs are written in more than one text file
...
If the word extern is placed in front of a variable then it can be
referenced across files:
File 1

File 2
int i;

main ()
{
extern int i;
}

function ()
{
}

In this example, the function main() in file 1 can use the variable i from the function main in file 2
...
The name static is given to variables which can hold their values between calls of a
function: they are allocated once and once only and their values are preserved between any number of function calls
...
NOTE: Every global variable, defined outside functions has the type static automatically
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Unless something special is done to force a function to return a different kind of value C will always
assume that the type of a function is int
...

There are two places where this must be done:
The name of the function must be declared a certain type where the function is declared
...
g
...
229);
}

A function which returns a character:
char function2 ()
{
return ('*');
}

As well as declaring a function's identifier to be a certain type in the function definition, it must (irritatingly) be
declared in the function in which it is called too! The reasons for this are related to the way in which C is
compiled
...

Node:Questionsdeclare, Previous:Functions types, Up:Variables

Questions
1
...
Say which of the following are valid C identifiers:
1
...
80shillings
3
...
A%
5
...
_off

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

4
...

6
...

8
...

10
...

What is the difference between the types floa and double
...

What type does a C function return by default?
If we want to declare a function to return long float , it must be done in, at least, two places
...
1256
...

Not all functions will be as simple as the ones which have been given so far
...
Examples
of this have already been seen in a limited way
...

CalculateBill (a,b,c)
int a,b,c;
{ int total;
total = a + b + c;
return total;
}

When variable values are handed to a function, by writing them inside a functions brackets like this, the function is
said to accept parameters
...
In C it
is a variable which carries some special information
...
In
other words, the value of total depends upon the starting values of a,b and c
...
They are like messengers which pass
information to and from different places
...
Parameters are usually split into two categories: value parameters and variable
parameters
...
Variable parameters are two-way
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Declaring Parameters
A function was defined by code which looks like this:
identifier (parameters
...
For instance:
function1 (i,j,x,y)
int i,j;
float x,y;
{
}

or
char function2 (x,ch)
double x;
char ch;
{ char ch2 = '*';
return (ch2);
}

Notice that they are declared outside the block braces
...
All of the examples up to know have been examples of
value parameters
...
An example helps to show this
...

#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

When this program is run, two new variables are automatically created by the language, called a and b
...
Obviously if a and b were given new values in the function add() then
this could not change the values 1 and 4 in main(), because 1 is always 1 and 4 is always 4
...


However if instead the program had been:
main ()
{ int a = 1, b = 4;
add (a,b);
}
/**************************************/
add (a,b)
int a,b;
{
printf ("%d", a+b);
}

then it is less clear what will happen
...

The value of a in main() is copied into the value of a in add()
...

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
This means that if a and b are altered in add() they will not
affect a and b in main()
...
Another name for this is an argument
...

Here are some points about value parameters
...
They do not have to be the same as the actual
parameters
...
h>
main ()
{ int a = 1, b = 4;
add (a,b);
}
/*******************************************/
add (i,j)
int i,j;
{
printf ("%d", i+j);
}

In this case the value of a in main() would be copied to the value of i in add() and the value of b in main()
would be copied to the value of j in add()
...
It is possible to copy a floating
point number into a character formal parameter, causing yourself problems which are hard to diagnose
...
e
...

main ()
{
function ('*',1
...
0 is a floating point value, not an integer
...
ANSI C has a way of checking this by function `prototyping',
but in Kernighan & Ritchie C there is no way to check this
...
If
the number of actual parameters is less than the number of formal parameters, then the compiler will assign some
unknown value to the formal parameters
...

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
In fact, we can send any literal value, or expression with an appropriate type to a function
...
41415);
cos(a+b*2
...
It does not have to be assigned to a
variable first
...

Node:Example 2, Next:Example 3, Previous:Functions as actual parameters, Up:Parameters

Example Listing
/**************************************************/
/*
*/
/* Value Parameters
*/
/*
*/
/**************************************************/
/* Toying with value parameters */
#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

printf (" %f", x_plus_one(x));
printf (" %f", x);
j = resultof (i);
printf (" %d",j);
}
/***************************************************/
/* level 1
*/
/***************************************************/
double x_plus_one(x)

/* Add one to x ! */

double x;
{
x = x + 1;
return (x);
}
/****************************************************/
resultof (j)

/* Work out some result */

int j;
{
return (2*j + 3);
}

/* why not
...
h>
/******************************************************/
main ()

/* Print out exam results */

{ int pupil1,pupil2,pupil3;
int ppr1,ppr2,ppr3;
float pen1,pen2,pen3;
pupil1 = 87;
pupil2 = 45;
pupil3 = 12;
ppr1 = 200;
ppr2 = 230;
ppr3 = 10;
pen1 = 1;
pen2 = 2;
pen3 = 20;
analyse (pupil1,pupil2,pupil3,ppr1,ppr2,
ppr3,pen1,pen2,pen3);
}
/*******************************************************/
analyse (p1,p2,p3,w1,w2,w3,b1,b2,b3)
int p1,p2,p3,w1,w2,w3;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
)
One way to hand information back is to use the return statement
...
There is another way of handing back values which is less
restrictive, but more awkward than this
...

It is most easily explained with the aid of an example:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h>
main ()
{ int i,j;
GetValues (&i,&j);
printf ("i = %d and j = %d",i,j)
}
/************************************/
GetValues (p,q)
int *p,*q;
{
*p = 10;
*q = 20;
}

To understand fully what is going on in this program requires a knowledge of pointers and operators, which are
covered in later sections, but a brief explanation can be given here, so that the method can be used
...
The ampersand & symbol should be read
as "the address of
...
This is easily confused with

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The difference is only in the context in which the symbol is used
...

So, in the program above, it is not the variables themselves which are being passed to the procedure but the addresses
of the the variables
...
These addresses are copied into two new variables p and q, which are said to be pointers to i
and j
...
This information can be used to alter the "actual
parameters" directly and this is done with the * operator
...
Recall that the address held in p is the address of the
variable i, so this actually reads: make i equal to 10
...
Other operations are also possible (and these are detailed
in the section on pointers) such as finding out the value of i and putting it into a new variable, say, a:
int a;
a = *p;

/* is equivalent to a = i */

Notice that the * symbol is required in the declaration of these parameters
...
h>
/**************************************************/
main ()

/* Scale measurements*/

{ int height,width;
height = 4;
width = 5;
ScaleDimensions (&height,&width);
printf ("Scaled height = %d\n",height);
printf ("Scaled width = %d\n",width);
}
/****************************************************/
ScaleDimensions (h,w)

/* return scaled values */

int *h, *w;
{ int hscale = 3;
int wscale = 1;

/* scale factors */

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

2
...

4
...

6
...

Where are parameters declared?
Can a function be used directly as a value parameter?
Does it mean anything to use a function directly as a variable parameter?
What do the symbols * and & mean, when they are placed in front of an identifier?
Do actual and formal parameters need to have the same names?

Node:Scope, Next:Preprocessor, Previous:Parameters, Up:Top

Scope : Local And Global
Where a program's fingers can't reach
...

Functions can be thought of as sealed capsules of program code which float on a background of white space, and are
connected together by means of function calls
...
The global white space is only the gaps between functions, not the gaps inside functions
...

Another analogy is to think of what goes on in a function as being like watching a reality on television
...
You can send a parameter (e
...
switch channels) to make some choices
...

Global variables:
Local variables:
Parameters again:
Example 5:
Style note:
Scope and style:
Questions 11:
Node:Global variables, Next:Local variables, Previous:Scope, Up:Scope

Global Variables
Global variables are declared in the white space between functions
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

anything inside any ship (See the diagram)
...
they are created when a
program is started and are not destroyed until a program is stopped
...

Node:Local variables, Next:Parameters again, Previous:Global variables, Up:Scope

Local Variables
Local variables are more interesting
...
To use the ship analogy: if it is imagined that on board every ship (which means inside every function) there is
a large swimming pool with many toy ships floating inside, then local variables will work anywhere in the swimming
pool (inside any of the toys ships, but can not get out of the large ship into the wide beyond
...
Every function has its own
swimming pool! The idea can be taken further too
...
Variables can reach anywhere inside them but they cannot get out
...
Whenever a pair of block braces is written into a program it is possible to make variable
declarations inside the opening brace
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

char localch;
/* statements */
}

These variables do not exist outside the braces
...
Because they only work in
this local area of a program, they are called local variables
...
The programmer does not have to think about this
...
It tells a programmer what a variables
horizons are!
Node:Parameters again, Next:Example 5, Previous:Local variables, Up:Scope

Communication : parameters
If functions were sealed capsules and no local variables could ever communicate with other parts of the program, then
functions would not be very useful
...
Parameters are a way of handing local
variables to other functions without letting them out! Value parameters (see last section) make copies of local variables
without actually using them
...
In other words, it can't
get out of the function to which is it passed
...

Node:Example 5, Next:Style note, Previous:Parameters again, Up:Scope

Example Listing
Notice about the example that if there are two variables of the same name, which are both allowed to be in the same
place ( c in the example below) then the more local one wins
...

(Technically adept readers will realize that this is because it was the last one onto the variable stack
...
h>
/***************************************************************/
main ()
{ int a = 1, b = 2, c = 3;
if (a == 1)
{ int c;
c = a + b;
printf ("%d",c);
}
handdown (a,b);
printf ("%d",c);
}
/**************************************************************/
handdown (a,b)

/* Some function */

int a,b;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

}

Node:Style note, Next:Scope and style, Previous:Example 5, Up:Scope

Style Note
Some programmers complain about the use of global variables in a program
...
Sometimes global
variables are very useful however, and this problem need not be crippling
...

int GLOBALINTEGER;

...
Another reason for restricting the use of global variables is that it is
easier to debug a program if only local variables are used
...
Global
variables punch holes in the sealed function capsules because they allow bugs from other functions to creep into tried
and tested ones
...

The following guidelines may help the reader to decide whether to use local or global data:
Always think of using a local variable first
...
Global variables will sometimes tidy up a program
...

The preference in this book is to use local variables for all work, except where a program centres around a single
data structure
...

Node:Scope and style, Next:Questions 11, Previous:Style note, Up:Scope

Scope and Style
All the programs in this book, which are longer than a couple of lines, are written in an unusual way: with a levelled
structure There are several good reasons for this
...

/**************************************/

Another good reason is that any function hands parameters down by only one level at a time and that any return()
statement hands values up a single level
...

The diagram shows how the splitting of levels implies something about the scope of variables and the handing of
parameters
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Node:Questions 11, Previous:Scope and style, Up:Scope

Questions
1
...

3
...


What is a global variable?
What is a local variable?
What is meant by calling a block (enclosed by braces {} ) a "sealed capsule"?
Do parameters make functions leaky? i
...
Do they spoil them by letting the variables leak out into other
functions?
5
...
Two integer variables called number_of_hats ,counter which are
GLOBAL and two float variables called x_coord,y_coord which are LOCAL inside the function main()
...
How many different storage
spaces are used when this program runs? (Hint: are x_coord,y_coord and their copies the same?)

Node:Preprocessor, Next:Pointers, Previous:Scope, Up:Top

Preprocessor Commands
Making programming versatile
...
This comes from its Unix origins
...
The preprocessor has two main uses: it allows
external files, such as header files, to be included and it allows macros to be defined
...

Pre-processor commands are distinguished by the hash (number) symbol #
...
h
...
h>

is a command which tells the preprocessor to treat the file stdio
...

Macros are words which can be defined to stand in place of something complicated: they are a way of reducing the
amount of typing in a program and a way of making long ungainly pieces of code into short words
...
g
...
In this particular case, the word
is clearly not any shorter than the number it will replace, but it is more meaningful and would make a program read
more naturally than if the raw number were used
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Using the macros instead makes the actions much clearer and allows the programmer to forget about what the numbers
actually are
...

The important feature of macros is that they are not merely numerical constants which are referenced at compile time,
but are strings which are physically replaced before compilation by the preprocessor! This means that almost anything
can be defined:
#define SUM

1 + 2 + 3 + 4

would allow SUM to be used instead of 1+2+3+4
...
"

would allow a commonly used string to be called by the identifier "string" instead of typing it out afresh each time
...
(Anything enclosed in string quotes is assumed to be complete and untouchable by the compiler
...
h such as:
EOF

The end of file character (= -1 for instance)
NULL

The null character (zero) = 0
Macro functions:
Macros with parameters:
Example 6:
Note about include:
Other Preprocessor commands:
Example 7:
Questions 12:
Node:Macro functions, Next:Macros with parameters, Previous:Preprocessor, Up:Preprocessor

Macro Functions
A more advanced use of macros is also permitted by the preprocessor
...
This works by defining a macro with some dummy parameter, say x
...
It is defined below:
#define ABS(x) ((x) < 0) ? -(x) : (x)

The result of this is to give the positive (or unsigned) part of any number or variable
...
Macros can also be made to take
parameters
...
If a programmer were to write ABS(4) then the preprocessor would substitute
4 for x
...
(There is no reason why
macros can't take more than one parameter too
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

names
...
) Notice that this definition uses a curious operator which belongs to C:
? :

This is like a compact way of writing an if
...
else statement, ideal for macros
...
then
...
Firstly the test is
made
...
As a memory aid, it
could be read as:
if then else

(Do not be confused by the above statement which is meant to show what a programmer might think
...
) C can usually produce much more efficient code for this construction than for a corresponding if-else
statement
...
To some
extent this is true for absolute beginners, but it is not a good idea to hold on to
...
The advantage of a macro, however, is speed
...
There is a limitation with macros though
...
Only variables or number constants will be substituted
...
It is simply not viable to copy complicated sequences of code all
over programs
...
No simple rules can be given
...
Functions are easier to debug
than macros, since they allow us to single step through the code
...

Node:Example 6, Next:Note about include, Previous:Macros with parameters, Up:Preprocessor

Example Listing
/************************************************************/
/*
*/
/* MACRO DEMONSTRATION
*/
/*
*/
/************************************************************/
#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

/************************************************************/
main ()
{
printf
printf
printf
printf
printf
printf
}

/* No #definitions inside functions! */

(STRING1);
(STRING2);
("%d\n",EXPRESSION);
("%d\n",EXPR2);
("%d\n",ABS(-5));
("Biggest of 1 2 and 3 is %d",BIGGEST(1,2,3));

Node:Note about include, Next:Other Preprocessor commands, Previous:Example 6, Up:Preprocessor

Note about #include
When an include statement is written into a program, it is a sign that a compiler should merge another file of C
programming with the current one
...
The includes are then said to be "nested"
...

Node:Other Preprocessor commands, Next:Example 7, Previous:Note about include, Up:Preprocessor

Other Preprocessor commands
This section lies somewhat outside the main development of the book
...

There are a handful more preprocessor commands which can largely be ignored by the beginner
...

NOTE : true has any non zero value in C
...

#undef

This undefines a macro, leaving the name free
...
It allows conditional compilation
...
This is different from not executing code--the code will not even be
compiled
...
If that macro is defined then this is true
...
If that name is not defined then this is true
...

#endif

This marks the end of a preprocessor statement
...
This statement causes the compiler to believe that the next line is line number
(constant) and is part of the file (filename)
...
It is intended for debugging
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

compilation
...

"
#else
#define OPTIONSTRING "The alternative"
#define DITTO
"i
...
This! "
#endif
/***********************************************************/
#ifdef SOMEDEFINITION
#define WHATEVER "Something was defined!"
#else
#define WHATEVER "Nothing was defined"
#endif
/************************************************************/
main ()
{
printf (OPTIONSTRING);
printf (DITTO);
}

Node:Questions 12, Previous:Example 7, Up:Preprocessor

Questions
1
...

3
...


Define a macro called "birthday" which describes the day of the month upon which your birthday falls
...
h
...
True or false?
A macro is always a constant
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Making maps of data
...
You need to find that essential piece of information which is
stored at some unknown location
...
Pointers point to these
locations by keeping a record of the spot at which they were stored
...
It is always possible to find the address of a piece of storage in C using the
special & operator
...

float location;
float *location_ptr,*address;
location_ptr = &(location);

or
address = &(location);

The declarations of pointers look a little strange at first
...
The four lines above make two identical pointers to a floating
point variable called location , one of them is called location_ptr and the other is called address
...

A pointer is a bundle of information that has two parts
...
The other part is the type of value that the pointer points to the beginning of
...
Thus, if the
pointer is of a type int, the segment of memory returned will be four bytes long (32 bits) and be interpreted as an
integer
...

If, like some modern day programmers, you believe in sanctity of high level languages, it is probably a source of
wonder why anyone Would ever want to know the address of these variables
...
This is
not quite fair though
...
That would really make the idea of a high level language a bit pointless
...
Remember:
A pointer is a variable which holds the address of the storage location for another given variable
...

Pointer operators:
Uses for pointers:
Pointers and Initialization:
Example 8:
Types Casts and Pointers:
Function pointers:
Calling functions by pointer:
Questions 13:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

They can be read in a program to have the following meanings:
&

The address of
...

Another way of saying the second of these is:
*

The contents of the location pointed to by
...
The two operators * and & are always written in front of a variable,
clinging on, so that they refer, without doubt, to that one variable
...

*ptr

The contents of the variable which is pointed to by ptr
...
Declare an int type variable called somevar
...
Declare a pointer to an int type called ptr_to_somevar
...

3
...

4
...
The value is the address of the variable somevar
...
Before this, its fate is quite open
...

5
...
So this will
be just 42
...
Let the contents of the location pointed to by ptr_to_somevar be 56
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Node:Uses for pointers, Next:Pointers and Initialization, Previous:Pointer operators, Up:Pointers

Uses for Pointers
It is possible to have pointers which point to any type of data whatsoever
...

Some examples are given below
...
They are far more important in C than in, say, Pascal or BASIC
( PEEK ,POKE are like pointers)
...

We shall meet these objects in later chapters
...
It is looked at in detail in the next
section
...
It is a bit like the reverse of printf() , except that it
uses pointers to variables, not variables themselves
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

int *i;
scanf ("%d",i);

The & sign or the * sign is vital
...
This is one reason why this
important function has been ignored up to now
...
One reason why one might want to know this would be for debugging
...
The & operator is flexible enough to allow this to be found
...
It is incorrect, logically, to initialize
pointers in a declaration
...

Think about what happens when the following statement is written
...
It will then attempt to fill the contents of some variable, pointed
to by a, with the value 2
...
a only contains garbage so the 2 could be stored anywhere
...
Nothing has been said about that yet
...

Node:Example 8, Next:Types Casts and Pointers, Previous:Pointers and Initialization, Up:Pointers

Example Listing
/**********************************************/
/*
*/
/* Swapping Pointers
*/
/*
*/
/**********************************************/
/* Program swaps the variables which a,b */
/* point to
...
h>
main ()

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
This is not necessarily the case
...
There are occasions however when it is actually necessary to convert one kind of pointer
into another
...
These objects are met later on in this book
...
The cast operator for
variables, See The Cast Operator, is written in front of a variable to force it to be a particular type:
(type)

variable

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The cast operator makes sure that the pointers are in step and
not talking at cross purposes
...
In practice it may not actually do anything, but it is a necessary part of the syntax of C
...

Node:Function pointers, Next:Calling functions by pointer, Previous:Types Casts and Pointers, Up:Pointers

Pointers to functions
This section is somewhat outside of the main development of the book
...

Let's now consider pointers to functions as opposed to variables
...
The idea behind pointers to functions is that you can pass a function as a parameter to
another function! This seems like a bizarre notion at first but in fact it makes perfect sense
...
That
means that you can plug in a new function in place of an old one just by passing a different parameter value to the
function
...
In machine code circles this is sometimes called indirection or
vectoring
...
For functions, the name of the function without the round brackets works as
a pointer to the start of the function, as long as the compiler understands that the name represents the function and not
a variable with the same name
...
The reason is that you must declare
function2() explicitly like this:
int function2();

If the function returns a different type then clearly the declaration will be different but the form will be the same
...
It is not important whether the variable is declared locally
or globally, since a function is a global object regardless
...
The function which accepts a function pointer as an argument
looks like this:
function1 (a)

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Similarly if you want
to declare a pointer to a function to a general type typename with the name fnptr , you would do it like this:
typename (*fnptr)();

Node:Calling functions by pointer, Next:Questions 13, Previous:Function pointers, Up:Pointers

Calling a function by pointer
Given a pointer to a function how do we call the function? The syntax is this:
variable = (*fnptr)(parameters);

An example let us look at a function which takes an integer and returns a character
...
First define
char function();
char (*fnptr)();
fnptr = function;

then call the function with
ch = (*fnptr)(i);

A pointer to a function can be used to provide a kind of plug-in interface to a logical device, i
...
a way of choosing the
right function for the job
...
The C++ language provides an abstract form of this with a more advanced syntax, but
this is the essence of virtual function methods in object oriented languages
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

BEWARE! A pointer to a function is an automatic local variable
...
If you inadvertently forget to initialize the pointer to a function, you will come quickly to grief
...

2
...

4
...
(This is not as
pointless as it seems
...
)
5
...
65; ?
Node:Standard Output and Standard Input, Next:Assignments Expressions and Operators, Previous:Pointers, Up:Top

Standard Output and Standard Input
Talking to the user
...
Without input and
output computers would be quite useless
...
A file is really just an abtraction: a place
where information comes from or can be sent to
...
In other situations files are called I/O streams
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

C has three files (also called streams) which are always open and ready for use
...
Stdin is the input which usually arrives
from the keyboard of a computer
...
stderr is the route by which all error messages pass:
usually the screen
...
In fact what happens is that these files are
just handed over to the local operating system to deal with and it chooses what to do with them
...
depending upon
how the user ran the program
...
Also the programmer never has to open or close these, because C does it automatically
...
h provides some methods for working with stdin and stdout
...
In order of importance, they are:
printf ()
scanf ()
getchar()
putchar()
gets
()
puts
()

printf again:
Example 9:
Output 9:
Formatting with printf:
Example 10:
Output 10:
Special Control Characters again:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Its name is meant to signify formatted printing because it gives the user
control over how text and numerical data are to be laid out on the screen
...
C makes this easy by allowing you to decide how the text will be printed in the available space
...
",variables,numbers)

It contains a string (which is not optional) and it contains any number of parameters to follow: one for each blank field
in the string
...
These fields are introduced by using a % character, followed by some
coded information, which says something about the size of the blank space and the type of number or string which will
be filled into that space
...

The simplest use of printf is to just print out a string with no blank fields to be filled:
printf ("A pretty ordinary string
...
");

The next simplest case that has been used before now is to print out a single integer number:
int number = 42;
printf ("%d",number);

The two can be combined:
int number = 42;
printf ("Some number = %d",number);

The result of this last example is to print out the following on the screen:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Notice the way that %d is swapped for the number 42
...

There are other kinds of data than integers though
...
%d is called a
conversion character for integers because it tells the compiler to treat the variable to be filled into it as an integer
...
Here is a list if the
different letters for printf
...
The example program and its output
below give some impression of how they work:
Node:Example 9, Next:Output 9, Previous:printf again, Up:Standard Output and Standard Input

Example Listing
/*******************************************************/
/*
*/
/* printf Conversion Characters and Types
*/
/*
*/
/*******************************************************/
#include ...
56;
double y = 3
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

printf ("single character %c\n",ch);
printf ("whole string -> %s",string_ptr);
}

Node:Output 9, Next:Formatting with printf, Previous:Example 9, Up:Standard Output and Standard Input

Output
signed integer -10
unsigned integer 10
This is wrong! 10See what happens when you get the character wrong!Hexadecimal FFFFFFF6 A
Octal 37777777766 12
Float and double 3
...
520000
ditto
3
...
520000E+00
ditto
3
...
520000
single character z
whole string -> any old string

Node:Formatting with printf, Next:Example 10, Previous:Output 9, Up:Standard Output and Standard Input

Formatting with printf
The example program above does not produce a very neat layout on the screen
...
The % and the character type act like brackets around the extra
information
...
g
...
3f

is an extended version of %f, which carries some more information
...
p] X

where the each bracket is used to denote that the item is optional and the symbols inside them stand for the following
...
In other words, how wide a space will be
made in the string for the object concerned? In fact it is the minimum field width because if data need more
room than is written here they will spill out of their box of fixed size
...

[-]

If this included the output will be left justified
...
Normally all numbers are right justified, or aligned with the right hand margin of
the field "box"
...
p]

This has different meanings depending on the object which is to be printed
...
For a string it specifies
how many characters are to be printed
...

%10d

%2
...
21s

%2
...
The width of a field is draw in by using the
| bars
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Object to
be printed

Control Spec
...
71828
2
...
71828
2
...
718
2
...
2f
%-10
...
4f
%
...
5f

|
2
...
71|
|2
...
7182|(overspill)
|2
...
71800|

2
...
71828
2
...
2e
%10
...
71828e+00|
| 2
...
71|

"printf"
"printf"
"printf"
"printf"
"printf"
"printf"

%s
%10s
%2s
%5
...
3s
%
...
h>
main ()

/* Printing in columns */

{ int i,j;
for (i = 1; i <= 10; i++)
{
for (j = 1; j <= 10; j++)
{
printf ("%5d",i * j);
}
printf ("\n");
}
}

Node:Output 10, Next:Special Control Characters again, Previous:Example 10, Up:Standard Output and Standard Input

Output
1
2
3
4
5
6
7
8

2
4
6
8
10
12
14
16

3
6
9
12
15
18
21
24

4
8
12
16
20
24
28
32

5
10
15
20
25
30
35
40

6
12
18
24
30
36
42
48

7
14
21
28
35
42
49
56

8
16
24
32
40
48
56
64

9
18
27
36
45
54
63
72

10
20
30
40
50
60
70
80

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
They have special purposes usually to do with cursor movement
...
These characters
are listed below
...

\xddd

character ddd where ddd is an ASCII code given in hexadecimal or base 16, See Character Conversion Table
...
Write a program which simply prints out: 6
...
Investigate what happens when you type the wrong conversion specifier in a program
...
g
...
This is bound to go wrong - but how will it go wrong?
3
...
printf (x);
2
...
printf ();
4
...
This is a very versatile

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
In fact it is probably the most difficult to understand of all the C
standard library functions
...
This makes quite a difference to the way that scanf works
...
",pointers);

with one important exception: namely that it is not variables which are listed after the control string, but pointers to
variables
...
Also notice the conversion specifiers which tell scanf what
types of data it is going to read
...
For instance:
function (i,ch,x)
int *i;
char *ch;
float *x;
{
scanf ("%d %c %f", i, ch, x);
}

In this case it would actually be wrong to write the ampersand & symbol
...

d

denary integer (int or long int)
ld

long decimal integer
x

hexadecimal integer
o

octal integer
h

short integer
f

float type
lf

long float or double
e

float type
le

double
c

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
If it is found that a program's
input seems to be behaving strangely, check these carefully
...
)
Node:How does scanf see the input, Next:First account of scanf, Previous:Conversion characters, Up:Standard Output
and Standard Input

How does scanf see the input?
When scanf is called in a program it checks to see what is in the input file, that is, it checks to see what the user has
typed in at the keyboard
...
This means that the characters are held in a kind of
waiting bay in the memory until they are read
...
If the buffer has some characters in it, scanf will start to look through
these; if not, it will wait for some characters to be put into the buffer
...
If the buffer is empty scanf will wait for some
characters to be put into it
...
A line is a bunch of characters
ending in a newline character \n
...
chars
...

|'\n'|
--------------------------------------

As far as scanf is concerned, the input is entirely made out of a stream of characters
...
In other words, it will look for some characters which make up a valid integer, such as a group of numbers all
between 0 and 9
...
If the user just wants a character then any character will do!
Node:First account of scanf, Next:The dangerous function, Previous:How does scanf see the input, Up:Standard
Output and Standard Input

First account of scanf
Consider the example which was give above
...
scanf looks at the control string and finds that the first conversion
specifier is %d which means an integer
...
It skips over any white space characters (spaces, newlines) which do not constitute a valid integer until it
matches one
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

conversion specifier %c which means a character
...
Finally it looks at the
last conversion specifier %f which means a floating point number and finds some characters which fit the description
of a floating point number
...

This brief account of scanf does not tell the whole story by a long way
...
At the first character it meets
which does not fit in with the conversion string's interpretation scanf aborts and control passes to the next C statement
...
These surplus data simply wait in the input file until the next scanf is brought into operation,
where they can also cause it to quit
...

is also dangerous for the opposite reason: what happens if scanf doesn't use up all the characters in the input
line before it satisfies its needs? Again the answer is that it quits and leaves the extra characters in the input file stdin
for the next scanf to read, exactly where it left off
...
scanf can get out of step with its input if the user types
something even slightly out of line
...

scanf

Node:Keeping scanf under control, Next:Example 11, Previous:The dangerous function, Up:Standard Output and
Standard Input

Keeping scanf under control
may be dangerous for sloppy programs which do not check their input carefully, but it is easily tamed by using
it as just a part of a more sophisticated input routine and sometimes even more simply with the aid of a very short
function which can be incorporated into any program:
scanf

skipgarb()

/* skip garbage corrupting scanf */

{
while (getchar() != '\n')
{
}
}

The action of this function is simply to skip to the end of the input line so that there are no characters left in the input
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

{
printf ("Get your act together out there!!\n");
scanf (
...

Node:Example 11, Next:Matching without assigning, Previous:Keeping scanf under control, Up:Standard Output and
Standard Input

Examples
Here are some example programs with example runs to show how scanf either works or fails
...
h>
main ()
{ int i = 0;
char ch = '*';
float x = 0;
scanf ("%d %c %f",&i,&ch,&x);
printf ("%d %c %f\n",i,ch,x);
}

This program just waits for a line from the user and prints out what it makes of that line
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
3
Output: 1 x 2
...
3 |'\n'|
------------------

In this example everything works properly
...
it is simple for scanf to see what
the first number is because the next character is x which is not a valid number
...
3
Output: 1
0
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

----------|1|' '| |x 2
...
The character is now a space and the x is left in the stream
...
3 still in the input stream
...

Output: 0 * 0
...
'|
---

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
scanf quits straight away because it looks for an integer
...
) in the input stream
...
h>

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
36
and the output is:
6
0
...
36 |
---------------------

Here the integer is successfully matched with 6
...

The second scanf function then picks these up
...

/****************************************/
/* Example 3
*/
/****************************************/
#include ...
3
output: 2
...
It also allows whole
sequences of characters to be matched and skipped
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

scanf ("%*c");

would skip a single character
...
Note carefully that the following is
wrong:
scanf ("%*c", &ch);

A pointer should not be given for a dummy conversion character
...
It might seem as though there
would be no sense in writing:
scanf ("%*s %f %c",&x,&ch);

because the whole input file is one long string after all, but this is not true because, as far as scanf is concerned a
string is terminated by any white space character, so the float type x and the character ch would receive values
provided there were a space or newline character after any string
...
For
example:
scanf (" Number = %d",&i);

If the input were: Number = 256 , scanf would skip over the Number =
...

/****************************************/
/* Example 4
*/
/****************************************/
#include ...
000000 23 *
Input : 26
Output: 0
...

Node:Formal Definition of scanf, Next:Summary of points about scanf, Previous:Matching without assigning,
Up:Standard Output and Standard Input

Formal Definition of scanf
The general form of the scanf function is:
n = scanf ("string
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

The value n returned is the number of items matched or the end of file character EOF , or NULL if the first item did not
match
...
The control string contains a number of conversion specifiers with the following
general form:
%[*][n]X
[*]

the optional assignment suppression character
...
That is, the
maximum number of characters which are to be thought of as being part of one the current variable value
...

Any white space characters in the scanf string are ignored
...
The pointers must be
pointers to variables of the correct type and they must match the conversion specifiers in the order in which they are
written
...
Both of the following imply strings:
%[set of characters]

a string made up of the given characters only
...

For example, to read the rest of a line of text, up to but not including the end of line, into a string array one would
write:
scanf("%[^\n]",stringarray);

Node:Summary of points about scanf, Next:Questions 15b, Previous:Formal Definition of scanf, Up:Standard Output
and Standard Input

Summary of points about scanf
Scanf works across input lines as though it were dealing with a file
...
The whole line is then thought of as being part of the input file pointer stdin
...

If scanf fails at any stage to match the correct type of string at the correct time, it will quit leaving the remaining
input still in the file
...

White space characters are ignored for all conversion characters except %c
...

White space characters in
Node:Questions 15b, Next:Low Level Input/Output, Previous:Summary of points about scanf, Up:Standard Output and
Standard Input

Questions
1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

2
...
Print out the answer
...

3
...

4
...

5
...
True or false?
Node:Low Level Input/Output, Next:Questions 15c, Previous:Questions 15b, Up:Standard Output and Standard Input

Low Level Input/Output
getchar and putchar:
gets and puts:
Node:getchar and putchar, Next:gets and puts, Previous:Low Level Input/Output, Up:Low Level Input/Output
getchar

and putchar

and printf() are relatively high level functions: this means that they are versatile and do a lot of hidden
work for the user
...
These functions are called getchar() and putchar() but, in fact, they might not be functions: they could be
macros instead, See Preprocessor
...

returns a character type: the next character on the input file
...
Notice that no conversion to different data
types can be performed by getchar() because it deals with single characters only
...

was used in the function skipgarb() to tame the scanf() function
...
Another way of writing it would be as below:
getchar

skipgarb ()

/* skip garbage corrupting scanf */

{ char ch;
ch = getchar();
while (ch != '\n')
{
ch = getchar();
}
}

The != symbol means "is not equal to" and the while statement is a loop
...
This function has many uses
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

statements of languages like BASIC, where a program responds to keys as they are pressed without having to wait for
return to be pressed
...
For example:
printf("Press RETURN to continue\n");
skipgarb();

does not receive any input until the user presses RETURN, and then it simply skips over it in one go! The
effect is that it waits for RETURN to be pressed
...
For example:

char ch = '*';
putchar (ch);
ch = putchar (ch);

These two alternatives have the same effect
...
In other words it just hands the same value back again
...

putchar() is not much use without loops to repeat it over and over again
...
This means that it might not be possible to use functions as parameters inside them:
putchar( function() );

This depends entirely upon the compiler, but it is something to watch out for
...
Their purpose is either to read a whole string from the input file stdin or write a whole string to
the output stdout
...
For instance:
char *string[length];
string = gets(string);
puts(string);

More information about these is given later, See Strings
...
Is the following statement possible? (It could depend upon your compiler: try it!)
putchar(getchar());

What might this do? (Hint: re-read the chapter about the pre-processor
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

2
...

Node:Assignments Expressions and Operators, Next:Decisions, Previous:Standard Output and Standard Input, Up:Top

Assignments, Expressions and Operators
Thinking in C
...

An operator is something which takes one or more values and does something useful with those values to produce a
result
...
The terminology of operators is the following:
operator
Something which operates on someting
...

operation
The action which was carried out upon the operands by the operator!
There are lots of operators in C
...
These rough groupings are thought of as follows:
Operators which produce new values from old ones
...
e
...
+, the addition
operator takes two numbers or two variables or a number and a variable and adds them together to give a new
number
...
e
...
less than, equal to, greater than
...

The majority of operators fall into the first group
...

C has no less than thirty nine different operators
...
The object of this chapter is to explain the basics of
operators in C
...

Expressions and values:
Example 12:
Output 12:
Parentheses and Priority:
Unary Operator Precedence:
Special Assignment Operators ++ --:
More Special Assignments:
Example 13:
Output 13:
The Cast Operator:
Expressions and Types:
Summary of Operators and Precedence:
Questions 16:
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
In C these are the following:
+

plus (unary)
-

minus (force value to be negative)
+

addition
-

subtraction
*

multiplication
/

floating point division
/

integer division "div"
%

integer remainder "mod"
These operators would not be useful without a partner operator which could attach the values which they produce to
variables
...
For example:
double x,y;
x = 2
...
As usual there is some standard jargon for this, which is useful to know because
compilers tend to use this when handing out error messages
...
An expression is simply the name
for any string of operators, variables and numbers
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

(22 + 4*(function() + 2))
function ()

/* provided it returns a sensible value */

Lvalues on the other hand are simply names for memory locations: in other words variable names, or identifiers
...

Node:Example 12, Next:Output 12, Previous:Expressions and values, Up:Assignments Expressions and Operators

Example
/**************************************/
/*
*/
/* Operators Demo # 1
*/
/*
*/
/**************************************/
#include ...
0 / 4
...
250000

Node:Parentheses and Priority, Next:Unary Operator Precedence, Previous:Output 12, Up:Assignments Expressions
and Operators

Parentheses and Priority

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
They have a value in the
sense that they assume the value of whatever expression is inside them
...
If an expression is written out in an ambiguous way, such as:
a + b / 4 * 2

it is not clear what is meant by this
...
By using parentheses, any doubt about what the expression means is removed
...

Putting parentheses in may remove the ambiguity of expressions, but it does not alter than fact that
a + b / 4 * 2

is ambiguous
...
The convention is that some operators are stronger
than others and that the stronger ones will always be evaluated first
...
Use parentheses to be sure
...

Node:Unary Operator Precedence, Next:Special Assignment Operators ++ --, Previous:Parentheses and Priority,
Up:Assignments Expressions and Operators

Unary Operator Precedence
Unary operators are operators which have only a single operand: that is, they operate on only one object
...

Node:Special Assignment Operators ++ --, Next:More Special Assignments, Previous:Unary Operator Precedence,
Up:Assignments Expressions and Operators

Special Assignment Operators ++ and -C has some special operators which cut down on the amount of typing involved in a program
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

which it becomes important to think in C and not in other languages
...
(character types too, with care
...
Normally, in other languages, this is accomplished by writing:
variable = variable + 1;

In C this would also be quite valid, but there is a much better way of doing this:
variable++; or
++variable;

would do the same thing more neatly
...
In some cases the
two are identical, but in the more advanced uses of C operators, which appear later in this book, there is a subtle
difference between the two
...
Like ++ and -- these are short ways of writing longer expressions
...
It could be done more simply using the general
increment operator: +=
variable += 23;

This performs exactly the same operation
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

as
variable1 += variable2;

and so on
...
There is, naturally, one for subtraction too:
variable = variable - 42;

can be written:
variable -= 42;

More surprisingly, perhaps, the multiplicative assignment:
variable = variable * 2;

may be written:
variable *= 2;

and so on
...

and there are more exotic kinds, used for bit operations or machine level operations, which will be ignored at this
stage:
>>=
<<=
^=
|=
&=

Node:Example 13, Next:Output 13, Previous:More Special Assignments, Up:Assignments Expressions and Operators

Example Listing
/**************************************/
/*
*/
/* Operators Demo # 2
*/
/*
*/
/**************************************/
#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

/**************************************/
main ()
{ int i;
printf ("Assignment Operators\n\n");
i = 10;
printf("i = 10 : %d\n",i);

/* Assignment */

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

/* i = i + 1 */

i += 5;
printf ("i += 5 : %d\n",i);

/* i = i + 5 */

i--;
printf ("i-- : %d\n",i);

/* i = i = 1 */

i -= 2;
printf ("i -= 2 : %d\n",i);

/* i = i - 2 */

i *= 5;
printf ("i *= 5 :%d\n",i);

/* i = i * 5 */

i /= 2;
printf ("i /= 2 : %d\n",i);

/* i = i / 2 */

i %= 3;
printf ("i %%= 3 : %d\n",i);
}

/* i = i % 3 */

Node:Output 13, Next:The Cast Operator, Previous:Example 13, Up:Assignments Expressions and Operators

Output
Assignment Operators
i = 10 : 10
i++ : 11
i += 5 : 16
i-- : 15
i -= 2 : 13
i *= 5 :65
i /= 2 : 32
i %= 3 : 2

Node:The Cast Operator, Next:Expressions and Types, Previous:Output 13, Up:Assignments Expressions and
Operators

The Cast Operator
The cast operator is an operator which forces a particular type mould or type cast onto a value, hence the name
...
It will always produce some value, whatever the conversion:
however remotely improbable it might seem
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Node:Expressions and Types, Next:Summary of Operators and Precedence, Previous:The Cast Operator,
Up:Assignments Expressions and Operators

Expressions and Types
There is a rule in C that all arithmetic and mathematical operations must be carried out with long variables: that is, the
types
double
long float
int
long int

If the programmer tries to use other types like short or float in a mathematical expression they will be cast into long
types automatically by the compiler
...
The compiler is perfectly correct of course, even though it appears to be wrong
...
So the right hand side is int type and the left hand side is short type: hence there is indeed a type
mismatch
...
3;
x = y * 2
...

Comparisons and Logic

Comparisons and Logic
Six operators in C are for making logical comparisons
...
The six operators which compare values are:
==

is equal to
!=

is not equal to
>

is greater than
<

is less than
>=

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The values which they produce are called
true and false
...
These comparison
operators are used for making decisions, but they are themselves operators and expressions can be built up with them
...
The statement:
int i;
i = (1 == 2);

would be false, so i would be false
...

Comparisons are often made in pairs or even in groups and linked together with words like OR and AND
...
The logical operators, as they are called, are as
follows:
&&

logical AND
||

logical OR inclusive
!

logical NOT
The statement which was written in words above could be translated as:
(A > B) && (A > C)

The statement:
(A is greater than B) AND (A is not greater than C)

translates to:
(A > B) && !(A > C)

Shakespeare might have been disappointed to learn that, whatever the value of a variable tobe the result of
thequestion = tobe || !tobe

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The NOT operator always creates the logical opposite: !true is false and !false is true
...
thequestion is therefore always true
...

Operator

Operation

Evaluated
...
What is an operand?
2
...

3
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Write a statement which subtracts -5 from 10
...
Write in C: if 1 is not equal to 23, print out "Thank goodness for mathematics!"
Node:Decisions, Next:Loops, Previous:Assignments Expressions and Operators, Up:Top

Decisions
Testing and Branching
...

Suppose that a fictional traveller, some character in a book like this one, came to the end of a straight, unfinished road
and waited there for the author to decide where the road would lead
...
If the traveller is thirsty he will stop for a drink before continuing
...

The road might have a crossroads or a meeting point where many roads come together
...

We are often faced with this dilemma: a situation in which a decision has to be made
...
They have all followed narrow
paths without any choice about which way they were going
...
For instance, one might want
to implement the following ideas in different programs:
If the user hits the jackpot, write some message to say so
...

If the user has typed in one of five things then do something special for each special case, otherwise do
something else
...

In the first case there is a simple choice: a do of don't choice
...

The final choice has several possibilities
...
They are listed here below
...

1:

if (something_is_true)
{
/* do something */
}

2a:

if (something_is_true)
{
/* do one thing */
}
else
{
/* do something else */
}

2b:

? (something_is_true) :
/* do one thing */
:
/* do something else */

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

}

if:
example f1:
if else:
Nested ifs and logic:
Example 14:
Stringing together if
...
if some condition is satisfied, do what is in the braces,
otherwise just skip what is in the braces
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Notice that, as well as a single statement, a whole block of statements can be written under the if statement
...
A compound statement is a block of single statements enclosed by curly braces
...
It must have a value
which is either true or false (1 or 0) and it must be enclosed by the parentheses ( and )
...
Some of the following examples help to show this:
int i;
printf ("Type in an integer");
scanf ("%ld",&i);
if (i == 0)
{
printf ("The number was zero");
}
if (i > 0)
{
printf ("The number was positive");
}
if (i < 0)
{
printf ("The number was negative");
}

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
This does no harm
...
It also has the appeal that it makes if statements look the same as all other
block statements and it makes them stand out clearly in the program text
...
To do much more for programs it needs to be extended
...

Node:example f1, Next:if else, Previous:if, Up:Decisions

Example Listings
/*****************************************/
/*
*/
/* If
...
h>
#define TRUE
#define FALSE

1
0

/******************************************/
main ()
{ int i;
if (TRUE)
{
printf ("This is always printed");
}
if (FALSE)
{
printf ("This is never printed");
}
}
/*******************************************/
/*
*/
/* If demo #2
*/
/*
*/
/*******************************************/
/* On board car computer
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

#include ...

*/
double *fuel,*distance;
{
/* how much fuel used since last check on values */
printf ("Enter fuel used");
scanf ("%lf",fuel);
/* distance travelled since last check on values */
printf ("Enter distance travelled");
scanf ("%lf",distance);
}
/**********************************************/
Report (fuel,distance)

/* on dashboard */

double fuel,distance;
{ double kpl;
kpl = distance/fuel;
printf ("fuel consumption: %2
...
else

The if
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

if (condition) statement1; else statement2;

This is most often written in the compound statement form:
if (condition)
{
statements
}
else
{
statements
}

The if
...
When it is executed, the condition is
evaluated and if it has the value `true' (i
...
not zero) then statement1 is executed
...
The if
...
For
instance:
int i;
scanf ("%ld",i);
if (i > 0)
{
printf ("That number was positive!");
}
else
{
printf ("That number was negative or zero!");
}

It is not necessary to test whether i was negative in the second block because it was implied by the if
...

That is, that block would not have been executed unless i were NOT greater than zero
...
Their purposes are exactly the
same
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

}
}

Both of these test i for the same information, but they do it in different ways
...

The second method is more complicated
...
It says:
If i is greater than 2, do what is in the curly braces
...
Now, if i is also less than 4, then do what is inside
the new curly braces
...
But wait! The whole of the second test is
held inside the "i is greater than 2" braces, which is a sealed capsule: nothing else can get in, so, if the program
gets into the "i is less than 4" braces as well, then both facts must be true at the same time
...
So i is 3
...
Using the logical
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
several multiple tests can be made
...
This is another
advantage of using the curly braces: it helps the programmer to see that if statements and if
...
Once inside a sealed capsule
if (i > 2)
{
/* i is greater than 2 in here! */
}
else
{
/* i is not greater than 2 here! */
}

the programmer can rest assured that nothing illegal can get in
...
This is an enourmous weight off the mind! The
programmer can sit back and think: I have accepted that i is greater than 2 inside these braces, so I can stop worrying
about that now
...
They learn to be satisfied that certain
things have already been proven and thus save themselves from the onset of madness as the ideas become too complex
to think of all in one go
...
else, Previous:Nested ifs and logic, Up:Decisions

Example Listing
/***********************************************/
/*
*/
/* If demo #3
*/
/*
*/
/***********************************************/
#include ...
\n");
}
/**************************************************/
getnumber ()

/* get a number from the user */

{ int num = 0;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
else, Next:switch, Previous:Example 14, Up:Decisions

Stringing together if
...
They both look identical when compiled and run
...
h>
main ()
{ int result;
printf("Type in exam result");
scanf ("%d",&result);
if (result < 10)
{
printf ("That is poor");
}
if (result > 20)
{
printf ("You have passed
...
h>
main ()
{ int result;
printf("Type in exam result");
scanf ("%d",&result);
if (result < 10)
{
printf ("That is poor");
}
else
{
if (result > 20)
{
printf ("You have passed
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

}
else
{
if (result > 70)
{
printf ("You got an A!");
}
}
}
}

The answer is that the second of these programs can be more efficient
...
Program one makes every single test, because the
program meets every if statement, one after the other
...
The
nested if statements make sure that the second two tests are only made if the first one failed
...
So the second program could end up doing a third of the work of the first
program, in the best possible case
...
Nested loops make a program branch into lots of possible paths, but choosing one path
would preclude others
...
else, Up:Decisions

switch :

integers and characters

The switch construction is another way of making a program path branch into lots of different limbs
...
else statements, but it is more versatile than that and it only works for
integers and character type values
...
(See the diagram
...

}

/* optional */

It has an expression which is evaluated and a number of constant `cases' which are to be chosen from, each of which
is followed by a statement or compound statement
...
break is a reserved word
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

The switch statement can be written more specifically for integers:
switch (integer value)
{
case 1:
case 2:

statement1;
break;

/* optional line */

statement2;
break;

/* optional line */


...
If a match is made (for instance,
if the expression is evaluated to 23 and there is a statement beginning "case 23 :
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

case statement and will carry on until either the closing brace } is encountered or a break statement is found
...
One of the cases is called default
...
switch is a way of choosing some action
from a number of known instances
...

Node:Example 15, Next:To try, Previous:switch, Up:Decisions

Example Listing
/************************************************/
/*
*/
/* switch
...
Enter a number and */
/* find out what it is in Morse code
*/
#include ...
9");
scanf ("%h",&digit);
if ((digit < 0) || (digit > 9))
{
printf ("Number was not in range 0
...
----");
("
...
--");
("
...
");
("-
...
");
("---
...
");

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
At every case in the switch, a break
statement is used
...
If break were
not included it would go right on executing the statements to the end, testing the cases in turn
...

There might be cases where it is not necessary or not desirable to jump out of the switch immediately
...

yes ()

/* A sloppy but simple function */

{
switch (getchar())
{
case 'y' :
case 'Y' : return TRUE
default : return FALSE
}
}

If the character is either 'y' or 'Y' then the function meets the statement return TRUE
...
The return statement does more
than break out of switch, it breaks out of the whole function, so in this case break was not required
...

Node:To try, Previous:Example 15, Up:Decisions

Things to try
1
...

2
...

3
...

Node:Loops, Next:Arrays, Previous:Decisions, Up:Top

Loops
Controlling repetitive processes
...
Loops free a program from the straitjacket of doing things only once
...
There are three kinds of loop in C
...
while
for

These three loops offer a great amount of flexibility to programmers and can be used in some surprising ways!
while:
Example 16:
Example 17:
do while:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
In common language while has a fairly obvious meaning: the while loop has a condition:
while (condition)
{
statements;
}

and the statements in the curly braces are executed while the condition has the value "true" ( 1 )
...

The first important thing about this loop is that has a conditional expression (something like (a > b) etc
...
If the value of the expression is true, then it will carry on
with the instructions in the curly braces
...
The computer then moves onto the next statement in the program
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

The second thing to notice about this loop is that the conditional expression comes at the start of the loop: this means
that the condition is tested at the start of every `pass', not at the end
...

The best way to illustrate a loop is to give an example of its use
...
That was:
skipgarb ()

/* skip garbage corrupting scanf */

{
while (getchar() != '\n')
{
}
}

This is a slightly odd use of the while loop which is pure C, through and through
...
Something which is immediately obvious from listing
is that the while loop in skipgarb() is empty: it contains no statements
...
at least it would do nothing if it were not for the assignment in the conditional
expression! It could also be written:
skipgarb ()

/* skip garbage corrupting scanf */

{
while (getchar() != '\n')
{
}
}

The assignment inside the conditional expression makes this loop special
...
When the
loop is encountered, the computer attempts to evaluate the expression inside the parentheses
...
getchar() then takes on the value of the character which it fetched from the input file
...
This means that there is a comparison to be made
...
If they are equal the expression is false
...
When
the expression eventually becomes false the loop will quit
...

Node:Example 16, Next:Example 17, Previous:while, Up:Loops

Example Listing
Another use of while is to write a better function called yes()
...
It uses a while loop which is always true to repeat the process of getting a response from the user
...

/***********************************************/
/*
*/
/* Give me your answer!
*/
/*
*/
/***********************************************/
#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

/*************************************************/
/* Level 0
*/
/*************************************************/
main ()
{
printf ("Yes or no? (Y/N)\n");
if (yes())
{
printf ("YES!");
}
else
{
printf ("NO!");
}
}
/*************************************************/
/* Level 1
*/
/*************************************************/
yes ()

/* get response Y/N query */

{ char getkey();
while (true)
{
switch (getkey())
{
case 'y' : case 'Y' : return (TRUE);
case 'n' : case 'N' : return (FALSE);
}
}
}
/*************************************************/
/* Toolkit
*/
/*************************************************/
char getkey ()

/* get a character + RETURN */

{ char ch;
ch = getchar();
skipgarb();
}
/**************************************************/
skipgarb ()
{
while (getchar() != '\n')
{
}
}
/* end */

Node:Example 17, Next:do while, Previous:Example 16, Up:Loops

Example Listing
This example listing prompts the user to type in a line of text and it counts all the spaces in that line
...

/***********************************************/
/*
*/
/* while loop
*/
/*
*/
/***********************************************/

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h>
main ()
{ char ch;
short count = 0;
printf ("Type in a line of text\n");
while ((ch = getchar()) != '\n')
{
if (ch == ' ')
{
count++;
}
}
printf ("Number of space = %d\n",count);
}

Node:do while, Next:Example 18, Previous:Example 17, Up:Loops

do
...
while loop resembles most closely the repeat
...
The do loop has the form:
do
{
statements;
}
while (condition)

Notice that the condition is at the end of this loop
...
while loop will always be executed at least
once, before the test is made to determine whether it should continue
...
while
...
while loop is like the "repeat
...

repeat

do
==

until(condition)

while (!condition)

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
while loop
...
If a string is found, the program prints out the contents of
the string only
...
"what a terrible
...


If the string has only one quote mark then the error message `string was not closed before end of line' will be printed
...
while demo
*/
/*
*/
/**********************************************/
/* print a string enclosed by quotes " " */
/* gets input from stdin i
...
keyboard
*/
/* skips anything outside the quotes
*/

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h>
/*************************************************/
/* Level 0
*/
/*************************************************/
main ()
{ char ch,skipstring();
do
{
if ((ch = getchar()) == '"')
{
printf ("The string was:\n");
ch = skipstring();
}
}
while (ch != '\n')
{
}
}
/*************************************************/
/* Level 1
*/
/*************************************************/
char skipstring () /* skip a string "
...
The name for is a hangover from
earlier days and other languages
...
The name comes from the
typical description of a classic for loop:
For all values of variable from value1 to value2 in steps of value3, repeat the following sequence of
commands
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

The C for loop is much more versatile than its BASIC counterpart; it is actually based upon the while construction
...
That
variable is somehow associated with the loop
...
The form of the for loop is:
for (statement1; condition; statement2)
{
}

For normal usage, these expressions have the following significance
...
This statement is only carried out once
before the start of the loop
...
g
...
The condition is evaluated at the beginning of every loop
and the loop is only carried out while this expression is true
...
g
...
In languages such as Pascal this
always means adding or subtracting 1 from the variable
...
e
...
i++ or i *= 20
or i /= 2
...

Compare a C for loop to the BASIC for loop
...
5:
FOR X = 0 TO 10 STEP 0
...
5)
{
}

The C translation looks peculiar in comparison because it works on a subtly different principle
...
The result is that a C for loop often has the <= symbol in it
...
It could be used
to find the sum of the first n natural numbers very simply:
sum = 0;
for (i = 0; i <= n; i++)
{
sum += i;
}

It generally finds itself useful in applications where a single variable has to be controlled in a well determined way
...
Prime numbers are
numbers which cannot be divided by any number except 1 without leaving a remainder
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

/*
/*
/*
/*

Check for prime number by raw number
crunching
...
h>
#define MAXINT
#define TRUE
#define FALSE

500
1
0

/*************************************************/
/* Level 0
*/
/*************************************************/
main ()
{ int i;
for (i = 2; i <= MAXINT; i++)
{
if (prime(i))
{
printf ("%5d",i);
}
}
}
/*************************************************/
/* Level 1
*/
/*************************************************/
prime (i)

/* check for a prime number */

int i;
{ int j;
for (j = 2; j <= i/2; j++)
{
if (i % j == 0)
{
return FALSE;
}
}
return TRUE;
}

Node:The flexible for loop, Next:Quitting Loops and Hurrying Them Up!, Previous:for, Up:Loops

The flexible for loop
The word `statement' was chosen carefully, above, to describe what goes into a for loop
...
C will accept any statement in the place of those above, including the empty
statement
...
This flexibility can be put to better uses though
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

for (x = 2; x <= 1000; x = x * x)
{

...
The loop starts off by initializing ch
with a star character
...
On each
new pass, ch is reassigned by calling the function getchar()
...

Why not put that statement in the curly braces? In most cases that would be the best thing to do, but in special
instances it might keep a program tidier or more readable to put it in a for loop instead
...

It is not only the statements which are flexible
...

int i, number = 20;
for (i = 0; i <= number; i++)
{
if (i == 9)
{
number = 30;
}
}

This is so nerve shattering that many languages forbid it outright
...

Node:Quitting Loops and Hurrying Them Up!, Next:Nested Loops, Previous:The flexible for loop, Up:Loops

Quitting Loops and Hurrying Them Up!
C provides a simple way of jumping out of any of the three loops above at any stage, whether it has finished or not
...

break;

If this statement is encountered a loop will quit where it stands
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

{
if (i == 12)
{
break;
}
}

Still another way of making skipgarb() would be to perform the following loop:
while (TRUE)
{
ch = getchar();
if (ch == '\n')
{
break;
}
}

Of course, another way to do this would be to use the return() statement, which jumps right out of a whole function
...

As well as wanting to quit a loop, a programmer might want to hurry a loop on to the next pass: perhaps to avoid
executing a lot of irrelevant statements, for instance
...
This might be useful to avoid dividing by zero in a program:
for (i = -10; i <= 10; i++)
{
if (i == 0)
{
continue;
}
printf ("%d", 20/i);
}

Node:Nested Loops, Next:Questions 18, Previous:Quitting Loops and Hurrying Them Up!, Up:Loops

Nested Loops
Like decisions, loops will also nest: that is, loops can be placed inside other loops
...
The idea of nested
loops is important for multi-dimensional arrays which are examined in the next section
...
Another outer loop could be used to control the
number of times that a whole loop is carried out
...

/*****************************************/
/*
*/
/* A "Square"
*/
/*
*/
/*****************************************/
#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

for (i = 1; i <= SIZE; i++)
{
for (j = 1; j <= SIZE; j++)
{
printf("*");
}
printf ("\n");
}
}

The output of this program is a "kind of" square:
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********

Node:Questions 18, Previous:Nested Loops, Up:Loops

Questions
1
...

3
...

5
...

Write a program to get 10 numbers from the user and add them together
...

Arrays are a convenient way of grouping a lot of variables under a single variable name
...
For example: an array of three integers
called "triplet" would be declared like this:
int triplet[3];

Notice that there is no space between the square bracket [ and the name of the array
...

int triplet:

|

-----------------------------------|
|
|
------------------------------------

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The three integers are called elements of the
array and they are referred to in a program by writing:
triplet[0]
triplet[1]
triplet[2]

Note that the indicies start at zero and run up to one less than the number which is placed in the declaration (which is
called the dimension of the array
...
Also notice that every element in an
array is of the same type as every other
...
When arrays are declared inside a function, storage is allocated for them, but that storage space is not
initialized: that is, the memory space contains garbage (random values)
...
This usually means that all the elements in the array
will be set to zero
...
It is then highly beneficial to move over to
arrays for storing information for two reasons:
The storage spaces in arrays have indicies
...

In C, arrays can be initialized very easily indeed
...

The first of these reasons is probably the most important one, as far as C is concerned, since information can be stored
in other ways with equally simple initialization facilities in C
...
By defining macros for the names of the different cars, they could easily
be linked to the elements in an array
...
e
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h>
#define
#define
#define
#define

NOTFINISHED
CAR
AUTO
BIL

1
0
1
2

/************************************************/
main ()
{ int type[3];
int index;
for (index = 0; index < 3; index++)
{
type[index] = 0;
}
while (NOTFINISHED)
{
printf ("Enter type number 0,1, or 2");
scanf ("%d", &index);
skipgarb();
type[index] += 1;
}

/* See text below */

}

This program, first of all, initializes the elements of the array to be zero
...
The effect is
to count the cars as they go past
...
(See
the section below about this
...
In short: it is not very
useful
...
Two dimensional arrays have a chessboard-like structure already and they require two
numbers (two indicies) to pinpoint a particular storage cell
...

Arrays play an important role in the handling of string variables
...

Node:Limits and The Dimension of an array, Next:Arrays and for loops, Previous:Why use arrays?, Up:Arrays

Limits and The Dimension of an array
C does not do much hand holding
...
This is especially true with arrays
...
If you wrote:
array[7] = '*';

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Unfortunately this would probably be memory taken up by some other variable or perhaps
even by the operating system
...

The value would corrupt the memory and crash the program completely! On Unix systems this leads to a
memory segmentation fault
...
Writing over the
bounds of an array is a common source of error
...

Node:Arrays and for loops, Next:Example 19, Previous:Limits and The Dimension of an array, Up:Arrays

Arrays and for loops
Arrays have a natural partner in programs: the for loop
...
Consider a one dimensional array called array
...
Consider:
#define SIZE

10;

main ()
{ int i, array[size];
for (i = 0; i < size; i++)
{
array[i] = i;
}
}

This fills each successive space with the number of its index:
index
element
contents

0

1

2

3

4

5

6

7

8

9

--------------------------------------| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---------------------------------------

The for loop can be used to work on an array sequentially at any time during a program, not only when it is being
initialized
...
This sieve is an array which is used for weeding out prime numbers, that is: numbers which
cannot be divided by any number except 1 without leaving a remainder or a fraction
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

numbers in turn and deleting (setting equal to zero) every multiple of every number from the array
...
Try to follow
the listing below
...
h>
#define SIZE
#define DELETED

5000
0

/*******************************************************/
/* Level 0
*/
/*******************************************************/
main ()
{ short sieve[SIZE];
printf ("Eratosthenes Sieve \n\n");
FillSeive(sieve);
SortPrimes(sieve);
PrintPrimes(sieve);
}
/*********************************************************/
/* Level 1
*/
/*********************************************************/
FillSeive (sieve)

/* Fill with integers */

short sieve[SIZE];
{ short i;
for (i = 2; i < SIZE; i++)
{
sieve[i] = i;
}
}
/**********************************************************/
SortPrimes (sieve)

/* Delete non primes */

short sieve[SIZE];
{ short i;
for (i = 2; i < SIZE; i++)
{
if (sieve[i] == DELETED)
{
continue;
}
DeleteMultiplesOf(i,sieve);
}
}
/***********************************************************/
PrintPrimes (sieve)

/* Print out array */

short sieve[SIZE];
{ short i;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
of an integer */

short i,sieve[SIZE];
{ short j, mult = 2;
for (j = i*2; j < SIZE; j = i * (mult++))
{
sieve[j] = DELETED;
}
}
/* end */

Node:Arrays Of More Than One Dimension, Next:Arrays and Nested Loops, Previous:Example 19, Up:Arrays

Arrays Of More Than One Dimension
There is no limit, in principle, to the number of indicies which an array can have
...
) An array of two dimensions could be declared as follows:
float numbers[SIZE][SIZE];

is some constant
...
) This is called a two dimensional
array because it has two indicies, or two labels in square brackets
...

SIZE

-----------------------------------| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
...


...
The elements are accessed by giving the coordinates of the
element in the grid
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

array[2][3] = 12;

The usual terminology for the two indicies is that the first gives the row number in the grid and that the second gives
the column number in the grid
...
) An array cannot be stored in the
memory as a grid: computer memory is a one dimensional thing
...
The following
array:
-----------| 1 | 2 | 3 |
-----------| 4 | 5 | 6 |
-----------| 7 | 8 | 9 |
------------

would be stored:
-----------------------------------| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
-----------------------------------* ROW # 1 * ROW # 2 * ROW #3
*

Another way of saying that arrays are stored row-wise is to say that the second index varies fastest, because a twodimensional array is always thought of as
...
That means the column index goes from 0
...

A three dimensional array, like a cube or a cuboid, could also be defined in the same kind of way:
double cube[SIZE][SIZE][SIZE];

or with different limits on each dimension:
short

notcubic[2][6][8];

Three dimensional arrays are stored according to the same pattern as two dimensional arrays
...

Node:Arrays and Nested Loops, Next:Example 20, Previous:Arrays Of More Than One Dimension, Up:Arrays

Arrays and Nested Loops
Arrays of more than one dimension are usually handled by nested for loops
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

}
}
}

In three dimensions, three nested loops would be needed:
main ()
{ int i,j,k;
float array[SIZE1][SIZE2][SIZE3];
for (i = 0; i < SIZE1; i++)
{
for (j = 0; j < SIZE2; j++)
{
for (k = 0; k < SIZE3; k++)
{
array[i][j][k] = 0;
}
}
}
}

An example program helps to show how this happens in practice
...
The aim is to mimic something like cell reproduction by applying some rigid rules to a pattern of dots

...
A dot is a place where there is no life (as we know it!) and a star is a place in which there is a living
thing
...
Things to notice are the way the program traverses the arrays and the
way in which it checks that it is not overstepping the boundaries of the arrays
...
Simulates the reproduction of cells
which depend on one another
...
h>
#define
#define
#define
#define

SIZE
MAXNUM
INBOUNDS
NORESPONSE

20
15
(a>=0)&&(a=0)&&(b1

/*********************************************************/
/* Level 0
*/
/*********************************************************/
main ()
{ int count[SIZE][SIZE];
char array[SIZE][SIZE];
int generation = 0;
printf ("Game of Life\n\n\n");
InitializeArray(array);
while (NORESPONSE)
{
CountNeighbours(array,count);

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
RETURN to continue
...
Type '
...
\n");
("RETURN after each line
...
')
{
array[i][j] = '
...
Press RETURN
...
New life will be born to a dead */
/* cell if there are exactly three neighbours */
char array[SIZE][SIZE];
int count[SIZE][SIZE];
{ int i,j;
for (i = 0; i < SIZE; i++)
{

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
';
break;
}
}
else
{
switch (count[i][j])
{
case 3 : array[i][j] = '*';
break;
default: continue;
}
}
}
}
}
/*******************************************************/
UpdateDisplay (array,g)

/* print out life array */

char array[SIZE][SIZE];
int g;
{ int i,j;
printf ("\n\nGeneration %d\n\n",g);
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
printf("%c",array[i][j]);
}
printf("\n");
}
}
/*******************************************************/
/* Level 2
*/
/*******************************************************/
numalive (array,i,j)
/* Don't count array[i,j] : only its neighbours */
/* Also check that haven't reached the boundary */
/* of the array
*/
char array[SIZE][SIZE];
int i,j;
{ int a,b,census;
census = 0;
for (a = (i-1); (a <= (i+1)); a++)
{
for (b = (j-1); (b <= (j+1)); b++)
{
if (INBOUNDS && (array[a][b] == '*'))
{
census++;
}
}
}
if (array[i][j] == '*') census--;
return (census);
}
/********************************************************/

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Type '
...

RETURN after each line
...


...


...


...


...


...

*********************

...


...


...


...
)

(It doesn't matter if the input
spills over the SIZE guide,
because "skipgarb()" discards it
...
Press RETURN
...


...


...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial


...


...


...


...


...


...


...


...

Q for quit
...

Generation 2

...


...


...


...


...


...
*

...


...


...


...

Q for quit
...

Generation 3

...


...


...


...


...


...
**

...


...


...


...

Q for quit
...

Generation 4

...


...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...


...


...


...
*
*
...
*

...


...


...


...
RETURN to continue
...
Try experimenting with different starting patterns
...
The first way is by assigning every element to some value with a statement like:
array[2] = 42;
array[3] = 12;

or perhaps with the aid of one or more for loops
...
This method only works for static variables and external variables
...
A 3 by 3 array could be initialized in the
following way:
static int array[3][3] =
{
{10,23,42},
{1,654,0},
{40652,22,0}
};

The internal braces are unnecessary, but help to distinguish the rows from the columns
...

Note that, if there are not enough elements in the curly braces to account for every single element in an array, the
remaining elements will be filled out with zeros
...

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
There is another way of looking at
arrays which follows the BCPL idea of an array as simply a block of memory
...

The name of an array variable, standing alone, is actually a pointer to the first element in the array
...
(In this
case it is type `pointer to float '
...
3;

or by writing
*numbers = 22
...

char arrayname[5];
char *ptr;
for (ptr = arrayname; ptr <= arrayname+4; ptr++)
{
*ptr = 0;
}

The code above sets the array arrayname to zero
...
If a program is running on a normal microcomputer, then there
should be few problems with this alternative method of handling arrays
...
A multi-tasking system
shares memory with other programs and it takes what it can find, where it can find it
...
So
ptr = arrayname + 5;

might not be a pointer to the fifth character in a character array
...
A
pointer to the fifth element can be reliably found with:
ptr = &(arrayname[5]);

Be warned!
Node:Arrays as Parameters, Next:Questions 19, Previous:Arrays and Pointers, Up:Arrays
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Arrays can be passed as parameters, but only as
variable ones
...
The Game of Life
program above does this
...

main ()
{
char array[23];
function (array);

...
Array parameters are
always variable parameters
Node:Questions 19, Previous:Arrays as Parameters, Up:Arrays

Questions
1
...
How do you pass an array as a parameter? When the parameter is received by a function does C allocate space
for a local variable and copy the whole array to the new location?
3
...
What numbers can be written
in the indicies of the array?
Node:Strings, Next:Putting together a program, Previous:Arrays, Up:Top

Strings
Communication with arrays
...
In C a string is represented as some characters
enclosed by double quotes
...

"Beep! \7 Newline \n
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Conventions and Declarations:
Strings Arrays and Pointers:
Arrays of Strings:
Example 21:
Strings from the user:
Handling strings:
Example 22:
String Input/Output:
Example 23:
Questions 20:
Node:Conventions and Declarations, Next:Strings Arrays and Pointers, Previous:Strings, Up:Strings

Conventions and Declarations
There is an important distinction between a string and a single character in C
...
g
...
Strings, on the hand, are enclosed by double quotes e
...

"string
...
Here are some declarations for strings
which are given without immediate explanations
...
It is stored at some place the memory and is given an end marker which
standard library functions can recognize as being the end of the string
...
Programs rarely gets to see this end marker as most
functions which handle strings use it or add it automatically
...
Perhaps the simplest way of seeing how C stores arrays is to give an extreme example which
would probably never be used in practice
...
The fact that a string is an array of characters might lead you to write something like:
#define LENGTH 9;
main ()

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
There are six ways of assigning constant strings to arrays
...
) They are written into a short compilable program
below
...

/**********************************************************/
/*
*/
/* String Initialization
*/
/*
*/
/**********************************************************/
char *global_string1 = "A string declared as a pointer";
char

global_string2[] = "Declared as an array";

main ()
{ char *auto_string = "initializer
...
";
static char statarraystr[] = "initializer
...
"; IS ILLEGAL! */
/* This is because the array is an "auto" type
*/
/* which cannot be preinitialized, but
...
It is a good idea to get revise pointers and
arrays before reading the explanations below
...

The first of these assignments is a global, static variable
...
Static
variables are assigned storage space in the body of a program when the compiler creates the executable code
...
That is the
reason for the rule which says that only static arrays can be initialized with a constant expression in a declaration
...
Notice that, because the string which is to be assigned to it, is
typed into the program, the compiler can also allocate space for that in the executable file too
...

The second statement works almost identically, with the exception that, this time the compiler sees the declaration of a
static array, which is to be initialized
...
This is quite legal
in fact: the compiler counts the number of characters in the initialization string and allocates just the right amount of
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Remember also that the name of the array
is a pointer to the first character, so, in fact, the two methods are identical
...
The difference between this and the other two declarations is that this pointer variable is created
every time the function main() is called
...
The
string which initializes it is stored in the executable file of the program (because it is typed into the text)
...

This is a slightly round about way of defining the string constant
...
In fact this is what is done in the fourth example
...

The sixth example is forbidden! The reason for this might seem rather trivial, but it is made in the interests of
efficiency
...
auto-arrays cannot be initialized with a string because they would have to be re-initialized every
time the array were created: that is, each time the function were called
...
Here an auto array of characters is declared (with a size this time,
because there is nothing for the compiler to count the size of)
...
Programs can take advantage of C's easy assignment
facilities to let the compiler count the size of the string arrays and define arrays of messages
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

" |
(3) Print Log Sheet
|\n",
" |
(4) Bill Calculator
|\n",
" |
(q) Quit
|\n",
" |
|\n",
" |
|\n",
" |
Please Enter Choice
|\n",
" |
|\n",
" -------------------------------------- \n"
};
return (t[n]);
}

Notice the way in which the static declaration works
...
This function retains the pointer information from call
to call
...

Node:Example 21, Next:Strings from the user, Previous:Arrays of Strings, Up:Strings

Example Listing
/************************************************/
/*
*/
/* static string array
*/
/*
*/
/************************************************/
/* Morse code program
...
h>
#define CODE 0
/*************************************************/
main ()
{ short digit;
printf ("Enter any digit in the range 0
...
9");
return (CODE);
}
printf ("The Morse code of that digit is ");
Morse (digit);
}
/************************************************/
Morse (digit)

/* print out Morse code */

short digit;
{
static char *code[] =
{
"dummy",
"-----",
"
...
---",
"
...
-",
"
...
",
"--
...
",
"----
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

printf ("%s\n",code[digit]);
}

Node:Strings from the user, Next:Handling strings, Previous:Example 21, Up:Strings

Strings from the user
All the strings mentioned so far have been typed into a program by the programmer and stored in a program file, so it
has not been necessary to worry about where they were stored
...
It might even be necessary to get a whole bunch of strings
and store them all
...
An
example of this was the Game of Life program the the previous chapter:
Define the array to be a certain size
Check that the user does not type in too many characters
...

Another way is to define a static string with an initializer as in the following example
...

char *filename()
{ static char *filenm = "
...
It makes exactly 24 characters plus a zero byte in the program file, which can be used by an application
...
The function
strlen() is a standard library function which is described below; it returns the length of a string
...

Neither of the methods above is any good if a program is going to be fetching a lot of strings from a user
...
C has special memory allocation functions which can do this, not only
for strings but for any kind of object
...
Here is one
way in which it could be done:
1
...
Call this a string buffer, or waiting
place
...
Define an array of ten pointers to characters, so that the strings can be recalled easily
...
Find out how long the string in the string buffer is
...
Allocate memory for the string
...
Copy the string from the buffer to the new storage and place a pointer to it in the array of pointers for reference
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

6
...

The function which allocates memory in C is called malloc() and it works like this:
malloc()

should be declared as returning the type pointer to character, with the statement:

char *malloc();

takes one argument which should be an unsigned integer value telling the function how many bytes of
storage to allocate
...
This should always be checked
...
The cast operator can force malloc() to give a pointer to any data type
...

malloc() has a complementary function which does precisely the opposite: de-allocates memory
...
free() returns an integer code, so it does not have to be declared as being any special type
...


int returncode;
returncode = free (ptr);

The pointer should be declared:
char *ptr;

The return code is zero if the release was successful
...
First of all, some explanation of
Standard Library Functions is useful to simplify the program
...
Here is a short
list of some common ones which are immediately relevant (more are listed in the following chapter)
...

strlen()

This function returns a type int value, which gives the length or number of characters in a string, not including
the NULL byte end marker
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

strcpy()

This function copies a string from one place to another
...
An example is
char *to,*from;
to = strcpy (to,from);

Where to is a pointer to the place to which the string is to be copied and from is the place where the string is to
be copied from
...
An example:
int value;
char *s1,*s2;
value = strcmp(s1,s2);

The value returned is 0 if the two strings were identical
...
s1 > s2, alphabetically, then the value is > 0
...
Note that numbers come before letters in the ASCII code sequence and also that upper case comes
before lower case
...

strncmp()

This function is like strcmp, but limits the comparison to no more than n characters
...

Node:Example 22, Next:String Input/Output, Previous:Handling strings, Up:Strings

Example Listing
This program aims to get ten strings from the user
...

It works as follows:
The user is prompted for a string which he/she types into a buffer
...
(Notice that this block of memory is one byte longer than the
value returned by strlen() , because strlen() does not count the end of string marker \0
...
Finally the strings is copied from the
buffer to the new storage with the library function strcpy()
...
Notice
that the program exits through a low level function called QuitSafely()
...
QuitSafely() uses the function exit() which should be provided as a standard
library function
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h>
/* #include another file for malloc() and
*/
/* strlen() ???
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

String Input/Output
Because strings are recognized to be special objects in C, some special library functions for reading and writing are
provided for them
...
There are four
of these functions:
gets()
puts()
sprintf()
sscanf()

gets():
puts():
sprintf():
sscanf():
Node:gets(), Next:puts(), Previous:String Input/Output, Up:String Input/Output
gets()

This function fetches a string from the standard input file stdin and places it into some buffer which the programmer
must provide
...
Otherwise it
returns NULL (==0)
...
) is that it will read spaces in strings, whereas
scanf() usually will not
...

NOTE: there are valid concerns about using this function
...
In order to write more secure code,
use fgets() instead
...
The NULL byte is not written
to stdout, instead a newline character is written
...
returncode == EOF if an end of
file was encountered or there was an error
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

This is an interesting function which works in almost the same way as printf() , the exception being that it prints to a
string! In other words it treats a string as though it were an output file
...
On most systems it works in the following way:
int n;
char *sp;
n = sprintf (sp, "control string", parameters, values);

is an integer which is the number of characters printed
...
Note carefully that this function does not perform any check on the output string to make sure that it is
long enough to contain the formatted output
...
Note that on system V Unix systems the sprintf functionr returns a pointer to the start of the printed string,
breaking the pattern of the other printf functions
...
));

Node:sscanf(), Previous:sprintf(), Up:String Input/Output
sscanf()

This function is the complement of sprintf()
...

int n;
char *sp;
n = sscanf (sp,"control string", pointers
...
The string must be NULL terminated (it must have a zero-byte
end marker '\0')
...
The conversion specifiers are identical to those for scanf()
...
h>
#define SIZE
#define CODE

20
0

/************************************************/
main ()
{ static char *s1 = "string 2
...
";
char ch, *string[SIZE];
int i,n;
float x;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
What are the two main ways of declaring strings in a program?
2
...
Write a program which gets a number between 0 and 9 and prints out a different message for each number
...

Node:Putting together a program, Next:Special Library Functions and Macros, Previous:Strings, Up:Top

Putting together a program
Putting it all together
...
Unix was designed with a command language which was
built up of independent programs
...
For instance:
ls -l /etc
cc -o program prog
...
We need some way getting this information into a C program
...
Since then
most other operating systems have adopted the same model, since it has become a part of the C language
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

}

The traditional names for the parameters are the argument count argc and the argument vector (array) argv
...
For example, in
the case of
cc -o program prog
...
c
The following program prints out the command line arguments:
main (argc,argv)
int argc;
char *argv[];
{ int i;
printf ("This program is called %s\n",argv[0]);
if (argc > 1)
{
for (i = 1; i < argc; i++)
{
printf("argv[%d] = %s\n",i,argv[i]);
}
}
else
{
printf("Command has no arguments\n");
}
}

Node:getopt, Next:envp, Previous:argc and argv, Up:Putting together a program

Processing options
getopt
Node:envp, Previous:getopt, Up:Putting together a program

Environment variables
When we write a C program which reads command line arguments, they are fed to us by the argument vector
...
Each child process inherits the
environment of its parent
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

In addition to the envp vector, it is possible to access the environment variables through the call getenv()
...

char *string;
string = getenv("HOME");

is now a pointer to static but public data
...
Copy it's contents to another string before using the data
...
Handling strings
...

C provides a repertoire of standard library functions and macros for specialized purposes (and for the advanced user)
...
For instance
Character identification ( ctype
...
h )
Mathematical functions ( math
...
The names of
the appropriate files can be found in particular compiler manuals
...

Character Identification:
Example 24:
Output 24:
String Manipulation:
Example 25:
Mathematical Functions:
Examples 26:
Maths Errors:
Example 27:
Questions 21:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The
programmer ought to beware that it would be natural for many of these facilities to exist as macros rather than
functions, so the usual remarks about macro parameters apply, See Preprocessor
...
Assume that `true' has any non-zero, integer value and that `false' has the integer value zero
...

isalpha(ch)

This returns true if ch is alphabetic and false otherwise
...
z or A
...

isupper(ch)

Returns true if the character was upper case
...

islower(ch)

Returns true if the character was lower case
...

isdigit(ch)

Returns true if the character was a digit in the range 0
...

isxdigit(ch)

Returns true if the character was a valid hexadecimal digit: that is, a number from 0
...
f or A
...

isspace(ch)

Returns true if the character was a white space character, that is: a space, a TAB character or a newline
...

isalnum(ch)

Returns true if a character is alphanumeric: that is, alphabetic or digit
...

isgraph(ch)

Returns true if the character is graphic
...
e
...
i
...
ASCII values 0 to 31 and 127
...
127
...

toupper(ch)

This converts the character ch into its upper case counterpart
...

tolower(ch)

This converts a character into its lower case counterpart
...

toascii(ch)

This strips off bit 7 of a character so that it is in the range 0
...

Node:Example 24, Next:Output 24, Previous:Character Identification, Up:Special Library Functions and Macros

Examples
/********************************************************/
/*
*/
/* Demonstration of character utility functions
*/
/*
*/
/********************************************************/
/* prints out all the ASCII characters which give */
/* the value "true" for the listed character fns */
#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

for (ALLCHARS)
{
if (iscsym(ch))
{
printf ("%c ",ch);
}
}
}

Node:Output 24, Next:String Manipulation, Previous:Example 24, Up:Special Library Functions and Macros

Program Output
VALID CHARACTERS FROM isalpha()
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j
k l m n o p q r s t u v w x y z
VALID CHARACTERS FROM isupper()
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
VALID CHARACTERS FROM islower()
a b c d e f g h i j k l m n o p q r s t u v w x y z
VALID CHARACTERS FROM isdigit()
0 1 2 3 4 5 6 7 8 9
VALID CHARACTERS FROM isxdigit()
0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f
VALID CHARACTERS FROM ispunct()
! " # $ % & ' ( ) * + , -
...

strcat()

This function "concatenates" two strings: that is, it joins them together into one string
...
new is a pointer to the complete string; it is identical to onto
...
The string which is to be copied to must be
large enough to accept the new string, tagged onto the end
...
(In
some programs the user might get away without declaring enough space for the "onto" string, but in general the
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
) To join two static strings together, the following code is
required:
char *s1 = "string one";
char *s2 = "string two";
main ()
{ char buffer[255];
strcat(buffer,s1);
strcat(buffer,s2);
}

buffer would then contain "string onestring two"
...
An example is:
int len;
char *string;
len = strlen (string);

strcpy()

This function copies a string from one place to another
...
An example is
char *to,*from;
to = strcpy (to,from);

Where to is a pointer to the place to which the string is to be copied and from is the place where the string is to
be copied from
...
An example:
int value;
char *s1,*s2;
value = strcmp(s1,s2);

The value returned is 0 if the two strings were identical
...
s1 > s2, alphabetically, then the value is > 0
...
Note that numbers come before letters in the ASCII code sequence and also that upper case comes
before lower case
...
These enable the
programmer to perform the same actions with the first n characters of a string:
strncat()

This function concatenates two strings by copying the first n characters of this to the end of the onto string
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

char *to,*from;
int n;
to = strncpy (to,from,n);

strncmp()

This function compares the first n characters of two strings
int value;
char *s1,*s2;
value = strcmp(s1,s2,n);

The following functions perform conversions between strings and floating point/integer types, without needing to use
sscanf()
...

atof()

ASCII to floating point conversion
...

int i;
char *stringptr;
i = atoi(stringptr);

atol()

ASCII to long integer conversion
...
h>
#define TRUE
1
#define MAXLEN 30
/********************************************************/
main ()
{ char string1[MAXLEN],string2[MAXLEN];

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h etc
...
All of C's
mathematical capabilities are written for long variable types
...
The variables used are all to be declared long
int i;
double x,y,result;

/* long int */
/* long float */

The functions themselves must be declared long float or double (which might be done automatically in the
mathematics library file, or in a separate file) and any constants must be written in floating point form: for instance,
write 7
...

ABS()

MACRO
...
See fabs() for a function version
...
This is like
rounding up
...
2) is 3 */

floor()

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
2) is 2 */

exp()

Find the exponential value
...
7);

log()

Find the natural (Naperian) logarithm
...
It does not have to be declared specifically as unsigned
...
g
...
71828);

log10()

Find the base 10 logarithm
...
It does not have to be declared specifically as unsigned
...

result = pow(x,y); /*raise x to the power y */
result = pow(x,2); /*find x-squared */
result = pow(2
...
2); /* find 2 to the power 3
...
*/

sqrt()

Find the square root of a number
...
0);

sin()

Find the sine of the angle in radians
...
14);

cos()

Find the cosine of the angle in radians
...
14);

tan()

Find the tangent of the angle in radians
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

result = tan(x);
result = tan(3
...
0 and -1
...

result = asin(x);
result = asin(1
...
0 and -1
...

result = acos(x);
result = acos(1
...

result = atan(x);
result = atan(200
...
This function is
set up to find this result more accurately than atan()
...
14);

sinh()

Find the hyperbolic sine of the value
...
0);

cosh()

Find the hyperbolic cosine of the value
...
0);

tanh()

Find the hyperbolic tangent of the value
...
0);

Node:Examples 26, Next:Maths Errors, Previous:Mathematical Functions, Up:Special Library Functions and Macros

Examples
/******************************************************/
/*
*/
/* Maths functions demo #1
*/

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h>
#include ...
h>
#define TRUE
#define AMPLITUDE
#define INC
double pi;

1
30
0
...
0)*2;

/* The simple pendulum program */
/* if PI is not defined */

printf ("\nTHE SIMPLE PENDULUM:\n\n\n");
Pendulum();
}
/*****************************************************/
/* Level 1
*/
/*****************************************************/
Pendulum ()
{ double x, twopi = pi * 2;
int i,position;
while (true)
{
for (x = 0; x < twopi; x += INC)
{
position = (int)(AMPLITUDE * sin(x));
for (i = -AMPLITUDE; i <= AMPLITUDE; i++)
{
if (i == position)
{
putchar('*');
}
else
{
putchar(' ');
}
}
startofline();
}
}
}
/*****************************************************/
/* Toolkit
*/
/*****************************************************/
startofline()
{
putchar('\r');
}

Node:Maths Errors, Next:Example 27, Previous:Examples 26, Up:Special Library Functions and Macros

Maths Errors
Mathematical functions can be delicate animals
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

sensible answers in all possible cases
...
0 to -1
...
The reason
for this is a mathematical one: namely that the sine function (of which asin() is the opposite) only has values in this
range
...
3);

is nonsense and it cannot possibly produce a value for y, because none exists
...
0);

would also be nonsense
...
What happens then when an erroneous statement is executed? Some sort
of error condition would certainly have to result
...
In C, as the reader might have come to expect, this is not the case
...

Errors like the ones above are called domain errors (the set of values which a function can accept is called the domain
of the function)
...
For example, division by zero is illegal, because dividing
by zero is "mathematical nonsense" - it can be done, but the answer can be all the numbers which exist at the same
time! Obviously a program cannot work with any idea as vague as this
...

Domain error
Illegal value put into function
Division by zero
Dividing by zero is nonsense
...

Loss of accuracy
No meaningful answer could be calculated
Errors are investigated by calling a function called matherr()
...
The function responds by returning a value which gives information
about the error
...
For instance a hypothetical example: if the error
could be recovered from, matherr() returns 0, otherwise it returns -1
...
This can be examined by
programs which trap their errors dutifully
...

Although it is not possible to generalize, the following remarks about the behaviour of mathematical functions may
help to avoid any surprises about their behaviour in error conditions
...
Be careful to check this
...
)
Some functions return the value NaN
...
e
...

Some method of signalling errors must clearly be used
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

variable) which gives information about the last error which occurred
...

Node:Example 27, Next:Questions 21, Previous:Maths Errors, Up:Special Library Functions and Macros

Example
Here is an example for the mathematically minded
...
The integral is found
between the limits 0 and 5 and the exact answer is 25
...
) The particular compiler used for this program
returns the largest number which can be represented by the computer when numbers overflow, although, in this simple
case, it is impossible for the numbers to overflow
...
h>
#include ...
h>
#define LIMIT 5
double inc = 0
...
0);
for ( y = inc/2; y < LIMIT; y += inc )
{
integral += integrand (y) * inc;
}
printf ("Integral value = %
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Questions
1
...

3
...

5
...
True or false?
What information is returned by strlen() ?
What action is performed by strcat() ?
Name five kinds of error which can occur in a mathematical function
...
Take, for example, the following
operators
=

++

--

+=

-=

etc
...
These innocent looking operators can be used in some surprising
ways which make C source code very neat and compact
...
They therefore produce one unique value each time they are used
...
Both kinds of operator have one thing in common however: both form statements which have
values in their own right
...
To paraphrase a famous author: "In C, no
statement is an island"
...

Increment/decrement operator statements, taken as a whole, have a value which is one greater / or one less than the
value of the variable which they act upon
...
Entire assignment statements have values too
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

has the value which is the value of the assignment
...
This has some important
implications
...
For instance, the value c = 0; could be
assigned to a variable b:
b = (c = 0);

or simply:
b = c = 0;

These equivalent statements set b and c to the value zero, provided b and c are of the same type! It is equivalent to the
more usual:
b = 0;
c = 0;

Indeed, any number of these assignments can be strung together:
a = (b = (c = (d = (e = 5))))

or simply:
a = b = c = d = e = 5;

This very neat syntax compresses five lines of code into one single line! There are other uses for the valued assignment
statement, of course: it can be used anywhere where a value can be used
...
)
As an index for arrays
...
Consider how an assignment statement might be used as a parameter to a function
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

This is a perfectly valid statement in C, because the hidden assignment statement passes on the value which it assigns
...
It would not make
sense the other way around, because, then there would be no value to pass on as a parameter
...
If there is any doubt, examine a little more of this imaginary character
processing program:
ProcessCharacter(ch = getchar());
if (ch == '*')
{
printf ("Starry, Starry Night
...
until it is re-assigned by a new assignment statement
...
All the same remarks apply about
the specialized assignment operators +=, *=, /= etc
...
2) < 20
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

/* end */

Node:Hidden ++ --, Next:Arrays Strings and Hidden Operators, Previous:Example 28, Up:Hidden Operators

Hidden ++ and -The increment and decrement operators also form statements which have intrinsic values and, like assignment
expressions, they can be hidden away in inconspicuous places
...
Look at the following example:
int i = 3;
PrintNumber (i++);

The increment operator is hidden in the parameter list of the function PrintNumber()
...
The question is then: which value is passed to the function? Is i incremented
before or after the function is called? The answer is that this is where the two forms of the operator come into play
...
If the operator is used as
a postfix, the operation is performed after the function call
...
The alternative is to write:
int i = 3;
PrintNumber (++i);

in which case the value 4 is passed to the function PrintNumber()
...

Node:Arrays Strings and Hidden Operators, Next:Example 29, Previous:Hidden ++ --, Up:Hidden Operators

Arrays, Strings and Hidden Operators
Arrays and strings are one area of programming in which the increment and decrement operators are used a lot
...
Consider the following example of a one dimensional array of integers
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

This is a neat way of initializing an array to zero
...
This
prevents the element array[0] from assigning zero to memory which is out of the bounds of the array
...
If the standard library function strlen() (which finds the length of a
string) were not available, then it would be a simple matter to write the function
strlen (string)

/* count the characters in a string */

char *string;
{ char *ptr;
int count = 0;
for (ptr = string; *(ptr++) != '\0'; count++)
{
}
return (count);
}

This function increments count while the end of string marker \0 is not found
...

*/
/* Also compare the prefix / postfix forms of ++/-- */
#include ...
h>
/*******************************************************/
main ()

/* prints out zero! */

{
printf ("%d",Value());
}

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
*/

{ int value;
if ((value = GetValue()) == 0)
{
printf ("Value was zero\n");
}
return (value);
}
/********************************************************/
GetValue()

/* Some function to get a value */

{
return (0);
}
/* end */

Node:Cautions about Style, Next:Example 30, Previous:Example 29, Up:Hidden Operators

Cautions about Style
Hiding operators away inside other statements can certainly make programs look very elegant and compact, but, as
with all neat tricks, it can make programs harder to understand
...
(It could be you in years or months to come!)
Statements such as:
if ((i = (int)ch++) <= --comparison)
{
}

are not recommendable programming style and they are no more efficient than the more longwinded:
ch++;
i = (int)ch;
if (i <= comparison)
{
}
comparison--;

There is always a happy medium in which to settle on a readable version of the code
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

/*
*/
/* Arrays and Hidden Operators
*/
/*
*/
/******************************************************/
#include ...
h>
#define MAXNO

20

/*****************************************************/
main ()

/* Print out 5 x table */

{ int i, ctr = 0;
for (i = 1; ++ctr <= MAXNO; i = ctr*5)
{

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Which operators can be hidden inside other statements?
2
...

3
...
e
...
Since C allows you to define new
data types we shall not be able to cover all of the possiblities, only the most important examples
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Questions 23:
Node:Special Constant Expressions, Next:FILE, Previous:More on Data Types, Up:More on Data Types

Special Constant Expressions
Constant expressions are often used without any thought, until a programmer needs to know how to do something
special with them
...

Up to now the distinction between long and short integer types has largely been ignored
...

long int variable = 23L;
variable = 236526598L;

Advanced programmers, writing systems software, often find it convenient to work with hexadecimal or octal numbers
since these number bases have a special relationship to binary
...
If ddd is a value, then:
Octal number
Hexadecimal number

0ddd
0xddd

For example:
oct_value = 077;

/* 77 octal */

hex_value = 0xFFEF;

/* FFEF hex */

This kind of notation has already been applied to strings and single character constants with the backslash notation,
instead of the leading zero character:
ch = '\ddd';
ch = '\xdd';

The values of character constants, like these, cannot be any greater than 255
...
These special files are
always handled implicitly by functions like printf() and scanf(): the programmer never gets to know that they are,
in fact, files
...
Files are distinguished by filenames and by file pointers
...
That type is called FILE and file pointers have to be declared "pointer to FILE "
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

File handling functions which return file pointers must also be declared as pointers to files
...
h and so, strictly speaking, it is not a
reserved word itself
...

Node:enum, Next:Example 31, Previous:FILE, Up:More on Data Types

enum
Abstract data are usually the realm of exclusively high level languages such as Pascal
...

is short for enumerated data
...
These words are given substitute integer numbers by the compiler which are used to identify
and compare enum type data
...
Enumerated data are called abstract because the low level number form of the
words is removed from the users attention
...
For this reason, they have a natural partner in programs: the switch statement
...
h>
enum countries
{
England,
Ireland,
Scotland,
Wales,
Danmark,

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Data which are declared enum are not the kind of
data which it makes sense to do arithmetic with (even integer arithmetic), so in most cases it should not be necessary
to know or even care about what numbers the compiler gives to the words in the list
...
The compiler then tries to give the values successive integer
numbers unless the programmer states otherwise
...
etc
...

The following example program listing shows two points:
types can be local or global
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

/*
*/
/**********************************************************/
/* The smallest adventure game in the world */
#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Here are some suggested uses for enum
...

Node:void, Next:volatile, Previous:Suggested uses for enum, Up:More on Data Types

void
is a peculiar data type which has some debatable uses
...
The main idea of void is to be able to declare functions which have no return value
...
If you recall, the default is for C functions to return a
value of type int
...
It did make compiler checks more difficult however: how do you warn someone about
inconsistent return values if it is legal to ignore return values?
void

The ANSI solution was to introduce a new data type which was called void for functions with no value
...
The words `novalue' or `notype' would have been better choices
...

void function();
void variable;
void *ptr;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The data type was introduced with functions in mind but the grammar of C allows us to define variables
of this type also, even though there is no point
...
For instance, scanf() returns the number of items it matches in the control string, but this is
usually discarded
...

A void pointer can point to to any kind of object
...
This is also a highly questionable feature of the ANSI draft
...
It allows assignments between incompatible pointer types
without a cast operator
...

Node:volatile, Next:const, Previous:void, Up:More on Data Types

volatile
is a type which has been proposed in the ANSI standard
...
Variables which are declared volatile will be able to have their values
altered in ways which a program does not explicitly define: that is, by external influences such as clocks, external
ports, hardware, interrupts etc
...

Independent processes which share common memory could each change a variable independently
...
The keyword volatile servers as a warning to the compiler that any optimizing code it
produces should not rely on caching the value of the variable, it should always reread its value
...
Types declared const must be assigned
when they are first initialized and they exist as stored values only at compile time:
const double pi = 3
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Since a constant array only exists at compile time, it can be initialized by the compiler
...
and so on
...


array[0]

It is worth comparing the const declaration to enumerated data, since they are connected in a very simple way
...
Enumerated data provide a
convenient way of classifying constants, however, while the compiler keeps track of the values and types
...

Node:struct again, Next:union, Previous:const, Up:More on Data Types

struct
Structures are called records in Pascal and many other languages
...
Structures are described in detail in chapter 25
...
They are like
general purpose storage containers, which can hold a variety of different variable types, at different times
...

Node:typedef, Next:Questions 23, Previous:union, Up:More on Data Types

typedef
C allows us to define our own data types or to rename existing ones by using a compiler directive called typedef
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

statement is used as follows:
typedef type newtypename;

So, for example, we could define a type called byte , which was exactly one byte in size by redefining the word char :
typedef unsigned char byte;

The compiler type checking facilities then treat byte as a new type which can be used to declare variables:
byte variable, function();

The typedef statement may be written inside functions or in the global white space of a program
...

It is not very often that you want to rename existing types in the way shown above
...
Structures and unions can, by their very definition, be all kinds of shape
and size and their names can become long and tedious to declare
...

Node:Questions 23, Previous:typedef, Up:More on Data Types

Questions
1
...

3
...

5
...

7
...

Enumerated data are given values by the compiler so that it can do arithmetic with them
...

Variables declared const can be of any type
...
Flags/messages
...

Down in the depths of your computer, below even the operating system are bits of memory
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

working at such a high level that it is easy to forget them
...
For precisely this reason, it is rare for high level languages to even
acknowledge the existence of bits, let alone manipulate them
...
C, however, is quite different from most other high level languages in that it allows a
programmer full access to bits and even provides high level operators for manipulating them
...
Many of the facilities which are
available for bit operations need not concern the majority of programs at all
...

You may wish to consult a book on assembly language programming to learn about low level memory operations, in
more detail
...
The only difference between a string and a floating point variable is
the way in which we choose to interpret the patterns of bits in a computer's memory
...
A flag is a message which
is either one thing or the other: in system terms, the flag is said to be `on' or `off' or alternatively set or cleared
...
A status register is a group of bits (a byte perhaps) in
which each bit signifies something special
...
Programmers are interested to
know about the contents of bits in these registers, perhaps to find out what happened in a program after some special
operation is carried out
...

Serially transmitted data
...
(Raster ports and devices)
Performing fast arithmetic in simple cases
...

Node:Flags registers, Next:Bit Operators and Assignments, Previous:Bit Patterns, Up:Machine Level Operations

Flags, Registers and Messages
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
A status register is a
register which is used to return information to a programmer about the operations which took place in other registers
...
In advanced
programming, there may be call for "pseudo registers" in addition to "real" ones
...

Messages are just like pseudo status registers: they are collections of flags which signal special information between
different devices and/or different programs in a computer system
...
Messages are a very compact way of passing information to low level functions in a
program
...
A program which makes use of
them must therefore be able to assign these objects to C variables for use
...

typedef char byte;
typedef int bitpattern;
bitpattern variable;
byte message;

The flags or bits in a register/message
...
A program can test for this by using combinations of the operators which C provides
...

Node:Bit operators, Next:Shift Operations, Previous:Bit Operators and Assignments, Up:Machine Level Operations

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
) A bit pattern is made up of 0s and 1s and
bitwise operators operate individually upon each bit in the operand
...

Bitwise operators (AND, OR) can be used in place of logical operators ( &&,||), but they are less efficient, because
logical operators are designed to reduce the number of comparisons made, in an expression, to the optimum: as soon as
the truth or falsity of an expression is known, a logical comparison operator quits
...

Below is a brief summary of the operations which are performed by the above operators on the bits of their operands
...
Every box represents a bit; the numbers
inside represent their values
...

128

64

32

16

8

4

2

1

------------------------------| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
-------------------------------

= 1

Shift operators move whole bit patterns left or right by shunting them between boxes
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

6 << 2 == 12
128

64

32

16

8

4

2

1

------------------------------| 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 |
-------------------------------

= 6

Shift left 2 places:
128

64

32

16

8

4

2

1

------------------------------| 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
-------------------------------

= 12

Notice that every shift left multiplies by 2 and that every shift right would divide by two, integerwise
...
So:
1
2
2
n

>>
>>
>>
>>

1
1
2
n

==
==
==
==

0
1
0
0

A common use of shifting is to scan through the bits of a bitpattern one by one in a loop: this is done by using masks
...
They are binary or dyadic operators
...

The operations performed by these bitwise operators are best summarized by truth tables
...
The same operation is then carried out for all the bits
in the variables which are operated upon
...
C provides a "one's complement" operator which
simply changes all 1s into 0s and all 0s into 1s
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Node:AND, Next:OR, Previous:Complement ~, Up:Truth Tables and Masking

AND

&

This works between two values
...
g
...

Node:OR, Next:XOR, Previous:AND, Up:Truth Tables and Masking

OR |
This works between two values
...
g
...

Node:XOR, Previous:OR, Up:Truth Tables and Masking

XOR/EOR ^
Operates on two values
...
g
...

Bit patterns and logic operators are often used to make masks
...
This is
particularly pertinent for handling flags, where a programmer wishes to know if one particular flag is set or not set and
does not care about the values of the others
...
For example: in
symbolic language:
MASK = 00000001
VALUE1 = 10011011
VALUE2 = 10011100
MASK & VALUE1 == 00000001

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Alternatively,
masks can be built up by specifying several flags:
FLAG1 = 00000001
FLAG2 = 00000010
FLAG3 = 00000100
MESSAGE = FLAG1 | FLAG2 | FLAG3
MESSAGE == 00000111

It should be emphasized that these expressions are only written in symbolic language: it is not possible to use binary
values in C
...
(See the appendices for conversion
tables)
...
The first program gets a
denary number from the user and converts it into binary
...

/***************************************************/
/*
*/
/* Bit Manipulation #1
*/
/*
*/
/***************************************************/
/*
/*
/*
/*

Convert denary numbers into binary */
Keep shifting i by one to the left */
and test the highest bit
...
h>
#define NUMBEROFBITS

8

/****************************************************/
main ()
{ short i,j,bit,;
short MASK = 0x80;
printf ("Enter any number less than 128: ");
scanf ("%h", &i);
if (i > 128)
{
printf ("Too big\n");
return (0);
}
printf ("Binary value = ");
for (j = 0; j < NUMBEROFBITS; j++)
{
bit = i & MASK;
printf ("%1d",bit/MASK);
i <<= 1;
}
printf ("\n");
}
/* end */

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h>
#define NUMBEROFBITS 8
/****************************************************/
main ()
{ short j,hex = 0;
short MASK;
char binary[NUMBEROFBITS];
printf ("Enter an 8-bit binary number: ");
for (j = 0; j < NUMBEROFBITS; j++)
{
binary[j] = getchar();
}
for (j = 0; j < NUMBEROFBITS; j++)
{
hex <<= 1;
switch (binary[j])
{
case '1' : MASK = 1;
break;
case '0' : MASK = 0;
break;
default : printf("Not binary\n");
return(0);
}
hex |= MASK;
}
printf ("Hex value = %1x\n",hex);
}
/* end */

Node:Example 35, Next:Questions 24, Previous:Example 34, Up:Machine Level Operations

Example
Enter any number less than 128: 56
Binary value = 00111000

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
What distinguishes a bit pattern from an ordinary variable? Can any variable be a bit pattern?
2
...
If you saw the following function call in a program, could you guess what its parameter was?
OpenWindow (BORDER | GADGETS | MOUSECONTROL | SIZING);

4
...
7 & 2
2
...
15 & 3
4
...
15 & 7 & 3
Try to explain the results
...
)
5
...
1 | 2
2
...
Find out the values of:
1
...
23 & (~23)
3
...
Use short type variables for all the numbers)
...
This includes disk files and it includes devices such as the
printer or the monitor of a computer
...
The most commonly used file streams are stdin (the keyboard) and stdout (the screen), but
more sophisticated programs need to be able to read or write to files which are found on a disk or to the printer etc
...
In order to examine the contents of a file or to write information to a file, a
program has to open one of these portals
...
Think of it as a protocol
...
A program which reads data simply reads values from its file portal and does
not have to worry about how they got there
...
To use a file then, a program
has to go through the following routine:
Open a file for reading or writing
...
)
Read or write to the file using file handling functions provided by the standard library
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Close the file to free the operating system "portal" for use by another program or file
...

Files Generally:
File Positions:
High Level File Handling Functions:
Opening files:
Closing a file:
fprintf:
fscanf:
skipfilegarb?:
Single Character I/O:
getc and fgetc:
ungetc:
putc and fputc:
fgets and fputs:
feof:
Printer Output:
Example 36:
Output 36:
Converting example:
File Errors:
Other Facilities for High Level Files:
fread() and fwrite():
ftell and fseek:
rewind:
fflush:
Low Level Filing Operations:
File Handles:
open:
close:
creat:
read:
write:
lseek:
unlink remove:
Example 37:
Questions 25:
Node:Files Generally, Next:File Positions, Previous:Files and Devices, Up:Files and Devices

Files Generally
C provides two levels of file handling; these can be called high level and low level
...
In fact, the data which go into the files are exactly what would be seen on the screen, character by character,
except that they are stored in a file instead
...
Any file, which is written to by high level file handling functions, ends up as a text file which could be

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

High level text files are also read back as character files, in the same way that input is acquired from the keyboard
...

The alternative to these high level functions, is obviously low level functions
...
Low level
input/output functions have the disadvantage that they are less `programmer friendly' than the high level ones, but they
are likely to work faster
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

rewind:
fflush:
Low Level Filing Operations:
File Handles:
open:
close:
creat:
read:
write:
lseek:
unlink remove:
Node:File Positions, Next:High Level File Handling Functions, Previous:Files Generally, Up:Files and Devices

File Positions
When data are read from a file, the operating system keeps track of the current position of a program within that file
so that it only needs to make a standard library call to `read the next part of the file' and the operating system obliges
by reading some more and advancing its position within the file, until it reaches the end
...

Although the operating system does a great deal of hand holding regarding file positions, a program can control the
way in which that position changes with functions such as ungetc() if need be
...

Node:High Level File Handling Functions, Next:Opening files, Previous:File Positions, Up:Files and Devices

High Level File Handling Functions
Most of the high level input/output functions which deal with files are easily recognizable in that they start with the
letter `f'
...
For instance:
fprintf()
fscanf()
fgets()
fputs()

These are all generalized file handling versions of the standard input/output library
...
The file versions differ only in that
they need an extra piece of information: the file pointer to a particular portal
...
they process data in an identical way to their standard I/O counterparts
...
For example:
fopen()
fclose()
getc()
ungetc();
putc()
fgetc()
fputc()
feof()

Before any work can be done with high level files, these functions need to be explained in some detail
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Node:Opening files, Next:Closing a file, Previous:High Level File Handling Functions, Up:Files and Devices

Opening files
A file is opened by a call to the library function fopen(): this is available automatically when the library file ...
There are two stages to opening a file: firstly a file portal must be found so that a program can access
information from a file at all
...
The
fopen() function performs both of these services and, if, in fact, the file it attempts to open does not exist, that file is
created anew
...
Filenames are system dependent so the
details of this must be sought from the local operating system manual
...
Finally, returnpointer is a pointer to a FILE
structure which is the whole object of calling this function
...
If the file could not be opened, this pointer is set to the
value NULL
...

A read only file is opened, for example, with some program code such as:
FILE *fp;
if ((fp = fopen ("filename","r")) == NULL)
{
printf ("File could not be opened\n");
error_handler();
}

A question which springs to mind is: what happens if the user has to type in the name of a file while the program is
running? The solution to this problem is quite simple
...

char *filename()

/* return

filename */

{ static char *filenm = "
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

{
printf ("Enter filename :");
scanf ("%24s",filenm);
skipgarb();
}
while (strlen(filenm) == 0);
return (filenm);
}

This function makes file opening simple
...
Once a file has been opened, it can
be read from or written to using the other library functions (such as fprintf() and fscanf() ) and then finally the file
has to be closed again
...
fclose() has the syntax:
int returncode;
FILE *fp;
returncode = fclose (fp);

is a pointer to the file which is to be closed and returncode is an integer value which is 0 if the file was closed
successfully
...
When closing a file, a program needs to do something like the following:
fp

if (fclose(fp) != 0)
{
printf ("File did not exist
...
Its name is meant to signify "file-print-formatted" and it is
almost identical to its stdout counterpart printf()
...
For example, assume that there is an open file, pointed to by fp:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
356;
char ch = 's';
fprintf (fp, "%d %f %c", i, x, ch);

The conversion specifiers are identical to those for printf()
...

printf ("Hello world %d", 1);
fprintf (stdout,"Hello world %d", 1);

Node:fscanf, Next:skipfilegarb?, Previous:fprintf, Up:Files and Devices

fscanf()
The analogue of scanf() is fscanf() and, as with fprintf() , this function differs from its standard I/O counterpart
only in one extra parameter: a file pointer
...

For example, assuming that fp is a pointer to an open file:
int i = 10;
float x = -2
...

Node:skipfilegarb?, Next:Single Character I/O, Previous:fscanf, Up:Files and Devices

skipfilegarb() ?
Do programs need a function such as skipgarb() to deal with instances of badly formatted input data? A programmer
can assume a bit more about files which are read into a program from disk file than it can assume about the user's
typed input
...
Is a function like skipgarb() necessary then? The answer is: probably not
...
On the other hand, a programmer is at liberty to assume that any file which does not contain
correctly formatted data is just nonsense: he/she does not have to try to make sense of it with a function like
skipgarb() , the program could simply return an error message like "BAD FILE" or whatever and recover in a
sensible way
...
For comparison alone,
skipfilegarb() is written below
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

{
}
}

Node:Single Character I/O, Next:getc and fgetc, Previous:skipfilegarb?, Up:Files and Devices

Single Character I/O
There are commonly four functions/macros which perform single character input/output to or from files
...
It might be that getc() is
implemented as a macro, whereas fgetc() is implemented as a function or vice versa
...
Check the manual, to be sure! Both getc() and fgetc() fetch a single character from
a file:
FILE *fp;
char ch;
/* open file */
ch = getc (fp);
ch = fgetc (fp);

These functions return a character from the specified file if they operated successfully, otherwise they return EOF to
indicate the end of a file or some other error
...

Node:ungetc, Next:putc and fputc, Previous:getc and fgetc, Up:Files and Devices

ungetc()
ungetc() is a function which `un-gets' a character from a file
...

This is not like writing to a file, but it is like stepping back one position within the file
...
An
example of this would be a program which looks for a word in a text file and processes that word in some way
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

The program would skip over spaces until it found a character and then it would know that this was the start of a word
...
The solution is to use ungetc()
to move the file position back a character:
int returncode;
returncode = ungetc(fp);

The returncode is EOF if the operation was unsuccessful
...
As with getc(), one of these may be a
macro
...

Node:fgets and fputs, Next:feof, Previous:putc and fputc, Up:Files and Devices

fgets()

and fputs()

Just as gets() and puts() fetched and sent strings to standard input/output files stdin and stdout, so fgets() and
fputs() send strings to generalized files
...
returnval is a pointer to a string: if
there was an error in fgets() this pointer is set to the value NULL , otherwise it is set to the value of "strbuff"
...
(One byte is reserved for the NULL terminator
...
returnval is set to EOF if there
was an error in writing to the file
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

feof()
This function returns a true or false result
...
The
form of a statement using this function is:
FILE *fp;
int outcome;
outcome = feof(fp);

Most often feof() will be used inside loops or conditional statements
...
A call to feof() is required in order to check for the end of the file
...
In better(?)
English the loop continues to fetch characters as long as the end of the file has not been reached
...

Node:Printer Output, Next:Example 36, Previous:feof, Up:Files and Devices

Printer Output
Any serious application program will have to be in full control of the output of a program
...
To do this, one of three things must be
undertaken:

stdout

must be redirected so that it sends data to the printer device
...
)

A new file must be opened in order to write to the printer device
The first method is not generally satisfactory for applications programs, because the standard files stdin and stdout
can only easily be redirected from the operating system command line interpreter (when a program is run by typing its
name)
...
The second method is reserved for only a few implementations of C in
which another `standard file' is opened by the local operating system and is available for sending data to the printer
stream
...
", integer);

The final method of writing to the printer is to open a file to the printer, personally
...
This could be something like "PRT:" or "PRN" or "LPRT" or whatever
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

filename (actually called a pseudo device name) is used to open a file in precisely the same way as any other file is
opened: by using a call to fopen()
...
The program code to do this should look something like the
following:
FILE *stdprn;
if ((stdprn = fopen("PRT:","w")) == NULL)
{
printf ("Printer busy or disconnected\n");
error_handler;
}

Node:Example 36, Next:Output 36, Previous:Printer Output, Up:Files and Devices

Example
Here is an example program which reads a source file (for a program, written in C, Pascal or whatever
...
This kind of program is useful for debugging programs
...
The printer device is assumed to have the filename "PRT:"
...

/***************************************************************/
/*
*/
/* LIST : program file utility
*/
/*
*/
/***************************************************************/
/* List a source file with line numbers attached
...

*/
#include ...
0\n\n");
if ((fin = fopen(filename(),"r")) == NULL)
{
printf ("\nFile not found\n");
exit (CODE);
}
printf ("Output to printer? Y/N");
if (yes())
{
Pon = Printer(ON);
}
while (!feof(fin))
{

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
";
do
{
printf ("Enter filename :");
scanf ("%24s",filenm);
skipgarb();
}
while (strlen(filenm) == 0);
return (filenm);
}

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

/********************************************************/
/*
*/
/* C programming utility : variable referencer
*/
/*
*/
/********************************************************/
/* See section 30 */
#include ...
h>
#define
#define
#define
#define
#define

TRUE
1
FALSE
0
DUMMY
0
MAXSTR
512
MAXIDSIZE 32


...


Node:Converting example, Next:File Errors, Previous:Output 36, Up:Files and Devices

Converting the example
The example program could be altered to work with a standard printer file "stdprn" by changing the following
function
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

{
switch (status)
{
case on:
fout = stdprn;
break;
case off:
}

fout = stdout;

}

Node:File Errors, Next:Other Facilities for High Level Files, Previous:Converting example, Up:Files and Devices

Filing Errors
The standard library provides an error function/macro which returns a true/false result according to whether or not the
last filing function call returned an error condition
...
To check for an error in an open file,
pointed to by fp:
FILE *fp;
if (ferror(fp))
{
error_handler();
}

This function/macro does not shed any light upon the cause of errors, only whether errors have occurred at all
...

Node:Other Facilities for High Level Files, Next:fread() and fwrite(), Previous:File Errors, Up:Files and Devices

Other Facilities for High Level Files
Files which have been opened by fopen() can also be handled with the following additional functions:
fread()
fwrite()
ftell()
fseek()
rewind()
fflush()

These functions provide facilities to read and write whole blocks of characters in one operation as well as further
facilities to locate and alter the current focus of attention within a file
...
The form of fread() is as follows:
FILE *fp;
int noread,n,size;
char *ptr;
noread = fread (ptr,size,n,fp);

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
fp is a pointer to an open file; ptr is a pointer to the start of a block of memory which is to store the data when
it is read; size is the size of a block of data in characters; n is the number of blocks of data to be read
...
It is important to
check that the number of blocks expected is the same as the number received because something could have gone
wrong with the reading process
...
)
fwrite() has an identical call structure to fread() :
FILE *fp;
int nowritten,n,size;
char *ptr;
nowritten = fread (ptr,size,n,fp);

This time the parameters in parentheses provide information about where the data, to be written to a file, will be
found
...
Again, this should be checked
...
It is assumed that the data are stored contiguously in the memory, that
is, side by side, in sequential memory locations
...
Memory which is allocated in C programs by the function
malloc() does not guarantee to find contiguous portions of memory on successive calls
...

Node:ftell and fseek, Next:rewind, Previous:fread() and fwrite(), Up:Files and Devices

File Positions: ftell() and fseek()
ftell() tells a program its position within a file, opened by fopen()
...
Normally high level read/write functions perform as much management over positions inside files
as the programmer wants, but in the event of their being insufficient, these two routines can be used
...
pos is a long integer value which describes the
position in terms of the number of characters from the beginning of the file
...
The call to fseek() looks like this:
fp

long int pos;
int mode,returncode;
FILE *fp;
returncode = fseek (fp,pos,mode);

The parameters have the following meanings
...
pos is some way of
describing the position required within a file
...
Finally, returncode is an integer whose value is 0 if the operation was successful and -1 if there was an
error
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

0
pos

is an offset measured relative to the beginning of the file
...


pos

is an offset measured relative to the end of the file
...

Node:rewind, Next:fflush, Previous:ftell and fseek, Up:Files and Devices

rewind()
rewind()

is a macro, based upon fseek(), which resets a file position to the beginning of the file
...
g
...
It flushes the
output buffer which means that it forces the characters in the output buffer to be written to the file
...
Example:
FILE *fp;
fflush(fp);

Node:Low Level Filing Operations, Next:File Handles, Previous:fflush, Up:Files and Devices

Low Level Filing Operations
Normally a programmer can get away with using the high level input/output functions, but there may be times when
C's predilection for handling all high level input/output as text files, becomes a nuisance
...
These are:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
They should be regarded as being
advanced features of the language because they are dangerous routines for bug ridden programs
...
Data are treated as a raw stream of bytes
...

Working at the low level, programs can create, delete and rename files but they are restricted to the reading and
writing of untranslated data: there are no functions such as fprintf() or fscanf() which make type conversions
...
These will be
documented, either in a compiler manual, or in an operating system manual, depending upon the system concerned
...
)
Node:File Handles, Next:open, Previous:Low Level Filing Operations, Up:Files and Devices

File descriptors
At the low level, files are not handled using file pointers, but with integers known as file handles or file descriptors
...
In other words, for all the different
terminology, they describe the same thing
...

Node:open, Next:close, Previous:File Handles, Up:Files and Devices

open()
open()

is the low level file open function
...

A program can give more information to this function than it can to fopen() in order to define exactly what open()
will do
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

and on some compilers:
O_CREAT
O_TRUNC
O_APPEND
O_EXCL

Create the file if it does not exist
Truncate the file if it does exist
Find the end of the file before each write
Exclude
...


The macro definitions of these flags will be included in a library file: find out which one and #include it in the
program
...
For example:
#define FAILED -1
main()
{ char *filename();
int fd;
fd = open(filename(), O_RDONLY);
if (fd == FAILED)
{
printf ("File not found\n");
error_handler (failed);
}
}

This opens up a read-only file for low level handling, with error checking
...
The four appended modes are values which can be bitwise ORed with one of the first three in order to
get more mileage out of open()
...
For example, to emulate the fopen()
function a program could opt to create a file if it did not already exist:
fd = open (filename(), O_RDONLY | O_CREAT);

open()

sets the file position to zero if the file is opened successfully
...
Like all other filing functions, it returns the value 0 if it performs successfully and the value
-1 if it fails
...
g
...
If a file which
already exists is created, its contents are discarded
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

fd = creat(filename,pmode);
filename must be a valid filename; pmode is a flag which contains access-privilege mode bits (system specific
information about allowed access) and fd is a returned file handle
...
Note that, the action of creating a file opens it too
...


Node:read, Next:write, Previous:creat, Up:Files and Devices

read()
This function gets a block of information from a file
...

The user must provide a place for them (either by making an array or by using malloc() to reserve space)
...

The following example reads n bytes from a file:
int returnvalue, fd, n;
char *buffer;
if ((buffer = malloc(size)) == NULL)
{
puts ("Out of memory\n");
error_handler ();
}
returnvalue = read (fd,buffer,n);

The return value should be checked
...
(If all went well this should be equal to n
...
It writes a block of n bytes from a contiguous portion of memory to a file
which was opened by open()
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Node:lseek, Next:unlink remove, Previous:write, Up:Files and Devices

lseek()
Low level file handing functions have their equivalent of fseek() for finding a specific position within a file
...
The constants should be declared long int , or simply long
...
The
values which mode can take are:
pos

0

Offset measured relative to the beginning of the file
...

2

Offset measured relative to the end of the file
...
Once deleted, files are usually irretrievable
...

#define FAILED -1
int returnvalue;
char *filename;
if (unlink (filename) == FAILED)
{
printf ("Can't delete %s\n",filename);
}
if (remove (filename) == FAILED)
{
printf ("Can't delete %s\n",filename);
}

is a string containing the name of the file concerned
...
(It is impossible to delete the printer!)
filename

rename()
This function renames a file
...
As usual,
it returns the value -1 if the action fails
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

if (rename(old,new) == FAILED)
{
printf ("Can't rename %s as %s\n",old,new);
}

rename()

can fail because a file is protected or because it is in use, or because one of the filenames given was not

valid
...
The idea is to
present a kind of file or "project" menu for creating, deleting, renaming files
...

/***************************************************************/
/*
*/
/* LOW LEVEL FILE HANDLING
*/
/*
*/
/***************************************************************/
#include ...
h>
#include ...
*/

/* Max size of filenames */

#define CLRSCRN() putchar('\f')
#define NEWLINE() putchar('\n')
int fd;
/***************************************************************/
/* Level 0
*/
/***************************************************************/
main ()
{ char *data,getkey(),*malloc();
if ((data = malloc(SIZE)) == NULL)
{
puts ("Out of memory\n");
return (CODE);
}
while (TRUE)
{
menu();
switch (getkey())
{
case 'l' : LoadFile(data);
break;
case 's' : SaveFile(data);
break;
case 'e' : Edit(data);
break;
case 'd' : DeleteFile();
break;
case 'r' : RenameFile();
break;
case 'q' : if (sure())
{
return (CODE);
}
break;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

if (yes())
{
if ((fd = CreateFile(fname)) == FAILED)
{
printf ("Cannot create file %s\n",fname);
return (FAILED);
}
}
else
{
return (FAILED);
}
}
error = write (fd,data,SIZE);
if (error < SIZE)
{
printf ("Error writing to file\n");
if (error != FAILED)
{
printf ("File only partially written\n");
}
}
close (fd,data,SIZE);
wait();
return (error);
}
/*************************************************************/
Edit(data)

/* primitive text editor */

char *data;
{ char *ptr;
int ctr = 0;
printf ("Contents of file:\n\n");
for (ptr = data; ptr < (data + SIZE); ptr++)
{
if (isprint(*ptr))
{
putchar(*ptr);
if ((ctr++ % 60) == 0)
{
NEWLINE();
}
}
}
printf ("\n\nEnter %1d characters:\n",SIZE);
for (ptr = data; ptr < (data + SIZE); ptr++)
{
*ptr = getchar();
}
skipgarb();
}
/*************************************************************/
DeleteFile()

/* Delete a file from current dir */

{ char *filename(),getkey(),*fname;
printf ("Delete File\n\n");
fname = filename();
if (sure())
{
if (remove(fname) == FAILED)
{
printf ("Can't delete %s\n",fname);
}
}
else
{

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

case 'y' : return (TRUE);
case 'n' : return (FALSE);
}
}
}
/**************************************************************/
wait()
{ char getkey();
printf ("Press a key\n");
getkey();
}
/**************************************************************/
char getkey()

/* single key + RETURN response */

{ char ch;
ch = getchar();
skipgarb();
return((char)tolower(ch));
}
/**************************************************************/
skipgarb()

/* skip garbage corrupting input */

{
while (getchar() != '\n')
{
}
}
/* end */

Node:Questions 25, Previous:Example 37, Up:Files and Devices

Questions
1
...
File name
2
...
File handle
2
...
Write a statement which opens a high level file for reading
...
Write a statement which opens a low level file for writing
...
Write a program which checks for illegal characters in text files
...
126
...

6
...
Print out all the header files on your system so that you can see what is defined where!
Node:Structures and Unions, Next:Data structures, Previous:Files and Devices, Up:Top

Structures and Unions
Grouping data
...

Tidy programs are a blessing to programmers
...
As programs become increasingly
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
What
one then needs is a data structure
...
struct types or structures are usually lumped together with another type of variable called a
union
...

Black Box Data:
struct:
Declarations again:
Scope again:
Using Structures:
Arrays of Structures:
Example 38:
Structures of Structures:
Pointers to Structures:
Example 39:
Pre-initializing Static Structures:
Creating Memory for Dynamical struct Types:
Unions:
Questions 26:
Node:Black Box Data, Next:struct, Previous:Structures and Unions, Up:Structures and Unions

Organization: Black Box Data
What is the relationship between a program and its data? Think of a program as an operator which operates on the
memory of the computer
...
Global data are wide open to alteration by any part of a program
...
One way of
visualizing a program is illustrated by the diagram over the page
...
This imaginative idea is not a bad picture of a computer program, but it is not
complete either
...
All of these things would be very difficult if data were scattered about liberally, with no particular
structure
...
These
capsules are called structures
...
Structures are not
like arrays: a structure can hold any mixture of different types of data: it can even hold arrays of different types
...

The word struct is a reserved word in C and it represents a new data type, called an aggregate type
...
Any particular structure type is given a name, called a structure-name and the variables (called
members) within a structure type are also given names
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

structure type has a name of its own too
...

Node:Declarations again, Next:Scope again, Previous:struct, Up:Structures and Unions

Declarations
A structure is declared by making a blank template for a variable package
...
The following statement is actually a declaration, so it belongs with other declarations, either at the head of a
program or at the start of a block
...
It says: define a type of variable which collectively holds a string called name , a string called address
and three integers called YearOfBirth, MonthOfBirth and DayOfBirth
...
The list of variable components which make up
the structure are called the members of the structure: the names of the members are not the names of variables, but are
a way of naming the parts which make up a structure variable
...
The distinction is maintained here in
places where confusion might arise
...
Older compilers did not
support this luxury
...
Having defined this type of structure, however, the programmer can declare variables to be of this type
...
x is certainly not a very good name for any variable
which holds a person's personal data, but it contrasts well with all the other names which are abound and so it serves
its purpose for now
...
The method shown above is probably the most common one, however there are two
equivalent methods of doing the same thing
...

struct PersonalData
{
char name[namesize];
char address[addresssize];
int YearOfBirth;
int MonthOfBirth;
int DayOfBirth;
}
x;
/* variable identifier follows type */

Alternatively, typedef can be used to cut down a bit on typing in the long term
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

typedef struct
{
char name[namesize];
char address[addresssize];
int YearOfBirth;
int MonthOfBirth;
int DayOfBirth;
}
PersonalData;

then declare:
PersonalData x;

Any one of these methods will do
...
Similarly if a structure type variable is declared locally
it is only valid inside the block parentheses in which it was defined
...
Early C compilers,
some of which still exist today, placed very severe restrictions upon what a program could do with structures
...

Although this sounds highly restrictive, it did account for the most frequent uses of structures
...
This makes structures extremely powerful data objects to have in a program
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

The reader will begin to see that structure names account for a good deal of typing! The typedef statement is a very
good way of reducing this burden
...
dot character
...
Consider the
structure variable x, which has the type struct PersonalData
...
name);
FillArray ("Some address", x
...
YearOfBirth = 1987;
x
...
DayOfBirth = 19;
}

where FillArray() is a hypothetical function which copies the string in the first parameter to the array in the second
parameter
...
Members of actual
structure variables are always accessed with this dot operator
...
member name

This applies to any type of structure variable, including those accessed by pointers
...
C provides a special member operator for pointers,
however, because they are used so often in connection with structures
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Although a structure
contains many different types, the compiler never gets to know this information because it is hidden away inside a
sealed structure capsule, so it can believe that all the elements in the array have the same type, even though that type is
itself made up of lots of different types
...
YearOfBirth = 1987;
i = array[2]
...
This allows more convenient handling of real-life strings
...
Does no error
*/
/* checking, so be wary of string sizes etc
...
h>
#define
#define
#define
#define

NAMESIZE
ADDRSIZE
NOOFPERSONS
NEWLINE()

30
80
20
putchar('\n');

/*********************************************************/
typedef struct
{
char *Name;
char *Address;
int YearOfBirth;
int MonthOfBirth;
int DayOfBirth;
}
PersonDat;
/*********************************************************/
main ()

/* Make some records */

{ PersonDat record[NOOFPERSONS];
PersonDat PersonalDetails();
int person;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Name = malloc(NAMESIZE);
strcpy (dat
...
Address = malloc(ADDRSIZE);
strcpy (dat
...
YearOfBirth = getint (1900,1987);
printf ("Month of birth:");
dat
...
DayOfBirth = getint(1,31);
return (dat);
}
/**********************************************************/
DisplayRecords (rec)
PersonDat rec[NOOFPERSONS];
{ int pers;
for (pers = 0; pers < NOOFPERSONS; pers++)
{
printf ("Name : %s\n", rec[pers]
...
Address);
printf("Date of Birth: %1d/%1d/%1d\n",rec[pers]
...
MonthOfBirth,rec[pers]
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

skipgarb();
return (i);
}
/**********************************************************/
skipgarb()

/* Skip input garbage corrupting scanf */

{
while (getchar() != '\n')
{
}
}
/* end */

Node:Structures of Structures, Next:Pointers to Structures, Previous:Example 38, Up:Structures and Unions

Structures of Structures
Structures are said to nest
...
Consider two
structure types:
struct first_structure
{
int value;
float number;
};

and
struct second_structure
{
int tag;
struct first_structure fs;
}
x;

These two structures are of different types, yet the first of the two is included in the second! An instance of the second
structure would be initialized by the following assignments
...
tag = 10;
x
...
value = 20;
x
...
number = 30
...
can be used over and over again
...
This nesting can,
in principle, go on many times, though some compilers might place restrictions upon this nesting level
...
tag1
...
tag3
...
Structures should nest safely a few times
...
There is a problem with the above scheme that has not yet been addressed
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

There is simply no way that this kind of statement can make sense, unless the compiler's target computer has an
infinite supply of memory! References to variables of this type would go on for ever and an infinite amount of
memory would be needed for every variable
...
What is not forbidden, however, is for a structure to contain an instance of a pointer to its own type (because
a pointer is not the same type as a structure: it is merely a variable which holds the address of a structure)
...
These extremely
valuable devices are described below
...
ptr can be assigned to any other pointer of similar
type and it can be used to access the members of a structure
...
According to the rules which have described so far, a structure member could be accessed by
pointers with the following statements:

ptr

struct PersonalData *ptr;
(*ptr)
...
Notice that *ptr , by itself,
means the contents of the address which is held in ptr and notice that the parentheses around this statement avoid any
confusion about the precedence of these operators
...
This is an arrow made out of a minus sign and a greater than symbol and it is used simply as
follows:
struct PersonalData *ptr;
ptr->YearOfBirth = 20;

This statement is identical in every way to the first version, but since this kind of access is required so frequently,
when dealing with structures, C provides this special operator to make the operation clearer
...

Node:Example 39, Next:Pre-initializing Static Structures, Previous:Pointers to Structures, Up:Structures and Unions

Example
/*********************************************************/
/*
*/
/* Structures Demo #2
*/
/*
*/
/*********************************************************/

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
i
...
this */
/* uses variable parameters instead of value params
*/
#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

printf ("Name : %s\n", rec[pers]
...
Address);
printf("Date of Birth: %1d/%1d/%1d\n",rec[pers]
...
MonthOfBirth,rec[pers]
...
Static and external structures can also be pre-assigned by the compiler so that programs can set up options and
starting conditions in a convenient way
...

Node:Creating Memory for Dynamical struct Types, Next:Unions, Previous:Pre-initializing Static Structures,
Up:Structures and Unions

Creating Memory for Dynamical struct Types
Probably the single most frequent use of struct type variables is in the building of dynamical data structures
...

Normal program data, which are reserved space by the compiler, are, in fact, static data structures because they do not
change during the course of a program: an integer is always an integer and an array is always an array: their sizes

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
A dynamical structure is built using the memory allocation function:
malloc()

and pointers
...
malloc() was described in connection with strings: it
allocates a fixed number of bytes of memory and returns a pointer to that data
...
When a program wants to create the space for a structure, it
has a template for that structure, which was used to define it, but it does not generally know, in advance, how many
bytes long a structure is
...
How then does a program know how must space to allocate? The C compiler comes
to the rescue here, by providing a compile time operator called
ptr

sizeof ()

which calculates the size of an object while a program is compiling
...

sizeof(char)

Works out the number of bytes occupied by a single character
...

works out the number of bytes needed to store a single structure variable
...
The memory allocation statement becomes something like:
sizeof(struct PersonalData)

ptr = malloc(sizeof(type name));

There is a problem with this statement though: malloc() is declared as a function which returns a type `pointer to
character' whereas, here, the programmer is interested in pointers of type "pointer to struct Something"
...
The cast operator casts pointers with a general form:
(type *) value

Consider the following example of C source code which allocates space for a structure type called SomeStruct and
creates a correctly aligned pointer to it, called ptr
...
The next section of this book discusses what we can do with dynamically allocated structures
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

A union is like a structure in which all the `members' are stored at the same address
...
Only one member can be stored in such an object at any one time, or it would be overwritten by
another
...
A union
can hold any one of its members but only at different times
...

The real purpose of unions is to prevent memory fragmentation by arranging for a standard size for data in the
memory
...
This is a natural strategy in system
programming where many instances of different kinds of variables with a related purpose and stored dynamically
...
It has a list of members, which are used to mould the type of object
concerned
...
Variables are then declared as:
union IntOrFloat x,y,z;

At different times the program is to treat x,y and z as being either integers or float types
...
ordinal = 1;

the program sees x as being an integer type
...
continuous) it takes on another
aspect: its alter ego, the float type
...

Node:Using unions, Previous:Declaration of union, Up:Unions

Using unions
Unions are coded with the same constructions as structures
...
operator selects the different members for
variable and the arrow -> selects different values for pointers
...
member;
union_pointer->member;

Unions are seldom very useful objects to have in programs, since a program has no automatic way of knowing what
type of member is currently stored in the union type
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

type currently held in the variable
...
Consider the following
kind of union:
union WhichType
{
int ordinal;
float continuous;
char letter;
};

This could be accompanied by an enumerate declaration such as:
enum Types
{
INT,
FLOAT,
CHAR
};

Variables could then go in pairs:
union WhichType x;
enum Types x_status;

which would make union type-handling straightforward:
switch (x_status)
{
case INT
: x
...
continuous = 12
...
letter = '*';
}

These variables could even be grouped into a structure:
struct Union_Handler
{
union WhichType x;
enum Types x_status;
}
var;

which would then require statements such as:
var
...
ordinal = 2;
ptr->x
...
x_status = CHAR;

and so on
...
What is the difference between a structure and a union?
2
...
If x is a variable, how would you find out the value of a member called mem
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

4
...

5
...
True or false?
Node:Data structures, Next:Recursion, Previous:Structures and Unions, Up:Top

Data Structures
Uses for struct variables
...

Data structures are organized patterns of data
...
Take the simplest kind of data structure: the
array
...
For
example, a chess board looks like a two dimensional array, so a chess game would naturally use a two dimensional
array to store the positions of pieces on the chess board
...

Most real application programs require a more complex data structure than C variables can offer; often arrays are not
suitable structures for a given application
...
This program has to store information about individual towns and it has to be able to
give directions to the user about how to get to particular towns from some reference point
...
(See figure 1
...
This sort of map is, ideally, just what a computer ought
to be able to store
...
If the map is ever going to be stored
in a computer it will need to look more mechanical
...
In order to make the map into a more
computer-like picture, it must be drawn as a structure diagram
...
Most often a structure diagram shows
how a problem is connected up by relating all the parts which go together to make it up
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

diagram just shows how program data are related to each other
...
This diagram is a data structure diagram: it is a diagram which shows how boxes of data must
relate to one another in order to solve the problem of the towns map
...
The arrows tend to suggest that pointers will play a role in
the data structure
...
Putting
these two together creates the idea of a `town structure' containing pointers to neighouring villages which lie on roads
to the North, South, East and West of the town, as well as the information about the town itself
...
This part of the information is actually irrelevant to the structure of the data because it is hidden inside the
sealed capsule
...
If the user of this imaginary application program
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

A data structure is built up, like a model, by connecting struct type variables together with pointers: these are the
building blocks
...

What is interesting about data structure diagrams is the way in which they resemble the structure diagrams of C
programs, which were drawn in chapter 7
...
The structure of a computer program is called a hierachy
...

Programs which behave exactly like their data operate very simply
...

Node:Tools, Next:Programme For Building Data Structures, Previous:Data Structure Diagrams, Up:Data structures

The Tools: Structures, Pointers and Dynamic Memory
The tools of the data structure trade are struct types and pointers
...
Pointers are the keys which
unlock a program's data
...
To understand this, make a note of the
following terms:
Root
This is a place where a data structure starts
...
The address of the root of a
data structure has to be stored explicitly in a C variable
...
Links are used to chain structures together
...

Data structures do not have to be linear chains and they are often not
...
In the map
example above, there were four pointers in each structure, so the chaining was not linear, but more like a latticework
...
Remember that pointers alone do not
create any storage space: they are only a way of finding out the contents of storage space which already exists
...
The key phrase is dynamic storage: a program makes space
for structures as new ones are required and deletes space which is does not require
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

computer
...

Using pointers to connect structures means that they can be re-connected in different ways as the need arises
...
)
Data structures can be made up of lots of "lesser" data structures, each held inside struct type storage
...

The remaining parts of this section aim to provide a basic plan or formula for putting data structures together in C
...

Node:Programme For Building Data Structures, Next:Setting Up A Data Structure, Previous:Tools, Up:Data structures

Programme For Building Data Structures
In writing programs which centre around their data, such as word processors, accounts programs or database
managers, it is extremely important to plan data structures before any program code is written: changes in program
code do not affect a data structure, but alterations to a data structure imply drastic changes to program code
...
The steps which a
programmer would undertake in designing a data structure follow a basic pattern:
Group all the data, which must be stored, together and define a struct type to hold them
...

Design the programming algorithms to handle the memory allocation, link pointers and data storage
...

The data structure is set up by repeating the following actions as many times as is necessary
...
For example:
struct Town
{
struct Town *north;
struct Town *south;
struct Town *east;
struct Town *west;
struct LocalInfo help;
};

Declare two pointers to this type:
struct Town *ptr,*root;

One of these is used to hold the root of the data structure and the other is used as a current pointer
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Be careful to check for errors
...

Initialize the members of the structure with statements such as:
root->north = NULL;
root->south = NULL;
root->help
...

When other structures have been created, the pointers can be assigned to them:
ptr = (struct Town *) malloc(sizeof(struct Town));
ptr->north = NULL;
ptr->south = NULL;
/* etc
...


pointer assignments tell the program handling the data structure when it has come to the edge of the structure:
that is when it has found a pointer which doesn't lead anywhere
...
)
A linked list is a linear sequence of structures joined together by pointers
...

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
If the blocks were labelled
A B C D E
...
Linked lists have two
advantages over one dimensional arrays: they can be sorted easily (see diagram) and they can be made any length at
all
...

struct BinaryTree
{
/* other info */
struct BinaryTree *left;
struct BinaryTree *right;
}
*tree = NULL;

A binary tree structure has two pointers per struct type
...

Right and left branches are taken to mean `greater than' and `less than' respectively
...
They are simple by professional
standards, but they are long by book standards so they are contained in a section by themselves, along with their
accompanying programmers' documentation, See Example Programs chapter
...

2
...

4
...


What is a structure diagram?
How are data linked together to make a data structure?
Every separate struct type in a data structure has its own variable name
...
Store that
address in a variable which is declared as follows:
struct BinaryTree *ptr;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Write a small program which makes a linked list, three structures long and assigns all their data to be zero
...

This section is about program structures which can talk about themselves
...
other statements
...
It is defined in terms of itself: it contains itself and it calls itself
...
What happens to such a function when it is called
in a C program? In the simple example above, something dramatic and fatal happens
...
This much is only normal: programs are designed to
do this and the computer could do no more and no less
...
It then begins executing statements in Well_function() ,
from the beginning, as though it were a new function, until it comes upon the statement Well_Function() and then it
calls the function again
...
The computer becomes totally consumed with the task of calling Well_Function() over and
over
...
Or is it?
Functions and The Stack:
Levels and Wells:
Tame Recursion and Self-Similarity:
Simple Example without a Data Structure:
Simple Example With a Data Structure:
Advantages and Disadvantages of Recursion:
Recursion and Global Variables:
Questions 28:
Node:Functions and The Stack, Next:Levels and Wells, Previous:Recursion, Up:Recursion

Functions and The Stack
We should think about the exact sequence of events which takes place when a function is called in a program
...
When a function is called, control
passes from one place in a program to another place
...
But how does the
computer know where it must go back to, when it has finished with a function call? It is suddenly thrown into a wildly

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
How can it get back again? A diagram does
not answer this question: program structure diagrams hide this detail from view
...
It does this by building a special data structure called a stack
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

A stack is quite literally a pile of data, organized in the memory
...
It is called a last in, first out (LIFO) structure because the last thing to go on the top of a stack is always
the first thing to come off it
...
When it calls a function, it leaves itself a reminder, on the top of its
program stack, which tells it where it has to go to when it has finished executing that function
...
When a function is finished,
the program takes the first message from the top of the stack and carries on executing statements at the place specified
by the message
...

What happens when a recursive function, like Well_Function() calls itself? The system works as normal
...
It then begins executing statements
...
It then begins the function again and when it finds the function call, it makes a new note and puts on the
top of the stack
...
Since the function has no chance of returning control to its caller, the messages
never get taken off the stack and it just builds up
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Each time a function is called, the program is said to drop down a level
...
The main() function is at level 0 because it is the root of the program
...
When a level one function returns, it hands control back to level
zero
...
The level number
is the number of messages or reminders on the stack
...
It punches a great hole in a program; it has no
place in a levelled structure diagram
...
A better name for this function would be:
StackOverflow()

/* Causes stack to grow out of control */

{
StackOverflow();
}

Node:Tame Recursion and Self-Similarity, Next:Simple Example without a Data Structure, Previous:Levels and
Wells, Up:Recursion

Tame Recursion and Self-Similarity
Recursion does not have to be so dramatically disastrous as the example given
...

Earlier we remarked that programs and data structures aim to model the situation they deal with as closely as possible
...
Since recursion is about functions which contain themselves at all levels, this tends to suggest that
recursion would be useful for dealing with these self-similar problems
...

Recursive functions can be tamed by making sure that there is a safe way exit them, so that recursion only happens
under particular circumstances
...
For example, it is
easy to make Well_Function recurse four times only, by making a test:
Well_Function(nooftimes)
int nooftimes;
{
if (nooftimes == 0)
{
return (0);
}
else

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Notice the way in
which the if
...
It effectively acts as
a safety net, stopping the programming from plunging down the level well infinitely
...
This is a mathematical
function which is important in statistics
...
) The factorial function is defined to be the "product" (multiplication) of all the natural (unsigned
integer) numbers from 1 to the parameter of the function
...
This strange definition seems to want to lift itself by its very bootstraps! The second statement saves
it, by giving it a reference value
...
The statement:
factorial (3);

causes a call to be made to factorial()
...
factorial() then tests whether n is zero
(which it is not) so it takes the alternative branch of the if
...
This instructs it to return the value of:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The
new call takes this value, checks whether it is zero (it is not) and tries to return the value 2 * factorial(1)
...
Finally, it calls factorial(0) which does not call factorial any more, but starts unloading the stack
and returning the values
...

Node:Simple Example With a Data Structure, Next:Advantages and Disadvantages of Recursion, Previous:Simple
Example without a Data Structure, Up:Recursion

Simple Example With a Data Structure
A data structure earns the name recursive if its structure looks identical at every point within it
...
At every point in a linked list, there are some data of identical type and one pointer to the
next structure
...
It has two
pointers, one which branches left and one which branches to the right
...

is a function which releases the dynamic memory allocated to a linked list in one go
...
It must therefore make a note of the pointer to the
next structure in the list, before it deletes that structure, or it will never be able to get beyond the first structure in the
list
...

deletetoend()

/* structure definition */
struct list
{
/* some other data members */
struct list *succ;
};
/**************************************************************/
struct list *deletetoend (ptr)
struct list *ptr;
{
if (ptr != NULL)
{
deletetoend (ptr->succ);
releasestruct (ptr);
}
return (NULL);
}
/**************************************************************/
releasestruct (ptr)

/* release memory back to pool */

struct list *ptr;
{

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
This need not be the very beginning: it could be any
place in the list
...
It does assume that
the programmer has been careful to ensure that the end of the list is marked by a NULL pointer
...
If the pointer supplied is already NULL then this function
does nothing
...
Notice that deletetoend()
calls itself immediately, passing its successor in the list as a parameter
...
The very last-called deletetoend() then reaches the statement releasestruct()
which frees the memory taken up by the last structure and hands it back to the free memory pool
...
This, in turn, returns and the process continues until the
entire list has been deleted
...

Node:Advantages and Disadvantages of Recursion, Next:Recursion and Global Variables, Previous:Simple Example
With a Data Structure, Up:Recursion

Advantages and Disadvantages of Recursion
Why should programmers want to clutter up programs with techniques as mind boggling as recursion at all? The great
advantage of recursion is that it makes functions very simple and allows them to behave just like the thing they are
attempting to model
...

The major disadvantage of recursion is the amount of memory required to make it work: do not forget that the program
stack grows each time a function call is made
...
There is also the slight danger that a recursive function will go out of
control if a program contains bugs
...
Most recursive routines only work because they are sealed capsules
and what goes on inside them can never affect the outside world
...
To
appreciate the danger, consider a recursive function, in which a second function alterGLOBAL() accidentally alters the
value of GLOBAL in the middle of the function:
int GLOBAL = -2;
recursion ()

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
If alterGLOBAL() makes
GLOBAL more negative, as fast as ++ can make it more positive then GLOBAL will never be able to satisfy the condition
of being zero and it will go on making recursive calls, never returning
...
The stack would fill
up the memory and the program would plunge down an unending recursive well
...
alterGLOBAL()
cannot alter a variable in recursion() by accident, if only local variables are used, because it only works with its own
local copies of parameters and variables which are locked away in a sealed capsule, out of harm's way
...
What is a recursive function?
2
...

3
...

Node:Example Programs chapter, Next:Errors and debugging, Previous:Recursion, Up:Top

Example Programs
The aim of this section is to provide two substantial examples of C, which use the data structures described in section
28
...
and so on, of those data
...
The editor works in insert or overwrite modes
...

The editor:
Insert Overwrite:

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
The editor first asks the user whether the current
number of sets of data is to be altered
...
Up to twenty independent sets of data can be used
...
If the number of sets is reduced at any time, the top
sets are cut off from the calculations, but they are not lost forever, provided the number is changed back to include
them before they are saved to disk, since the number of sets is used as an upper bound in a for loop: it does not
actually alter the memory
...

Node:Insert Overwrite, Next:Quitting section, Previous:The editor, Up:Statistical Data Handler

Insert/Overwrite
A project file can be edited in either insert mode or overwrite mode
...
The editor senses this and selects the mode automatically
...

Type 0
...
In overwrite mode the user is offered each entry in turn
...
(dot) or a - (dash) etc
...
However, if a new
value is entered, the new value will replace the old one
...
However, on selecting overwrite mode, the user is prompted for a starting value, and the values are offered from
the starting number to the end
...

Node:Quitting section, Next:Program listing stat, Previous:Insert Overwrite, Up:Statistical Data Handler

Quitting Sections
When quitting sections in which the user is supposed to enter data, the convention is that typing a zero value (0
...
Typing 0
...

Node:Program listing stat, Previous:Quitting section, Up:Statistical Data Handler

The Program Listing
The program includes three library files, which are used for the following purposes
...
h>

Standard IO eader file
#include ...
h>

Includes math function declarations
The flow of program logic is most easily described by means of a program structure diagram
...
The general scheme of the program

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Various flags concerning the data structure are cleared
...
A menu is printed and the program cycles through the menu options
...
The editor determines the data group to be edited, updates the screen with the data in the current group and
loops through insert or overtype editing until the user quits
...
The analysis calls custom functions which scan through the data structure calculating the relevant quantities
...
Various toolkits perform run of the mill activities
...
The array provides the roots of several independent linked
lists: one for each group of data
...

Node:Listing stat, Next:Variable Cross Referencer, Previous:Statistical Data Handler, Up:Example Programs chapter

Listing
/************************************************************/
/*
*/
/* Statistical Calculator
*/
/*
*/
/************************************************************/
#include ...
h>
#include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

#define ENDMARK
#define NOTENDMARK
#define BIGNUM

-1
...
";

/* list data */
/* project name */

/**********************************************************/
/** STRUCTURES
**/
/**********************************************************/
struct list
{
double value;
struct list *succ;
};
struct Vlist
{
struct list *datptr;
int datathere;
}
Data[GRPS];
/***********************************************************/
/** LEVEL 0 : Main Program
**/
/***********************************************************/
main ()
{ char getkey();
clrflags();
while (TRUE)
{
Menu();
switch (getkey())
{
case '1' : edit(noofgroups());
break;
case '2' : LoadSave();
break;
case '3' : Analyse();
break;
case 'q' : if (wantout(CAREFULLY)) quit();
}
}
}
/************************************************************/
/** LEVEL 1
**/
/************************************************************/
clrflags()

/* Initialize a virtual list */

{ short i;
for (i=1; i<=GRPS; i++);
{
Data[i]
...
datptr = NULL;
}
}
/***********************************************************/
Menu ()
{
CLRSCRN();
printf ("\nStatistical Calculator V1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

/*************************************************************/
edit (no_grps)

/* Edit a linked list */

int no_grps;
{ char s,status(),getkey();
int i,stop = FALSE,ctr;
void saveproject();
double over(),t,correct,getfloat();
struct list *ptr,*here,*eolist(),
*install(),*startfrom();
while (TRUE)
{
i = whichgroup();
switch (s = status(i))
{
case 'i':
for (here = eolist(i,&ctr); TRUE; ctr++)
{
updatescrn (i,s);
printf("%d:",ctr);
if ((t = getfloat ()) == 0) break;
here = install (here,t,i);
}
printf ("\n\nFile closed\n\n");
break;
case 'o':
for (ptr=startfrom(&ctr,i); ptr != NULL; ptr = ptr->succ)
{
if (ctr % 4 == 1) updatescrn (i,s);
correct = over(ctr++,ptr->value);
ptr->value = correct;
}
break;
case 's': saveproject();
break;
case 'l': loadproject();
break;
case 'q': stop = wantout(FAST);
}
if (stop) break;
}
}
/************************************************************/
noofgroups ()

/* Check no
...
%d)\n\n",GRPS);
return (DATSETS = getint(0,GRPS));
case 'e' : return (DATSETS);
}
}
/*************************************************************/
LoadSave ()

/* Project options */

{ char ch,getkey();
CLRSCRN();
printf ("\nCurrent Project %s\n\n\n", FSP);
printf ("Load new project or Save current one (L/S/Quit) ?\n\n");
ch = getkey();
switch (tolower(ch))

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
datptr);
}
exit(0);
}
/************************************************************/
/* LEVEL 2
*/
/************************************************************/
void saveproject ()
{ FILE *dfx;
char *filename(),ch,getkey();
struct list *ptr;
int i;
if ((dfx = fopen (filename(),"w")) == 0)
{
printf ("Cannot write to file\nPress a key\n");
ch = getkey();
return;
}
fprintf (dfx,"%ld\n",DATSETS);
for (i=1; i <= DATSETS; i++)
{
for (ptr = Data[i]
...
datathere);

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
0;
struct list *ptr,*install(),*deletetoend();
if ((dfx = fopen(filename(),"r")) == NULL)
{
printf ("File cannot be read\nPress any key\n");
ch = getkey();
return (0);
}
fscanf (dfx,"%ld",&DATSETS);
for (i = 1; i <= DATSETS; i++)
{
t = NOTENDMARK;
Data[i]
...
datptr);
Data[i]
...
datptr; t != ENDMARK;)
{
fscanf (dfx,"%lf",&t);
if (t != ENDMARK)
{
ptr = install (ptr,t,i);
}
}
fscanf (dfx,"%ld",&r);
Data[i]
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

if (i==0)
{
stat = 'q';
}
else
{
if (Data[i]
...
0\n\n");
printf ("\nThis project file contains %d groups
...
datptr; (ptr != NULL); ptr=ptr->succ)
{
if ((ctr % 3) == 0) NEWLINE();
printf (" (%2d) %12g ",ctr+1,(ptr->value));
ctr++;
}
printf ("\n\nEditing Group %d
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

{ struct list *ptr;
double sum;
int num;
sum = num = 0;
for (ptr = Data[i]
...
datptr; ptr != NULL; ptr=ptr->succ)
{
sum += (ptr->value - mean) * (ptr->value - mean);
num ++;
}
var = sum/num;

/* "biased" value */

printf ("Variance %d = %f\n",i,var);
printf ("Std deviation %d = %f\n",i,sqrt(var));
}
/************************************************************/
double millikan (i)

/* smallest diffnce between 2 data */

int i;
{ double temp,record = BIGNUM;
struct list *ptr1,*ptr2;
for (ptr1 = Data[i]
...
datptr; ptr2!=ptr1; ptr2=ptr2->succ)
{
temp = (ptr1->value) - (ptr2->value);
if (ABS(temp) < record)
{
record = ABS(temp);
}
}
}
return(record);
}
/************************************************************/
/* LEVEL 3
*/
/************************************************************/
char *filename ()
{
do
{
printf ("Enter filename : ");
scanf ("%s",FSP);
skipgarb();
}
while (strlen(FSP) == 0);
return (FSP);
}

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
datptr; ptr != NULL; ptr = ptr->succ)
{
++(*c);
p = ptr;
}
return (p);
}
/*************************************************************/
struct list *startfrom (ctr,i)

/* Find ith node in list */

int *ctr,i;
{ struct list *ptr,*p = NULL;
int j = 0;
printf ("Overtype starting from which entry");
*ctr = getint(1,99);
for (ptr=Data[i]
...
datathere)
{
Data[i]
...
datathere = TRUE;
}
else
{
ptr->succ = thispos;
}
thispos->value = t;
thispos->succ = NULL;
return (thispos);
}
/************************************************************/
struct list *deletetoend (ptr)

/* RECURSIVE WELL - returns
NULL for easy deletion of
call ptr */

struct list *ptr;

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

/*************************************************************/
sure (becareful)

/* Are you sure : boolean */

int becareful;
{
if (becareful)
{
printf ("Are you sure? (Y/N)\n");
if (yes()) return (TRUE); else return (FALSE);
}
return (TRUE);
}
/***********************************************************/
yes ()

/* boolean response Y/N query */

{
while (TRUE)
{
switch (getkey())
{
case 'y' : case 'Y' : return (TRUE);
case 'n' : case 'N' : return (FALSE);
}
}
}
/***********************************************************/
char getkey ()

/* get single character */

{ char ch;
scanf ("%c",&ch);
skipgarb();
return (ch);
}
/***********************************************************/
getint (a,b)

/* return int between a and b */

int a,b;
{ int

p, i = a - 1;

for (p=0; ((a > i) || (i > b)); p++)
{
printf ("?");
scanf ("%d",&i);
if (p > 3)
{
skipgarb();
p = 0;
}
}
skipgarb();
return (i);
}
/***********************************************************/
double getfloat ()

/* return long float */

{ double x = 0;
printf ("? ");
scanf ("%lf",&x);
skipgarb();
return (x);
}
/************************************************************/
skipgarb()

/* Skip input garbage corrupting scanf */

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
) and lists the line numbers of those identifiers within the source file
...
The program is listed here, with its line numbers, and its output (applied to itself)
is supplied afterwards for reference
...


Listing Cref
...
c:
Node:Listing Cref
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Listing Cref
...
h>
#include ...
in file
Input BUFFER for IDs
Current input character
macro/pointer flag

*/
*/
*/
*/

/**********************************************************/
/* TABLE
*/
/**********************************************************/
char *WORDTABLE [WORDTABLE] =

/* Table of resvd words */

{
"auto"
,
"break"
,
"case"
,
"char"
,
"const",
"continue",
"default" ,
"do"
,
"double" ,
"else"
,
"entry"
,
"enum"
,
"extern" ,
"float"
,
"for"
,
"goto"
,
"if"
,
"int"
,
"long"
,
"register",
"return" ,
"short"
,
"signed" ,
"sizeof" ,
"static" ,
"struct" ,
"switch" ,
"typedef" ,
"union"
,
"unsigned",
"void"
,
"volatile",
"while"
,
};
/********************************************************/
/** STRUCTURES
**/
/********************************************************/
struct heap
{
short num;
char spec;
struct heap *next;
};

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
0\n\n");
if ((fp = fopen (filename(),"r")) == NULL)
{
printf ("Can't read file
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238

SPECIALCHAR = ' ';
}
/**********************************************************/
listIDs (p)

/* List Binary Tree */

struct BinaryTree *p;
{ struct heap *h;
int i = 0;
if (p != NULL)
{
listIDs (p->left);
printf ("\n%-20s",p->name);
for (h = p->line; (h != NULL); h = h->next)
{
printf ("%c%-5d",h->spec,h->num);
if ((++i % 8) == 0)
{
printf ("\n
");
}
}
printf ("\n");
listIDs (p->right);
}
}
/*********************************************************/
struct BinaryTree *CloseDataStruct (p)

/* Recursive! */

struct BinaryTree *p;
{
if (p->left != NULL)
{
CloseDataStruct(p->left);
}
else if (p->right != NULL)
{
CloseDataStruct(p->right);
}
deleteheap(p->line);
releasetree(p);
return (NULL);
}
/*********************************************************/
/* LEVEL 2
*/
/*********************************************************/
ParticularSkip (fp)

/* handle particular characters */

FILE *fp;
{ char c;
switch (CH)
{
case '/' : if ((c = getc(fp)) == '*')
{
skipcomment (fp);
}
else
{
CH = c;
return (DUMMY);
}
break;
case '"' : if (skiptochar (fp,'"') > MAXSTR)
{
printf ("String too long or unterminated ");
printf ("at line %d\n",LINECOUNT);

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400

{
if (!(CH == ' ' || CH == '\n'))
{
break;
}
else if (CH == '\n')
{
++LINECOUNT;
}
CH = getc(fp);
}
if (CH == '(')
{
return (TRUE);
}
else
{
return (FALSE);
}
}
/**********************************************************/
deleteheap (h)

/* Release back to free memory pool */

struct heap *h;
{ struct heap *temp = h;
while (h!=NULL && temp!=NULL)
{
temp = h->next;
releaseheap(h);
h = temp;
}
}
/**********************************************************/
/** LEVEL 3
**/
/**********************************************************/
skipcomment (fp)

/* skip to char after comment */

FILE *fp;
{ char cs = 'x';
for (CH = getc(fp); !feof(fp); CH = getc(fp))
{
switch (CH)
{
case '\n': ++LINECOUNT;
break;
case '/' : if (cs == '*')
{
CH = getc(fp);
return(DUMMY);
}
}
cs = CH;
}
}
/*********************************************************/
skiptochar (fp,ch)

/* skip to char after ch */

FILE *fp;
char ch;
{ int c=0;
while (((CH =getc(fp)) != ch) && !feof(fp))
{
if (CH == '\n')
{
++LINECOUNT;
}
c++;
}

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
to heap */

struct heap *h;
{ struct heap *hp,*newheap();
hp = newheap();
hp->num = LINECOUNT;
hp->spec = SPECIALCHAR;
hp->next = h;
return (hp);
}
/*********************************************************/
/* TOOLKIT file input
*/
/*********************************************************/
backone (ch,fp)

/* backspace one in file */

char ch;
FILE *fp;
{
if (ungetc(ch,fp) != ch)
{
printf ("\nDebug: Toolkit file input: backone() FAILED\n");
exit(0);
}
}
/**********************************************************/
/* TOOLKIT stdin
*/

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
";
do
{
printf ("Enter filename of source program: ");
scanf ("%33s",fsp);
skipgarb ();
}
while (strlen(fsp) == 0);
return (fsp);
}
/*********************************************************/
skipgarb ()

/* skip garbage upto end of line */

{
while (getchar() != '\n');
}
/**********************************************************/
/* TOOLKIT data structure
*/
/**********************************************************/
char *stringin (array)

/* cpy str in arry to ptr loc*/

char *array;
{ char *malloc(),*ptr;
int i;
ptr = malloc (strlen(array)+1);
for (i = 0; array[i] != '\0'; ptr[i] = array[i++]);
ptr[i] = '\0';
return(ptr);
}
/**********************************************************/
struct heap *newheap ()
{ char *malloc ();
return ((struct heap *) malloc(sizeof(struct heap)));
}
/**********************************************************/
struct BinaryTree *newtree ()
{ char *malloc ();
return ((struct BinaryTree *) malloc(sizeof(struct BinaryTree)));
}
/*********************************************************/
releaseheap (ptr)
struct heap *ptr;
{
if (free((char *) ptr) != 0)
{
printf ("TOOLKIT datastruct: link release failed\n");
}
}
/**********************************************************/
releasetree (ptr)
struct BinaryTree *ptr;
{
if (free((char *) ptr) != 0)
{

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
c, Previous:Listing Cref
...
0
Enter filename of source program: Cref
...
htm[6/29/2009 12:42:58 PM]

386

C Programming Tutorial

feof()

393

368

319

filename()

484

102

98

fnflag

301

296

294

fopen()

102
473
376
319
254
217
130
102

470
368
316
249
215
126
97

free()

560

546

fsp

495
402
245

fp
386
329
261
224
139
107

getc()
254
getchar()

267

130

109

467
368
314
245
156
124

402
368
270
243
152
112

393
364
267
235
148
111

393
362
263
226
146
109

388

494

491

486

393
224

376
107

368

368

329

270

503

h

458
346
176

451
344
168

449
178

354
178

353
176

352
176

350

348
176

543
348

528
346

528
168

525
84

453
75

451
72

449

412

460

458

457

456

455

453

519
282
179

518
282
169

518
282

518
280

518
273

515
269

install()

439

435

408

308

304

299

iscsym()

267

iscsymf()

133

isfunction()

314

156

left

435

435

422

199

197

173

line

429

429

421

206

176

84

listIDs()

186

173

164

115

main()

95

malloc()

536

535

528

527

517

514

MAXIDSIZE

20

#16

MAXSTR

235

#15

name

427

420

174

83

newheap()

525

455

453

newtree()

533

419

413

next

458

352

176

num

456

178

73

442
427
417
199
173

439
424
410
197
171

439
423
408
194
166

435
422
207
192
164

435
421
206
186

430
420
203
176

429

pos

433

427

415

printf()

563

549

490

475

238

237

185

heap

hp
i
284
265

p
429
419
201
174

286

85

75

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
c, Previous:Output of Cross Referencer, Up:Variable Cross Referencer

Comments
This simplified program could be improved in a number of ways
...
g
...
It could be
made to mark them at every line, so that #undef-ined symbols and variables were clearly distinguished
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Debugging can be a difficult process
...
Often the error messages give a completely misleading
impression of what has gone wrong
...
These
few examples here should help beginners get started and perhaps give some insight into the way C works
...
Every statement must end with a semi colon
...

statement;
but:
{
}; <-- This semi colon is only needed if the curly
braces enclose a type declaration or an
initializer for static array/structure etc
...

Count braces carefully
...

So write
{
}

and fill in the statements afterwards
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
If a program fails at the linking stage because it has found a
reference to a function which had not been defined, this is often the cause
...


Node:Variable not declared or scope wrong, Next:Using a function or assignment inside a macro, Previous:Missing
inv comma, Up:Compiler Trappable Errors

Variable not declared or scope wrong
This means that a variable is used which has not first been declared, or that a variable is used outside of its sealed
capsule
...
This error might generate something like "lvalue required"
...
If it is required that they return another type of variable, this must by
declared in two places: a) in the function which calls the new function, along with the other declarations:
CallFunction ()
{ char ch, function1(), *function2();
}

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
This must also be declared where the function is
defined:
char function1 ()
{
}

and
char *function2()
{
}

This error might result in the message "type mismatch" or "external variable/function type/attribute mismatch"
Node:Type mismatch in expressions, Previous:Forgetting to declare a function which is not type int, Up:Compiler
Trappable Errors

Type mismatch in expressions
There is a rule in C that all maths operations have to be performed with long variables
...
If the user forgets this and tries to use short C automatically converts it into long form
...
So the following is wrong:
short i,j = 2;
i = j * 2;

If a short result is required, the cast operator has to be used to cast the long result to be a short one
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Mathematical Error:
Uncoordinated Output using put/get I/O:
Global Variables and Recursion:
Node:Confusion of = and ==, Next:Missing & in scanf, Previous:Run time errors, Up:Run time errors

Confusion of = and ==
A statement such as:
if (a = 0)
{
}

is valid C, but notice that = is the assignment operator and not the equality operator ==
...
To compare a to zero the correct syntax is:
if (a == 0)
{
}

Node:Missing & in scanf, Next:Confusing C++ and ++C, Previous:Confusion of = and ==, Up:Run time errors

Missing & in scanf
This error can often be trapped by a compiler, but not in all cases
...
Thus the following is wrong:
int i;
char ch;
scanf ("%c %d",ch,i);

and should read:
int i;
char;
scanf ("%c %d", &ch, &i);

Notice however that the & is not always needed if the identifier in the expression is already a pointer
...
If this error is trappable then it will be something like "Variable is not a pointer"
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Confusing C++ and ++C
In many cases these two forms are identical
...
g
...
++C causes C to be incremented by 1 before the assignment takes place whereas C++
causes C to be incremented by 1 after the assignment has taken place
...

Node:Unwarranted assumptions about storage of arrays/structures, Next:Number of actual and formal parameters does
not match, Previous:Confusing C++ and ++C, Up:Run time errors

Unwarranted assumptions about storage
C stores arrays in rows, and as far as the language is concerned the storage locations are next to one another in one
place up to the end of the array
...
A program will be loaded into one or more
areas (where ever the operating system can find space) and new variable space will be found wherever it is available,
but this will not generally be in whole blocks `side by side' in the memory
...

*(array + 10) = 0;

While it is true that the variable "array" used without its square brackets is a pointer to the first element of the array, it
is not necessarily true that the array will necessarily be stored in this way
...

array[10] = 0;

is safe
...
Use:
&(array[3])

Do not assume that the size of a structure is the sum of the sizes of its parts! There may be extra data inside for
operating system use or for implementation reasons, like aligning variables with particular addresses
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

This problem can be avoided in ANSI C and C++ but not in K&R C
...
The values which are assumed for missing parameters cannot be guaranteed
...

Node:Conversion string in scanf or printf wrong, Next:Accidental confusion of int short and char, Previous:Number of
actual and formal parameters does not match, Up:Run time errors

The conversion string in scanf / printf is wrong
Incorrect I/O is can be the result of poorly matched conversion strings in I/O statements
...
Suppose the left hand box were i and the right hand box were j and you wanted to input the
value of i: instead of getting:
|

-------------------002345 |
|
-------------------i

scanf

j

might store

0000000000000002345

as
-----------------------| 000000000 | 0000002345 |
-----------------------i

j

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
If characters/integers are passed as
parameters it is easy to mistype char for int etc
...
Characters are stored by their ASCII values
...

Node:Arrays out of bounds, Next:Mathematical Error, Previous:Accidental confusion of int short and char, Up:Run
time errors

Arrays out of bounds
C does not check the limits of arrays
...
However the computer might! In
the worst case this could cause the program to crash
...
A program might continue regardless of the fact that a mathematical
function failed
...
h at
the start of the program
...
This means that it is not written to the
screen until the buffer is either full or is specifically emptied
...
One cure is to terminate with a newline \n character which flushes the buffers on each write operation
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Special functions on some systems such as getch() may also suffer from this problem
...
Most recursive routines work only because they are sealed
capsules and what goes on inside them can never affect the outside world
...
Consider a recursive
function:
int GLOBAL;
recursion ()
{
if (++GLOBAL == 0)
{
return (0);
}
alterGLOBAL();
recursion();
}

/* another function which alters GLOBAL */

This function is treading a fine line between safety and digging its own recursive grave
...
The stack would fill up the memory and the program would plunge down an unending recursive well
...
Here are some tips for fault finding:
1
...
Never rely on global variables for passing
messages between functions
...
Check variable declarations and missing parameters
...
Check that a program has not run out of private memory
...
) Make the program stack size bigger if that is possible
...
Use statements like printf("program is now here") to map out the progress of a program and to check that all
function calls are made correctly
...
Use statements like ch = getchar() to halt a program in certain places and to find out the exact location at which
things go wrong
...
Try "commenting out" lines of suspect code
...


file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
Check that the compiler disk has not been corrupted (make a new copy) - getting desperate now!
8
...

9
...

Failing these measures, try to find someone who programs in C regularly on the computer system concerned
...
Sometimes these will be the result of
misconceptions about C functions, but occasionally they may be the result of compiler bugs, or operating system
design peculiarities
...
The deletion of
CLRSCRN() cured the problem entirely! In general it is worth checking carefully the names of all functions within a
program to be sure that they do not infringe upon library functions
...
Even capitalizing (Read() / Write()) might not work: beware that special operating system libraries have not
already reserved these words as library commands
...
A programmer can only hope to try to eliminate all possibilities in
homing in on the problem
...
"
Node:Porting Programs between computers, Next:Qu, Previous:Pathological Problems, Up:Errors and debugging

Porting Programs between computers
Programs written according to the style guidelines described in this book should be highly portable
...
The most likely area of
incompatibility betwee compilers regards filing operations, especially scanf()
...
scanf() is capable of producing a full spectrum of weird effects
which have nothing to do with I/O
...

Check conversion characters in printf() and scanf() as some compilers choose slightly different conventions
for these
...
This can cause errors at
run time if a program runs out of space, even though there is nothing wrong with the code
...
For example, pause() or wait loops
...
e
...
limited/unlimited size, valid characters etc
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Node:Qu, Previous:Porting Programs between computers, Up:Errors and debugging

Questions
Spot the errors in the following:
1
...
while (a < b)
{
while (b == 0)
{
printf ("a is negative");
}

3
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

break

statement (escape from switch or loop)
case

option prefix within switch statement
char

typename
continue

statement (branch to start of next loop)
default

option in switch statement
do

statement
double

typename
else

statement
entry

(reserved for the future use)
extern

storage class specifier
float

typename
for

statement
goto

goto label
if

statement
int

typename
long

typename
register

storage class specifier
return

functional statement
short

typename
sizeof

compile time operator
static

storage class specifier
struct

partial typename
switch

statement
typedef

statement
union

partial typename
unsigned

typename
while

statement
enum

partial typename: ordinal types only
void

typename
const

storage class specifier(no storage allocated)
signed

typename
volatile

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
They supplement the object code libraries which are linked at compile time for
standard library functions
...
Typical names for
header files are:
stdio
...

ctype
...

math
...
9 only
Octal
Prefix 0 (zero) chars 0
...
f A
...
9
Explicit Long
Integer/Octal or Hexadecimal types can be declared long by writing L immediately after the constant
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Character
Declared in single quotes e
...
'x' '\n'
Float
Characters 0
...
" May also use scientific notation exponents with e or E preceding them
...
g
...
14E12
3
...
g
...

Node:Primitive Data Types, Next:Storage Classes, Previous:Constants, Up:Summary

Primitive Data Types
char

Holds any character
int

Integer type
short int

Integer no larger than int
long int

Integer no smaller than int
float

Floating point (real number)
long float

Double precision float
double

(ditto)
void

Holds no value, uses no storage (except as a pointer)
Node:Storage Classes, Next:Identifiers, Previous:Primitive Data Types, Up:Summary

Storage Classes
auto

Local variable (redundant keyword)
const

No variable allocated, value doesn't change
extern

Variable is defined in another file
static

Value is preserved between function calls
register

Stored in a register, if possible
volatile

Value can be changed by agents outside the program
...
9 , A
...
z and _ (the underscore character)
...
(The compiler assumes that an object beginning with a number is a number
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Statements
A single statement is any valid string in C which ends with a semi colon
...
g
...
");

A compound statement is any number of single statements groued together in curly braces
...
Any pair of curly braces may contain local declarations
after the opening brace
...
g
...
");
}

Summary of Operators and Precedence
The highest priority operators are listed first
...
htm[6/29/2009 12:42:58 PM]

left
left
left
left
left
left
left
left

right
right
right
right

right
right
right
right
right

to
to
to
to
to
to
to
to
to

left
left
left
left
left
left
left
left
left

C Programming Tutorial

^=
|=

exclusive OR assign
inclusive OR assign

right to left
right to left

Node:Character Utilities, Next:Special Control Characters, Previous:Statements, Up:Summary

Character Utilities
char ch;
isalpha(ch)

Is alphabetic a
...
Z
isupper(ch)

Is upper case
islower(ch)

Is lower case
isdigit(ch)

Is in the range 0
...
9 or a
...
F
isspace(ch)

Is white space character (space/newline/tab)
ispunct(ch)

Is punctuation or symbolic
isalnum(ch)

Is alphanumeric (alphavetic or number)
isprint(ch)

Is printable on the screen (and space)
isgraph(ch)

If the character is printable (not space)
iscntrl(ch)

Is a control character (not printable)
isascii(ch)

Is in the range 0
...
They have special purposes usually to do with cursor movement and are
written into an ordinary string or character by typing a backslash character \ followed by some other character
...

\b

backspace BS
\f

form feed FF (also clear screen)
\n

new line NL (like pressing return)
\r

carriage return CR (cursor to start of line)

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
(See Appendix C)
Node:Input/Output Functions, Next:print conversions, Previous:Special Control Characters, Up:Summary

Input/Output Functions
printf ()

Formatted printing
scanf ()

Formatted input analysis
getchar()

Get one character from stdin file buffer
putchar()

Put one charcter in stdout file buffer
gets ()

Get a string from stdin
puts ()

Put a string in stdout
fprintf()

Formatted printing to general files
fscanf()

Formatted input from general files
fgets()

Get a string from a file
fputs()

Put a string in a file
fopen()

Open/create a file for high level access
fclose()

Close a file opened by fopen()
getc()

Get one character from a file (macro?)
ungetc();

Undo last get operation
putc()

Put a character to a file (macro?)
fgetc()

Get a character from a file (function)
fputc()

Put a character from a file (function)
feof()

End of file
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Moves file position to the start of file
fflush()

Empties file buffers
open()

Open a file for low level use
close()

Close a file opened with open()
creat()

Create a new file
read()

Read a block of untranslated bytes
write()

Write a block of untranslated bytes
rename()

Rename a file
unlink()

Delete a file
remove()

Delete a file
lseek()

Find file position
Node:print conversions, Next:scanf conversions, Previous:Input/Output Functions, Up:Summary

printf

conversion specifiers

d

signed denary integer
u

Unsigned denary integer
x

Hexadecimal integer
o

Octal integer
s

String
c

Single character
f

Fixed decimal floating point
e

Scientific notation floating point
g

Use f or e, whichever is shorter
The letter l (ell) can be prefixed before these for long types
...

d

Denary integer
ld

Long int
x

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
It is important to include
math
...

ABS(x)

Return absolute (unsigned) value
...
(Function)
ceil(x)

Rounds up a "double" variable
floor(x)

Rounds down (truncates) a "double" variable
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Hyperbolic tangent
Node:goto, Previous:Maths Library Summary, Up:Summary

goto
This word is redundant in C and encourages poor programming style
...

For completeness, and for those who insist on using it (may their programs recover gracefully) the form of the goto
statement is as follows:
goto label;

label

is an identifier which occurs somewhere else in the given function and is defined as a label by using the colon:

label : printf ("Ugh! You used a goto!");

Node:reserved words list, Next:Comparisons, Previous:Summary, Up:Top

All the Reserved Words
Here is a list of all the reserved words in C
...
Many more words are out of bounds
...
Once a library has been included in a program,
its functions are defined and you cannot use their names yourself
...
(This does mean that, typed in upper case, the reserved
words could be used as variable names, but this is not recommended
...
)
auto d
break
case
char d
continue
default
do
double d
else
entry
extern d
float d
for
goto

if
int d
long d
register d
return
short d
sizeof
static d
struct
switch
typedef d
union d
unsigned d
while

also in modern implementations:
enum d
void d
const d
signed d
volatile d

Node:Comparisons, Next:Character Conversion Table, Previous:reserved words list, Up:Top

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
etc) or BBC BASIC, the following table will give you a rough and
ready indication of how the main words and symbols of the three languages relate
...
");

writeln ('
...
');

PRINT "
...
",a);

readln (a);
read (a);

INPUT a

for (x =
...
to
begin

FOR x =
...
)
{
}

while
...
)

REPEAT
UNTIL
...
;
else
...
then
...
;

IF
...

ELSE

switch (
...
of

N/A

{
}
while (
...
*/

end;
{
...


*

^

? ! $

struct

record

N/A

union

N/A

N/A

The conditional expressions if and switch are essentially identical to Pascal's own words if and case but there is no
redundant "then"
...
The loop constructions of C are far superior to
those of either BASIC or Pascal however
...
Input and Output in C can match all of BASICs string operations and
provide more, though string variables can be more awkward to deal with
...

Decimal

Octal

Hexadecimal

Character

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

/
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
?
@
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
(Thomas Sevaldrud)
;;;
(defconst burgess-c-style
'((c-tab-always-indent
(c-hanging-braces-alist
(c-hanging-colons-alist

(c-cleanup-list
(c-offsets-alist


...
((substatement-open before after)
(brace-list-open)))

...
(scope-operator))

...
c-lineup-arglist)
(defun-block-intro

...
3)
(statement-block-intro
...
-1)

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
0)

...
-)))

;(c-echo-syntactic-information-p
...
We can put these in
;; c-mode-map because c++-mode-map and objc-mode-map inherit it
(define-key c-mode-map "\C-m" 'newline-and-indent)
)
(add-hook 'c-mode-common-hook 'burgess-c-mode-common-hook)

;;;
;;; Lite hack for å slippe å skrive inn kompileringskommandoen i c,
;;; (hvis ikke Makfile eksisterer)
;;; samt en fancy heading hvis det er en ny fil
...
h>\n"))))
(outline-minor-mode 1)
(or (file-exists-p "makefile")
(file-exists-p "Makefile")
(set (make-local-variable 'compile-command)
(concat "gcc -o "
(substring
(file-name-nondirectory buffer-file-name)
0
(string-match
"\\
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

"/*" (make-string 75 ? ) "*/\n"
"/* Revision: $Id$
*/\n"
"/*" (make-string 75 ? ) "*/\n"
"/* Description:
*/\n"
"/*" (make-string 75 ? ) "*/\n"
"/*" (make-string 75 ?=) "*/\n"
"/*
*/\n"
"/*" (make-string 75 ?=) "*/\n"
"\n#include ...
C$"
(file-name-nondirectory buffer-file-name)))
" "
(file-name-nondirectory buffer-file-name))))))

;;; Mark hacks
( setq perl-mode-hook
'(lambda()
(setq perl-indent-level 0)
(setq perl-continued-statement-offset 3)
(setq perl-continued-brace-offset -3)
(setq perl-brace-offset 3)
(setq perl-brace-imaginary-offset 0)
(setq perl-label-offset -3)
(define-key perl-mode-map "\C-m" 'newline-and-indent)
)
)
( setq java-mode-hook
'(lambda()
(setq java-indent-level 0)
(setq java-continued-statement-offset 3)
(setq java-continued-brace-offset -4)
(setq java-brace-offset 3)
(setq java-brace-imaginary-offset 0)
(setq java-label-offset -4)
(setq java-statement-block-intro
...
3)
(setq java-substatement-open

...
0)
(setq java-statement-case-open

...
0)
(define-key java-mode-map "\C-m" 'newline-and-indent)
)
)

Node:Answers to questions, Next:Index, Previous:Emacs style file, Up:Top

Answers to questions
Chapter 1

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...

2) By typing the name of an executable file
...

Chapter 3
1) printf ("Wow big deal");
2) printf ("22");
3) printf ("The 3 wise men");
printf ("The %d wise men",3);
4) Most facilities are held in libraries
Chapter 4
1) To provide a basic set of facilities to the user
2) The filename used by a computer to reference a device
3) accounts
...
x (or perhaps accounts
...
h
3) No
...

4) Header file
...

2) Comments, preprocessor commands, functions, declarations, variables,
statements
...
)
3) Not necessarily
...

4) It signifies the end of a block, the return of control to somethng else
...

3) The value is discarded
...

5) By using "return"
...
htm[6/29/2009 12:42:58 PM]

comment!

C Programming Tutorial

1) A name for some variable, function or macro
2) a,c,f
3) int i,j;
4) double is twice the length of float and can hold significantly larger values
...
Unsigned can only be + and can hold
slightly larger + values than int
...

9) printf ("%d",(int)23
...

Chapter 11
1) With variable parameters or with return()
2) Where a function is definned, after its name: e
...

function (
...

4) No and it is illegal
...

Chapter 12
1) A global variable can be accessed by any part of a program
...

3) Local variables cannot leak out
...

4) Variable parameters do
...

5)

int i,j;
main ()
{ float x,y;
another(x,y);
}
another(x,y)
float x,y;
{
}

There are 6 storage spaces altogether
...
h>
3) false
4) false
Chapter 14

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
e
...
int *i;
3) Any type at all!
4) doubleptr = (double *)chptr;
5) Because number has not been initialized
...
(See main text)
Chapter 15
printf
1) #include ...
23);
}
2) This depends on individual compilers
3) a)
b)
c)
d)

No conversion string
Conversion string without matching value
Probably nothing
Conversion string without matching value

scanf
1) space, newline or tab
5) true
...
It copies the input to the output: a simple way of writing on the
screen
...

2) printf ("%d",5 % 2);
3) rem = 5 % 2;
4) variable = 10 - -5;
5) if (1 != 23)
{
printf ("Thank goodness for mathematics");
}
Chapter 18
1) Three: while, do
...
while
4) #include ...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

{
ch = getchar();
putchar (ch);
}
Chapter 19
1) The array identifier (without square brackets) is a pointer to the
first element in the array
...

No! Arrays are always variable parameters
...
Pointers to arrays of characters
...
(See main text)
3) See the Morse code example
...
This is implementation dependent
...

3) The length of a string (excluding NULL byte)
4) Joins two strings
...

Chapter 23
1) ++, -- and any assignment or unary operator
2) It could make a program too difficult to read
3) No
...

Chapter 23
1) FILE is defined by stdio
...
It is not a built in part of the language
...
They are meant for comparitive purposes only
...

4) Yes
...
i
...
one which can be assigned to
any other pointer type
...

Chapter 24
1) Nothing -- only the way it is used
...
It is normal to use integer or character types for bit
patterns
...
Exclusive OR is false if all possibilites are true
simultaneously
...
A bit pattern for certain
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

e) 00001111 & 00000111 & 00000011 == 00000011 = 3
5) a) 00000001 | 00000010 == 00000011 == 3
b) 00000001 | 00000010 | 00000011 == 00000011 == 3
6) a) 1 & (~1) == 00000001 & 11111110 == 0
b) 23 & ~23 == 00011111 & 11100000 == 0
c) similarly 0: n & (NOT n) is always zero
Chapter 26
1) a) a string which labels a file
b) a variable of type *fp which points to a FILE structure
c) the number of a file "portal" in the I/O array
2) High level filing performs translations to text
...

3) fp = fopen ("filename","r");
4) fd = open ("filename",O_WRONLY);
6) fprintf ()
Chapter 27
1) A structure can hold several values at the same time
...

2) A part of a structure, or a possible occupant of a union
...
mem
4) ptr->mem
5) False
...

2) With pointers
...
Pointers are used to reference variables and data structures
are built in such a way as to require only one name for a whole
structure
...
ptr->member etc
...

2) A data structure run by the C-language for keeping track of function calls and for storing
local data
...

Chapter 31
1) Declarations are in the wrong place
...
out: The compiler
&

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

File descriptors: File Handles
File extensions: Filenames
File handles: File Handles
File, detecting end of: feof
File, opening: Opening files
Files: Files and Devices
Files and devices: Files devices
Files as abstractions: Standard Output and Standard Input
Format specifiers, printf: Formatting with printf
Formatting text and variables: printf
Function names: Functions
Functions: Functions
Functions with values: Functions with values
Game of life: Example 20
gcc: The compiler
getchar: getchar and putchar
getenv() function : envp
gets: gets and puts, gets()
Global variables: Global variables
Global variables and recursion: Advantages and Disadvantages of Recursion
GNU compiler: The compiler
Header files: Libraries
Hidden assignment: Example 28
High level: Levels
Identifier names: Functions
if: Decisions
if statement: if
Initialization of arrays: Initializing Arrays
Initializing structures: Pre-initializing Static Structures
Initializing variables: Declarations and Initialization
int: integers, Variables
Integer types: Variables
Integers: integers
Interrupting a program: Command languages
Keyboard input: Standard Output and Standard Input
Layout: Programming style
Levels of detail: Levels
Libraries: Reserved words & example
Libraries of functions: Libraries
Linked list: Example Structures
Linker: The compiler
Local environment: Levels
Local variables: Where to declare things, Local variables
Logical errors: Errors
long: Variables, integers
Loop variables: Choosing Variables
Loops: Loops
Low level: Levels
Machine level operations: Machine Level Operations
Macros: Preprocessor
main function: Form of a C program
Mainframe: Operating systems
malloc: Creating Memory for Dynamical struct Types
Math errors: Maths Errors
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
h: Libraries
stdout: Standard Output and Standard Input
strcmp: Handling strings
strcpy: Handling strings
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Operating systems and environments
Files and Devices
Filenames
Command Languages and Consoles
Questions
Libraries
Questions
Programming style
The form of a C program
Questions
Comments
Example 1
Example 2
Question
Functions
Structure diagram
Program Listing
Functions with values
Breaking out early
The exit() function
Functions and Types
Questions
Variables, Types and Declarations
Declarations
Where to declare things
Declarations and Initialization
Individual Types
char

Listing
Integers
Whole numbers
Floating Point
Choosing Variables
Assigning variables to one another
Types and The Cast Operator
Storage class static and extern
Functions, Types and Declarations
Questions
Parameters and Functions
Declaring Parameters
Value Parameters
Functions as actual parameters
Example Listing
Example Listing
Variable Parameters
Example Listing
Questions
Scope : Local And Global
Global Variables
Local Variables
Communication : parameters
Example Listing
Style Note
Scope and Style
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Comparisons and Logic
Summary of Operators and Precedence
Questions
Decisions
if

Example Listings
if
...
else
switch: integers and characters
Example Listing
Things to try
Loops
while

Example Listing
Example Listing
do
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

The argument vector
Processing options
Environment variables
Special Library Functions and Macros
Character Identification
Examples
Program Output
String Manipulation
Examples
Mathematical Functions
Examples
Maths Errors
Example
Questions
Hidden operators and values
Extended and Hidden =
Example
Hidden ++ and -Arrays, Strings and Hidden Operators
Example
Cautions about Style
Example
Questions
More on data types
Special Constant Expressions
FILE
enum

Example
Example
Suggested uses for enum
void
volatile
const
struct
union
typedef

Questions
Machine Level Operations
Bit Patterns
Flags, Registers and Messages
Bit Operators and Assignments
The Meaning of Bit Operators
Shift Operations
Truth Tables and Masking
Complement ~
AND &
OR |
XOR/EOR ^
Example
Output
Example
Example
Questions
Files and Devices
file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

The Tools: Structures, Pointers and Dynamic Memory
Programme For Building Data Structures
Setting Up A Data Structure
Example Structures
Questions
Recursion
Functions and The Stack
Levels and Wells
Tame Recursion and Self-Similarity
Simple Example without a Data Structure
Simple Example With a Data Structure
Advantages and Disadvantages of Recursion
Recursion and Global Variables
Questions
Example Programs
Statistical Data Handler
The Editor
Insert/Overwrite
Quitting Sections
The Program Listing
Listing
Variable Cross Referencer
Listing Cref
...
htm[6/29/2009 12:42:58 PM]

C Programming Tutorial

Preprocessor Directives
Header Files and Libraries
Constants
Primitive Data Types
Storage Classes
Identifiers
Statements
Character Utilities
Special Control Characters
Input/Output Functions
printf conversion specifiers
scanf conversion specifers
Maths Library
goto

All the Reserved Words
Three Languages: Words and Symbols Compared
Character Conversion Table
Emacs style file
Answers to questions
Index

file:///C|/Users/HKN/Desktop/C%20Programming%20Tutorial1
Title: C Programming Tutorials
Description: Every program is limited by the language which is used to write it. C is a programmer's language. Unlike BASIC or Pascal, C was not written as a teaching aid, but as an implementation language. C is a computer language and a programming tool which has grown popular because programmers like it! It is a tricky language but a masterful one. Sceptics have said that it is a language in which everything which can go wrong does go wrong. True, it does not do much hand holding, but also it does not hold anything back. If you have come to C in the hope of finding a powerful language for writing everyday computer programs, then you will not be disappointed. C is ideally suited to modern computers and modern programming.