Вы находитесь на странице: 1из 32

Class Objectives

The objectives of this class are as follows:


Teach you how to read C programs
Teach you how to write C programs
Teach you how to debug C programs
Teach you how to design good C programs
How to Succeed in this Class
Attend class
"90 percent of life is just showing up." --Woody Allen
Eams are hea!ily "ased on material presented in class
Never miss more than one consecutive week of classes
#f you just have to ta$e that two wee$ !acation% plan it so that
you only miss one wee$ of classes -- really&
'issing e!en one class will se!erely limit your a"ility to $eep
up% particularly wrt the eams
ead ahead
!o the homework
(tudents with a pre!ious programming )e.g. *ascal or C++,
"ac$ground should plan on spending "#$% hours per wee$
(tudents with a no programming background "ut computer
literate $%#&% hours per wee$
(tudents with a no programming background and no computer
experience &%#'% hours per wee$...you will "e spending a lot of
Introduction to Programming in C
time struggling with the tools as well as learning how to
program
The "est plan of action is to do a little "it of the la" assignment
wor$ each day% particularly if you ha!e a home computer
The worst plan of action is to do e!erything the night "efore the
homewor$ is due
Ask (uestions
1-2
Introduction to Programming in C
How to )ail in this Class
*iss two consecutive weeks of class sessions
Tr+ to survive without access to a C com,iler
-ou learn C "y doing% i.e.% you must write C programs% compile
them% and run them
Never s,end an+ time on this outside of class
!o not attem,t an+ of the homework
Habituall+ show u, late for class or habituall+ leave earl+
The bottom line is that you will get out of this class
what you put into it!!!
To succeed% you need to spend at least . to /0 hours per wee$
on your own
1-3
Introduction to Programming in C
Overview of a Com,uter # Hardware
eference: -rooks. Cha,ter $/ 01. Cha,ter $
Central *rocessing 0nit )C*0, controls the flow of instructions and data and performs
the necessary manipulation of data
*rimary storage )memory, is used to store information for immediate access "y the
C*0
1ote that there are many le!els of cache used in primary storage
(econdary storage de!ices )e.g.% the hard dri!e% C2-34' dri!es% tapes% etc., pro!ide
permanent storage of large amounts of data% "ut are much slower than primary storage
#nput and 4utput de!ices pro!ided interfaces "etween the computer and the user
1-4
Secondary
Storage
Primary
Storage
Control
Unit
Arithmetic
Logic Unit
Central Processing
Unit
(CPU)
Input
Devices
Output
Devices
Introduction to Programming in C
Overview of a Com,uter # !ata e,resentation
The first computers used !acuum tu"es to hold data
5acuum tu"es ha!e two states - 41 and 466
An 41 state represents a /
An 466 state represents a 0
Eight !acuum tu"es strung together can represent an 7 digit string of 0s and /s
*ut another way% this string is an 7 digit "inary )"ase 8, num"er
We use decimal )"ase /0, num"ers in our daily life
A decimal num"er is a string of digits whose !alues are drawn from the set
90%/%8%:%;%.%<%=%7%9>
#n general% a num"er system is simply a way of representing num"ers
A num"er system has a "ase )the num"er of digits used in the num"er system,
Consider a num"er in a "ase b num"er system?
The !alue of this num"er is?
A binar+ num"er has a "ase of 8 where the !alid digits are 0 or /
E.g.% /00/ "inary @@ 9 decimal )/A7 + 0A; + 0A8 + /,
An octal num"er has a "ase of 7 where the !alid digits are 0 through =
E.g.% 0:/ octal @@ 8. decimal ):A7 + /,
A decimal num"er has a "ase of /0 where the !alid digits are 0 through 9
E.g.% 8000 decimal @@ 8000 )-8B "ug C-,,
A he2adecimal num"er has a "ase of /< where the !alid digits are 0 through 6% i.e.
90%/%8%:%;%.%<%=%7%9%A%D%C%2%E%6>
E.g.% ADDA he @@ ;:9<8 decimal )/0A;09< + //A8.< + //A/< + /0,
1-5
0 / /
a a a a
n n

