You are on page 1of 17

LECTURE ONE VARIABLES AND FUNCTIONS

What these lecture notes cover


These lecture notes should cover the following topics:
Some introductory material in which I justify this courses existence.
More detail about the !ello "orld program.
#lements of $ % pre-processor& language and libraries.
'eywords in $ % a first loo(.
)ariables and types in $.
"hat are functions and what is prototyping*
"hat is scope and why is it useful*
Syntax of the $ language
These notes assume you have already wor(ed through and understood the exercises in "or(sheet +ne.
,ecture +ne % )ariables and -unctions......................................................................................................
"hat these lecture notes cover................................................................................................................
Introduction % "hat we hope to teach you /and why0............................................................................
"hy teach $*.........................................................................................................................................1
"riting compiling and running a $ program.........................................................................................1
!ello "orld revisited.............................................................................................................................2
#lements of $ % 3re4processor& ,anguage and ,ibrary.........................................................................5
'eywords in $.......................................................................................................................................5
Types of variable....................................................................................................................................6
$hoosing names for variables................................................................................................................6
char variables.........................................................................................................................................7
+ther types signed8unsigned short8long and const.................................................................................7
Some more simple mathematical operations 99& 44& 9:& 4:& ;:& 8: and <............................................=
$asting between types............................................................................................................................>
-unctions ...............................................................................................................................................?
void functions........................................................................................................................................@
Aeturning from functions /the return statement0...................................................................................@
3rototypes of functions.........................................................................................................................1
,ocal variables& Blobal )ariables and Scope.......................................................................................1
Cebugging.............................................................................................................................................2
Summary of ,anguage elements learned in wor(sheet and lecture one...............................................5
#xample code using language elements from wor(sheet and lecture one............................................7
Introducton What !e ho"e to teach #ou $and !h#%
This course aims to teach you how to program in the $ programming language /obviously0. There are
very good reasons why a mathematician should learn how to program:
.0 D good chun( of modern mathematics /much of chaos theory and proving the four colour theorem to
give but two examples0 relies on computer programming and would be inaccessible without it.
10 $omputer simulation techniEues allow us to apply mathematical ideas to solve real4world problems
/such as setting traffic signals or curing congestion on the internet0.
20 If you decide that you donFt li(e being a mathematician after all& computer programming will ma(e
you employable.
finally& and most importantly&
50 $omputer programming can be fun /really& it can be fun I donFt necessarily guarantee that it will be
fun0.
In this course I hope to teach you:
!ow to program in the $ language and use the most common libraries.
.
!ow to write stylish and elegant programs.
!ow to write mathematical programs that are small and fast running.
!ow to document code so that other people who might have to use it donFt want to (ill you.
!ow to tell a good algorithm from a bad algorithm /well& how to ma(e an educated guess anyway0.
Some simple and handy techniEues which will serve for everyday programming needs.
I do not plan to teach you:
The latest fancy "indows graphical widget /it may be fun but youFll have to learn a new one in a
few years0.
!ow to create all4singing& all4dancing multimedia products /sorry& weFre mathematicians not
internet consultants0.
Wh# teach C&
There are a large number of programming languages in the world today. "hy am I teaching you $ and
not /to name but a few0 $99& Gava& Dda& HDSI$& $+H+,& 3erl& 3ascal& Smalltal(& Dssembler or
-+ATADI. There are several reasons to learn $:
$ is a common language. There are an awful lot of $ programs out there. In fact we would go so
far as to say that there are more lines of $ code than any other language in the world today.
$ is a small language. $ has only thirty two (eywords /and only about twenty of them are in
common use0. This ma(es it relatively easy to learn /we hope0 compared with bul(ier languages.
$ is a stable language. The DISI standard for $ was created in .?>2. The language has not been
revised since then. /Sadly this doesnFt mean that all $ code is standard0. In newer languages
/mentioning no names0 the standard changes regularly and often and what is good code today may
not compile properly tomorrow.
$ is a Euic( language. D well written $ program is li(ely to be as Euic( or Euic(er than a well
written program in any other high4level language.
$ is a core language. That is to say& a number of common and popular computer languages are
based upon $. !aving learned $& it will be much easier for you to learn languages which are
largely& or in part based upon $. Such languages include: $99& Gava& aw( and 3erl.
Indeed& it is often said that $ is the second best language for any given programming tas(. The best
language depends on the nature of the particular tas( but the second best language is $& whatever the
tas(.
Wrtn' co("ln' and runnn' a C "ro'ra(
Some jargon listed for you:
%Source code: The stuff you type into the computer. The program you are writing.
%$ompile /build0: Ta(ing source code and ma(ing a program that the computer can understand.
%#xecutable: The compiled program that the computer can run.
%,anguage: /Special sense0 The core part of $ central to writing $ code.
%,ibrary: Ddded functions for $ programming which are bolted on to do certain tas(s.
%!eader file: -iles ending in .h which are included at the start of source code.
Gust to remind you about your experience in wor(sheet one& there are three stages to writing a $
program as shown by the diagram:
1
#include <stdio.h>

int main()
{
printf (Hello World);
return 0;
}
hello.cpp

Hello World
ress an! "e! to
continue.
Edit the program
Compile (build)
the program
Execute
(or run)
the
program
This is source code
-irstly you must write the programs source code % that is to say the $ language instructions shown in
the first box above. /Teaching you how to do this is what this course is about0.
The second stage is to compile the program. This causes the computer to ta(e the source code and
attempt to ma(e it into an executable % that is to say a program which the computer can run. Ds a
beginner you will find that your programs will often fail at this compilation stage and the compiler will
complain about problems with your code.
The final stage is to run the executable code. Some errors will still turn up at this stage.
)ello World revsted
Jou probably saw easily enough of the !ello world program in "or(sheet one. !ere it is again to
remind you:
#include <stdio.h>
#$ %! first & pro'ram (hich prints Hello World $#
int main (int ar'c) char $ar'*+,)
{
printf (-Hello World./n-);
return 0;
}
ThereFs a lot to be learned from this particular example. -or one thing& $ doesnFt care about whitespace
much /spaces& returns and tabs0. So the program would wor( just as well as:
#include <stdio.h>#$ %! first & pro'ram (hich prints Hello World $#
int main(int ar'c) char $ar'*+,){printf(-Hello World./n-);return 0;}
/Hut note that nothing but the comment could go on the K line and it was necessary to (eep some of the
spaces.0
+n the other hand it could be written as:
#include <stdio.h>
#$ %! first
& pro'ram
(hich prints
Hello World $#
2
int
main
(
int
ar'c
)
char
$ar'*+,
)
{
printf
(
-Hello World./n-
)
;
return
0
;
}
/The #include statement cannot be bro(en up and anything within - mar(s should stay on the same
line but other than that anything goes0. The first version of the program loo(s ML$! nicer and it is
expected your code will loo( more li(e the first version than the strange example given.
Ele(ents o* C +re,"rocessor- Lan'ua'e and L.rar#
There are three main elements to the $ language all of which are represented in !ello "orld. The
pre4processor is so called because it ma(es alterations to the $ source code before the source code is
compiled. 3re4processor statements begin with a # character. In this case& the pre4processor statement
we have is a #include statement. #include tells the pre4processor to glue in another bit of $
source code here. Included files are (nown as header files and by convention have the extension .h.
The angle brackets surrounding the file name tell you that the file being included is part of the $
libraries on this machine. In this case& it is the standard library header stdio.h which contains
information about standard input and output routines. "e will learn more about the pre4processor later
and also how /and why0 $ programmers write their own header files.
The $ language /which is& after all& what is being taught0 is an extremely small base of a very few
(eywords and syntactical elements. /$ has only thirty two (eywords % they are listed later in these
notes % and most of them you donFt need to use anyway0.
-inally& there are the $ libraries. The libraries are full of helpful routines which do general useful
things that you might commonly want to do. If the tas( youFre thin(ing of is Euite simple or common
/sorting a list of numbers into order or calculating cosines for example0 then the chances are thereFs
something in the $ libraries to do it. In $& even things as basic as printing to screen or writing
information to dis( are library routines. In !ello "orld& we used the library routine printf which
writes to screen. To access the stdio library /standard input and output0 we had to include the
header file. It sometimes surprises people that $ considers dis( access and printing to screen as not
important enough to be in the language but instead consigns them to a library.
/e#!ords n C
!ere are the $ (eywords /the categories depend on the prejudices of your lecturer0:
5
-low control /70 % if) else) return) s(itch) case) default
,oops /60 % for) do) (hile) 0rea") continue
$ommon types /60 % int) float) dou0le) char) *oid
-or dealing with structures /20 % struct) t!pedef) union
$ounting and siMing things /10 % enum) si1eof
Aare but still useful types /=0 % e2tern) si'ned) unsi'ned) lon') short) static)
const
'eywords which are pure and unadulterated evil and which we I#)#A use /.0 % 'oto
"ierdies that we donFt use unless weFre doing something strange /20 % auto) re'ister)
*olatile
/Total (eywords: 210
"e will revisit it later in the course& when& hopefully& it will mean a little more. Ds you can see& weFve
already covered a good chun( of the language: int) float) dou0le) (hile) return)
if) else and for means that weFve already covered >821 of the $ language. /#ven more if we ta(e
into account that the last four (eywords wonFt be used0. ConFt bother learning the table /most $
programmers couldnFt list all 21 (eywords0 but just ta(e heart that youFve already got so far through it.
T#"es o* vara.le
$ is a wea(ly typed language. That means& you canFt just plon( down a variable name and start using
it % you have to tell the compiler what type of variable it is first.
This may seem a nuisance for you but it has a number of benefits to the programmer % not least of
which is that it prevents code li(e this from compiling:
m!3*aria0le 4 5;
(hile (m!3*ari0le < 6) { #$7ops 8 fum0le fin'ered spellin'$#
do something
m!3*aria0le99;
}
which would cause you a lot of headaches.
ND strongly typed language is one where you cannot convert between one type and another without
explicitly telling the program are about to do so % the bondage and discipline school of the
programming. Dn untyped or run4time typed language is one where you do not have to declare a
variable before using it. In an untyped language the above program would be legal but would not do
what you might expect if you didnt notice they spelling error.OO
"eFve already met int) dou0le and /briefly0 float so letFs loo( at some other common variable
types.
dou0le is li(e a float but has twice the precision /loosely spea(ing& it has more decimal places0.
So why not use dou0le all the time* Hecause it has more digits& itFs li(ely to be slower and itFs
definitely going to ta(e more memory up. Lse a float when you want to save memory or time and
dou0le is too large or slow.
I0+ORTANT RULE: "henever you want to use a variable in your program it must first be declared.
This means you must tell the $ compiler its type and its name. This is done at the start of main /or at
the start of a function0. The type of the variable will be int) float) dou0le /or some other
things we will see later0. Its name is up to you but there are good names and bad names.
Choosn' na(es *or vara.les
)ariable names can be just about any combination of letters and underlines but must not start with a
number. Hy convention& $ programmers use lower case or Mixed $ase variable names but not L33#A
$DS# Nthe reason should become clear later& but& in any case& if you program in all L33#A $DS#&
6
people will thin( youFre a -+ATADI programmer& which is in itself enough reason to not do itO. The
exact rules for naming variables are found in 'PA on page 26.
Bood variable names reflect the purpose of the variable and how commonly it is used. They should not
be too long nor too short for their role in the program. If you only use a variable three or four times
you will not mind calling it %!3important3loop3*aria0le3used3to3count3sheep but if
you have to use it a lot you might regret all that typing. -or historic reasons& it is traditional to use i):
and " as loop counter variables in for loops. Jou donFt have to do this but& when you do& it reassures
everyone else that you (now what youFre doing and also helps clarify whatFs going on.
Try to express what your variable does in the program using its name /if it counts the number of
students call it noQstudents not n or num0. Jou might li(e to use underscores for this. )ariable names
are usually lower case or Mixed$ase.
char vara.les
char is a character variable. That is to say that it can hold one /and only one0 alpha4numeric
character. In $& single characters must be specified using single Euotes. -or example:
char a4 ;<;;
char space4 ; ;;
char one4 ;5;;
char ne(3line4 ;/n;;
/The last example might seem a bit confusing since it loo(s li(e two characters& as in the !ello world
program % ;/n; translates to only one character % the character newline which returns you to the
start of the next line of printing.0
Cauton: It is a common beginner mista(e to put a char in double Euotes or a string /see later in the
course0 in single Euotes.
In a printf statement you can use =c to print a char.
Iote: In fact& a char is really just a one byte number % so you can eEually well say:
char a4 6>;
Jou can find out what numbers correspond to what characters by doing something li(e this:
printf (-&haracter =c is the same as num0er =d/n-);e;);e;);
#$ ;e; is interpreted first as a character then as a num0er $#
Other t#"es s'ned1uns'ned short1lon' and const
It is important to remember that variables ta(e up a certain amount of storage space and have a limit on
what type of numbers they can store. -or example& a char variable can never store a number larger
than 166. !ow high a value an int can store depends upon your compiler.
There are a number of alterations we can ma(e to variables. -or example:
si'ned or unsi'ned can be added before the type to say whether or not a variable can be negative
or not. -or example:
unsi'ned char c;
declares that $ can hold a number from @ to 166. "e can also declare ints to be si'ned or
unsi'ned.
7
"e can also declare ints& floats and dou0les to be lon' or short. lon' uses the
maximum length for that type of variable permitted on that computer and short uses the minimum
length. lon' and short can be combined with si'ned and unsi'ned.
Iote that no guarantees are made that on any given machine longs are bigger than ints or that
shorts are smaller.
Jou will not often use lon') short) si'ned or unsi'ned except when space is extremely
low and you want a large number of variables of that type.
"e can also declare a variable as const meaning that it is constant and cannot be changed. This can
be useful for example when declaring fundamental constants.
const float e4 ?.@5A?A5A?A;
So(e (ore s("le (athe(atcal o"eratons ++, --, +=, -=, *=, /= and %
Aecall from the wor(sheets that 99 is shorthand for add one to variable and BB is shorthand for
subtract one
I0+ORTANT RULE: 99i means increment and then use and i99 means use then increment. -or
example:
i4 >;
printf (-=d/n-)i99);
would print 6 whereas:
i4 >;
printf (-=d/n-)99i);
would print 7.
!owever& it is far clearer and better not to rely on this behaviour since it is confusing and can bac(fire.
It is far safer and clearer to write:
i4 >;
printf (-=d/n-)i);
i99;
for the first example and:
i4 C;
printf (-=d/n-)i);
for the second example. In $ it is possible to construct horrendous and complicated examples % but it
is usually better for everyoneFs sa(e if you donFt.
In addition we have the following:
BB /subtract one from variable0 e.g. countdo(nBB; /$ount down counts down by one0.
94 /add to a variable0 e.g. a94 >; /add 6 to a0.
B4 /subtract from variable0 e.g. num3li*in'B4 num3dead; /Subtract the dead from the living 0.
$4 /multiply a variable0 e.g. no30unnies$4?; /They breed li(e rabbits0.
#4 /divide a variable0 e.g. fraction#4 di*isor; /Civisor was clearly a good name for it0.
Dnother mathematical operation that we missed out is modulo =.
(2 = !) returns the remainder when 2 is divided by ! % obviously using integers.
=
Casting .et!een t#"es
Mixing types can cause problems. -or example:
int a4 D;
int 04 ?;
float c;
c4 0$(a#0);
printf (-? $ (D#?) 4 =f/n-) c);
doesnFt behave as you might expect. Hecause the first (a#0)is performed with integer arithmetic it
gets the answer 5 not 5.>. Therefore the program prints:
? $ (D#?) 4 ?.000
The best way round this is what is (nown as a cast. "e can cast a variable of one type to another type
li(e so:
int a4 D;
int 04 ?;
float c;
c4 0$ ( (float)a # 0);
the /float)a construct tells the compiler to switch the type of variable of a to be a float. N0 was
automatically cast to float to match a0. This isnFt often useful but can sometimes get you out of
trouble. The main use of casting is when you have written a routine which ta(es a variable of one type
and you want to call it with a variable of another type. -or example say we have written a power
function with a prototype li(e so:
int po( (int n) int m); #$rotot!pe for sEuare root function $#
#$(hich calculates nFm $#
"e might well have a float that we want to find an approximate power of. Jour compiler should
complain bitterly about you writing:
float n4 6.0;
int sEuared;
sEuared4 po( (n)?); #$ Ghe compiler (ill not li"e this 0ecause it
e2pects n to 0e of t!pe int not float$#
!owever& in this case& we want to tell the compiler that we do (now what weFre doing and have good
reason for passing it a float when it expects an int /whatever that reason might be0. Dgain& a cast
can rescue us:
float n4 6.0;
int sEuared;
sEuared4 po( ((int)n)?); #$ We cast the float do(n to an int$#
I0+ORTANT RULE: To move a variable from one type to another then we use a cast which has the
form (variable_type)variable_name.
CAUTION: It can be a problem when we downcast % that is cast to a type which has less precision
than the type we are casting from. -or example& if we cast a double to a float we will lose some bits of
precision. If we cast an int to a char it is li(ely to overflow Nrecall that a char is basically an int
which fits into > binary bitsO.
>
Functons
Dn important concept in $ is the idea of the function. D function is an effective sub4unit of a program.
"e have already encountered one function without explicitly calling it that: printf. $ allows you to
write your own functions /indeed& if you are to write anything but the simplest programs it reEuires you
to do so0. main itself is a function. ,etFs ta(e an example. "e might want to have a function which
returns the largest of two integers. !ereFs how you would write it:
int ma2imum (int a) int 0)
#$ Heturn the lar'est inte'er $#
{
if (a > 0) return a;
return 0;
}
This function ta(es two arguments both of which are integers. It returns the value of the largest
integer. /If the two values are the same& it will return the value of the second % which doesnFt matter
because the two values are the same0. Iote that return is being used here in the same way as
return was used from main but returning from main exits the program whereas returning from a
function returns control to wherever the function was called from.
I0+ORTANT2RULE3 -unction names follow the same rule as variable names. ,etters& numbers&
underscores and donFt start with a number. ItFs also a wise idea not to call your function the same as a
library function % using lower case letters is conventional.
"e can use this from main or from another function as follows:
#include <stdio.h>
int ma2imum (int) int); #$ rotot!pe 8 see later in lecture $#
int main(int ar'c) char $ar'*+,)
{
int i4 6;
int :4 >;
int ";
"4 ma2imum (i):); #$ &all ma2imum function $#
printf (-=d is the lar'est from =d and =d/n-)")i):);
printf (-=d is the lar'est from =d and =d/n-)ma2imum(D)>)) D) >);
return 0;
}
int ma2imum (int a) int 0)
#$ Heturn the lar'est inte'er $#
{
if (a > 0) return a;
return 0;
}
Iote that in the printf function& we used the result from a function ma2imum(D)>) as a function
argument. "e can use a function inside another function to build up a more complex function as
follows:
?
int ma23of3three (int i5) int i?) int iD)
#$ returns the ma2imum of three inte'ers $#
{
return (ma2imum (ma2imum(i5) i?)) iD));
}
This example ta(es a bit more thin(ing about. "eFre using our previously defined function ma2imum
in Euite a sophisticated way. 3erhaps it would help if we thin( of the example using some actual
values. If we called the function ma23of3three with the values /5&=&>0 using the line
ma23of3three(6) @) A); then we would set the local variables i5& i? and iD to the values
5&= and >. The complicated loo(ing statement first calls ma2imum(i5)i?) where i. is 5 and i1 is =
which& as we would expect returns =. The line then calls ma2imum a second time with = and iD
which is > which is what the function returns. Therefore it has correctly found the maximum of 5&= and
>. +'& so thatFs not exactly roc(et science& but it gives you an idea of how functions can build upon
each other.
"e could have made the above bit of code loo( a bit clearer by writing:
int ma23of3three (int i5) int i?) int iD)
#$ returns the ma2imum of three inte'ers $#
{
int d;
d4 ma2imum (i5) i?);
d4 ma2imum (d) iD);
return d;
}
Iot only is this second version a bit clearer& it is li(ely to be just as fast using a modern optimising
compiler. /Many people ma(e the mista(e of assuming that more semi4colons means a slower
program. It isnFt necessarily so.0
vod *unctons
Iote that a function doesnFt have to ta(e any arguments or return any. To indicate this we declare the
function as *oid. "e might for example want to write a function which simply prints hello:
*oid print3hello (*oid)
#$ this function prints hello $#
{
printf (-Hello/n-);
}
or we might want a function which prints odd or even depending on the argument we send it
*oid odd3or3e*en (int num)
#$ this function prints odd or e*en appropriatel! $#
{
if ((num = ?) 44 0) {
printf (-I*en/n-);
return;
}
printf (-7dd/n-);
}
Returnn' *ro( *unctons $the return state(ent%
Iote here that we use return to jump bac( out of the function early without getting to the end. Iote
that it is an error to fall off the end of a function which is supposed to return something.
.@
int function3returnin'3int (*oid)
#$ Ghis is an error $#
{
printf (-J am not 'oin' to return an int/n-);
}
Dnd it is also an error to try and return a value from a function which is supposed to return *oid.
*oid print3i3*alue (int i)
#$ Ghis is also an error$#
{
printf (-i is eEual to =d/n-) i);
return i;
}
I0+ORTANT RULE3 D function can only return one value. /D *oid function doesnFt return any
values0.
Heginners often see this rule as a fundamental problem with $. "hat if I want to return T"+
values* "e shall see later that this rule is not as limiting as it seems and when it is a problem& there
are ways round it.
I0+ORTANT RULE: D function does not change the values of its arguments.
-or example if we define a function to return the sEuare of a number:
int sEuared (int i)
#$ KEuares i $#
{
i4 i$i;
return i;
}
then we can test it with this code:
#include <stdio.h>
int main()
{
int i4 ?;
printf (-i sEuared is =d/n-)sEuared(i));
printf (-i is =d/n-)i);
return 0;
}
which will print:
i sEuared is 6
i is ?
it will I+T print:
i sEuared is 6
i is 6
The reason for this is that functions only have a local copy of the values sent to them. In $ this is
(nown as pass by value. )ariables passed by value to a function
..
"e shall be returning to the concept of functions a lot since they are one of the most important
concepts in the $ language. -or now& simply remember that& using a function you can create an
addition to the $ language which ta(es a number of arguments and may return a single value.
+rotot#"es o* *unctons
+ne important thing about functions is that they should be prototyped. Prototyping involves telling the
compiler in advance about the function that you write later. !ere are function prototypes from some of
the functions above:
int ma2imum (int)int); #$ rotot!pe for ma2imum function a0o*e$#
int ma23of3three (int)int)int); #$ Heturn lar'est of D ints $#
int function3returnin'3int (*oid); #$ Heturns an int $#
*oid print3i3*alue (int); #$ rints the *alue of the inte'er $#
+bviously the comments are optional but function prototypes are an excellent place to add comments
to your code. Since the function prototypes are all together in the same place& it is a convenient place
for someone browsing your code to loo( for what the functions actually do. Jou might li(e to repeat
the comments later when you actually come to write the functions themselves.
I0+ORTANT RULE3 #very function that you write /apart from main0 should have a prototype and
the prototype should occur before the first time the function is used and before the function is defined.
The correct place for a prototype is after any #include statements but before you start any other
functions. NDctually& the strictly correct place to put function prototypes is in a header file of their own
we will tell you how to do this later % for now put them after the #include statements but before
main and the other functions.O Shrewd students might well be as(ing "hy doesnFt printf need a
prototype*. It does. The prototype for printf /along with lots of other things0 was what you were
including in your program when you #include d that mysterious stdio.h file.
It doesnFt matter which order you actually put the functions in the code. Some people li(e to have
main as the first function in a file % which ma(es some sense since it is the first one which runs. It
doesnFt matter to the compiler which order you have them in though.
Local vara.les- 4lo.al Vara.les and Sco"e
In $& variables are local to the function in which they are declared. That is to say if we have a function:
float circumference (dou0le r)
#$ Heturn the circumference of a circle 'i*en its radius$#
{
dou0le pi4 D.56;
return (?$pi$r);
}
the value of pi cannot be used in a subseEuent function for example:
float dou0le(float r)
#$ Heturn area of circle 'i*en radius $#
{
dou0le (pi$r$r); #$ pi is not defined here althou'h it (as
defined earlier$#
}
would be an error since pi was defined in circumference locally % it is undefined in area. ,i(e
many rules of $ that seem Euir(y to the beginner& there is a very good reason for this. Imagine it were
not the case. "e might& if we were inclined& write a routine to print n asteris(s.
.1
*oid print3stars (int n)
{
int i;
for (i4 0; i < n; i99)
printf (-$-);
printf (-/n-);
}
If we want to write a routine to print 6 lines of 6 stars we should expect that the following will wor(:
int i;
for (i4 0; i < >; i99)
print3stars (>);
Dnd& indeed& this does wor( as we would expect and prints 6 rows of 6 stars. !owever& if the variable i
were I+T local in scope then by the time the first row of stars had been printed& i would be set to 7
and the loop would exit after printing only one row of stars. This would be startling for the
programmer and this is the reason why $ variables are normally local in scope.
If you do want to use global variables /and sometimes you do0 then it can be done. Simply put the
variable declaration outside function bodies in your program and the variable will be global and will be
usable by any function below the point where it is defined. Iormally you will want global variables to
be visible in the entire program and therefore they are normally positioned after the #includes but
before the first function and the main function.
I0+ORTANT RULE: D variable which is declared outside a function is global and it is usable in any
function below the point where you declared it. It is good practice if you are going to use globals to
put them at the top of the code /but see the next note0.
CAUTION: Lsing global variables is extremely bad style. They have their purpose& of course& but
they can be extremely confusing and cause more problems than they are worth. Lse #RTA#M#,J
sparingly.
De.u''n'
D good techniEue for debugging code is to thin( of yourself in place of the computer. Bo through all
the loops in the program and as( what is in each variable* #ach time you go through a loop as( is
the condition met and should I continue The factorial program shows how to do this. $an you see
the bug*
#include <stdio.h>
int main(int ar'c) char$ar'*+,)
{
int num0er4 6;
int ans(er;
int count;

ans(er4 5;
count4 num0er;
(hile (count >4 0) {
ans(er4 ans(er$ count;
countBB;
}
printf (-=d. 4 =d/n-)
num0er)ans(er);
return 0;
}
.2
num0er4 6
ans(er4 5
count4 6
enter (hile loop
ans(er4 5$646
count4D
enter (hile loop
ans(er46$D4 5?
count4?
enter (hile loop
ans(er45?$?4 ?6
count4 5
enter (hile loop
ans(er4 ?6$54 ?6
count4 0
enter (hile loop
ans(er4 ?6$04 0
<H< 8 J see...
CODE T)OU4)TS ABOUT CODE
!ere are some other debugging techniEues:
.. $hec( missing brac(ets and commas.
1. $hec( that you have a semicolon at the end of every line which needs one.
2. 3ut in some printfs% if you (now what your program is C+IIB you will (now what it is
C+IIB "A+IB.
5. Try to explain to someone else what the program is meant to do.
6. Ta(e a brea(& get a cup of coffee and come bac( to it fresh. /Cebugging is -ALSTADTIIB0.
Su((ar# o* Lan'ua'e ele(ents learned n !or5sheet and lecture one
+ne of the most confusing things to a new $ programmer is the syntax of the language. "hen do you
need to put a semi4colon on the end of the line* "hen do you need a { or a } to indicate a bloc( of
code* "hen do you use 4 and when do you use 44* "hat goes in which order* "hen do I begin a
statement with a # and when donFt I*
"hile we will try our very best to answer these Euestions& there is no substitute for experience. The
best way to learn programming is to get out there and practice it. If you canFt wor( out how to say
something in $ then try to find some code that says something similar. N+f course& just because
someone out there does something a certain way does not necessarily mean that is the best way to do
it.O
The complete syntax of $ is listed in a mildly confusing way in 'PA pages .?.4122 and in a really&
really confusing way it is summarised on pages 1254 12?. Io $ programmer ever learned how to write
$ by reading and memorising these rules. ,etFs instead summarise some of the rules we have learned
so far:
$omments begin with #$ and end with $# and can contain anything /well& anything except for a $#0.
,ines beginning with # are pre4processor directives. #include adds in a header file to your code.
3re4processor directives do not have semi4colons at the end.
#very function should have a prototype which comes before the function /preferably at the top of the
code just after the #includes % later weFll show you how to use header files which is the proper
place for prototypes0. #xample function prototypes are:
int add3three3ints (int) int) int);
*oid print3a3char (char);
D function starts with the type of the function followed by its name then the arguments with their types
and names % and no se(colon.
int add3three3ints (int i5) int i?) int iD)
*oid print3a3char (char c)
#very $ program has a main function which returns an int. "e can declare it li(e so:
int main(int ar'c) char $ar'*+,)
D function body starts with a { and ends with a }.
The first thing in the function should be declarations of variables /which can also be initialised at this
point0 for example:
.5
int mil") 0rilliant; #$ Leclares mil" and 0rilliant as inte'ers $#
float pi4 D.56; #$ Leclares a float pi and sets it to D.56 $#
dou0le 0i'3num4 DeM; #$ Ni'3num 4 D)000)000)000$#
char c4 ;c;; #$ Leclares a char and sets it to ;c; $#
int same3as3c4 c; #$ Leclares an int and sets it to the *alue of
the char c $#
)ariables declared outside functions are global and are available for use in any function below where
they are declared. Blobal variables are bad style and should be avoided.
There are various mathematical assignment operations: 9&B&$&#)= and shorthands 99) BB) 94)
$4) B4) #4
(hile (condition){
commands;
}

repeats the commands inside the braces until condition is false. /If condition starts false then while
never does anything % this can be useful sometimes0. If we miss out the braces& then the (hile loop
only repeats the one next command % for example:
i: .S
(hile (i < C)
printf (-=d/n-)i99);
is the same as:
(hile (i < C) {
printf (-=d/n-)i99);
T
both would print numbers from . to 6. NIf weFd used 99i it would have printed the numbers from 1 to
7O
D for loop has three parts separated by semicolons an initialiser& a condition and an counter increment.
/Iote that any one of these three parts can be omitted0. D for loop sets the initialiser and then repeats
the commands within the loop until the condition is false % the count initialiser is performed once at the
end of each loop. -or example:
for (i4 5; (i < C); i99){
printf (-=d/n-)i);
}
"ill also count from . to 6.
if (condition) {
commands;
} else {
other commands;
}
will perform commands once if condition is true and other commands once if condition is false. Ds
with for and (hile& if the braces are omitted then only the next single statement part of the if
statement.
$onditions for (hile& for and if are > >4 < <4 44 and .4.
.4 means not eEual to 4 . means not and can negate any expression for example .(a 44 D) is the
same as (a .4 D)
.6
@ means false and non Mero means true. /So if(>) is always true and if(0) is never true0. D true
expression evaluates to . so:
a4 (D < 6);
will set a to be eEual to ..
OO within a condition means +A& PP means DIC and . means I+T.
-inally return; returns from a *oid function and return variable name; returns from a function
returning a variable of type variable name.
E6a("le code usn' lan'ua'e ele(ents *ro( !or5sheet and lecture one
8; 3rogram does very simple arithmetic for numbers U 6@.
Dnswers are printed as stars.
Might be useful for showing children maths ;8
Kinclude stdafx.h
Kinclude Ustdio.hV
void printQnumber/int0S
8; 3rints int stars in a bloc( ;8
void printQstars /int0S
8; 3rints a row of stars ;8
int main/int argc& char; argvNO0
W
int no.: 5>S 8; Two input numbers and an answer ;8
int no1: =S
int answerS
int sumQtype: 5S 8; . means add 1 means subtract
2 means multiply and 5 means divide ;8
char opQsignS 8; Sign of this operation ;8
int remainderS 8; Aemainder 44 if we are doing division ;8
8; $hec( our inputs are in range ;8
if /no. U: @ XX no. V: 6@0 W
printf /The first number is not in the range . 4 5?0S
return 4.S
T
if /no1 U: @ XX no1 V: 6@0 W
printf /The second number is not in the range . 4 5?0S
return 4.S
T
8; $hec( for divide by Mero ;8
if /sumQtype :: 5 PP no1 :: @0 W
printf /$annot divide by MeroYn0S
return 4.S
T
8; $alculate the answer ;8
if /sumQtype :: .0 W
answer: no. 9 no1S
opQsign:F9FS
T else if /sumQtype :: 10 W
answer: no. 4 no1S
opQsign:F4FS
T else if /sumQtype :: 20 W
.7
-unction prototypes go
here at the start
answer: no. ; no1S
opQsign:F;FS
T else if /sumQtype :: 50 W
answer: no. 8 no1S
opQsign:F8FS
remainder: no. < no1S
T else W
printf /Ln(nown sum type <dYn& sumQtype0S
T
if /answer U: @ XX answer V: 6@0 W
printf /The answer is not in the range . 4 5?0S
return 4.S
T
printQnumber/no.0S
printf / <cYn& opQsign0S
printQnumber/no10S
printf / :Yn0S
printQnumber/answer0S
if /sumQtype :: 5 PP remainder V @0 W
printf / remainderYn0S
printQnumber/remainder0S
T
return @S
T
void printQnumber/int inpQnumber0
8; 3rint inpQnumber stars as bloc(s of ten ;8
W
8; "hile there are more than ten stars to print then print a full row ;8
while /inpQnumber V .@0 W
printQstars/.@0S
inpQnumber4: .@S
T
printQstars/inpQnumber0S
T
void printQstars/int stars0
8; 3rint FstarsF many stars ;8
W
int iS
for /i: @S i U starsS i990 W
printf /;0S
T
printf /Yn0S
T
.=
!ere are the functions themselves

You might also like