through C++
Abhiram Ranade
Do not distribute
Prefa e . . . 12
1 Introdu tion 15 1.1 A simpleprogram . . . 16
1.1.1 Exe uting the program . . . 17
1.2 Remarks . . . 18
1.2.1 Exe ution order . . . 18
1.3 Repeatinga blo k of ommands . . . 19
1.3.1 Drawingany regularpolygon . . . 19
1.3.2 Repeat within arepeat . . . 21
1.4 Some useful turtle ommands . . . 21
1.5 Numeri alfun tions. . . 22
1.6 Con ludingRemarks . . . 23
1.7 Overview of the book . . . 24
1.7.1 A note regarding the exer ises . . . 25
1.8 Exer ises . . . 25
2 A bird's eye view 27 2.1 Representing real life entities using numbers . . . 28
2.2 Representing numbers ona omputer . . . 29
2.2.1 Bits, Bytes, Words . . . 30
2.2.2 Storingnatural numbers . . . 30
2.2.3 Storingintegers . . . 30
2.2.4 Storingreal numbers . . . 31
2.2.5 Storingtext . . . 32
2.2.6 Remarks . . . 32
2.3 Organizationof a omputer . . . 33
2.4 Memory . . . 33
2.4.1 Registers. . . 34
2.5 Arithmeti Logi Unit . . . 34
2.6 Input-OutputDevi es. . . 35
2.7 The Control Unit . . . 36
2.7.1 ControlFlow . . . 37
2.7.2 Some tri ky instru tions . . . 39
2.8 Highlevel programminglanguages . . . 41
2.10 A simpliedsimulator . . . 42
2.11 Con ludingRemarks . . . 43
2.12 Exer ises . . . 43
3 Numbers 45 3.1 Variables and data types . . . 45
3.1.1 Remarks onTable 3.1 . . . 47
3.1.2 Types har and bool . . . 47
3.1.3 Identiers . . . 48
3.1.4 Initializingvariables . . . 48
3.1.5 onst keyword . . . 49
3.1.6 Reading dataintoa variable . . . 50
3.1.7 Printing . . . 51
3.1.8 Exa t representational parameters. . . 51
3.2 Arithmeti and assignment . . . 52
3.2.1 Modulo operator: % . . . 53
3.2.2 Subtleties . . . 53
3.2.3 Over ow . . . 55
3.2.4 Expli it type onversion . . . 55
3.2.5 Assignment expression . . . 55
3.3 Examples . . . 56
3.4 Assignmentwith repeat . . . 57
3.4.1 ProgrammingIdioms . . . 58
3.4.2 Combiningsequen e generation and a umulation . . . 60
3.5 Some operatorsinspired by the idioms . . . 61
3.5.1 In rement and de rement operators . . . 61
3.5.2 Compound assignment operators . . . 62
3.6 Comments . . . 62
3.7 Invariants . . . 63
3.8 Blo ks and variable denitions . . . 65
3.8.1 Blo k. . . 66 3.8.2 Generalprin iple 1 . . . 66 3.8.3 Generalprin iple 2 . . . 67 3.9 Con ludingremarks . . . 68 3.10 Exer ises . . . 69 4 Simple pp graphi s 72 4.1 initCanvas and loseCanvas . . . 72
4.2 Multiple Turtles . . . 73
4.3 Other shapes besides turtles . . . 73
4.3.1 Cir les . . . 74
4.3.2 Re tangles . . . 74
4.3.3 Lines . . . 74
4.3.4 Text . . . 74
4.4.1 Resettinga shape . . . 76
4.5 Cli kingonthe anvas . . . 76
4.6 Proje tile Motion . . . 76
4.7 Best tstraight line. . . 77
4.8 Con ludingRemarks . . . 78
4.9 Exer ises . . . 79
5 Conditional Exe ution 81 5.1 The If statement . . . 81
5.2 Blo ks . . . 84
5.3 Other formsof the if statement . . . 84
5.4 A dierent turtle ontroller. . . 87
5.4.1 \Buttons" onthe anvas . . . 88
5.5 The swit h statement . . . 89
5.6 ConditionalExpressions . . . 91
5.7 Logi alData . . . 92
5.7.1 Reasoning about logi al data . . . 93
5.7.2 Determiningwhether a number is prime . . . 94
5.8 Remarks . . . 95
5.9 Exer ises . . . 96
6 Loops 100 6.1 The while statement . . . 100
6.1.1 Counting the number of digits . . . 102
6.1.2 Determiningif a number isprime . . . 103
6.2 Developingloopbased programs . . . 104
6.2.1 Virahanka numbers . . . 104
6.2.2 Mark averaging . . . 107
6.3 The break statement . . . 109
6.4 The ontinue statement . . . 110
6.5 The do while statement . . . 111
6.6 The forstatement . . . 112
6.6.1 Variablesdened ininitialization . . . 114
6.6.2 Break and ontinue . . . 114
6.6.3 Style issue . . . 114
6.6.4 Primality . . . 115
6.6.5 Natural logby numeri alintegration . . . 115
6.7 Un ommon ways of using for . . . 116
6.7.1 Commaseparated assignments. . . 117
6.7.2 Input in initialization and update . . . 117
6.8 Remarks . . . 118
7 Computing ommon mathemati al fun tions 121
7.1 Taylor series . . . 121
7.1.1 Sine of anangle . . . 123
7.1.2 Natural log . . . 123
7.1.3 Some generalremarks . . . 124
7.2 Bise tion method fornding roots . . . 124
7.3 Newton RaphsonMethod . . . 126
7.4 GreatestCommon Divisor . . . 128
7.5 Summary . . . 130
7.5.1 Mathemati al ideas . . . 131
7.5.2 Programmingideas . . . 131
8 Testing and Debugging 133 8.1 Clarity of spe i ation . . . 133
8.1.1 Input and output examples . . . 135
8.2 Hand exe ute the program . . . 135
8.3 Assertions . . . 135
8.4 Testing . . . 136
8.4.1 Automated testing: input/outputredire tion . . . 137
8.4.2 File I/O . . . 137
8.4.3 End of leand readingerrors . . . 139
8.4.4 Input-Output expressions . . . 139
8.4.5 Assert with le reading . . . 140
8.5 Debugging . . . 140
8.6 Randomnumbers . . . 141
8.6.1 randuv ommand in simple pp . . . 142
8.7 Con ludingremarks . . . 142
8.8 Exer ises . . . 142
9 Fun tions 144 9.1 Dening afun tion . . . 144
9.1.1 Exe ution: all by value . . . 146
9.1.2 Names of parameters and lo alvariables . . . 147
9.2 Nested fun tion alls: LCM . . . 148
9.3 The ontra t viewof fun tion exe ution. . . 149
9.3.1 Fun tionspe i ation. . . 149
9.4 Fun tions that do not returnvalues . . . 151
9.5 A textdrawing program . . . 151
9.6 The main programis afun tion! . . . 153
9.7 Organizingfun tions into les . . . 153
9.7.1 Fun tionDe laration . . . 154
9.7.2 Separate ompilation and obje t modules . . . 154
9.7.3 Header les . . . 156
9.7.4 Pa kaging software . . . 157
9.8 Fun tionsize and readability. . . 157
9.9 Con ludingremarks . . . 158
10 Re ursive Fun tions 159 10.1 Eu lid'salgorithmfor GCD . . . 160
10.1.1 Exe ution of re ursive g d . . . 161
10.1.2 Interpretation of re ursiveprograms . . . 161
10.1.3 Corre tness of re ursive programs . . . 162
10.2 Re ursive pi tures . . . 163
10.2.1 Trees without using aturtle . . . 165
10.2.2 Hilbert spa e lling urve . . . 166
10.3 Virahanka numbers . . . 167
10.3.1 Usinga loop . . . 169
10.3.2 Histori al Remarks . . . 169
10.4 The game of Nim . . . 170
10.4.1 Remarks . . . 172 10.5 Con ludingremarks . . . 172 11 More on Fun tions 175 11.1 Some diÆ ulties . . . 175 11.2 Callby referen e . . . 176 11.2.1 Remarks . . . 178 11.2.2 Referen e variables . . . 178 11.3 Pointers . . . 179
11.3.1 \Address of" operator & . . . 179
11.3.2 Pointer variables . . . 179 11.3.3 Dereferen ingoperator* . . . 180 11.3.4 Use infun tions . . . 181 11.3.5 Referen e vs. Pointers . . . 183 11.4 Fun tionPointers . . . 183 11.4.1 Some simpli ations . . . 185
11.5 Defaultvalues of parameters . . . 185
11.6 Fun tionoverloading . . . 186
11.7 Fun tiontemplates . . . 187
11.8 Exer ises . . . 188
12 Arrays 189 12.1 Array: Colle tion of variables . . . 189
12.1.1 Array element operations. . . 190
12.1.2 A eptable range for the index . . . 191
12.1.3 Initializingarrays . . . 191
12.2 Examples . . . 192
12.2.1 Notation forsubarrays . . . 192
12.2.2 A marks display program. . . 192
12.2.5 Histogram . . . 195
12.2.6 A taxidispat hprogram . . . 196
12.2.7 A geometri problem . . . 200
12.3 The inside story . . . 201
12.3.1 Out of range array indi es . . . 203
12.3.2 The array name by itself . . . 203
12.3.3 [℄ as anoperator . . . 204
12.4 Fun tionCalls involvingarrays . . . 204
12.4.1 Examples . . . 206 12.4.2 Summary . . . 207 12.5 Sortingan array . . . 207 12.6 Binary sear h . . . 209 12.6.1 Time required . . . 211 12.7 Representing Polynomials . . . 211
12.8 Array Length and onst values . . . 213
12.8.1 Why onst de larations? . . . 214
12.8.2 What we use in this book . . . 214
12.9 Summary . . . 214 12.10Exer ises . . . 215 13 More on arrays 219 13.1 Chara ter strings . . . 219 13.1.1 Output. . . 220 13.1.2 Input . . . 220
13.1.3 Chara ter string onstant . . . 222
13.1.4 Examples . . . 222
13.2 Two dimensional Arrays . . . 224
13.2.1 Passing 2 dimensional arrays to fun tions. . . 226
13.2.2 Drawingpolygons insimple pp . . . 226
13.3 Arrays of Pointers . . . 227
13.3.1 Command lineargumentsto main . . . 228
13.4 A home-made2 dimensional array . . . 230
13.4.1 Matrixmultipli ationfun tion . . . 231
13.5 Linear simultaneous equations . . . 232
13.6 All sour eshortest paths . . . 234
13.6.1 Algorithm . . . 235
13.6.2 Exe ution example . . . 236
13.6.3 Explanationof the algorithm . . . 236
13.7 Generating permutations . . . 239
13.8 Exer ises . . . 241
14 Stru tures and Classes 244 14.1 Basi sof stru tures . . . 245
14.1.1 Visibility of stru ture typesand stru ture variables . . . 247
14.1.3 Pointers tostru tures . . . 248
14.1.4 Constant referen es . . . 249
14.1.5 Arrays of stru tures. . . 249
14.2 Representing 3dimensional ve tors . . . 250
14.2.1 Operator overloading . . . 251
14.2.2 Pass by value orby referen e . . . 252
14.2.3 Putting ittogether . . . 252
14.3 Stru tures: advan ed features . . . 253
14.3.1 Constru torfun tions. . . 254
14.3.2 Ordinary memberfun tions . . . 255
14.3.3 Overloadingoperators . . . 256
14.4 Additionalissues . . . 257
14.4.1 Callby referen e and onst de laration. . . 257
14.4.2 Default values toparameters . . . 257
14.4.3 Default Constru tor . . . 258
14.4.4 Constru tors ofnested stru tures . . . 258
14.4.5 Initializationlists . . . 259
14.4.6 Constant members . . . 260
14.4.7 Stati data members . . . 261
14.4.8 Stati memberfun tions . . . 261
14.4.9 The this pointer . . . 262
14.5 A queue data stru ture . . . 262
14.6 A ess Control . . . 264
14.6.1 A ess spe iers . . . 264
14.6.2 Friends . . . 265
14.7 Classes . . . 266
14.8 Header and implementationles . . . 266
14.8.1 Separate ompilation . . . 268
14.8.2 Remarks . . . 268
14.9 Template lasses . . . 269
14.10Graphi s . . . 269
14.11Exer ises . . . 269
15 A proje t: osmologi al simulation 271 15.1 Mathemati s of Cosmologi alsimulation . . . 271
15.2 Overview of the program . . . 274
15.2.1 MainProgram. . . 275
15.3 The lass Star . . . 277
15.4 Compilingand exe ution . . . 278
15.5 Con ludingRemarks . . . 279
16 Representing variable length entities 281
16.1 The Heap Memory . . . 281
16.1.1 A detailedexample . . . 283
16.1.2 Lifetimeand a essibility . . . 283
16.2 Representing text: a preliminaryimplementation . . . 284
16.2.1 The basi storage ideas . . . 285
16.2.2 Constru tor . . . 285
16.2.3 The print memberfun tion . . . 285
16.2.4 Assignments . . . 286
16.2.5 Dening operator + . . . 287
16.3 Advan ed topi s. . . 288
16.3.1 Destru tors . . . 288
16.3.2 Copy onstru tor . . . 288
16.3.3 An improved assignment operator . . . 289
16.3.4 Use . . . 290
16.4 Remarks . . . 290
16.4.1 Class invariants . . . 292
16.5 Exer ises . . . 292
17 Stru tural re ursion 295 17.1 Layout of mathemati alformulae . . . 296
17.1.1 Stru ture of mathemati alformulae . . . 297
17.1.2 Representing mathemati alformulae ina program . . . 297
17.1.3 Reading ina formula . . . 299
17.1.4 Drawingthe formulaonthe anvas . . . 300
17.1.5 Drawingthe pi ture . . . 304
17.1.6 The omplete main program . . . 305
17.1.7 Remarks . . . 305
17.2 Maintainingan ordered set . . . 306
17.2.1 A sear h tree . . . 306
17.2.2 The generalidea . . . 308
17.2.3 The implementation . . . 309
17.2.4 A note about organizing the program . . . 311
17.2.5 On the eÆ ien y of sear htrees . . . 311
17.2.6 Balan ing the sear h tree . . . 312
17.3 Exer ises . . . 312
18 The standard template library 316 18.1 The template lass ve tor . . . 317
18.1.1 Inserting and deletingelements . . . 318
18.1.2 Index bounds he king . . . 318
18.1.3 Fun tions on ve tors . . . 318
18.1.4 Multidimensionalve tors . . . 319
18.2 Sortinga ve tor . . . 320
18.2.2 Marks display variation2 . . . 320
18.2.3 Customized sorting . . . 321
18.2.4 Fun tionObje ts . . . 322
18.2.5 Use inthe sort fun tion . . . 322
18.3 The string lass . . . 322
18.3.1 Fun tions on strings. . . 324
18.4 The maptemplate lass . . . 324
18.4.1 Marks display variation3 . . . 326
18.4.2 Time toa ess a map. . . 327
18.5 Containers and Iterators . . . 327
18.5.1 Findingand deleting mapelements . . . 330
18.5.2 Inserting and deletingve tor elements . . . 330
18.6 Other ontainers inthe standard library . . . 331
18.7 Exer ises . . . 331
19 Inheritan e 334 19.1 Turtles with anodometer. . . 335
19.2 Another example . . . 336
19.3 Generalprin iples . . . 337
19.3.1 A ess rules and prote ted members . . . 338
19.3.2 Constru tors and destru tors . . . 339
19.3.3 Polymorphismand virtual fun tions . . . 340
19.3.4 Polymorphismand pointers . . . 341
19.4 Programto print past tense . . . 342
19.5 Abstra t Classes . . . 344
19.6 Multiple inheritan e . . . 345
19.6.1 Diamond Inheritan e . . . 346
19.7 Exer ises . . . 346
20 Inheritan e based design 349 20.1 Formuladrawing revisited . . . 350
20.1.1 Basi design . . . 350
20.1.2 Comparison ofthe two approa hes . . . 353
20.1.3 Adding exponentialexpressions . . . 354
20.2 The simple pp graphi ssystem . . . 355
20.3 Composite graphi s obje ts . . . 358
20.3.1 Ownership . . . 358
20.3.2 The Composite lass onstru tor . . . 359
20.3.3 A Car lass . . . 359
20.3.4 Frames . . . 361
20.3.5 Mainprogram . . . 361
21 Dis rete event simulation 363 21.1 Dis rete event simulation overview . . . 364
21.3.1 A Resour e lass . . . 370
21.3.2 The simulation . . . 371
21.4 Singlesour e shortest path . . . 373
21.4.1 Dijkstra's algorithmasa simulation . . . 374
22 Simulationof an airport 379 22.1 Airport onguration and operation . . . 380
22.1.1 Safeoperation rules . . . 381
22.1.2 S hedulingstrategy . . . 381
22.1.3 Simulatorinput and output . . . 382
22.2 Implementationoverview . . . 382
22.2.1 Mainprogramand main data stru ture . . . 383
22.3 The taxiway lass . . . 384
22.4 The plane lass . . . 386
22.4.1 The fun tion wakeup . . . 387
22.4.2 The fun tion enter . . . 391
22.4.3 The fun tion getGate . . . 391
22.5 Deadlo ks . . . 392
22.6 On Global variables vs. referen e variables . . . 393
23 Non-linear simultaneous equations 395 23.1 Newton-Raphson methodin many dimensions . . . 395
23.1.1 The general ase . . . 397
23.1.2 Termination . . . 398
23.1.3 Initialguess . . . 398
23.2 How ane kla e reposes . . . 398
23.2.1 Formulation . . . 398 23.2.2 Initialguess . . . 399 23.2.3 Experien e. . . 400 23.3 Remarks . . . 400 23.4 Exer ises . . . 400 A Installing Simple pp 401 B S ope and Global Variables 402 B.1 Blo ks . . . 402
B.2 S ope . . . 402
B.3 Creation and destru tion of variables . . . 404
B.4 Globalvariables . . . 404
C Managing Heap Memory 406 C.1 Referen e Counting . . . 408
C.2 The template lass shared ptr . . . 408
C.2.1 Syntheti example . . . 409
C.2.2 Generalstrategy . . . 410
C.2.4 Weak pointers . . . 413
C.2.5 Solutionidea . . . 413
C.3 Con ludingremarks . . . 414
D Libraries 415 D.0.1 Linkingbuilt-infun tions . . . 415
E IEEE oating point standard 417 F Reserved words in C++ 418 G Less frequently used operators 419 G.1 Bitwise Logi aloperators . . . 419
G.1.1 Or . . . 419 G.1.2 And . . . 419 G.1.3 Ex lusive or . . . 420 G.1.4 Complement . . . 420 G.1.5 Left shift. . . 420 G.1.6 Rightshift . . . 420 G.2 Commaoperator . . . 421
Prefa e
Learningto programis like learninga naturallanguagein many ways. A few stages an be
identied in the pro ess of language learning: (a) being able understand spoken or written
language,(b) being abletospeakorwritethelanguage, ( )write/speak formally,(d)ability
tounderstandthe literature ofthat language(e) write/speak reatively. Insome ways these
stages are present even in learningprogramminglanguages.
The rst stage of programming language a quisition is understanding the syntax and
semanti s of the language. Mastery of this basi ally enables the learner to simulate the
exe ution of anarbitrary program using pen and paper. It is not expe ted that the learner
infers the intent in any way; the learner merely knows what ee t the exe ution of ea h
statement has, and an thusstep through exe ution, keeping tra k of the programstate by
writing it down on paper if needed. This is by no means a trivial skill, espe ially given
the omplexity of languages su h as C++. But even if we onsider a simple subset of the
language (or onsider simpler languages), learly understanding ideas su h as ontrol ow,
storage allo ation,s operules, is a noteworthy a hievement for any learner.
The next stage, analogous to speaking a natural language, is one in whi h the learner
starts writing programs. Of ourse, the two stages are not temporally disjoint. Indeed,
when a learner speaks a language she is not only ommuni ating her thoughts, but also
putting up her omposition for riti ism. Through su h intera tion, her omprehension
skills are aÆrmed, in addition to expression skills. Likewise, someone learningC++ might
write a simple program having just a single for statement to see if her understanding of
the statement is orre t. Su hexperiments are extremely valuable forlanguage a quisition,
and they ome for free if you have a omputer. A learner must be en ouraged to try su h
experiments from day one of the learning pro ess.
Thereisof oursemoretoexpressing yourself inalanguage. Forprogramminglanguages,
theanalogoussituationisasfollows. SupposeyouhavelearnedtheNewton-Raphsonmethod
of nding roots in a ourse in Mathemati s. Can you write a program to nd the roots?
Whatisrequiredhereistheabilitytotranslatefromtheinformaldes riptionofanalgorithm
learned in the mathemati s lassroom into the onstru ts provided by the programming
language. Theinformallanguageusingwhi halgorithmsarelearnedinmathemati smaynot
mat hthe programminglanguage. This anbebe auseof avarietyof reasons. Forexample,
there is no equivalent of a programming language variable in traditional mathemati s. To
make matters worse, there exists a notion of a variable in mathemati s whi h is dierent
and hen e an ause onfusion. Another diÆ ulty is presented by looping onstru ts: the
standard onstru ts havealoopexittest atthe beginningorattheend, whereasthenatural
des ription of most pro esses require a loop exit somewhere in the middle. This an either
be handled using a break onstru t, or by hoisting some ode out of the loop (often the
more favoured style). These are some of the skills tobe learnt.
The thirdstage isanalogous toformal ommuni ationinnaturallanguages. This an be
metaphori ally onsideredtobeequivalenttothe abilitytoreasonformallyabout programs.
On the one hand this involves the ability to write down lear spe i ations (as opposed to
havinganintuitiveidea)oftheproblembeingsolved,andreasoningwiththesespe i ations.
On theother hand,thisleads tovariousparadigms ofprogramorganization,withparti ular
veri ation ofprograms. Given that formalveri ation isnot pra tised by professional
pro-grammers, it is debatable how mu h this should be stressed in an introdu tory ourse. We
feel, however, that even a beginnershould understand that in prin iple, programs must be
proved orre t, andthatthereexistte hniquesfordoingthis. Notionssu haspre onditions,
post onditions and invariants must be understood. It is felt that these ideas will
sub on-s iouslyguide thestudent intowritingbetterprograms, even if they arefound toolaborious
toimplementrigorouslyatthe presenttime. Astoprogrammingparadigms,ourapproa his
somewhat pragmati . Atevery pointin the book we have tended to hoose a programming
style whi h appears most appropriate for the job at hand, given the tools the student has.
From time to time we have given alternate ways of writing a program. However, there is a
progression towards obje t oriented programming. It has happened as a byprodu t of the
requirements,rather than be ause of the goalof followinga stylisti di tat.
The fourth stageisanalogous toreadinggoodliterature. What isthe pointoflearninga
new language if not toread something ex iting writtenin it? Forprogramming this means
a quiring some familiaritywith some lassi al algorithms. We have made a ons ious eort
in this book toa quaint the reader with interesting omputationalproblems in a variety of
areas,frommathemati sand physi als ien es tooperationsresear h. Of ourse,this barely
s rat hes theplethoraof elegant algorithmsthat ould beex iting forthe reader. Ourhope
is merely that it will reate a taste and ex itement in the reader to seek out omputations
and algorithms. We willhave served our purpose, for example, if this book auses readers
towant to learnmore about osmologi al simulation,oroptimizingairportlayouts, ordata
stru tures or error analysis innumeri al algorithms.
The nal stage, the ability to design new algorithms, is perhaps analogous to reative
writing in natural language. Algorithm design is a vast subje t, and there are huge tomes
written on it. But we feel that an introdu tion to programmingand problem solving must
ontain a des ription of the most primitive and yet perhaps the most powerful problem
solving idea: re ursion. We have attempted to give a somewhat detailed introdu tion to
re ursion using several examples. Re ursion is important not only as an algorithm design
tool, but also as a me hanism for expressing programs: several programs are more elegant
whenexpressed re ursively. Wehavealso onsideredmemoizationasa naturaloptimization
for re ursion, and so we ould have said to have tou hed upon the te hnique of dynami
programmingas well. The se ond theme inour presentation on erns the use of exhaustive
sear h. Exhaustive sear h an be expressed leanly using re ursion, and hen e it is a good
testinggroundto exer isere ursion. More importantly,we feelthat itreassures the student
of the power of omputer programs by expanding his vision of what an be solved using
omputers.
Most of the book, enough to learn basi s of C++, ismeant to be a essible to students
who have passed standard X. Some se tions are addressed more to s ien e and
engineer-ing students. However, I would like to mention that when I taught a ourse based on this
material several students ame up and said that the programming exer ises related to
ad-van edmathemati stopi s a tuallyhelpedthem understandthe mathemati stopi s better.
So even if you feel mathemati s is not your strong point, you may still want to read the
mathemati allyinvolved se tions of the bookwith an optimisti attitude.
I feel that a ourse in programming should ex ite the problem solver in you, and you
problems (more useful and often as diÆ ult!). If this book an en ourage you to view day
to day problems as omputation, and give you the onden e that you an write programs
Introdu tion
A omputeris oneof the most remarkable ma hines invented by man. Mostotherma hines
have a very narrow purpose. A wat h shows time, a amera takes pi tures, a tru k arries
goodsfromonepointtoanother,anele tronmi ros opeshowsmagniedviews ofverysmall
obje ts. Some of these ma hines are mu h larger than a omputer, and many mu h more
expensive, but a omputer is mu h, mu h more omplex and interesting inthe kind ofuses
it an be put to. Indeed, many of these ma hines, from a wat h to an ele tron mi ros ope
typi allymight ontaina omputerinsidethem,performingsomeofthemost vitalfun tions
of ea h ma hine. The goalof this book is to explain how a omputer an possibly be used
for somany purposes, and many more.
Viewed one way, a omputer is simply an ele tri al ir uit; a giant, omplex ele tri al
ir uit,but a ir uitnevertheless. Inprin iple, itispossible tomake omputers withoutthe
use of ele tri ity { indeed there have been designs of omputers based onusing me hani al
gears, or uidi s devi es. 1
But all that is mostly of histori al importan e. For pra ti al
purposes, today, itis ne toregard a omputer as anele tri al ir uit. Parts of this ir uit
are apable of re eiving data from the external world, remembering it so that it an be
reprodu edlater, pro essingit,and sendingthe results ba k tothe external world. Bydata
we ouldmeandierentthings. Forexample,it ouldmeansomenumbersyoutypefromthe
keyboard of a omputer. Or it ould mean ele tri al signals a omputer an re eive from a
sensorwhi hsensestemperature,pressure,lightintensityandsoon. Thewordpro essmight
mean something as simple as al ulating the average of the sequen e of numbers you type
from the keyboard. It ould also mean something mu h more omplex: e.g. determining
whether the signals re eived from a light sensor indi ate that there is some movement in
the vi inity of the sensor. Finally, by \send data to the external world" we might mean
something as simple as printing the al ulated average on the s reen of your omputer so
that you an read it. Orwe ould mean a tivating a beeper onne ted to your omputer if
the movement dete ted is deemed suspi ious. Exa tly whi h parts of the ir uit are a tive
atwhat time is de ided by aprogram fedto the omputer.
Itistheprogramwhi hdistinguishesa omputerfrommostotherma hines;byinstalling
dierentprogramsthe same omputer anbemadetobehaveindramati allydierentways.
How to develop these programs is the subje t of this book. In this hapter, we will begin
1
Also it is appropriate to think of our own brain as a omputer made out of biologi al material, i.e.
by seeing an example of a program. It turns out that we an understand, or even develop
(typi ally alled write) programs withoutknowing a lot about the spe i ir uits that the
omputer ontains. Thisisverysimilartohowonemightlearntodrivea ar; learlyone an
learntodrivewithoutknowinghowexa tlyanautomobileengineworks. Soyouwillbeable
tonot onlyunderstand the programthat weshow you, but yourself write some programs.
There are many languages using whi h programs an be written. The languagewe will
use in this book is the C++ programming language, invented in the early 1980s by Bjarne
Stroustrup. For the initial part of the book, we will not use the bare C++ language, but
instead augment itwith a pa kage alled simple pp (whi h stands for simple C++) whi h
we have developed. How to install this pa kage is explained in Appendix A. Wedeveloped
this pa kageso thatC++appears morefriendlyandmore funtopeoplewho are startingto
learnC++. Touse the drivingmetaphor again,it ouldbesaid that C++islikea omplex
ra ing ar. When you are learning to drive, it is better to start with a simpler vehi le, in
whi h there aren't too many onfusing ontrols. Also, standard C++ does not by default
ontain the ability todraw pi tures. The pa kage simple pp does ontain this feature. We
thusexpe t that by using thesimple pp pa kage itwillbeeasier andmore funtolearn the
language. But in a few hapters, you will outgrow simple pp and be able to use standard
C++ (like \the pros"), unlessof ourse youare using the graphi sfeatures.
1.1 A simple program
Our rst example programis given below.
#in lude <simple pp> main_program{ turtleSim(); forward(100); left(90); forward(100); left(90); forward(100); left(90); forward(100); wait(5); loseTurtleSim(); }
If youexe ute this programonyour omputer,itwillrst open a window. Then asmall
triangle whi h we all a turtle 2
will appear in the window. Then the turtle will move and
drawlines asitmoves. Theturtle willdrawa squareand thenstop. After that,the window
willvanish,and the programwillend. Shortlywe willdes ribehowtoexe utethe program.
2
First we willtell you why the program does all that it does, and this will help you modify
the programto make itdo something else if youwish.
The rstline#in lude <simple pp> de laresthat theprogrammakesuseofsome
fa il-ities alled simple pp inadditionto what is provided by the C++ programminglanguage.
The next line, main programf, says that what follows is the main program. 3
The main
programitself is ontained inthe bra esf g followingthe text main program.
The line following that, turtleSim() auses a window with a triangle at its enter to
be opened on the s reen. The triangle represents our turtle, and the s reen the ground on
whi h it an move. Initially, the turtlepoints inthe East dire tion. The turtle is equipped
withapen,whi h an eitherberaisedorlowered totou hthe ground. Ifthepen islowered,
then it draws on the groundas the turtle moves. Initially, the pen of the turtle is lowered,
and it isready todraw.
The next line forward(100) auses the turtle to move forward by the amount given
in the parentheses, (). The amount is to be given in pixels. As you might perhaps know,
your s reen is really an array of small dots, ea h of whi h an be of any olour. Typi al
s reens haveanarrayofabout10001000dots. Ea hdotis alledapixel. Sothe ommand
forward(100) ausesthe turtletogoforward inthe urrentdire tionitispointingby about
a tenth of the s reen size. Sin e the pen was down, this auses aline tobe drawn.
The ommand left(90) auses the turtle to turn left by 90 degrees. Other numbers
ould alsobespe ied insteadof 90. Afterthis, the next ommand isforward(100), whi h
ausestheturtletomoveforwardby100pixels. Sin etheturtleisfa ingnorththistime,the
lineis drawn northward. This ompletes the se ondside of the square. The next left(90)
ommand ausestheturtle toturnagain. Thefollowingforward(100) drawsthe thirdside.
Then the turtle turns on e more be ause of the third left(90) ommand, and the fourth
forward(100) nallydraws the fourth side and ompletes the square.
After this the linewait(5) auses the programto donothing for 5 se onds. This is the
time youhave toadmire the work of the turtle!
Finallythelastline loseTurtleSim() ausesthewindowtoberemovedfromthes reen.
After exe utingthis line, the programhalts.
Perhapsyouarepuzzledbythe()followingthe ommandsturtleSimand loseTurtleSim.
Theexplanationissimple. A ommandinC++willtypi allyrequireadditionalinformation
to doits work, e.g. for the forward ommand, youneed to spe ify a number denoting how
far to move. It just so happens that turtleSim and loseTurtleSim do not require any
additionalinformation. Hen e weneed tosimplywrite(). Lateryouwillsee thatthere an
be ommands whi h will need more than one pie es of information, in this ase we simply
put the pie es inside () separated by ommas.
1.1.1 Exe uting the program
Toexe ute thisprogram, wemust rst haveit inaleonyour omputer. Itis ustomaryto
use thesuÆx . ppforles ontainingC++ programs. Soletussuppose youhavetyped the
program into a le alled square. pp { you an also get the le fromthe CD or the book
webpage.
3
Next, we must ompile the le, i.e. translate it into a form whi h the omputer
under-stands more dire tly and an exe ute. The translation is done by the ommand s++ whi h
got installedwhen youinstalledthe pa kage simple pp. The ommand s++ merely invokes
the GNU C++ ompiler, whi h must be present on your omputer (See Se tion A). In a
UNIXshellyou an ompilealebytypings++followed bythenameofthe le. Inthis ase
youwouldtypes++ square. pp. Asaresultofthis anotherleisprodu ed,whi h ontains
the programinaformthat isready toexe ute. On UNIX,this leistypi ally alleda.out.
This le an be exe uted by typing its nameto the shell
% a.out
Youmayberequiredtotype./a.out be ause ofsome quirksof UNIX.Oryoumaybeable
to exe ute by double li king its i on. When the programis thus exe uted, you should see
a window ome up, with the turtle whi h then draws the square.
1.2 Remarks
A C++ program is similar in many ways to a paragraph written in English. A paragraph
onsistsofsenten esseparatedbyfullstops;aC++program ontains ommandswhi hmust
be separated by semi- olons. Note that while most human beings will tolerate writing in
whi hafull-stopismissed,a omputerisveryfastidious,ea h ommandmustbefollowedby
asemi- olon. Notehowever, thatthe omputerismoreforgivingaboutthe useofspa esand
linebreaks. Itisa eptabletoputinspa esandlinebreaksalmostanywheresolongaswords
ornumbers are not split or joined. Thus itis perfe tlylegal (though not re ommended!) to
write
turtleSim();forward(100) ;
left (90
);
if youwish. This exibility ismeant toenableyou towrite su hthat theprogramiseasyto
understand. Indeed, we have put empty lines in the program so as to help ourselves while
reading it. Thus the ommands whi h a tually draw the square are separated from those
thatopenand losethewindows. Anotherimportantideaistoindent,i.e. putleadingspa es
before lines that are part of main program. This isagain done to makeit visuallyapparent
what is a part of the main program and what is not. As you might observe, indentation is
alsoused in normalwriting inEnglish.
1.2.1 Exe ution order
Another important similarity on erns the order of the senten es and ommands. A
para-graph is expe ted tobe read fromleft to right, top to bottom. So is aprogram. By default
a omputer exe utes the ommands left to right, top to bottom. But just as you have
di-re tives in magazines or newspaper su h as \Please ontinue from page 13, olumn 4", the
orderinwhi hthe ommandsofaprogramareexe uted anbe hanged. Wesee anexample
1.3 Repeating a blo k of ommands
At this point you should be able to write a program to draw any regular polygon, say a
de agon. Youneedtoknowhowmu htoturn atea hstep. The amountby whi hyouturn
equals the exterior angle of the polygon. But we know from Eu lidean Geometry that the
exterior angles of a polygon add up to 360 degrees. A de agon has 10 exterior angles, and
hen e after drawing ea h side you must turn by 360=10=36 degree. So todraw a de agon
of side length 100, we repeat the forward(100) and right(36) ommands 10 times. This
works, but you may get bored writing down the same ommand several times. Indeed, you
dont need todothat. Here iswhat youwould writeinstead.
#in lude <simple pp> main_program{ turtleSim(); repeat(10){ forward(100); left(36); } loseTurtleSim(); }
This program, when exe uted, will draw a de agon. The new statement in this is the
repeat. Its generalform is
repeat( ount){
statements
}
Inthis, ount ouldbeanynumber. Thestatements ouldbeanysequen eofstatements
whi h would be exe uted as many times as the expression ount, in the given order. The
statements are said to onstitute the body of the repeat statement. Ea h exe ution of the
body is said to be an iteration. Only afterthe body of the loop is exe uted as many times
as the value of ount, dowe exe ute the statement followingthe repeat statement.
So in this ase the sequen e forward(100); left(36); is exe uted 10 times, drawing
all10 edges of the de agon. Onlyafter that we exe ute loseTurtleSim().
1.3.1 Drawing any regular polygon
Our next program when exe uted, asks the user to type in how many sides the polygon
should have, and then draws the required polygon.
#in lude <simple pp>
main_program{
int nsides;
out << "Type in the number of sides: ";
turtleSim(); repeat(nsides){ forward(50); left(360.0/nsides); } wait(5); loseTurtleSim(); }
This program has a number of new ideas. The rst statement in the main program
is int nsides; whi h does several things. The rst word int is short for \integer", and
it asks that a region be reserved in memory in whi h integer values will be stored during
exe ution. Se ond, italsogivesanametothis region: nsides. Finally itde lares thatfrom
now on, whenever the programmer uses the name nsides it should be onsidered to refer
tothis region. It is ustomary tosay that nsides is avariable,whose value is storedin the
asso iatedregionof memory. Thisstatementissaid todenethevariablensides. Asmany
variables as you want an be dened, either by givingseparate denition statements, orby
writingoutthe nameswith ommasinbetween. Forexample,int nsides, length; would
dene two variables, the rst alled nsides, the se ond length. We will learn more about
names and variables inthe next hapter.
The next new statementis relativelysimple. out isaname that refers tothe omputer
s reen. Itis ustomarytopronoun ethe in out(and ininthenext statement)as\see".
The sequen e of hara ters << denotes the operation of writing something on the s reen.
What gets written is to be spe ied after the <<. So the statement in our program will
display the message
Type inthe numberof sides:
onthe s reen. Of ourse,youmay putina dierent messageinyourprogram, and that will
get displayed.
In the statement after that, in >> nsides;, the name in refers to the keyboard. It
asksthe omputertowaituntiltheusertypesinsomethingfromthekeyboard,andwhatever
istyped ispla edintothe (regionasso iatedwith)the variablensides. The usermusttype
in an integer value followed by typing the return key. The value typed in gets pla ed in
nsides.
After the in >> nsides; statement is exe uted, the omputer exe utes the repeat
statement. Exe uting a repeat statement is nothing but exe uting its body as many times
as spe ied. In this ase, the omputer is asked to exe ute the body nsides times. So
if the user had typed in 15 in response to the message asking for the number of sides to
be typed, then the variable nsides would have got the value 15, and the loop body would
be exe uted 15 times. The loop body onsists of the two statements forward(100) and
left(360.0/nsides). Noti e that insteadof dire tly givingthe numberof degrees toturn,
we have given an expression. This is allowed! The omputer will evaluate the expression,
variablensides,and theresultisthe turningangle. Thus, ifnsidesis15,theturningangle
willbe 24. So itshould be lear that inthis ase a15 sided polygon would be drawn.
1.3.2 Repeat within a repeat
What do you thinkthe program belowdoes?
#in lude <simple pp>
main_program{
int nsides;
turtleSim();
repeat(10){
out << "Type in the number of sides: ";
in >> nsides; repeat(nsides){ forward(50); left(360.0/nsides); } } loseTurtleSim(); }
The key new idea in this program is the appearan e of a repeat statement inside another
repeat statement. How does a omputer exe ute this? Its rule is simple: to exe ute a
repeat statement, it just exe utes the body as many times as spe ied. In ea h iteration
of the outer repeat statement there will one exe ution of the inner repeat statement. But
one exe ution of the inner repeat ould have several iterations. Thus, in this ase a single
iterationof theouterrepeatwill ausetheuser tobeasked forthenumberof sides,afterthe
user types in the number, the required number of edges will be drawn by the inner repeat
statement. After that, the next iterationof the outer repeat would begin, for a total of 10
iterations. Thusa total of 10polygons would be drawn, one ontop of another.
1.4 Some useful turtle ommands
The following ommands an also be used.
penUp(): This ausesthe pen toberaised. Soafterexe utingthis ommand, the turtle
willmove but no linewillbe drawn until the pen is lowered. There is nothing inside the ()
be ausenonumberisneededtobespe ied,aswasthe asewithforward,e.g. forward(10).
penDown(): This auses the pen tobe lowered. Soafterexe uting this ommand,a line
willbe drawn whenever the turtlemoves, until the pen israised again.
Thus if you write repeat(10)fforward(10); penUp(); forward(5); penDown();g a
1.5 Numeri al fun tions
The ommandsyouhaveseensofarfor ontrollingtheturtlewillenableyoutodrawseveral
interesting gures. However you will noti e that it is umbersome to draw some simple
gures. For example, if you wish to draw an iso eles right angled triangle, then you will
need to take square roots { and we havent said how to do that. Say you want to draw
a simple right angled triangle with side lengths in the proportion 3:4:5. To spe ify the
angles would require a trigonometri al ulation. We now provide ommands for these and
some ommon operations that you might need. You may wonder, how does a omputer
al ulatethe value of the sine of an angle,or the square root of anumber? The answers to
these questions will ome later. For now you an just use the following ommands without
worrying about how the al ulation a tually happens.
Letusstartwithsquareroots. Ifyouwanttondthesquarerootofanumberx,thenthe
ommandforthatissqrt. Yousimplywritesqrt(x)inyourprogramandduringexe ution,
the square root of x will be al ulated, and will be used in pla e of the ommand. So for
example, here ishow you an draw aniso eles right angledtriangle.
forward(100);
left(90);
forward(100);
left(135);
forward(100*sqrt(2));
The ommands for omputing trigonometri ratios are sine, osine and tangent. Ea h
of these take asingle argument: the angle indegrees. Sofor example,writingtangent(45)
willbe as goodas writing 1.
The ommands for inverse trigonometri ratios are ar sine, ar osine and ar tan.
These will take a single number as an argument and will return an angle (in degrees). For
example, ar osine(0.5) willbe60 asexpe ted. These ommands returnthe angle in the
range-90to+90. Animportantadditional ommandisar tan2. Thisneedstwoarguments,
yand xrespe tively. Writingar tan2(y,x) willreturntheinversetangentofy/xinthefull
range,-180 to+180. This an bedone bylookingatthe signsof yand x,informationwhi h
would be lost if the argument had simply been y/x. Thus ar tan2(1,-1) would be 135,
while ar tan2(-1,1) would be -45, and ar tan(-1/1)=ar tan(1/-1 )=ar tan (-1 ) would
alsobe-45.
Nowyou willbe able todoa trianglewith side lengths300,400,500 asfollows.
forward(300);
left(90);
forward(400);
left(ar tan2(3,-4));
forward(500);
As you might guess, we an put expressions into arguments of ommands, and put the
ommands themselves into otherexpressions and so on.
1. exp, log, log10 : Thesereturnrespe tively forargument xthe value of e x
(where e
is Euler's number, the base of the natural logarithm), the natural logarithm and the
logarithmtobase 10.
2. pow: This takes 2 arguments,pow(x,y) returnsx y
.
C++alsohas ommandssin, os, tanwhi hreturnthetrigonometri ratiosgiven the
angle inradians. And forinverse trigonometri ratios we have the ommandsasin, a os,
atan, atan2 whi h returnthe anglein radians.
The name PI an be used in your programs to denote , the ratio of the ir umferen e
of a ir leto itsdiameter.
1.6 Con luding Remarks
Although itmay not seem like it,inthis hapter you have already learned alot.
First, you have some idea of what a omputer programis and how it exe utes: starting
atthe topand movingdownone statementatatimegoingtowards the bottom. Ifthere are
repeat statements, the program exe utes the body of the loop several times; the program
is said toloop through the body forthe requirednumberof iterations.
You have learned the notion of a variable, i.e. a region of memory into whi h you an
read in avalue, whi h an later be used while performing omputations.
Youhavealsolearnedthatthe languagemightprovideyou ommandswhi hyou an use
withouthaving toknowhow exa tlythey work. Lateron wewillsee how toourselvesbuild
new ommands.
Finally,averyimportantpoint on ernsobservingthepatternsinwhateveryouaredoing.
When we draw a polygon, we repeat the same a tion several times. This is a pattern that
we an mirror inour programby using the repeat statement. By using arepeat statement
we an keepour program ompa t;indeedwemay bedrawingapolygonwith 100sides, but
our program only has a few statements. You will see other ways of apturing patterns in
your programs later. In generalthis isa veryimportantidea.
At this point you should also see why the notation used to write programs is alled a
language. Aspokenlanguageisvery exibleandgeneral. Ithasagrammati alstru ture,e.g.
there is a subje t, verb, and obje t; or there an be lauses, whi h an themselves ontain
subje ts, verbs, obje ts and other lauses. And so long as the stru ture is respe ted, you
an havemany,many, indeedaninnitenumberof senten es. Similarly, omputer programs
have a stru ture, e.g. a repeat statement must be followed by a ount and a body; but
inside the body there an be other statements in luding a repeat statement. Indeed our
treatment of the C++ programming language will be somewhat similar to how you might
be taught Tamil or Fren h. Just as language learning is more fun if you read interesting
literature,we willintrodu e theC++languageaswetrytosolvemore andmoreinteresting
omputationalproblems. Hope youwillnd this enjoyable.
It willbeimportantto learnthe various grammati alrules of the C++ languageas you
go along. However, it will also be important for you to develop some intuition for what
the rules might be or ought to be. For example, we said in the se tion above that instead
used. You should ask yourself, is this a general rule? It turns out, indeed, that this is a
generalrule. In most pla es wherenumbers are expe ted,youmay alsospe ifyexpressions.
The omputer willevaluate those expressions and use the resulting values. So for example,
you may write out << nsides*100; whi h will ause the perimeterof the polygon being
drawn to beprinted on the s reen (assuming the side length is 100).
ThemajordiÆ ultyinwritingprogramsisnot, of ourse,the grammati alrulesofC++.
Theseyouwillmasterwithsomepra ti e. ThemaindiÆ ultyisinde idingwhat ommands
togive,whatorder togivethe ommands in,howtogroup themintorepeat statements. In
this hapter,twoideashaveappearedregarding this,and itisworth statingthemexpli itly.
The rst idea is: before you starting to write a program that makes a omputer do
something,thinkabout howyouyourself solve the problem. Howwould youdrawasquare?
How wouldyoudrawasquare sitting ontopof areal turtle? Youwillrealizethat what you
writeisoftenjusta areful statementof whatyouyourselfwould have done. Sothishas two
parts: youshouldyourselfknowhowtosolvethe problem,andyoushouldbeabletoexplain
in words howyou solve the problem. In some sense, programmingis abit like tea hing.
The se ond idea is: whatever a tivity you are doing, there are likely to be patterns
or symmetries in it. If you are drawing a square, then you repeat the same draw-turn
pattern four times. Seeing this pattern is extremely important. The pattern ontains some
insight about the a tivity whi h is inherently valuable, but more dire tly it enables us to
write ompa t programs. Writing ompa tly and su h that the patterns in the a tivity are
re e ted in the programis a major goalof programming.
1.7 Overview of the book
The next hapter gives you a bird's eye view of the world of omputers and programming.
We will study at a high level how omputers are onstru ted, and how real life problems
fromplaying hess to makingtrain reservations an berepresented onthem. We willtryto
get an intuitive sense of omputer hardware so that the working of a omputer as will be
dis ussed insubsequent hapters appears reasonable to you, and you donot feel that there
is toomu hmagi in allthis. 4
The subsequent hapters will tea h you how to program using C++. The phrase \how
to program" an have many interpretations. Here are some of the possible interpretations,
starting fromthe least ambitious going onto the most ambitious:
1. Understandingthe dierentstatementsinC++. Another way ofstating this is: given
a program and enough time, an you in prin iple say what output the program will
if you know what input is given to it? The issue here is only omprehension, and not
design.
2. Abilitytowriteprogramstosolveproblemsthatyou anyourselfsolveusingpen iland
paperand given enoughtime. Forexample, weknow the formulaforndingthe roots
ofa quadrati equation. Canwe expressthis omputationinaprogram? Orgiven the
setofmarksobtainedbystudentsina ourse,wewouldbedeterminetheaveragemark,
4
Well, evenpeoplewhofully understand omputers think there issomethingmagi alin them, but that
or the maximum mark. Can we write a program to do su h omputation? There are
many su h problems whi h you solve routinely without omputers, be ause you have
a systemati pro edure in mind. Can you express these rules in programs sothat the
problems an be solved by a omputer? If the answer is yes, then you have rea hed
the se ond level of programmingability.
3. Cooperate with a team of people to solve a large problem. Issues su h as how to
de- omposetheproblem,howtodoyourworksothatothers anuseitbe omeimportant.
4. Dis overingnewwaysofsolvingaproblem. Forexample,whatistheshortestwaytogo
fromMumbai toTanjore, spending at most Rs1000? You may thinkyouknow many
ways to make this travel, however, it isquitelikely that youmay not know enoughto
be sure that no better way is possible. Solving su h problems requires a higher level
of problemsolving/programming ability.
Thesituationisnotunlikelearningaforeignlanguage. Beingabletounderstandthelanguage
isonelevelof ompeten e. Beingabletospeakitisthe next. Often, your generalexpression
abilitiesimproveasyoulearnanewlanguage,andyouarebetterabletosaythingswhi hyou
didnt know how tosay earlier. This is perhaps the analogueof the fourth pointmentioned
above: ability to solve new problems. Of ourse, when you learn a new language, you need
tolearn the etiquette, the way tosay things formally,in that ulture. This isdierentfrom
merely being able to onverse on the street. It is hoped that you willkeep these analogies
in mindas youread the book, and gaugeyour own progress alongthese dire tions.
1.7.1 A note regarding the exer ises
Programming is not a spe tator sport. To reallyunderstand programming, you must write
many, many programs yourself. That is when you will dis over whether you have truly
understood what is said in the book. To this end, we have provided many exer ises at the
end of ea h hapter,whi h you should assidouslysolve.
Another important suggestion: while reading many times youmay nd yourself asking,
\What ifwewrite this programdierently". Whilethe authorwillnot bepresent toanswer
your questions, there is an easy way to nd out { write it dierently and run it on your
omputer! This is the best way to learn.
1.8 Exer ises
Inallthe problems relatedtodrawing,youareexpe tedtoidentifythe patterns/repetitions
in what is asked, and use repeat statements to write a on ise program as possible. You
should alsoavoid ex essive movement of the turtle and tra ing over what has already been
drawn.
1. Modify the programgiven inthe textsothat itasksforthe side lengthof the polygon
tobedrawn in additionto asking for the number of sides.
3. Drawa hessboard, i.e. a square of side length say 80divided into64 squares ea h of
sidelength 10.
4. Ifyoudrawapolygonwithalargenumberofsides, say100,thenitwilllookessentially
like a ir le. In fa t this is how ir les are drawn: as a many sided polygon. Use this
idea todraw the numeral 8{ two ir les pla ed tangentiallyone abovethe other.
5. A pentagram is a ve pointed star, drawn without lifting the pen. Spe i ally, let
A,B,C,D,E be 5 equidistantpointson a ir le, then this isthe gureA{C{E{B{D{A.
Drawthis.
6. Draw a seven pointed star in the same spirit as above. Note however that there are
more than onepossiblestars. An easyway togure out the turningangle: howmany
times does the turtle turnaround itselfas it draws?
7. We wrote \360.0" in our program rather than just \360". There is a reason for this
whi h we will dis uss later. But you ould have some fun guring it out. Rewrite
the program using just \360" and see what happens. A more dire t way is to put
in statements out << 360/11; out << 360.0/11; and see what is printed on the
s reen. This is an important idea: if you are urious about \what would happen if I
wrote ... instead of ...?" { you should simplytry itout!
8. Read in the lengthsof the sides of a triangle and draw the triangle. You willneed to
know and use trigonometry for solving this.
9. When youhold aset of ardsinyour hand,youusually arrangethemfanned out. Say
you start with ards sta ked one on top of the other. Then you rotate the ith ard
from the top by an amount proportionalto i (say 10i degrees to the left) around the
bottom left orner. Now, we an see the top ard ompletely,but the other ards are
seen only partially. In parti ular, only a triangularportion of ea h ard is seen, with
the top left orner being at the apex of ea h triangle. This is the gure that you are
to draw. (a) Draw it assuming the ards are transparent. (b) Draw it assuming the
ards are opaque. For this some trigonometri al ulation will be ne essary. In both
ases, use repeat statements tokeep your program smallaspossible.
10. Drawa pattern onsisting of 7 ir lesof equal radius: one in the enter and 6around
it,ea houter ir le tou hing the entral ir le andtwoothers. Trytowrite aprogram
whi h minimizes turtle movement. Your program statements should be hosen to
A bird's eye view
At rst glan e, it is indeed surprising that a single devi e like a omputer should be able
to predi t the weather, or help design ars, or analyze pi tures, or sear h the books and
do uments allover the world and tellyou whereyoumight nd informationregarding your
topi of interest, orplay hess better than the human world hampion. The purpose of this
hapteristoredu ethissurprisesomewhat,tomakeitmorebelievablethata omputer ould
perhapsbeable todoallthis. Theargumenthas twoparts. The rstpartisthe observation
that allthe problems des ribed above, frompredi ting the weather toplaying hess, an be
des ribed inthe languageof numbers, Mathemati s. In asense,Mathemati s isuniversal,it
an be used to analyze almostevery phenomenon orpro ess or entity known toman. On e
we have redu ed the problem we want to solve to some mathemati al problem, then what
remainsisto devi ea ir uitwhi h an solvethe problem. Even inthis, there isanelement
of universality: we willargue that a single(but huge) ir uit that amodern omputer is,is
apableof solving many, many problems simplyby running appropriateprograms.
The s ien e of programming, then ould be said to be founded on two great s ien es.
On one side, we have Mathemati s, and on the other side, we have the s ien e of designing
ele tri al ir uits, Ele tri al Engineering. We wish to des ribe the relationshipof
program-ming to these s ien es. Our des ription, espe ially that related to ir uit design, will be
quitesuper ial. However, itis hoped that this des riptionwillprovidesomeba kground,a
helpful reassuran e, asyou navigate through subsequent hapters.
We begin with the question of representing real life phenomenon using numbers. We
dis uss this brie y and we will return to this question in later hapters. The rest of the
hapter attempts to provide a plausible view of the ir uits onstituting a omputer. We
present avery simpliedmodelof a omputer and using itexplain some basi ideas su h as
the notionof aprogramstoredinmemory,the ideaof stepby stepexe utionofinstru tions,
and the notion of anaddress for referring to regions of memory. These ideas are entralto
design of omputers aswell asprogramming.
We expe t our des ription of omputers inthis hapter to be read like a short, popular
s ien e arti le. We will try to anti ipate the main questions you might have about how
omputers work, and answer them at an intuitive level. We will gloss over many details,
andalsooversimplifyseveral ideas. We annotgivea omplete answertoallquestions,after
all, ir uitdesignand omputer ar hite turearedeepsubje ts, ea hneedinganindependent
0 0 0 1 1 1 0 0 0 0
0 0 1 0 0 0 1 1 0 0
0 1 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1 0
1 0 1 0 0 0 1 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 1 1 1 0 0 1 0
0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 1 1 0 0
0 0 0 1 1 1 0 0 0 0
(a)
(b)
(c)
Figure 2.1: A pi ture,its representation, and re onstru tion
hardware, providingadequate ba kground forthe study of programmingto ome later.
2.1 Representing real life entities using numbers
Some entitiesin real lifehavean obviousmathemati al hara ter; any quantity that we an
measure, su h as mass, for e, voltage, on entration of hemi als, is naturally expressed
numeri ally. But for some other entities, it is not immediately obvious how they an be
expressed using numbers. Can we express pi tures or languageusing numbers? We dis uss
these questions brie y.
Here is how a pi ture mightbe represented using numbers. Consider a bla k and white
pi ture to begin with. The pi ture is divided into small squares by putting down a ne
grid over it, as in Figure 2.1(a). Then for ea h small square we determine whether it is
more white or more bla k. If the square is more white we assign it the number 0, if it is
mostly bla k, we assign it the number 1. So if we have divided the pi ture into m n
small squares(pixels), m alongthe height andn along the width,we have asequen e of mn
numbers, ea h either 1 or 0 that represents the pi ture. Figure 2.1 shows the numbers we
haveassigned toea hsquare. Given the mn number representation, we an re onstru t the
pi tureasfollows: wherevera0 appears, weleavethe orresponding squarewhite, wherever
a1appears,wemakethe orrespondingsquarebla k. There onstru tion,usingthenumbers
in Figure2.1(b) is shown inFigure 2.1( ). As you an see, the re onstru ted pi ture is not
identi al to the originalpi ture, but reasonably similar. By hoosing aner grid, we would
have been able to get a better approximation of the original pi ture. Sin e our eye annot
individually see very small squares, it turns out that pixels of size about 0.1 mm are good
enough, i.e. the re onstru ted pi ture is hard to distinguish from the original. Pro essing
a pi turemeans doing omputationsinvolvingthese numbers. Forexample, hanging every
zero to aone and vi eversa, will hange the pi ture from\positive"to\negative"!
The idea of putting down a grid over the obje t of interest is very powerful. Suppose
we wish to represent the worldwide weather. Typi ally, we divide the surfa e of the globe
into small regions. Forea h region we onsider all the parameters relevant to the weather,
e.g. the ambient temperature, pressure, humidity. Of ourse, allpoints ina region will not
have identi al temperature, but we nevertheless an hoose an approximate representative
temperature, if the region is reasonably small. The key to predi ting weather are laws of
but, it is orre t inessen e. 1
Text an also be represented using numbers. Essentially, we devi e a suitable ode.
The most ommon ode is the so alled ASCII (Ameri an Standard Code for Information
Inter hange) ode. In this, the letter \a" is represented as the number 97,\b" as 98and so
on. Standard symbols and the spa e hara ter also have a ode assigned to them. So the
word \ omputer"isrepresented bythe sequen e ofnumbers 99,111,109,112,117,116,101,114.
Thus we might be given a sequen e representing a paragraph. Finding whether a given
word o urs in this paragraph is simply he king whether one sequen e of numbers is a
subsequen e of another sequen e of numbers! On e we an express text, we have a foothold
for expressing senten es, and allof language! The ASCII ode is meant onlyfor the Roman
alphabet, there are odes meant for other alphabets, su h as the Devanagari alphabet as
well.
Wewillsee morereal lifeobje ts (andmathemati alobje tstoo,su h assets, fun tions)
and how torepresent them inthe rest of the book.
2.2 Representing numbers on a omputer
God made natural numbers, the rest is the work of man.
{ Leopold Krone ker.
There are, of ourse, dierent types of numbers. Starting with the simplest, the so
alled natural numbers or ounting numbers, we have integers (whi h an be negative),
rational numbers, real numbers, and even omplex numbers. We begin by dis ussing how
to represent natural numbers. The other types of numbers an in fa tberepresented using
natural numbers. Note that there is some ambiguity about whether 0is to be onsidered a
naturalnumber; we in lude itand use the term tomean non-negative integers.
To represent a naturalnumberwe rst write it inbinary. Soif we wish to represent the
de imal number 25 on a omputer, we rst write it as 11001 in binary. Now ea h binary
digit, orbit of the binary number, isrepresented separately. Forea hbit thereare only two
possibilities: 0or1. Torepresentabit, wewouldtypi allydedi ateone apa itorsomewhere
in our omputer, and put a low orhigh voltage onthat apa itor depending upon whether
wewanttorepresent a0or1respe tively. Ifwewanttostore a5bitnumber, su has11001,
we would have to designate some 5 apa itors, and store respe tively high, high, low, low,
and high voltages onthem. It is of ourse our reponsibility to keep tra k of where we store
ea h number, and even whi h of the apa itors stores the least signi ant bit, se ond least
signi ant bit, and so on. High voltage might mean 0.7 volts, low voltage might mean 0
volts.
Usingvoltageson apa itorstorepresentnumbersisnottheonlyway. Itisalsopossibleto
designatewiresinour omputersforthispurpose: alow urrentinthewiresmightrepresent
0,and ahigh urrent mightrepresent 1 (againwith some agreed uponvalues for what high
and low means). Magnetization might also be used: magnetization in one dire tion might
1
This is not to say that all physi al phenomenon related to the weather are well understood. Infa t,
many simplethings are notunderstood, e.g. howpre isely do rain drops form. However, we understand
mean 0, in another might mean 1. This is ommon for storing data on magneti dis s (or
tapes, long ago). On opti al dis s, a re e tive region might represent a 1, a non re e tive
region a0. Anopti al CDis divided intoa large numberof su h regions,ea h ofwhi h an
be used tostore abit.
Youmaywonderwhether using bitstorepresentnumbers isthe onlypossibleway. Why,
for instan e, dowe not use 0 voltsto represent 0, 0.1to represent 1, 0.2to represent 2,0.3
torepresent3,andso on. Inanidealworld, thisidea ouldbeimplemented. Butinthe real
world,thereareimperfe tions: itispossiblethatweintended toraisethevoltageofawireto
0.2 butbe auseofsome ele tri alnoise orsome ir uit imperfe tionit onlygotraised to0.1
This would then hange the value that westored! Ifthis numberrepresentsa letter, thenit
would hange a\p" to\q"orsomething likethat {whi hwould bequiteuna eptable. On
the other hand, suppose we instead have 0.0voltsrepresent a 0and 0.7volts represent a1.
This inee t means: any voltage below0.35 will beinterpreted as 0and any voltage above
0.35 as 1. Now to ause a misinterpretation we would need to have noise as large as 0.35
volts. This turns out to be unlikely for the te hnology we have for building su h ir uits.
Be ause ofsu h onsiderations, itturnsout thatusing thebinary representationisthe most
onvenient.
On e we have found a way to represent numbers using voltages or urrents, the task of
pro essing numbers an be expressed as an ele tri al engineering question: given a ertain
ongurationof voltages or urrents, produ e another ongurationof voltages or urrents.
2.2.1 Bits, Bytes, Words
The basi unit of memory is a bit. As mentioned earlier, a bit is typi ally stored using a
apa itor, high voltage a ross it denoting the value 1and low voltage denoting the value 0.
Groups of 8 bits are alled bytes, and a group of 4 bytes onstitutes a word. We will use
this denition of a word, even though itis not as universally as a epted as the denitions
of bits and bytes. The term half-word is often used to refer to the two bytes onstituting
ea hhalf of a word, and the term double-word fortwo onse utive words of memory.
2.2.2 Storing natural numbers
Wehavealreadydis ussedthat naturalnumbersarestoredinbinary. Tostoreanumber, we
need toallo ateat least asmany bits of memory asthere are bits inthe number. However,
when allo ating memory to store a number, we usually do not ask for anarbitrary number
of bits;itis ustomarytoaskfora byte,orahalf-word, oraword, oradouble-word, aswill
be seen inthe following hapters. Ifwe asked for32 bits,or aword of memory, andwish to
store 25in it,wemust rst write 25using 32 bits, as:
00000000000000000000000000011001
This pattern of bits would then have tobe stored inthe hosen word.
2.2.3 Storing integers
The simplest representation is the so alled sign-magnitude representation. In this, if n
bitsareusedintotal,oneoftheseisdesignatedasasignbit. Soinadditiontothe apa itors
we dedi ate for storing the magnitude, we will also dedi ate one apa itor for storing the
sign. We ould de ide that a lowvoltage onthe apa itor indi atesthat the stored number
ispositive,while ahigh voltageindi atesthat the storednumber isnegative. Wemight use
the bit in the most signi ant position as the sign bit, so the representation for -25 using
the 32 apa itors would be:
10000000000000000000000000011001
Amore ommonlyused representationistheso alled2's omplementrepresentation. The n
bit2s omplementrepresentationisdened asfollows. Inthistheintegerxisrepresentedby
thebinary numberxif0x2 n 1
1,andbythebinarynumber2 n
xif 2 n 1
x<0.
Thus, in 32 bit 2's omplement representation, -25 would be represented by the bit
pattern:
11111111111111111111111111100111
2.2.4 Storing real numbers
Mu h omputing needs to be done with real numbers. For example, velo ities of parti les,
voltages, temperatures and so on in general need not take only integral values. In the
s ienti world su h quantities are typi ally written using the so alled s ienti notation,
in the form: f 10 q
, where the signi and f typi allyhas a magnitude between 1 and 10,
and the exponentq isa positiveor negative integer. For example the mass of an ele tron is
9:10938210 31
kilograms,or Avogadro'snumberis 6:02210 23
.
How should we store Avogadro's number on a omputer? First of ourse, we must
represent itin binary,this is easily done: it is
1:111111100010101011111112 1001110
Note that this is approximate, and orre t only to3 de imal digits. But then, 6:02210 23
was only orre t to 3 digits anyway. The exponent 1001110 in de imal is 78. Thus the
number when written out fully will have 78 bits. We ould use 78 bits memory to store
the number, however, it seems unne essary, espe ially sin e many of those 78 bits will be
0s anyway. A better alternative, is to store ea h number in two parts: one part being the
signi and, and the other being the exponent.
Forexample,we oulduse8bitstostoretheexponent,and24bitstostorethesigni and,
so that a number is neatly tted into a single word! This turns out to be essentially the
method of hoi e onmodern omputers. Youmightask why use an8-24 split of the 32 bits
and why not 10-22? The answer tothis isexperien e: for many al ulations itappears that
24 bits of pre ision in the signi and is adequate, while the exponent size of 8 bits is also
needed. There are s hemes that use adouble word as welland the split here is11-53, again
based onexperien e.
Note that the signi andas well as the exponent an be both positive ornegative. One
simple way to deal withthis isto use a sign-magnituderepresentation, i.e. dedi ate one bit