0
0
/
/
/
/
b a b a b a b a
n
n
n
n
+ + + +


Introduction to Programming in C
Overview of a Com,uter # !ata e,resentation 3&4
1owers of &
&5%
1
&5$$
2048 2K
&5$
2
&5$&
4096 4K
&5&
4
&5$'
8192 8K
&5'
8
&5$6
16,384 16K
&56
16
&5$"
32,768 32K
&5"
32
&5$7
65,536 64K
&57
64
&5$8
131,072 128K
&58
128
&5$9
263,144 256K
&59
256
&5$:
524,288 512K
&5:
512
&5&%
1,048,576 1M
&5$%
1024 1K
&5&$
2,097,152 2M
1 KILO = 2^10 = 1024
1 MEG = 2^20 = 1024*1024 = 1,048,576
1 GIGA = 2^30 = 1024*1024*1024 = 1,073,741,824
To e!aluate a "inary num"er% say /0//0/% simply add up the corresponding powers of
8?
1-6
0 / 8 : ; .
8 / 8 0 8 / 8 / 8 0 8 / /0//0/ + + + + + =
;. / 0 ; 7 0 :8 = + + + + + =
Introduction to Programming in C
Overview of a Com,uter # He2adecimal Numbers
A headecimal num"er is a string of headecimal digits
2igits A% D% C% 2% E% 6 represent the num"ers /0% //% /8% /:% /;% and /.
Eeadecimal is popular in the computer field "ecause it can "e used to concisely
represent a long string of "inary digits
Consider a /< digit "inary num"er?
1011000111000101
Drea$ this up into groups of ;?
1011 0001 1100 0101
Con!ert each group of ; into decimal?
11 1 12 3
Then con!ert each decimal num"er into he?
B1C3
And you now ha!e the num"er? Baker 1 Charlie 3
Able = A = 10 = 1010
Baker = B = 11 = 1011
Charlie = C = 12 = 1100
Dog = D = 13 = 1101
Eas = E = 14 = 1110
!o" = ! = 15 = 1111
Dy the same to$en% the EEF num"er ')&C$":7 represents the "inary string?
0011 1111 0010 1110 0001 0101 1001 0110
1-7
Introduction to Programming in C
Overview of a Com,uter # 1rimar+ Storage
*rimary storage% also $nown as main memor+ or 3A' )random access memory, is
used to store information for immediate access "y the Central *rocessing 0nit )C*0,
'emory can "e !iewed as a series of memor+ cells with each cell ha!ing its own
indi!idual address
E.g.% thin$ of a "an$ of mail"oes at a post office
The information contained in a memory cell is called the contents of that cell
'emory cells can "e used to store data% such as characters or numbers
#nternally% of course% they are all num"ers% "ut we can choose to interpret some
num"ers as characters
They can also "e used to store ,rogram instructions
These are GspecialH num"ers that are meaningful to a C*0&
The smallest unit of computer storage is a bit% as in binary digit
'ost computers group "its together to form larger entities
E.g.% 9 consecuti!e "its often form a b+te and '& consecuti!e "its often form a
word
A word on an #ntel 87< computer is /< "its or 8 "ytes
A word on an #ntel :7<% ;7<% and *entium computers is :8 "its or ; "ytes
The net generation of #ntel computers )e.g. the 'erced, will use <; "it words% i.e.
7 "ytes
The 2EC Alpha computer is currently using <; "it words
'any mainframe computers% such as the 0nisys A-(eries% use ;7 "it words
'emory cells in a computer are typically one b+te or one word in siIe
A word is a unit of information that can "e transferred to and from memory
A kilob+te of memory% as in /B% is /08; "ytes of memory
A megab+te of memory% as in /'% is /08;B of memory% or 8J80 "ytes
A gigab+te of memory% as in /K% is /08;' of memory% or 8J:0 "ytes
1ote that a :8 "it word can represent 8J:8 different possi"le !alues
1-8
Introduction to Programming in C
1rogramming ;anguages # ;ow ;evel ;anguages
Computers only do what they are told to do
Ecept in Eollywood mo!ies% e.g.% 800/% Terminator 8% the 'atri% etc. C-,
#n order for a computer to perform a tas$% it must "e gi!en a series of specific
instructions in a language it can understand
The fundamental language of any computer is its machine language
This is typically seLuences of Ieroes and ones
#n the very early days of computers% this was the only way one could write
programs&&&
To relie!e the suffering of these early programmers% a higher le!el language called
assembly language was de!eloped
Assem"ly language contains mnemonic words and sym"ols for the "inary machine
instructions
An assembler maps assem"ly language instructions into machine language
instructions
Assem"ly language programming is indeed a significant impro!ement o!er machine
language programming
Eowe!er% it has the following draw"ac$s?
'achine dependent - each computer architecture has its own uniLue assem"ly
language
Mow le!el instructions - writing programs is !ery time consuming% tedious% and
error-prone
1-9
Introduction to Programming in C
1rogramming ;anguages # High ;evel ;anguages
A general trend in computing o!er the past ; decades is to ele!ate programming from
low le!el to higher le!el languages
#.e.% high le!el languages are geared more toward people writing the programs
rather than the computer
Assem"ly language instructions map directly to machine instructions
Eigh le!el language instructions must "e translated/compiled into machine
instructions
Eigh le!el languages are more Gpro"lem-orientedH than assem"lyNmachine languages
E.g% they reLuire little or no $nowledge of the underlying computer architecture
Mearning how to writeNde"ug programs in high le!el languages is much easier and less
error-prone than learning how to writeNde"ug eLui!alent programs in assem"ler
E.g.% high le!el languages reLuired fewer statements to do the same thing as
assem"ler
*rograms written in high le!el languages can "e ported much more easily to different
computer architectures
E.g.% the compiler encapsulates the machine-dependent details of the target
assem"ly language
A special program called a compiler is needed to translate a program written in a high
le!el language into assem"ly code )which is then transformed into nati!e machine
code "y an assembler,
The statement written in the high le!el language are called source code
The compilerNassem"lerOs output is called object code
1-1
!ource
Code
Com"iler #$%ect
Code

