Title: Introduction to C Lecture 1: Overview
1Introduction to CLecture 1 Overview
2My Web Site
- www.sussex.ac.uk/physics/teaching/pgh/C
- Links to
- Lecture notes (.pdf, .doc)
- Handouts
- Powerpoint slides
- Software (scp etc)
- Course documents
- Previous students comments on the course
3Computers and C
- A computer is a machine that stores information
and performs mathematical calculations on that
information at speeds much faster than human
beings can think. - A program, which is stored in the computer's
memory, tells the computer what sequence of
calculations are required and which information
to perform the calculations on. - The major components of a computer are the
central processing unit (CPU), main memory,
secondary memory, and input and output devices. - The CPU performs the control and calculation
functions of the computer. - Main memory is fast, relatively expensive memory
that stores the program being executed and its
associated data. Main memory is volatile, meaning
that its contents are lost whenever power is
turned off. - Secondary memory is slower and less expensive
than main memory. It is nonvolatile. Hard disks
are popular secondary memory devices. - Input and output devices are used to read data
into the computer and to output data from the
computer. The most common input device is a
keyboard, and the most common output devices are
screens and printers.
4Computers and C, contd
- Computer memories are composed of millions of
individual switches, each of which can be either
ON or OFF, but not at a state in between. These
individual switches are binary devices called
bits. - Eight bits are grouped together to form a byte of
memory, and 2 or more bytes (depending on the
computer) are grouped together to form a word of
memory. - Computer memories can be used to store
character, integer, or real data. - Each character in most character data sets
occupies 1 byte of memory. The 256 possible
values in the byte allow for 256 possible
character codes. (Characters in the Unicode
character set occupy 2 bytes, allowing for 65,536
possible character codes.) - Integer values occupy 1, 2, 4, or 8 bytes of
memory, and they store integer quantities. - Real values store numbers in a kind of scientific
notation. They usually occupy 4 bytes of memory.
The bits are divided into a separate mantissa and
exponent. The precision of the number depends on
the number of bits in the mantissa, and the range
of the number depends on the number of bits in
the exponent. - The earliest computers were programmed in machine
language. This process was slow, cumbersome, and
error prone. - High-level languages began to appear in about
1954, and they quickly replaced machine-language
coding for most uses. For example, FORTRAN was
one of the first high-level languages created. C
was developed in the 1970s, by Kernighan and
Ritchie at Bell Labs.
5C
- C is
- a small, terse language, with few
keywords - extremely powerful
- a native language of Unix standard
development language (now alongside C) for PC
software. - highly portable
- modular
- very efficient on most machines
- the basis of C and Java
- There is very little error checking etc
it assumes that you know what you are doing, and
it gives you the power to do what you ask.
Freedom brings responsibility! -
- This course aims to teach good programming
practices using the ANSI C version of the
language this is now an almost universal
standard. -
6Operating System
- The PCs here run Windows from this platform, we
will use ExCeed to run X-session to a computer in
my lab, upon which you each have an account. -
- To access the computer, you will have to use SSH
(Secure SHell), which (unlike telnet) encrypts
your password before sending it over the network.
This is good practice you should not be using
telnet at all. -
- Note If you want to run SSH from your PC at
home, you can download the relevant software
from, e.g., www.ssh.com there is a link to
http//www.openssh.com/windows.html, from where
you can find PuTTY (needed to log on and work at
a terminal) and WinSCP (used for transferring
files). I can help you further with this. Please
do not telnet on to one machine (e.g. the central
sussex server) and then SSH to my machine it
potentially exposes all of your work, and that of
your classmates, to any hackers who are listening
in. We were attacked in 2002 dont let it
happen again through your carelessness. -
- Be aware also that while youre logged on, people
will be watching what youre doing. Please dont
try to poke around where you shouldnt, or to run
any programs that we wouldnt approve of. -
- Note Unix is case-sensitive, as is C.
-
7Unix and Emacs
- Suggested editor emacs. This is
straightforward a good tutorial exists to help
you use it efficiently. The most essential
command to know ctrl-X ctrl-C to exit. Emacs is
sensitive to indentation etc. in C sourcecode. - Useful Unix commands
- cd change directory use cd .. to go
up one level cd to go to your home
directory - ls -a -l list (i.e., list all
files in directory) -
option -a shows hidden files (those beginning
with .) -
option -l (lowercase L, not number 1) shows all
file details. - man manual i.e., help.
- rm remove, i.e. delete file.
- mkdir, rmdir make, remove directories.
- cp copy (use cp
r to copy entire directory structures) - exit to finish the session and log out.
- mv input filename output filename or
directory to move (rename) a file. This is
useful to rename your executable programs from
a.out. - Unix command to compile C code
- cc -lm input files -o output file
name - (The -lm option loads the maths libraries, to
make, e.g., sin, cos, sqrt etc available). If
you omit the -o output file name the output
file will be called a.out.
8Exercise
- ssh in to my lab computer its name is
- lepton.maps.susx.ac.uk.
- Change to directory lect1 the rest of this
weeks exercises should be done there.
9Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
-
-
- Now compile the program (to make a file
called a.out), change the name to sea (command
mv a.out sea), and run it (by typing a.out).
10Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
-
-
include preprocessor command causes the
contents of the file stdio.h to be inserted at
this point in the code, before the compiler
processes the file. The file stdio.h is a header
file (hence .h) with information about the
standard input-output (hence stdio) routines for
this operating system. This will tell the program
how to write the output onto the screen. The
angle brackets ltgt around the filename indicate
that it is to be found in the usual place,
wherever that may be. In general, the character
means do this before you start compiling the
program.
11Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
-
-
int main(void) Every program has a
function called main(), and program execution
starts here. The function main() will itself
call secondary functions, which will call more
functions of their own... For those with some
knowledge already The keyword int tells the
compiler that when you call this function, it
brings back a value of type integer. The
parentheses () following main tell the compiler
that main() is a function. The keyword void
tells the compiler that this function takes no
arguments. (Counter example the function cos
takes a real argument the angle and returns a
real value the cosine).
12Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
-
-
Braces surround the body of a function
definition, and are also used to group statements
together. A group of statements within braces is
a compound statement, and needs no semicolon
afterwards.
13Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
printf() is one of a number of standard
functions this particular one prints output to
the screen.
14Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
-
-
She sells ... \n is a string, or series of
characters, surrounded by double quotes. The \n
at the end is a single character called newline,
which moves the cursor on the screen to the start
of the next line.
15Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
Statements in C generally C end with a
semicolon other separation characters (carriage
return, tab, more than one space etc.) are
ignored (except as parts of a string).
16Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
return 0 This causes the value 0 (or whatever
the function has calculated) to be returned to
whatever called it. Example If this function
were cos instead of main, the return wouldnt
be zero it would be the cosine of the angle.
17Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
Finally, note how the sourcecode is indented,
which makes it much more readable.
18Our First Program
- Use an editor to open a file called sea.c
(e.g. by typing emacs sea.c), and write into it
the following lines -
- include ltstdio.hgt
-
- int main (void)
-
- printf(She sells C shells on the sea
shore.\n) - return 0
-
- Exercise What happens if you leave out the \n,
or put extra ones in? Can you print out some
more lines of text?
19Simple i/o, and define An example
relativity.c
- include ltstdio.hgt /---------------
Header files ----------------- / - include ltmath.hgt
- define C 299792458
- /---- Now the main program --------------- /
- int main (void)
-
- double speed, beta, gamma
- int light_speed C / speed of light in
m/s / -
- printf("\ns", "Input a speed in m/s ")
- scanf("lf", speed)
- if (speed gt light_speed)
- / Notice how the lines are indented inside
this if construct / - printf(\nOops! Thats faster than light! Try
again...) - exit(1)
-
- beta speed/light_speed
- gamma 1/sqrt(1-betabeta)
- printf("The speed of light is 9d
m/s.\n",light_speed)
20Simple i/o, and define
- include ltstdio.hgt /---------------
Header files ----------------- / - include ltmath.hgt
- define C 299792458
- /---- Now the main program --------------- /
- int main (void)
-
- double speed, beta, gamma
- int light_speed C / speed of light in
m/s / -
- printf("\ns", "Input a speed in m/s ")
- scanf("lf", speed)
- if (speed gt light_speed)
- / Notice how the lines are indented inside
this if construct / - printf(\nOops! Thats faster than light! Try
again...) - exit(1)
-
- beta speed/light_speed
- gamma 1/sqrt(1-betabeta)
- printf("The speed of light is 9d
m/s.\n",light_speed)
Compile the code using the command cc lm o
relativity relativity.c which tells the compiler
to call the output file relativity instead of
a.out. The additional lm tells it to include
maths library code, needed for the square root.
Run the code to see what it does.
21Simple i/o, and define
- include ltstdio.hgt /---------------
Header files ----------------- / - include ltmath.hgt
- define C 299792458
- /---- Now the main program --------------- /
- int main (void)
-
- double speed, beta, gamma
- int light_speed C / speed of light in
m/s / -
- printf("\ns", "Input a speed in m/s ")
- scanf("lf", speed)
- if (speed gt light_speed)
- / Notice how the lines are indented inside
this if construct / - printf(\nOops! Thats faster than light! Try
again...) - exit(1)
-
- beta speed/light_speed
- gamma 1/sqrt(1-betabeta)
- printf("The speed of light is 9d
m/s.\n",light_speed)
Note that the program is split into chunks by
comments /----------------------------/
Anything between / and / is ignored by the
compiler its only there to make things easier
to read.
22Simple i/o, and define
- include ltstdio.hgt /---------------
Header files ----------------- / - include ltmath.hgt
- define C 299792458
- /---- Now the main program --------------- /
- int main (void)
-
- double speed, beta, gamma
- int light_speed C / speed of light in
m/s / -
- printf("\ns", "Input a speed in m/s ")
- scanf("lf", speed)
- if (speed gt light_speed)
- / Notice how the lines are indented inside
this if construct / - printf(\nOops! Thats faster than light! Try
again...) - exit(1)
-
- beta speed/light_speed
- gamma 1/sqrt(1-betabeta)
- printf("The speed of light is 9d
m/s.\n",light_speed)
define C 299792458 is a so-called
preprocessor directive it causes all occurrences
of C to be replaced by 299792458 in the rest of
the file, before any compilation. In this case,
its only used once the constant light_speed is
used through most of the code for readability.
By convention, capital letters are used for
identifiers defined by preprocessing in this way.
The use of symbolic constants makes the code
more readable, and easier to change later if
necessary.
23Simple i/o, and define
- include ltstdio.hgt /---------------
Header files ----------------- / - include ltmath.hgt
- define C 299792458
- /---- Now the main program --------------- /
- int main (void)
-
- double speed, beta, gamma
- int light_speed C / speed of light in
m/s / -
- printf("\ns", "Input a speed in m/s ")
- scanf("lf", speed)
- if (speed gt light_speed)
- / Notice how the lines are indented inside
this if construct / - printf(\nOops! Thats faster than light! Try
again...) - exit(1)
-
- beta speed/light_speed
- gamma 1/sqrt(1-betabeta)
- printf("The speed of light is 9d
m/s.\n",light_speed)
We are here using double for our variables,
which is a double-precision floating-point
number. The computer can deal with other types
of variables for example, char variables are of
type character, int is an integer, and float is a
floating-point (i.e. real) number. (This is
like double, but not as precise). All of these
are stored as numbers in the computers memory.
24Simple i/o, and define
- include ltstdio.hgt /---------------
Header files ----------------- / - include ltmath.hgt
- define C 299792458
- /---- Now the main program --------------- /
- int main (void)
-
- double speed, beta, gamma
- int light_speed C / speed of light in
m/s / -
- printf("\ns", "Input a speed in m/s ")
- scanf("lf", speed)
- if (speed gt light_speed)
- / Notice how the lines are indented inside
this if construct / - printf(\nOops! Thats faster than light! Try
again...) - exit(1)
-
- beta speed/light_speed
- gamma 1/sqrt(1-betabeta)
- printf("The speed of light is 9d
m/s.\n",light_speed)
Just as printf() is used for output, so
scanf() is used for input. The arguments of both
printf() and scanf() are control_string and
other_arguments, where control_string may contain
format specifications for the other arguments to
follow. For example, 3d specifies that a
decimal number is to follow, for which 3
characters should be allocated. Other examples
are s for string f for float lf for long
float, i.e. double and e for a number in
exponential format. You can specify the output
in a more detailed way 12.3f says write out as
a floating point number, using a total of 12
spaces, with 3 numbers after the decimal
point. Notice the in scanf - its
essential.
25Control Flow
- While programs generally step sequentially from
line to line, it is often necessary to modify
this behaviour. In particular, if and if-else
provide alternative actions depending upon some
condition and calculations may be repeated many
times in a while or for loop. An example of if
was shown in the previous exercise. -
- Logical expressions are either true (represented
by any non-zero value) or false. -
- Comparison is often done by the is equal to
operator, represented by -
- Beware this is not at all the same as , which
assigns the value on the right to the variable on
the left! - eg. x 5 assigns the value
5 to x - (x 5) asks the question Is x
equal to five?
26Control Flow
-
- Consider the code
-
- if (cnt 0)
- a 2
- b 3
- c 5
-
- else
- a -1
- b -2
- c -3
-
- printf(d, abc)
-
- This causes 10 to be printed if cnt has the value
0, and -6 to be printed otherwise.
27Control Flow
-
- Consider the code
-
- if (cnt 0)
- a 2
- b 3
- c 5
-
- else
- a -1
- b -2
- c -3
-
- printf(d, abc)
-
- This causes 10 to be printed if cnt has the value
0, and -6 to be printed otherwise.
Note the braces that group several statements
together into one. Note the indenting of
such groups of statements.
28Control flow While loops
- The following program, consecutive_sums.c,
illustrates the use of a while loop -
- include ltstdio.hgt
-
- int main (void)
-
- int i , sum
- i 1
- sum 0
- while (i lt 5)
- sum sum i
- i i 1
-
- printf(sum d\n, sum)
- return 0
-
lt means less than or equals
29Control flow While loops
- The following program, consecutive_sums.c,
illustrates the use of a while loop -
- include ltstdio.hgt
-
- int main (void)
-
- int i , sum
- i 1
- sum 0
- while (i lt 5)
- sum sum i
- i i 1
-
- printf(sum d\n, sum)
- return 0
-
lt means less than or equals
What value is printed at the end?
30Control flow For loops
- Another loop is the for loop. It has the form
- for (expr.1 expr. 2 expr. 3)
- statement
-
- If all three expressions are present, it is
equivalent to - expr 1
- while (expr 2)
- statement
- expr 3
-
31Control flow For loops
- Another loop is the for loop. It has the form
- for (expr.1 expr. 2 expr. 3)
- statement
-
- If all three expressions are present, it is
equivalent to - expr 1
- while (expr 2)
- statement
- expr 3
-
This happens before the loop starts
32Control flow For loops
- Another loop is the for loop. It has the form
- for (expr.1 expr. 2 expr. 3)
- statement
-
- If all three expressions are present, it is
equivalent to - expr 1
- while (expr 2)
- statement
- expr 3
-
The loop keeps going as long as this expression
is true (i.e. not zero)
33Control flow For loops
- Another loop is the for loop. It has the form
- for (expr.1 expr. 2 expr. 3)
- statement
-
- If all three expressions are present, it is
equivalent to - expr 1
- while (expr 2)
- statement
- expr 3
-
This is the last thing that happens before the
loop repeats
34Exercise
- Rewrite the consecutive sums program using for
instead of while. - include ltstdio.hgt
-
- int main (void)
-
- int i , sum
- i 1
- sum 0
- while (i lt 5)
- sum sum i
- i i 1
-
- printf(sum d\n, sum)
- return 0
-
Reminder for (expr.1 expr. 2 expr.
3) statement is equivalent to expr 1 while
(expr 2) statement expr 3
35Shortcuts
- C contains a number of little shortcuts to make
your code more compact. Two examples - sum i This is a compact way of
writing sum sum i. This same style may be
applied to other operators. - i (or i) is a compact way of writing
i i 1. and - - are known as the
increment and decrement operators respectively. - The for loop above could therefore be written
- for (i 1, sum 0 i lt 5 i)
- sum i
- or, even more compactly,
- for (i 1, sum 0 i lt 5 sum i, i)
36Input/output formats
- Lets look more closely at the statement
- scanf("f",x)
- The part between quotes f determines the
format of the expected input it says read in a
floating-point variable. Likewise, d
specifies that a decimal integer is expected.
Other formats are available e is exponential
format (i.e. it includes a power of 10), x is
hexadecimal, and s is a string. -
- Within each of these formats, we can specify the
exact length - 10.6f
- specifies that ten characters in total are to be
allocated to this number (although more can be
used if the number is too big), and that six of
those characters will come after the decimal
point. The ten characters include, for example,
a minus sign if there is one, and the decimal
point itself. -10.6f specifies that the number
should be left-justified within the allocated ten
spaces. Full details are provided in books and
the handouts.
37Debugging
- If you make a mistake of syntax in your code
(e.g. leaving out a semicolon), the compiler will
always tell you the first line where it sees a
problem often the line after the problem
actually occurred. Dont be discouraged by a
long stream of error messages fix the first
one, and the others often disappear. - Phew! OK, lets do some exercises...