&ssem$le
r
Introduction to Programming in C
;anguage Ta2onom+
FORTRAN
FORTRAN IV
FORTRAN77
COBOL
PL/1
ALGOL
BRROG!"
E#TEN$E$
ALGOL
ALGOL68
COBOL85
APL
LI"P
"MALLTALK
PROLOG
PA"CAL
MO$LA%2
A$A
A""EMBLER
B,BCPL
C
AN"I C
C&&
E
1-11
Introduction to Programming in C
Histor+ of C<=<=
/9=0O(
Early /970Os
Mate /970Os
C
T3A2#T#41AM C
A1(# C
P43 (TA12A32 CQ
American
1ational
(tandards
#nstitute
F:R// Committee
Add !oid type
enumeration
other impro!ements
Add !oid A
function prototypes
new function definition synta
minimum standard li"rary
more functionality to preprocessor
Add const and !olatile
struct as parameter
1-12
Introduction to Programming in C
Significant 1oints About C
(mall num"er of $eywords
Widely a!aila"le% particularly on personal computers and wor$stations
Can "e used !ery porta"ly
(tandard li"rary
*reprocessor may "e used to isolate machine dependent code
0nli$e *ascal% which has many dialects
1ati!e language of 01#F )tm, and Windows 1T
Terse
*owerful set of operators
(tatements can "e !ery powerful
(ome are bit le!el operators
2esigned to "e implemented efficiently on many machines
'odular -- functions
*arameters are typically passed S"y !alueT
1o nested functions
(ynta is complicated
(emantics of certain features are comple and error-prone
1-13
Introduction to Programming in C
A Com,arison of 1rogramming ;anguage 1hiloso,h+
1ascal
(trict *arent )a G"ondage and disciplineH language C-,,
3estricts programmer for hisNher own good
A white% automatic transmission automo"ile with lots of safety features )e.g.% air "ags%
controls that limit speed to .. miles per hour and prohi"it lea!ing the lights on or
loc$ing the $eys in the car,
C
A permissi!e% easy going parent )a UlassiIe-faireT language C-,,
Assumes that the programmer $nows what heNshe is doing and will assume
responsi"ility for hisNher actions. )(ome descri"e it as a Ggun with which you can
shoot yourself in the foot.H,
A "right red T<. Cor!ette with a "ig "loc$ engine% manual transmission% optional seat
"elt% and with fuIIy dice hanging from the rear !iew mirror.
C<<
A less permissi!e% yet open minded parent )e.g.% UThomas Euta"leT C-,,
Assumes that the programmer generally $nows what heNshe is doing% "ut pro!ides
more chec$ing "y default. )GWith C++ itTs harder to shoot yourself in the foot% "ut
when you do% youTll "low off "oth of your legsH V Djarne (troustrup,
A "right red 8000 Cor!ette with a < speed manual transmission% air "ag% and heads
up display% many on "oard computers
1-14
Introduction to Programming in C
>2am,le C 1rogram
#$
!ile% hello&'
Des'ri()io*% +ri*)s a gree)i*g )o s),o-)&
A-)hor% Do-glas C& .'h/i,) 0s'h/i,)1-'i&e,-2
$#
3i*'l-,e 0s),io&h2
i*) /ai* 45oi,6 #$ e"e'-)io* s)ar)s i* /ai* $#
7
(ri*)8 49:ello ;orl,&<*96=
re)-r* 0=
>
All C programs must ha!e a function in it called main
Eecution starts in function main
C is case sensitive?
Comments start with /* and end with */. Comments may span o!er many lines.
C is a Gfree formatH language.
The 3i*'l-,e 0s),io&h2 statement instructs the C compiler to insert the entire
contents of file '()*+,- in its place and compile the resulting file.
1-15
Introduction to Programming in C
Com,iling a C 1rogram
4n a personal computer using 5isual (tudio% you will create a .c file% e.g. hello.c )as in
the pre!ious eample,. -ou will then compile it to produce a .ee file )e.g.% hello.ee,
and perhaps a .o"j file )hello.o"j,. Consult your compiler documentation )each one is
different,.
1-16
Introduction to Programming in C
#n 5isual (tudio% do a 6ileW1ew and you will see the following dialog...
1-17
Introduction to Programming in C
Eere% you must first select @in'& Console A,,lication. Then press the ... "utton that
appears to the right of the Mocation
1-18
Introduction to Programming in C
1ow choose the location. -ou may need to create a folder on your file system. #n this
case% # "rought up the Windows 1T eplorer and created the new folder Ece//-s97.
Whate!er you do% you should place the project in a place such that you can easily find
it later.
1-19
Introduction to Programming in C
1ow that you ha!e specified a Mocation% i.e. a folder where you want your project
created% you should see the following...
1-2
Introduction to Programming in C
1ow% specify the name of your project. 5isual (tudio will create a folder underneath
the one you specified for Mocation "y that name. This will also "ecome the name of
your eecuta"le... 6inally% clic$ on the O0 "utton to record your selection.
#t is !ery important that you do each of these initial steps in the eact order that # ha!e
descri"ed a"o!e. That is% first specify that you want a Console Application% then
specify the location% then specify the project name. !o not forget an+ of these ste,sA
#n other words% pay attention&&&
1-21
Introduction to Programming in C
As a result% you will see the following in 5isual (tudio
1otice that the Wor$space window now has three ta"s. #t has a ClassBiew ta"% a
)ileBiew ta"% and an CnfoBiew ta". (elect )point the mouse to, the )ileBiew ta".
1-22
Introduction to Programming in C
After selecting the 6ile5iew ta"% you should see the following. 1otice what appears
in the Wor$space window...
1-23
Introduction to Programming in C
1ow we need to create a source file and include it in the project. #f we do the correct
seLuence of steps% 5isual (tudio will automatically include the new file into the
project.
2o a )ileDNew and select Te2t )ile and then specify a 6ile name. 2o not accept the
default choice% Active Server 1age )or whate!er happens to "e the default,. 2o not
select CNC++ Eeader 6ile. 2o not select C++ (ource 6ile. (elect Tet 6ile. 2o not
forget to type in the file name% i.e. hello.c )or whate!er you wish to call it,% but it
must end with Ac &&& The file suffi tells 5isual (tudio what t+,e of file this is so it
$nows which com,iler to invoke on itA 6inally% clic$ O0 to select your choice.
1-24
Introduction to Programming in C
As a result of your efforts% you should see the following.
1-25
Introduction to Programming in C
# usually mo!e the windows around at this point% adjusting the siIes.
Type in the program.
1-26
Introduction to Programming in C
#f you clic$ on the + "y Eello files under Wor$space% you will see a list of all of the
files in your project
Duild your program "y selecting the -uildD-uild menu option
1-27
Introduction to Programming in C
3un it )Duild W Eecute,
1ow letOs loo$ at the files?
!.//+,)'0? this is your W43B(*ACE
!.//+,)'1? this is the project "uild file
These two files% along with -.//+,2 are worth sa!ing.
1-28
Introduction to Programming in C
The program we just "uilt is EEMM4.EFE under the 2e"ug directory
Decause it is a C41(4ME application% we can run it directly from our Windows 1T
command )or Windows 9. 2os, prompt.
When # typed hello "elow at the 2os prompt% Windows ran the program helloAe2e.
Delow you can see the results of this run.
1-29
Introduction to Programming in C
Com,iling Ender ENCF
To compile a C program under 01#F% one may do it in the following ways?
3 22 -.//+,2
This compiles the file and creates an eecuta"le named aAout
3 22 -.//+,2 %+ -.//+
This compiles the file "ut renames the eecuta"le hello
3 22 %2 -.//+,2
This compiles the file "ut does not link it% thus producing an object module which may "e
lin$ed later on. That file% "y default% is helloAo
3 22 -.//+,+ %+ -.//+
This lin$s the o"ject file helloAo to create the eecuta"le hello
0nder 01#F% suffies are important )i.e.% .c !ersus .o,. They tell the compiler what type
of file they are% i.e. a C program file !ersus an o"ject module.
3 22 4++,+ 567,+ %+ 48567
This lin$s two separately compiled modules into an eecuta"le named fubarA
1-3
Introduction to Programming in C
The com,iling ,rocess ## overview
C P7+976: %% 4++,2
3 22 %2 4++,2
211 %% C 17.17+2.''+7
!6;)/.' <%)*7.2(*=.'> 7.:+=.' 2+::.;('
4++,E
C O1(*:*?.7
@+1(*+;6/A
22+: %% C C+:1*/.7
2+:1*/. 17+976:
4++,'
4++,+
6' %% 6''.:5/.7
1-31
Introduction to Programming in C
Com,iling ,rocess ## translation ,hases 3ANSC4
/. *hysical source file characters are mapped to the source character set )including new-
line characters and end-of-file indicators, if necessary. Trigraph sequences are
replaced "y corresponding single-character internal representations.
8. Each instance of a new-line character and an immediately preceding "ac$slash
character )B, is deleted% splicing physical source lines to form logical source lines.
:. The source file is decomposed into preprocessing to$ens and seLuences of white-
space characters )including comments,. A source file shall not end in a partial
preprocessing to$en or comment. Each comment is replaced "y one space character.
1ew-line characters are retained.
;. *reprocessing directi!es are eecuted and macro in!ocations are epanded. A
<*;2/8). preprocessing directi!e causes the named header or source file to "e
processed from phase / through phase ; recursively.
.. Each source character set mem"er and escape seLuence in character constants and
string literals is con!erted to a mem"er of the eecution character set.
<. Adjacent character string literal to$ens are concatenated and adjacent wide string
literal to$ens are concatenated.
=. White-space characters separating to$ens are no longer significant. Each
preprocessing to$en is con!erted into a to$en. The resulting to$ens are syntactically
and semantically analyIed and translated.
7. All eternal o"ject and function references are resol!ed. Mi"rary components are
lin$ed to satisfy eternal references to functions and o"jects not defined in the current
translation. All such translation output is collected into a program image which
contains information needed for eecution in its eecution en!ironment.

1-32

Вам также может понравиться