computer programming - initial version
DESCRIPTION
CS110 Course TextbookTRANSCRIPT
-
COMPUTERCOMPUTERPROGRAMMINGPROGRAMMING
A Course TextbookA Course Textbook
Robert P. Batzinger
Payap University PressChiang Mai 50000, Thailand
-
COMPUTERPROGRAMMING
The Course Textbook
Robert P. Batzinger
Payap University PressChiang Mai 50000, Thailand
-
Copyright 2013 Robert P. Batzinger
Payap University PressAmphur Muang Chiang Mai 50000Thailand Permission is granted to copy, distribute, and/or modify this document under the terms of the
Creative Commons Attribution-NonCommercial 3.0 Unported License, which is available at http://creativecommons.org/licenses/by-nc/3.0/.
The original form of this book was developed as XLATEX source code which can be compiled to generatea device-independent representation of a textbook, which can be converted to other formats and printed.For those interested in translating this book into other languages, the XLATEX source for this book isavailable from the author.
-
Contents
Front matter iiiTable of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iiiList of Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viList of Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viiiList of Flowcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ixList of Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xList of Code Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiiList of Supplemental Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv
Acknowledgements xvii
Acronyms xix
1 Introduction 11.1 Why study programming? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Overview of this course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 Organization of this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.4 Features of this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Computer Fundamentals 72.1 Main Components of a Computer System . . . . . . . . . . . . . . . . . . . . . 7
2.1.1 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.1.2 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.1.3 Peopleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2 Key Ingredients of Good Computer Programming . . . . . . . . . . . . . . . . . 172.2.1 Algorithms employed . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172.2.2 Nature of man-computer interaction . . . . . . . . . . . . . . . . . . . . . 182.2.3 Programming language selected . . . . . . . . . . . . . . . . . . . . . . . 182.2.4 Data representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3 Scratch Programming 293.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.1.1 Interactive Development Enironment . . . . . . . . . . . . . . . . . . . . 293.1.2 A first program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303.1.3 The Scratch command pallet . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2 Conditional Operation within Scratch . . . . . . . . . . . . . . . . . . . . . . . 323.2.1 Combining multiple logic conditions . . . . . . . . . . . . . . . . . . . . 34
3.3 Programming Loops in Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.3.1 Endless repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363.3.2 Controlled repetitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393.3.3 Nesting of loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
iii
-
iv CONTENTS
3.4 Using variables in Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423.5 Calling subroutines in Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.5.1 An extended example using subroutines . . . . . . . . . . . . . . . . . . 453.6 Lists and arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4 Program Design Tools 534.1 Different methods for describing a process . . . . . . . . . . . . . . . . . . . . . 534.2 Program design tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
4.2.1 Flow chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564.2.2 Pseudo code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.3 Basic programming patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644.4 Commenting source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5 Basic Concepts of C Programming 695.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695.2 Basic building blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
5.2.1 Variables and constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 715.2.2 Operators and precedence . . . . . . . . . . . . . . . . . . . . . . . . . . 725.2.3 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785.2.4 Expressions and statements . . . . . . . . . . . . . . . . . . . . . . . . . 78
5.3 Program Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805.3.1 Conditional execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805.3.2 Loop structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 825.4.1 Standard Library Functions in stdlib.h . . . . . . . . . . . . . . . . . . . 835.4.2 Mathematical Functions in math.h . . . . . . . . . . . . . . . . . . . . . 845.4.3 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845.4.4 Return values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845.4.5 Local vs Global variables . . . . . . . . . . . . . . . . . . . . . . . . . . 84
5.5 Compiler Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845.5.1 Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845.5.2 Conditional compiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
5.6 C Programming Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845.6.1 Grade conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845.6.2 Prime Number Listings . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6 Composite Data Types 996.1 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 996.2 String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1086.3 Character functions - ctype.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1096.4 User-defined data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1096.5 Enumerated data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
7 File Processing 1137.1 Data stream handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1137.2 Sequential text file input/output . . . . . . . . . . . . . . . . . . . . . . . . . . 1147.3 Formatted input and output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1157.4 File open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167.5 Random access file input/output . . . . . . . . . . . . . . . . . . . . . . . . . . 1177.6 Parsing a CSV file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
-
CONTENTS v
8 Pointers 1218.1 The concept of a pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1218.2 Pointers as function parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . 1218.3 Pointers and arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1218.4 Arrays of pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1218.5 Pointers of functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
9 Software Programming Paradigms 1279.1 Software development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
9.1.1 Module development . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1279.1.2 Agile programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1299.1.3 Debugging and Unit testing . . . . . . . . . . . . . . . . . . . . . . . . . 1299.1.4 Version control and makefile . . . . . . . . . . . . . . . . . . . . . . . . 1299.1.5 Conditional compiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
9.2 Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1299.2.1 Structured programming . . . . . . . . . . . . . . . . . . . . . . . . . . . 1299.2.2 Object-oriented programming . . . . . . . . . . . . . . . . . . . . . . . . 1299.2.3 Parallel/concurrent programming . . . . . . . . . . . . . . . . . . . . . . 129
A Software installation 133A.1 Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133A.2 yEd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134A.3 GNU gcc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
B A Quick Guide to Programming Languages 135B.1 Keyword list of some popular programming languages . . . . . . . . . . . . . . 135B.2 Scratch Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
C Comparison between standard Computer Science curriculum 139C.1 ACM CC2001 Programming Fundamentals . . . . . . . . . . . . . . . . . . . . 141
D C Reference Card 143
Bibliography 145
Index 147
About this Book 149
-
List of Figures
1.1 The estimate of the unfilled computer programming jobs in the United States. . . 21.2 Sequence of Computer Science Courses in Prerequisite Order . . . . . . . . . . 3
2.1 Basic hardware components of electronic computers . . . . . . . . . . . . . . . 82.2 Bus line communications between the microprocessor and internal memory. . . . 92.3 Early electronic computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.4 Photomicrograph of Intel 8080 introduced in 1974. . . . . . . . . . . . . . . . . 112.5 Photomicrographs of popular microprocessors produced in 1993. . . . . . . . . . 122.6 A photomicrograph of the Intel iCore7 quad core microprocessor . . . . . . . . . 132.7 47 Years of Moore's Law . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.8 Hardware standards for PC I/O ports . . . . . . . . . . . . . . . . . . . . . . . . 152.9 Successful technology comes with good technical support. . . . . . . . . . . . . 172.10 Children's Product Table at the Apple Store in Singapore . . . . . . . . . . . . . 182.11 Origins of common computer languages . . . . . . . . . . . . . . . . . . . . . . 192.12 Bits can be used to monitor individual sensors or combined to store a number
using powers of 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212.13 Converting the binary number 101001012 to its decimal equivalent of 165 . . . . 22
3.1 Scratch Interactive Development Environment . . . . . . . . . . . . . . . . . . 303.2 Thai and English view of hello.scr . . . . . . . . . . . . . . . . . . . . . . . 303.3 Groups of Scratch Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.4 Flowchart and pseudocode of a script to center the cat . . . . . . . . . . . . . . . 333.5 Endless loop structures within the Scratch language . . . . . . . . . . . . . . . . 363.6 Conditional Processing: Stage screen shots . . . . . . . . . . . . . . . . . . . . 383.7 Controlled loop structures within the Scratch language . . . . . . . . . . . . . . 393.8 Loop execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393.9 Pseudocode and outcome of nested loops . . . . . . . . . . . . . . . . . . . . . 403.10 Sample polygons drawn with Scratch . . . . . . . . . . . . . . . . . . . . . . . 433.11 Storyboard Frames of the Scratch Screen . . . . . . . . . . . . . . . . . . . . . 453.12 Interaction between the character subroutines . . . . . . . . . . . . . . . . . . . 463.13 Costumes of used by the sprites . . . . . . . . . . . . . . . . . . . . . . . . . . 463.14 Making change for 188 cents . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493.15 Jumping frogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523.16 Solving a maze . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.1 Video on cooking a scrabbled egg . . . . . . . . . . . . . . . . . . . . . . . . . 544.2 Recipe for scrambled eggs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544.3 Step by step graphic instruction . . . . . . . . . . . . . . . . . . . . . . . . . . 554.4 IBM Flowcharting Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574.5 The user interface for yEd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
vi
-
LIST OF FIGURES vii
5.1 Steps to run a program in the C language . . . . . . . . . . . . . . . . . . . . . 705.2 Variables must be declared by type and set to known values. . . . . . . . . . . . 715.3 Output of the bitops.c program . . . . . . . . . . . . . . . . . . . . . . . . . . . 735.4 Variables must be declared by type and set to known values. . . . . . . . . . . . 95
6.1 Bitmapped Numerical Digits . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1036.2 Output of Version 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
8.1 Comparsion between iteration and recursion version of the Euclid GCD algoirithm125
A.1 The Online Version of the Wizard vs Ogre Example . . . . . . . . . . . . . . . . 134
D.1 A Bilingual Introduction to Chemistry . . . . . . . . . . . . . . . . . . . . . . . 149
-
List of Tables
2.1 Size of memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2 A Short List of Popular Open-Source Computer Languages . . . . . . . . . . . . 202.3 Keyword Count of Some Computer Languages . . . . . . . . . . . . . . . . . . 202.4 Powers of 2 represented by each binary digit of a 32 bit number . . . . . . . . . 222.5 Binary representation of some signed numbers . . . . . . . . . . . . . . . . . . 232.6 Bit allocation within an IEEE floating point number . . . . . . . . . . . . . . . . 242.7 Binary, Octal and Hexidecimal and ASCII Character Representation of Values 0
to 127 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252.8 The Thai Character Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.1 Comparison Operators of Scratch . . . . . . . . . . . . . . . . . . . . . . . . . 323.2 Mathematical Operations of Scratch . . . . . . . . . . . . . . . . . . . . . . . . 333.3 Truth Table for AND Combinations . . . . . . . . . . . . . . . . . . . . . . . . . 353.4 Truth Table for OR Combination . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.1 Flowchart Symbols used in this Course . . . . . . . . . . . . . . . . . . . . . . 574.2 Common action words used in pseudocodes . . . . . . . . . . . . . . . . . . . . 594.3 Information to be included in Software Sourcecode . . . . . . . . . . . . . . . . 664.4 Comparison between the Lyrics of Hey Jude and a Flowchart Version . . . . . . 67
5.1 C basic data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725.2 Precedence and meaning of C Operators . . . . . . . . . . . . . . . . . . . . . . 725.3 Bit-wise Outcomes of Bit-wise Operators . . . . . . . . . . . . . . . . . . . . . 735.4 Comparison of Pseudocode and Flowchart of an Application to Convert Percent-
ages to Letter Grades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.1 String manipulation functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
9.1 Header files of the ANSI C Library . . . . . . . . . . . . . . . . . . . . . . . . 128
A.1 The Scratch program is available for Mac Os-X, Windows and Linux . . . . . . 133
B.1 Keywords of the C language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135B.2 Keywords of the Ardunio language . . . . . . . . . . . . . . . . . . . . . . . . 135B.3 Keywords of the Java language . . . . . . . . . . . . . . . . . . . . . . . . . . . 136B.4 Keywords of the Processing language . . . . . . . . . . . . . . . . . . . . . . . 136
D.1 Common computer terms in the some languages of the AEC . . . . . . . . . . . 150
viii
-
List of Flowcharts
3.1 Conditional movement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334.1 Making scrambled eggs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564.2 Cockpit takeoff warning controller . . . . . . . . . . . . . . . . . . . . . . . . 604.3 Calculating storage capacity . . . . . . . . . . . . . . . . . . . . . . . . . . . 604.4 Score to Letter Grade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614.5 Line-tracing robot behavoir . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
ix
-
x LIST OF FLOWCHARTS
-
List of Algorithms
3.1 Conditional movement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333.2 Pseudocode of a loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393.3 Pseudocode of nested loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404.1 Instructions for making scrambled eggs . . . . . . . . . . . . . . . . . . . . . 554.2 Pilot warning system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594.3 Calculating storage capacity . . . . . . . . . . . . . . . . . . . . . . . . . . . 604.4 Score to Letter Grade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614.5 Robot line following behavior . . . . . . . . . . . . . . . . . . . . . . . . . . 624.6 Storing information in variables and constants . . . . . . . . . . . . . . . . . . 648.1 Euclids algorithm
by iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1258.2 Euclids algorithm
by recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
xi
-
xii LIST OF ALGORITHMS
-
List of Code Examples
3.1 Hello World in Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.2 Centering the cat: (First try) . . . . . . . . . . . . . . . . . . . . . . . . . . . 343.3 Centering the cat: (Corrected version) . . . . . . . . . . . . . . . . . . . . . . 353.4 Walking forever . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363.5 Conditional Processing: Program code for 2 Sprites . . . . . . . . . . . . . . . 373.6 A Scratch program to draw a triangle . . . . . . . . . . . . . . . . . . . . . . . 403.7 Scratch program with nested loops . . . . . . . . . . . . . . . . . . . . . . . . 413.8 Scratch program to draw a hexagon- . . . . . . . . . . . . . . . . . . . . . . . 423.9 A generic polygons drawn with Scratch . . . . . . . . . . . . . . . . . . . . . 423.10 Sum of the first 10 integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433.11 Sum of the first 10 integers: Improved version . . . . . . . . . . . . . . . . . . 443.12 An improved version of the code in Figure 3.7 . . . . . . . . . . . . . . . . . . 443.13 Main and event-driven scripts of the wizard . . . . . . . . . . . . . . . . . . . 473.14 Main and event-driven scripts of the spark . . . . . . . . . . . . . . . . . . . . 473.15 Main and event-driven scripts of the Ogre . . . . . . . . . . . . . . . . . . . . 483.16 Making change: setup and calculation subroutines . . . . . . . . . . . . . . . . 493.17 Making change application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495.1 Hello.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705.2 bitops.c: a program to illustrate binary operators . . . . . . . . . . . . . . . . . 755.3 increment.c: a program to illustrate ways to increment an integer . . . . . . . . 765.4 Comparison between 2 styles of C programming . . . . . . . . . . . . . . . . . 765.5 accuracy.c: program to demonstrate floating point errors . . . . . . . . . . . . 775.6 Converting a percentage to a letter grade: chained if version . . . . . . . . . . 875.7 Converting a percentage to a letter grade: Function version . . . . . . . . . . . 885.8 Converting a percentage to a letter grade: Function version . . . . . . . . . . . 895.9 Score to Grade Conversion: student submission . . . . . . . . . . . . . . . . . 905.10 Printing all the prime numbers less than 50 . . . . . . . . . . . . . . . . . . . . 915.11 Finding the prime factors of a number . . . . . . . . . . . . . . . . . . . . . . 945.12 Score to Grade Conversion: student submission . . . . . . . . . . . . . . . . . 965.13 Finding the prime factors of a number . . . . . . . . . . . . . . . . . . . . . . 976.1 Displaying bitmapped digits . . . . . . . . . . . . . . . . . . . . . . . . . . . 1036.2 Displaying bitmapped digits (Version 2) . . . . . . . . . . . . . . . . . . . . . 1046.3 Print the longest line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1129.1 Parallel processing using fork() . . . . . . . . . . . . . . . . . . . . . . . . . . 1319.2 An example of switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
xiii
-
xiv LIST OF CODE EXAMPLES
-
List of Supplemental Material
1.1 Why is the job market for computer programmers growing? . . . . . . . . . . . 21.2 Why study C? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.1 Converting a binary number to a decimal number . . . . . . . . . . . . . . . . 222.2 Addition and Subtraction with binary signed numbers . . . . . . . . . . . . . . 235.1 Why study a language like C? . . . . . . . . . . . . . . . . . . . . . . . . . . 795.2 Avoiding the Six Most Common Programming Errors . . . . . . . . . . . . . . 855.3 Steps to Writing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . 925.4 Six Most Common Programming Errors . . . . . . . . . . . . . . . . . . . . . 955.5 Steps for Writing a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
xv
-
xvi LIST OF SUPPLEMENTAL MATERIAL
-
Acknowledgements
Colleagues in the Departments of Computer Science and Software Engineering
Student editorial team
Freshmen students of CS110
Wife and friends
xvii
-
xviii ACKNOWLEDGEMENTS
Now to Him who is able to dofar more abundantly thanall that we ask or think,according to the power
at work within us,to Him be glory
Eph 3:20
3:20
-
Acronyms
AEC ASEAN Economic Community. 4
ASEAN Association of Southeast Asian Nations. 4
CPU Central Processing Unit. 9
IDE Interactive Development Environment. 29, 31
xix
-
Chapter 1
Introduction
Learning to write programs stretches your mind, and helps you think better,creates a way of thinking about things that I think is helpful in all domains.
Bill Gates, co-founder of Microsoft
Coders change the world. They build new, amazing things faster than everbefore. Anyone with imagination can learn to write code.
Jeff Wilke, computer developer
1.1 Why study programming?Every year there are new computer applications in every field of human endeavour and theirnumber grows an ever increasing rate. In fact, it is very difficult to find a career where someapplication of computers has not had a significant impact. Despite all this development, thereis growing need for new solutions and new applications in every field. However, all computersoftware are limited in part by the nature of its creators particularly in regards to their under-standing of the problem, their abilty to quickly develop reliable software and their creativity inproviding a meaningful and pleasant user experience. Wile basic understanding of programmingmight be sufficient to extend the usefulness of some software systems, computer programmersare needed to develop the software to the point where significant increases in speed, reliabilityand functionality needed to meet the expectation of users.
As the global market continues to demand newer, faster and more powerful applications, theneed for computer programmers to develop this software continues to grow as well. Computerprogramming has become an essential and highly marketable skill within the global economy.In fact, the demand is so high that such those with programming skills are usually able createa career in the location and problem domain of their choosing. Thus, the job market for thosewho can program is very good and is expected to continues to grow world wide over the newseveral decades.
1
-
2 CHAPTER 1. INTRODUCTION
Figure 1.1. The estimate of the unfilled computer programming jobs in the United States.[1]In the past decade, the number of computer programming students has not grown to meetthe demand for new software creating a serious world-wide shortage of programmers. Atthe same time the amount of data online has literately exploded with millions of new photo-graphics uploaded, tens of millions of new webpages created, and billions of tweets and textmessages creating a need for new ways to create, transmit and manage this information. Inaddition, the omputer technology has grown with the development of faster, cheaper pro-cessors, new mobile computing devices and increased use of embedded microprocessors.
As shown in Figure 1.1, it is estimated that 1 million programming jobs go unfilled eachyear in the United States.[1] The world-wide shortage is estimated to be closer to 2 mil-lion,[2] creating new opportunities for small, local software companies to develop for theinternational market.
1.2 Overview of this courseThe purpose of this course is to provide both the background and the skills for developing com-puter programs that solve problems. The aim is to develop fluency with the major conceptsof programming computers that allow one to design, develop and test sequences of steps re-quired to create software that solves problems. As shown in Figure 1.2, this introductory courseat Payap University is the first course for Computer Science majors offered by the ComputerScience Department and acts a prerequisite to all other courses within the department.
Readings, homework problems, lab exercises and programming assignments have been de-veloped to provide understanding the nature of five factors essential to effective computer pro-gramming:
The problem to be solved: At the heart of all computer programs is a basic problem to besolved. This is true regardless of whether one is playing a game, attempting to developand transmit an email message, playing a audio-visual media clip, drawing a picture orprinting a report.
-
1.2. OVERVIEW OF THIS COURSE 3
Figure 1.2: Sequence of Computer Science Courses in Prerequisite Order
Input: The incoming stream of data. The computer depends on sensors and/or input data de-vices like the mouse or the console keyboard to provide the context and parameters of theproblem to be solved.
Algorithm: The data processing procedures. The computer depends on the programmer tocapture and describe the core algorithm as a logical sequence of data transformationsrequired to convert the data input into useful information.
Output: The required response. The computer also depends on the program to describe thenature and design of the response. Depending on the application, this may come in theform of printed or displayed reports, or changes in the audio-visual channel output, or byactivation of motors, relays and solenoids.
The computer programming language: a limited set of instructions (vocabulary) and somebasic functions (or data processing methods) that can be combined using a specific syntax(or grammar) to create programs that return solutions.
The basic goal of this programming course is build the skill for developing and communicat-ing a sequence of steps within a program that command and control the actions of a computer.Computer programs generally acquire some basic data or input and then uses various functionsand procedures to process this information to develop a solution which governs the response oroutput of the computer. This is true regardless of whether the program is just a few commandsrunning on a microprocessor designed to monitor a sensor or as complex as the intensive parallelprocessing requiring millions of lines of code running concurrently on a network of computers.The basic principles on taught in this course will provide a firm foundation for developing abroad range of computer solutions.
-
4 CHAPTER 1. INTRODUCTION
Supplemental Material 1.2.Why study C?With over 1,000 programming languages in active use, why should one study the C lan-guage? There are some good reasons to learn to program in C:
1. C is a very stable language that has been around for over 40 years. This his-tory has resulted in optimized compilers and an extensive collection of libraryfunctions that produce efficient executable code as well as creating a verylarge body of source code.
2. C has become something of the lingua franca of programming. The C sourcecode can be very succinct and will compile to executable code that is similarin speed and size of code written in Assembly.
3. C has become the basis for many languages. The C library is used by manylanguages because compilers for other languages are written in C.
4. The nature of C is very close to that of microprocessors. It is relatively easierto demonstrate and explore techniques that manipulate pointers, bytes, andindividual bits. Attempts to optimize applications are more likely to work asexpected than applications written in higher level languages. Often constructsof higher level languages do not map closely to the implementation at themachine operation level.
5. C supports a wide range of programming projects. In fact C is the language ofchoice for developing operating systems, games, device drivers and even forcreating and extending compilers for other languages.
However, acquiring computer programming skills is similar to learning a foreign language.The computer programming student requires the ability to state instructions clearly as a logicalsequence of events using the limited vocabulary and grammar of a programming language. Atthe same time, student need to develop the ability to clearly communicate concepts, paradigmsand procedures to both the computer and to other programmers working on the same problem.The purpose of this book is to help the reader cultivate these disciplines which are in highdemand world-wide.
To this end, this book will attempt to help students by encouraging and supporting moderntechniques used in modern computer education such as active learning techniques, peer pro-gramming,[3] and bilingualism.[4] The objective is to help students in non-Anglophone partsof Association of Southeast Asian Nations (ASEAN) to acquire the basic computer program-ming skills and vocabulary needed to function effectively as professional programmers withinASEAN Economic Community (AEC). This Thai-English Diglot edition is an initial step to-wards this goal.
1.3 Organization of this bookEach chapter of this textbook represents another module in a college course that introducescomputer programming as a series of exercises to increase fluency and problem solving skills.
Chapter 2 - Computer Fundamentals: introduces the key building blocks of Computer Pro-
-
1.4. FEATURES OF THIS BOOK 5
gramming, starting with a basic understanding the components, data types and operationsof a primitive computer system. The role and purpose of high-level computer languagesare also introduced.
Chapter 5 - Creating a program: introduces the development of programs as a planned pro-cess using the Scratch programming language.
Chapter 4 - Program Design Tools: Introduces the art of designing and describing computerprograms. Various program design tools are introduced as well as the basic patterns andbuilding blocks of a program.
Chapter 5 - Introduction to the C programming language: The basics of programming inC including variables, control structures and subroutines/functions. The emphasis will beon development of software in C as an extension of the software design process. The useof compiler directives to support multi-platform development will also be covered.
Chapter 6 - Composite Data Types: The definition and use of aggregates of data will be in-troduced. These will include arrays, strings, user-defined data types such as enumerateddata, struct and unions.
Chapter 7 - File Processing: Interaction with files will be introduced starting with the estab-lishment of data stream handles. Sequential, random access and block file input/outputwill be covered.
Chapter 8 - Pointers: The concept of address pointers will be introduced as well as their prac-tical application in function parameters, and arrays processing. The definition and use ofarrays of pointers of both functions and data will be covered.
Chapter 9 - Software Engineering Paradigms: This chapter will take a closer look at thesoftware development process. Various techniques for ensuring rapid development oftested software such as agile programming, module development, and unit testing will beintroduced. The use of makefiles and version control software to monitor and encour-age progress will also be covered. Structured programming will be contrasted with otherprogram structures such as object-oriented, event-driven and parallel/concurrent program-ming paradigms.
Appendix A - Software installation: This section will cover the downloading and installationof the open-source software introduced in this course.
Appendix B - Programming in Scratch: In this section, the contents of Chapter 5 have beenadapted for the Scratch programming language to provide a more graphic and visual ap-proach to this material.
Appendix C - Quick reference guides to C and Scratch: A concise description of the C andScratch programming languages have been included as a resource.
1.4 Features of this bookIn this electronic age of textbooks, students expect a growing range of learning helps and guidesto assist their study. This book was designed as both a hypertexted electronic document and a
-
6 CHAPTER 1. INTRODUCTION
printed book including the following features that are standard in English textbooks world-wide,namely:
Translated text The diglot rendering of the text is provided to help studentsbetter understand concepts and provide a richer set of key words for searching inGoogle.
Chapter reviews The key words used in the chapter are listed in this section tohelp students review the material covered in the chapter. covered. This providesa checklist of the topics covered.
Exercises Most of these exercises were designed to build on examples given inthe text and provide and opportunity for developing understanding and skill. Thequestions often appear on exams and in interviews while applying for employmentor graduate school. The answers are primarily code fragments and short answers.
Lab exercises These are projects that will require a software program to bedeveloped. The benefit of these exercise is maximized when students work ontheir own and search to find their own solutions.
Discussion questions These questions are meant to provide a broader context andapplication of the topics covered in the chapter. Many of these questions requirean essay and/or flowchart to answer.
Supplemental Materials Related stories given in parallel text units which aremeant to help provide depth in the material presented without interupting the maintrain of thought. Many of these stories provide additional information from theprespective of history or practical application.
Cartoons Line drawings help to provide humor and comic relief for what could beconsidered a heavy subject. The original line drawings are vector graphics createdwith Inkscape.
Code examples The text is peppered with numerous code fragments to thatillustrate a particular programming paradigm or technique. Line numbers havebeen added to assist in reference specific code expression in the correspondingsection of text.
Installation of open-source software Appendix 2.9 contains the instructions fordownloading and installing software used in this book. Although the instructionswere updated at the time of publication, it is possible that newer versions mayexist but they should also work well for use in this programming course.
See alsoSection A.1
Cross-references and hypertext links This books makes full use the cross-references, citations and indexing functions of LATEX. In the PDF version of thisdocument, all references have been converted to hyperlinks making it even easierto find information.
Online exercises, quizzes and activity This course is taught at Payap Universityusing Moodle to deliver classroom handouts, assignments and course content.The online version of this course also contains slides, assignments, lab exercises,and quizzes that correspond to sections of this book. Many of these are
auto-correcting. The contents of these web resources are available to teachers of otherinstitution from the author.
-
Chapter 2
Computer Fundamentals
Computers are good at following instructions,but not at reading your mind.
Donald Knuth, computer science professor
People who are more than casually interested in computers should have atleast some idea of what the underlying hardware is like. Otherwise the
programs they write will be pretty weird.Donald Knuth, computer science professor
Programming is 10% science, 20% ingenuity,and 70% getting the ingenuity to work with the science.
Anonymous
Design is a funny word. Some people think design means how it looks andwhat it feels like. But of course, if you dig deeper, it's really how it works.
Steve Jobs, co-founder of Apple Computers
2.1 Main Components of a Computer System
Current computer technology is the result of developments in distinct 3 streams of activities: (1)building more portable, powerful interconnected machines (hardware), (2) creation of softwareapplications, data and resources that provide services which are relevant, useful and desired(software), (3) establishing a user experience and establishing a workspace in which the user iscomfortable and feels in control (peopleware). Each of these streams are further explained inthe following sections.
7
-
8 CHAPTER 2. COMPUTER FUNDAMENTALS
2.1.1 HardwareHardware generally refers to the physical parts or components of a computer that require power.They would include keyboard, mouse, monitor, keyboard, and all other physical objects thatcan be touched. Figure 2.1 illustrates the 4 basic groups of hardware components that makeup a typical computer system. These hardware components can be found even in small mobilecomputing devices.
Figure 2.1: Basic hardware components of electronic computers
Input devices are used to collect and recieve data entering the computer as input. Informationis collected using devices like electronic mice, touch pads, keyboards, scanners, barcodereaders, cameras, microphones, multitouch surface and a wide range of other sensors.Each of these devices have the ability to interupt to cpu to ensure that incoming data iscaptured and processed before it can be lost. In recent years, computers have equippedwith global positioning sensors (GPS), motion sensors, and acclerometers, as well as prox-imity and temperature sensors to better detect the activities and intentions of its users.
Input devices often use an interface to translate captured signals into a data streamthat be read by the processor. In this way, movement of a mouse is understood by theprocessor as a request for movement of the cursor to a particular location or a keystrokeof a key located at a particular row and column on a keyboard is interpreted as the inputof a particular character.
Output devices are used to display and communicate results to the user in the form of out-put that can be seen, felt and heard. This is achieved using monitors, printers, speakers,and vibrators. Like input devices, interfaces are needed to translate binary values intosignals that trigger the corresponding devices. For example, audio devices translate am-plitude into analog signals that drive speakers and video monitors convert values into theamplitude of the primary color circuits for each pixel or dot.
Memory is used to store information and is available within a computer system in multipleforms of varying size and speed. Within a computer system, memory is used to store
-
2.1. MAIN COMPONENTS OF A COMPUTER SYSTEM 9
both information and program instructions. Table 2.1 gives the standard units used formeasuring the quantities of memory.
Table 2.1: Size of memory
Prefix Symbol Number of bytes English wordbit b 1/8 1/8 one eighth bytenibble - 1/2 1/2 one half bytebyte b 20 1 one byteword w 21 2 two byteslong word lw 22 4 four byteskilobyte KB 210 103 thousand bytesmegabyte MB 220 106 million bytesgigabyte GB 230 109 billion bytesterabyte TB 240 1012 trillion bytespetabyte PB 250 1015 quadrillion bytesexabyte EB 260 1018 quintillion byteszettabyte ZB 270 1021 sextillion bytesyottabyte YB 280 1024 septillion bytes
Central Processing Unit (CPU) is the component that picks up data and manipulates it beforetransfering the results to other system components according to a pre-established set ofinstructions.
Figure 2.2: Bus line communications between the microprocessor and internal memory.
Processors have limited number of high speed registers which are used for storing andmanipulating data. Most processors have fewer than 12 registers which may be between
-
10 CHAPTER 2. COMPUTER FUNDAMENTALS
4 and 128 bits long depending on the processors used. Memory chips wired to the dataand address buslines of the motherboard of processors provide a means for storing and re-trieving gigabytes of information. Processors can also transfer information from memoryto and from peripheral memory devices such as hard drives, memory tapdre ives and DVDreaders/writers. Hard drives can now manage tetrabytes of information. More recently,processors can address even more data using the banks of memory devices connected tothe Internet Cloud, allowing access to petrabytes of information at a rate of speed that iscontrolled by the bandwidth of the Internet connection.
Colossus Mark 2 codebreaking computer,19431
ENIAC used for calculatingartillery firing tables, 19462
Figure 2.3: Early electronic computers.
As shown in Figure 2.3, the electronics of the earliest CPUs occupied several cabinetsthe size of a room. Colossus Mark was the world's first electronic digital computer. TheColossus computers were used by British codebreakers during World War II to help in thecryptanalysis of the Lorenz cipher. However, programming the Colossus required settingswitches and plugging in jumper wires. Data was read from patterns of holes punched inpaper tape.
The Electronic Numerical Integrator And Computer (ENIAC) was the world's first elec-tronic general-purpose computer launched in 1946 by the United States Army's BallisticResearch Laboratory. The ENIAC was designed to calculate artillery firing tables used todetermine the range of projectiles. It was Turing-complete, digital, and capable of beingreprogrammed to solve a full range of computing problems. This programmable com-puter excited scientists and industrialists because of its flexibility to apply tremendousmathematical power to solve a wide range of problems.
These early computers used vaccuum tubes to perform all Boolean operations and math-ematical calculations. Despite their size, these computers had the ability to address ap-proximately 30 bytes of memory, 2 registers and could support about 100 operations persecond from a very a limited setr of operators. (Operations like multiplication and divisionrequired special programming.) Today the typical CPU can perform billions of operationsper second, address trillions of bytes of information with a wide range of functions. Thecircuit has been reduced to fit a single microprocessor chip that is less than 5mm across.
1The National Archives Document Record FO850/234, United Kingdom, 19432K. Kempf, U.S. Army Photo, 1946
-
2.1. MAIN COMPONENTS OF A COMPUTER SYSTEM 11
Most modern microprocesssors increase performance by using multiple processors work-ing in parallel within the same chip as shown in Figure 2.6.
Figure 2.4: Photomicrograph of Intel 8080 introduced in 1974.[5]
Figure 2.4 clearly shows the patterned texture seen in photomicrographs of micropro-cessors. Each patterned segments represents are a collection of various micro digital cir-cuits designed to be activated and perform specific functions within the microprocessor.These operations fall into the following categories:
Operations of the Program Control System which includes: Fetch and decode the next program instruction Set corresponding bit flags depending on the outcome of the instruction. Update the program instruction pointer to the location of the next instruction
Operations on Data Registers Fetch data from the location of external memory specified by the address bus
using the data bus conduct the data into the internal registers Manipulate the data within its internal data registers Test the nature of data held in the data registers Transfer the data from its internal data registers back to the data bus for storage
at the location specified on the address bus.
In the race to produce faster computers, there are two distinct approaches that havebeen used to improve the preformance.
Reduced instruction set computing (RISC): Microprocessors of this type are reallyfast because they have a limited minimal number of instructions which reducing the
-
12 CHAPTER 2. COMPUTER FUNDAMENTALS
IBM PowerPC RISC microprocessor Intel Pentium CISC microprocessor
Figure 2.5: Photomicrographs of popular microprocessors produced in 1993[5]
need for extensive decoding of of each command instruction. These chips generallyrequire less power making them ideal for mobile devices. A photomicrographs ofIntel Pentium RISC microprocessor is shown in the left panel of Figure 2.5.
Complex instruction set computing (CISC): Microprocessors of this type have a verylarge number of functions built into the chip. A photomicrograph of the Motorola68000 CISC microprocessor is shown in the right panel of Figure 2.5. The pur-pose is to reduce the number of instructions needed to perform complex operationssuch as high speed graphics processing, floating point mathematics, data compres-sion, global positioning and other forms of signal processing. While individual com-mands may be slower than RISC device, the theory is that fewer commands wouldbe required by an application.
In the past decade, the trend has been to add multiple processors or cores to the micropro-cessor chip. While each of these cores have access to all the hardware resources of thecomputer, they work independantly. The operating system coordinates the allocation oftasks or processes to the individual processors on the chip. Multicore parallel computinggreatly improved the hardware support of multitasking allowing users to run more ap-plications simultaneously such as listening to music and uploading pictures to Facebook,while replying to a Facebook message while doing homework in Microsoft Word. Figure2.6 shows a photomicrograph of a Intel microprocessor that contains 4 cores.
In 1965 Gordon Moore observed that the number of transitors per chip seemed to doublenearly every 18-24 months. Moores Law states that the density of transistors doublesevery 18 to 24months. The actual growth in the number transitors per microprocessorchip are given in Figure 2.7. This has meant that for the past 40 years, processors havenearly doubled in speed and capacity as well while reducing power comsumption. Italso has driven the world-wide business practice of replacing computers every 3-5 yearscreating mountains of old discarded computers that noone wants.
-
2.1. MAIN COMPONENTS OF A COMPUTER SYSTEM 13
Figure 2.6: A photomicrograph of the Intel iCore7 quad core microprocessor[5]
ll llll
ll l
l llll
l
ll
l lll l
lll ll
ll ll
l lll ll
l l lll lll ll l l
l ll l lll
1970 1980 1990 2000 2010
45
67
89
Increase in the Number of Transistors in a Microprocessor Chip
Year
Num
ber o
f Tra
nsi
stor
s pe
r chi
p (Lo
g10)
Figure 2.7: 47 Years of Moore's Law[6]
-
14 CHAPTER 2. COMPUTER FUNDAMENTALS
2.1.2 SoftwareSoftware includes everything that can be held in memory, stored for later use in retrieval. Thereare 2 basic categories of software:
Program code: sequences of instructions. At the machine level, program code is a sequenceof binary numbers that correspond to operations that take place within the CPU. Regard-less the language used, size or complexity of the program, every program must providedevelop a detailed description of the process by which a solution can be found usingavailable information and computing resources. Good programs execute in reasonabletime, produce correct responses and are understood by the computer, the users and otherprogrammers.
Boot loader: a series of functions whose purpose is to check the hardware and load anappropriate version of the operating system. This is activated whenever a computeris turned on or reset.
Operating system (OS): a collection of functions that manage processes and appli-catons running on a computer. It also provides system calls to the Graphic UserInterface (GUI) and the Basic Input/Output Systems (BIOS). Examples of modernoperating systems written in C include UNIX, Solaris, Linux, BeOs, Solaris, andAndroid.
Applications: games, office, software compilersutilities Libraries of functions: mathematics, statistics Drivers for I/O devices:
Data: information handled by the program
Documents: Text, Hypertext, e-Book Media: Audio, Video, Graphics: photographs, fonts, icons, avatars Data sets: business accounts, research data, Information: maps, spelling/translation dictionaries Personal information: account and passwords, history, correspondence, email and
text messages, contact addresses, bookmarked favorites, configurations and prefer-ences.
2.1.3 PeoplewarePeopleware has be used to describe all components and services designed to make the user ex-perience easier to understand and use. It also addresses such issues as developer productivity,teamwork, group dynamics, the psychology of programming, project management, organiza-tional factors, human interface design, and human-machine-interaction.Peopleware generallycomes in one the following forms:
Awareness campaigns: Various events and services to launch a product and make the benefitsand capabilities of the technology known.
-
2.1. MAIN COMPONENTS OF A COMPUTER SYSTEM 15
Hiring experts to promote the adoption and use of new technology: These promotersare often seen at trade shows or professional meetings and often carry the job titleof Evangelist, Consultant, or Developer.
Providing venues for early adoptors to demonstrate the benefits of using new tech-nology, such as Seminars, Webinars, Road shows, and Show rooms open house
Providing hands-on training in the use of the technology through seminars, work-shops, and online user training
Standards: attempts to simplify and provide uniformity in the production, use and commu-nication of technology, particularly by establishing common principles that governs thenature and behaviour of the technology.
Hardware standards: designing the physical characteristics of a device in order tolimit the possibility for damage to the device to occur because of misconfigurationor by faulty hardware. This includes the use of colors, shapes, and sizes used in thearray of input/output ports of computers. The ports on the back of a standard PCdesktop computer are shown in Figure 2.8. This design scheme helps users to figureout how the equipment is put together with minimal training and error.
Figure 2.8: Hardware standards for PC I/O ports
Hardware standards also cover the internal components of computer in numerousways: the size and shape of connectors. the voltages and electrical current require-ments of components, the electrical protection mechanisms, pin and lead assign-ments of all connectors, and the control behavoir and timing of all interaction thattakes place on the address and data buslines.
Interface behavior: Users have come to expect particular behaviour from GraphicUser Interafaces (GUI). For example, Warning messages are displayed in Red, But-tons are meant to be clicked to activate a function, and tabs of pull down menus arelocated near the top of screen. Confusion can result if the wrong color, object shapeand location is chosen.
Data standards: Because data is often used for multiple applications, data standardsare used to facilitate the exchange and sharing of information. XML, CSV, andSQL are commonly used to stored structured data in files. ASCII, TIS620, andUTF8 are commonly used to identify the individual characters of text. Viewersrequire graphics to conform to on of a limited number of graphics standards such asPNG, JPEG, GIF or SVG. The current trend in software development is to use opendata and file standards because these standards are best supported and are upwardcompatible with future revisions of that standard.
-
16 CHAPTER 2. COMPUTER FUNDAMENTALS
Software standards: In the past several decades of computer development, therehas emerged a concensus on how softare should behave. Each of these standardsis meant to preserve user data and minimize data loss due to mistakes or programerrors. The following is a list of common standards of software behavior.
Ask the user to confirm the intent to delete information before deleting a file. Check with the user when attempting to close a program when there is unsaved
data still in memory Editing functions should contain the ability to undo and redo changes to a dataset. Editing software will automatically save a shadow copy of the working copy
every couple of minutes to prevent data loss in the event that the applicationterminated unexpectedly.
A backup file is created everytime a file is updated.
Documentation: Software companies publish and distribute resources to provide users anddevelopers with in-depth information about the nature, application and use of the tech-nology.
Installment charts and guides: Simple step by step instructions to help users startusing the new software.
User manuals and howto guides: Initially users tend to develop a few essential skillsunaware of the bredth of functions that have been designed into the computer soft-ware. The purpose of these documents is to provide users with the ability to discoverand use the full range of functions provided by the software.
Online support pages: Ongoing support for technology is provided via web pagesand video clips. This is often facilitated by contributions from the user community.
User Support: development of a satisfied user community by addressing issues that individualusers are having with the computer technology.
Active communications: These services provide the user with the ability to commu-nicate with a real people via chat, email, bulletin board or voice.
Services: Occasionally users will require an expert to help them to effect repairor installation of technology. Companies often employ subcontractors to providesupport facilities in remote locations.
User community support: User groups tend to be useful and helpful in promotingsoftware and in developing new applications and functions. Software houses likeAdobe have discovered that users very creative and effective in motivating otherusers to adopt, adapt and develop software. This is often accomplished using FAQ,email groups, Facebook, Twitter, and/or Bulletin boards.
Bug tracking: All software is prone to bugs especially as users use it for purposesfor which it was not designed. Bug trackers help users to follow the progress ofthe fixing of reported bugs. In addition, websites are often provided to help dis-tribute official software patches and updates and well as contributions from the usercommunity.
-
2.2. KEY INGREDIENTS OF GOOD COMPUTER PROGRAMMING 17
Figure 2.9: Successful technology comes with good technical support.
2.2 Key Ingredients of Good Computer ProgrammingThe invention of computing devices, computer applications and services have all been drivenby a need to solve specific problems. To this end, computer software attempts to provide basicbackground information and a description of the steps in the process for finding a solution. Goodcomputer programs make effective use of the resources and capabilities of computers as theyaccept and process input in order to produce some appropriate response. The nature of effectiveprograms is the result of careful and deliberate design choices within each of the areas describedin the sections that follows.
2.2.1 Algorithms employed
Algorithm provide a description of the sequence of operations needed to solve a problem. Intheory, efficient and effective algorithms attempt to use minimum amounts of memory to solveproblems in minimum time. but the reality for most problems solved by computers is thatthere is an inverse relationship between the amount of memory used and the computationaltime required. In addition, there are often several ways to accomplish the same thing but each
-
18 CHAPTER 2. COMPUTER FUNDAMENTALS
method will have its strengths and weaknesses. For example, the quicksort method of sortingis known for its speed in sorting arrays of items in random order but if the elements in the arrayare already presorted the performance can be poor.
Therefore, programmers need to be able to study an algorthm to identify that the methodused is appropriate for the application in that it will produce correct output, in reasonable timewhile putting reasonable demands on the key computing resources of cpu time and internalmemory.
2.2.2 Nature of man-computer interactionThe value of a computer program to solve problem depends greatly on the ease by which theproblem can be of described and the solution understood. In a similar way, the popularlityof the technology depends on user-friendliness, and the nature and aesthetics of the interactionbetween man and machine. Both input and output need to be organized in a format and sequencethat seems locical to the user even if processing of this information would require a differentorder. Because a good interface needs to be easy to learn, acts in predictable ways and useconventions that are intuitive and easily understood by the user, end users are often part of thesoftware development team. In fact, companies like Apple and Samsung are famous for usingchildren and other naiive users to actively test the user friendliness of their products.
Figure 2.10: Children's Product Table at the Apple Store in Singapore
2.2.3 Programming language selectedThe entire sequence of operations that comprise a computer program must be encoded within theinstruction set of a given programming language chosen. There are literally thousands of com-puter languages in current use and each language was designed for creating a particular range ofapplications to address problems in specific problem domains. Figure 2.11 shows the origins ofthe most popular languages in use. Each language represents a different set of instructions andsyntax. Although it generally takes a month or two for experienced programmers to becomefluent in a new language, most programmers are proficient in 3 or 4 computer languages whichthey use regularly.
The central processing units of computers use binary numbers for all steps of each opera-tions: to determine the addresses of the data and the code of the next operation, the values ofthe data, the nature of the operation to performed and the memory location to store the result.
-
2.2. KEY INGREDIENTS OF GOOD COMPUTER PROGRAMMING 19
Figure 2.11: Origins of common computer languages. (Adapted from Pixel[7]
However, this is too complicated for human programmers. The purpose of computer program-ming languages is to allow the programmer to use a simpler language to express commands thatcan be translated into the binary language native to the central processing units. Each computerlanguage approaches this process differently.
Compiled languages translate the source code into native code that is saved as an ex-ecutable program file which can be run at a later time without any further translation.Examples include C and Forth. Migration to a different cpu will require recompiling ofthe source code.
Interpreted languages read, interpret and execute the source code expression by expres-sion. This process is repeated until all instructions of the source code have been com-pleted. Applications written in these languages tend to run slower than written languagesthat compile to native code.. Examples include scripted languages like Perl, Python andRuby.
Hybrid systems compile source code into the native code for a virtual machine. Thiscompiled code requires an interpretor to execute this code on specific processors. Thisapproach allows software to be compiled once and then used on the range of hardware forwhich virtual machine interpretors are available.
Some languages require the commands to be compiled and saved as native code before itcan be run. that can be executed Some of the most popular, open-source computer languagesare listed in Table 2.2.
The keywords associated with each language establishes the basic vocabulary of that lan-guage. Each keyword is reserved to represent a particular core concept built into a language and
-
20 CHAPTER 2. COMPUTER FUNDAMENTALS
Table 2.2: A Short List of Popular Open-Source Computer Languages
Name DescriptionC a small compiled language that produces machine-native code that
is compact and fast.Forth a small compiled stack oriented language often used for motor con-
trol and boot loaders.Java a general purpose language that compiles programs that can be run
on a wide range of computers and mobile devices.Javascript a scripting language that is embedded in webpages and runs on most
browsers.LATEX a macro language designed to typeset a wide range of documents that
includes slides, handouts, articles, thesis, and books.Lisp a stack oriented scripting language used for text processing and arti-
ficial intelligenceOctave A matrix oriented mathematical programming language used for en-
gineering applications.PHP A general purpose embedded scripting language used for developing
web-based applications.Python a general purpose scripting language often used for developing pro-
totypes of applications that use mathematics, artificial intelligence,and linguistics and natural language processing.
R a script language that supports a wide range of data analysis includ-ing forecasting, graphics, modelling, and statistics.
Ruby an object-oriented scripting language used for web site developmentand computer system programming.
generally cannot be redefined to represent variables or methods. Table 2.3 shows the numberof keywords for some computer lanugages.
Table 2.3: Keyword Count of Some Computer Languages
Number of % Overlap of Keywords Between LanguagesLanguage keywords Processing Scratch Java C ArduinoArduino 27 100C 32 100 -Java 54 100 - -Processing 56 100 - - -Scratch 80 100 - - - -
2.2.4 Data representationsAll modern computers are designed as binary devices that reduce all processes to sequences of1's and 0's. Therefore, all data must be represented in some binary format regardless of whetherthe data is being entered as input, or stored and manipulated internally, or displayed as someoutput response.
The individual bits of a byte can be used to represent the state of a collection of sensors such
-
2.2. KEY INGREDIENTS OF GOOD COMPUTER PROGRAMMING 21
Figure 2.12: Bits can be used to monitor individual sensors or combined to store a number usingpowers of 2.
as parallel printer port status shown in Figure 2.12. A single byte is capable of monitoring 8bits of information which could correspond to the On/Off State of 8 sensors.
Bits can also be combined as a sequence of binary digits each representing a value of aincreasing different power of 2. The sum of the bit value times its corresponding value of itscorresponding power of 2 is used to is represent numbers as shown in Figure 2.13. Table 2.4gives a list of the values of the powers of 2 for each column of a binary number that is 32 bitslong.
In addition different bit patterns of binary numbers can be used to represent the different nu-merical data types. The following sections describe the primitive numerical data types directlysupported by processors within the computer.
Unsigned Integers
Generally, unsigned integers can be 8, 16, 32, 64 or 128 bits long and each bit represents a largerpower of 2. Thus a system with unsigned integers n bits long can respresent a range of numericalvalues between 0 and 2n1. Big-endian computers arrange the byte order of multi-byte binary
-
22 CHAPTER 2. COMPUTER FUNDAMENTALS
Figure 2.13. Converting the binary number 101001012 to its decimal equivalent of 165The basic process of converting between binary numbers and decimal numbers requirescreating the sum of the products between the decimal value of each binary digit and itsbinary value (either 0 or 1).
V alue =nXi=0
digitvaluei bitvaluei
Figure 2.13 illustrates the mathematics of this with the conversion of an 8 bit number intoits decimal equivalent.
Bit values: 1 0 1 0 0 1 0 1 101001012Powers 27 26 25 24 23 22 21 20
of 2: 1 1 = 10 2 = 0
1 4 = 40 8 = 0
0 16 = 01 32 = 32
0 64 = 01 128 = 128
Sum: 16510
Table 2.4: Powers of 2 represented by each binary digit of a 32 bit number
Exp Value Exp Value Exp Value Exp Value0 1 8 256 16 65,536 24 16,777,2161 2 9 512 17 131,072 25 33,554,4322 4 10 1,024 18 262,144 26 67,108,8643 8 11 2,048 19 524,288 27 134,217,7284 16 12 4,096 20 1,048,576 28 268,435,4565 32 13 8,192 21 2,097,152 29 536,870,9126 64 14 16,384 22 4,194,304 30 1,073,741,8247 128 15 32,768 23 8,388,608 31 2,147,483,648
numbers starting with the byte that contains the most significant bits first. Little-endian systemsstart with the byte containing the least significant bits. The value of the bits of a 8 bit numberare shown below.
27 26 25 24 23 22 21 20
Signed Integers
The most significant bit is used to represent the sign of the number where 0 is a positive numberand 1 is a negative number. Positive numbers are represented as unsigned integers. Negetativenumbers are represented as 2s complement of the unsigned number. Signed numbers n bits longcan represents a range of number between 2n1 and 2n1. The 16-bit representation of somesigned numbers are given below:
-
2.2. KEY INGREDIENTS OF GOOD COMPUTER PROGRAMMING 23
Supplemental Material 2.2.Addition and Subtraction with binary signed numbersAddition of two numbers is achieved by adding each digit starting with the least significantone. If the result equals 2 the zero is recorded and 1 bit carry is added to the next column.
Decimal Binary Binary additionAddition Addition with carries marked
0 0 1 1 1 1 0 0 (carry values)15 00001111 00001111
+ 22 + 00010110 0001011037 00100101 00100101
Decimal equivalents: 32+4+1 = 37Substraction is achieved by adding the first number to the 2s complement of the secondnumber. The 1s complement is calculated by inverting the zeros and ones of a number. The2s complement is the result of adding 1 to the 1s complement.
Decimal Addition of 2s Addition withAddition Complement carries marked
1 1 0 0 0 0 0 0 (carry values)37 00100101 00100101
- 22 + 11101010 1110101015 00001111 00001111
Decimal equivalents: 8+4+2+1 = 15
Table 2.5: Binary representation of some signed numbers
Positive Numbers Negetative NumbersDecimal Binary Representation Decimal 1s complement 2s complement
1 0000000000000001 -1 1111111111111110 111111111111111110 0000000000001010 -10 1111111111110101 1111111111110110
170 0000000010101010 -170 1111111101010101 1111111101010110255 0000000011111111 -255 1111111100000000 1111111100000001
Floating point or real numbers
A float point number N is represented as the product of the sign s, a binary fraction f and 2raised to the power of exponent e which mathematically is described as N = s f 2e.
The IEEE Standard for Binary Floating-Point Arithmetic is the most common among thefloating point representations that exist. Within this standard, e is within the range of Eminto Emax and fractions are generally normalized so that the leading bit equals 1. However, fornumbers smaller than Emin, the fraction begins with a corresponding number of leading zeros.Exponents are stored as unsigned numbers which result from adding the bias to the exponent.Binary formats for single and double precision floating point numbers which are shown in Table2.6.
-
24 CHAPTER 2. COMPUTER FUNDAMENTALS
Table 2.6: Bit allocation within an IEEE floating point number
Number Sign Exponent FractionBit size bit bits Emin Emax Bias bits32 bits 1 8 -126 127 127 2364 bits 1 11 -1022 1023 1023 52
Character codes
Although most CPUs use integers to represent individual characters, graph processing units andmonitor circuits require standards to be able to look up and display the specific shapes associatedwith characters. In 1963 the American Standards Association published the American StandardCode for Information Interchance which has been abbreviated as ASCII. This standard specifiesthe code values of 128 character of which 95 are printable characters and 33 are non-printingcontrol characters used to control serial data communications of teleprinters. This quickly be-came the most common character code standard for Roman characters. Table 2.7 illustates howsequences of bit values can be used to designate the value of binary, octal, hexidecimal anddecimal numbers as well as ASCII characters.
In 1990 The Thai Industrial Standards Institute published the Thai Industrial Standard 620-2533 which is know internationally as TIS-620.[8] This national standard defined an 8-bit stan-dard for encoding Thai characters as an extension of the ASCII character set. The characters arearranged in alphabetical order to facilitate the sorting of Thai words. However, this characterset was not compatiable with codepages used to encode Chinese and Japanese text.
However, UTF-8 was introduced in 1993 at the USENIX conference as a means to encodemultiple multibyte character. Because UTF-8 encodes all of the 1,112,064 code points of theUnicode standard, UTF-8 can be used to encode text files and web pages that contain multiplelanguages of diverse scripts such as Arabic, Chinese, Japanese, Korean and Russian. EvenHierglyphic Egyptian characters are supported by the Unicode standard. The Thai charactercode points for both TIS-620 and UTF-8 standards are given in Table 2.8.
-
2.2. KEY INGREDIENTS OF GOOD COMPUTER PROGRAMMING 25
Tabl
e2.
7:Bi
nary
,Oct
alan
dH
exid
ecim
alan
dA
SCII
Char
acte
rRep
rese
ntat
ion
ofVa
lues
0to
127
Bina
ryO
ctH
exD
ecA
SCII
Bina
ryO
ctH
exD
ecA
SCII
Bina
ryO
ctH
exD
ecA
SCII
Bina
ryO
ctH
exD
ecA
SCII
0O
00x
00
NUL
1000
00O
400x
2032
SPC
1000
000
O10
00x
4064
@11
0000
0O
140
0x60
96`
1O
10x
11
SOH
1000
01O
410x
2133
!10
0000
1O
101
0x41
65A
1100
001
O14
10x
6197
a10
O2
0x2
2ST
X10
0010
O42
0x22
34"
1000
010
O10
20x
4266
B11
0001
0O
142
0x62
98b
11O
30x
33
ETX
1000
11O
430x
2335
#10
0001
1O
103
0x43
67C
1100
011
O14
30x
6399
c10
0O
40x
44
EOT
1001
00O
440x
2436
$10
0010
0O
104
0x44
68D
1100
100
O14
40x
6410
0d
101
O5
0x5
5EN
Q10
0101
O45
0x25
37%
1000
101
O10
50x
4569
E11
0010
1O
145
0x65
101
e11
0O
60x
66
ACK
1001
10O
460x
2638
&10
0011
0O
106
0x46
70F
1100
110
O14
60x
6610
2f
111
O7
0x7
7BE
L10
0111
O47
0x27
39'
1000
111
O10
70x
4771
G11
0011
1O
147
0x67
103
g10
00O
100x
88
BS10
1000
O50
0x28
40(
1001
000
O11
00x
4872
H11
0100
0O
150
0x68
104
h10
01O
110x
99
TAB
1010
01O
510x
2941
)10
0100
1O
111
0x49
73I
1101
001
O15
10x
6910
5i
1010
O12
0xa
10LF
1010
10O
520x
2a42
*10
0101
0O
112
0x4a
74J
1101
010
O15
20x
6a10
6j
1011
O13
0xb
11VT
1010
11O
530x
2b43
+10
0101
1O
113
0x4b
75K
1101
011
O15
30x
6b10
7k
1100
O14
0xc
12FF
1011
00O
540x
2c44
,10
0110
0O
114
0x4c
76L
1101
100
O15
40x
6c10
8l
1101
O15
0xd
13CR
1011
01O
550x
2d45
-10
0110
1O
115
0x4d
77M
1101
101
O15
50x
6d10
9m
1110
O16
0xe
14SO
1011
10O
560x
2e46
.10
0111
0O
116
0x4e
78N
1101
110
O15
60x
6e11
0n
1111
O17
0xf
15SI
1011
11O
570x
2f47
/10
0111
1O
117
0x4f
79O
1101
111
O15
70x
6f11
1o
1000
0O
200x
1016
DLE
1100
00O
600x
3048
010
1000
0O
120
0x50
80P
1110
000
O16
00x
7011
2p
1000
1O
210x
1117
DC1
1100
01O
610x
3149
110
1000
1O
121
0x51
81Q
1110
001
O16
10x
7111
3q
1001
0O
220x
1218
DC2
1100
10O
620x
3250
210
1001
0O
122
0x52
82R
1110
010
O16
20x
7211
4r
1001
1O
230x
1319
DC3
1100
11O
630x
3351
310
1001
1O
123
0x53
83S
1110
011
O16
30x
7311
5s
1010
0O
240x
1420
DC4
1101
00O
640x
3452
410
1010
0O
124
0x54
84T
1110
100
O16
40x
7411
6t
1010
1O
250x
1521
NAK
1101
01O
650x
3553
510
1010
1O
125
0x55
85U
1110
101
O16
50x
7511
7u
1011
0O
260x
1622
SYN
1101
10O
660x
3654
610
1011
0O
126
0x56
86V
1110
110
O16
60x
7611
8v
1011
1O
270x
1723
ETB
1101
11O
670x
3755
710
1011
1O
127
0x57
87W
1110
111
O16
70x
7711
9w
1100
0O
300x
1824
CAN
1110
00O
700x
3856
810
1100
0O
130
0x58
88X
1111
000
O17
00x
7812
0x
1100
1O
310x
1925
EM11
1001
O71
0x39
579
1011
001
O13
10x
5989
Y11
1100
1O
171
0x79
121
y11
010
O32
0x1a
26SU
B11
1010
O72
0x3a
58:
1011
010
O13
20x
5a90
Z11
1101
0O
172
0x7a
122
z11
011
O33
0x1b
27ES
C11
1011
O73
0x3b
59;
1011
011
O13
30x
5b91
[11
1101
1O
173
0x7b
123
{11
100
O34
0x1c
28FS
1111
00O
740x
3c60
10
1111
0O
136
0x5e
94^
1111
110
O17
60x
7e12
6~
1111
1O
370x
1f31
US11
1111
O77
0x3f
63?
1011
111
O13
70x
5f95
_11
1111
1O
177
0x7f
127
DEL
-
26 CHAPTER 2. COMPUTER FUNDAMENTALS
Table2.8:The
ThaiCharacterSet
TISU
TFCharacter
TISU
TFCharacter
TISU
TFCharacter
TISU
TFCharacter
62016
Description
62016
Description
62016
Description
62016
Description
A1
E01
Ko
Kai
B7E17
Tho
ThahanCD
E2D
OA
ngE7
E47
Maitaikhu
A2
E02
Kho
Khai
B8E18
Tho
ThongCE
E2E
Ho
Nokhuk
E8E48
M
aiekA
3E03
K
hoK
huatB9
E19
No
Nu
CFE2F
Paiyannoi
E9E49
M
aithoA
4E04
K
hoK
hwai
BAE1A
Bo
Baimai
D0
E30
SaraAEA
E4A
Maitri
A5
E05
Kho
Khon
BBE1B
Po
PlaD
1E31
M
aihanakatEB
E4B
Maichattaw
aA
6E06
K
hoRakhang
BCE1C
Pho
PhungD
2E32
SaraA
aEC
E4C
ThanthakhatA
7E07
N
goN
guBD
E1D
FoFa
D3
E33
SaraAm
EDE4D
N
ikhahitA
8E08
Cho
ChanBE
E1E
PhoPhan
D4
E34
SaraIEE
E4E
Yamakkan
A9
E09
ChoChing
BFE1F
Fo
FanD
5E35
SaraIi
EFE4F
Fongm
anA
AE0A
Cho
ChangC0
E20
PhoSam
phaoD
6E36
SaraU
eF0
E50
ZeroA
BE0B
So
SoC1
E21
Mo
Ma
D7
E37
SaraUee
F1E51
O
neA
CE0C
Cho
ChoeC2
E22
YoYak
D8
E38
SaraUF2
E52
Two
AD
E0D
YoYing
C3E23
Ro
RuaD
9E39
SaraU
uF3
E53
ThreeA
EE0E
D
oChada
C4E24
Ru
DA
E3A
PhinthuF4
E54
FourA
FE0F
To
PatakC5
E25
LoLing
DF
E3F
BahtF5
E55
FiveB0
E10
ThoThan
C6E26
Lu
E0E40
E
F6E56
Six
B1E11
Tho
Nangm
onthoC7
E27
Wo
Waen
E1E41
A
eF7
E57
SevenB2
E12
ThoPhuthao
C8E28
So
SalaE2
E42
OF8
E58
EightB3
E13
No
Nen
C9E29
So
RusiE3
E43
AiM
aimuan
F9E59
N
ineB4
E14
Do
Dek
CAE2A
So
SuaE4
E44
AiM
aimalai
FAE5A
A
ngkhankhuB5
E15
ToTao
CBE2B
H
oH
ipE5
E45
LakkhangyaoFB
E5B
Khom
utB6
E16
ThoThung
CCE2C
Lo
ChulaE6
E46
Maiyam
ok
-
2.2. KEY INGREDIENTS OF GOOD COMPUTER PROGRAMMING 27
Chapter 2 Review
Key Terms:
algorithmbitbyteintegerexponentfloating pointinputmatissaoutputprecisionregistersigned integer
Discussion Questions:
1. Although the character codes in Thai character set given in Table 2.8 are assigned inalphabetical order, this is insufficient for sorting Thai words in alphabetic order. Describethe steps that would be needed to compare the sorting word of two Thai words.
2. Are children always good test subjects for all types of software products? What kind ofproducts would they be particularly good test subjects for? If Apple Computers did notuse children as part of their test stratgeties do you think their computers would be so easyto use?
Exercises:
1. Identify the byte wise value of the characters in the following words:
a. mat:b. cot:c. cat:d. Matt:e. code:f. cod:
Based on a left to right bytewise comparison of these code values, list thesewords in ascending sorted order.
, , , , , .
-
28 CHAPTER 2. COMPUTER FUNDAMENTALS
2. Calculate the 8 bit binary equivalents of the following numbers, and their 1s complements and2s complements:
a. 12:b. 35:c. 63:d. 96:e. 120:f. 126:
3. Calculate the decimal equivalents considering the following 8-bit binary numbers as both signedand unsigned:
Binary number Decimal number fromDecimal number fromBinary number an unsigned number a signed numbera. 00010101:b. 01010101:c. 01111001:d. 10000001:e. 10101010:f. 11111111:
Laboratory Exercises:
-
Chapter 3
Scratch Programming
If you don't know where you are going, any road will get you there.Lewis Carroll, author
A journey of a thousand miles begins with a single step.
Laozi, Chinese philosopher
3.1 Getting startedScratch is a programming language that was designed to teach programming principles in a waythat is easy to learn and fun to use. The Interactive Development Environment (IDE) allows theprogrammer to place objects on a stage and then provide instructions that will govern the reactionof these objects to events that occur. The outcomes of these instructions are animated providingthe programmer with instant feedback for evaluating the correctness of the code. While Scratchwas primarily designed for 8 to 16 year olds, it is also used by people of all ages, includingyounger children with their parents as well as freshmen students at various universities aroundthe globe.[9]
3.1.1 Interactive Development EnironmentScratch comes with a built-in interactive development environment (IDE) as shown in Figure.3.1. Within this environment, the programmer can select various backgrounds and objects tobe displayed and manipulated on stage. Programming is accomplished graphically by draggingprogram elements found in the left side of the screnn into the program editor window located inthe middle.
The Scratch programming language is distributed as an open source product to encourageinternational participation the development of this product. The designers of the InteractiveDevelopment Environment (IDE) for this language have built in support for over 45 languagesof the world. By clicking on the globe icon, it is possible to select a different human languagefor the interface and script programs. While Thai and English views of a simple Scratch will
29
-
30 CHAPTER 3. SCRATCH PROGRAMMING
Figure 3.1: Scratch Interactive Development Environment
appear in their respective languages (see Figure 3.2, the script program recorded internally isalways the same regardless of the language chosen for the human interface. In addition, thetranslation of program views does not effect the content of string of text. In this textbook, onlythe English interface will be used to help students make the transistion to other programminglanguages covered later in this book. However, some students have found it helpful to use thelanguage change feature to verify the meaning of their program scripts in the early days of theirstudy.
English interface Thai interface
Figure 3.2: Thai and English view of hello.scr
3.1.2 A first programEver since the launch of the C language, the starting point for learning a programming languagehas been centered on a simple problem: The need to demonstrate that it has understood programwe have written. A simple solution would be to establish a message in a string and then get the
-
3.1. GETTING STARTED 31
computer to transfer the string to the screen. Even though this program task uses no specialcontrol structures, it is an excellent test of whether the compiler or interpetor has been installedand is working. By tradition, the message is often the greeting "Hello, World!" and the programis often named hello. This hello program can be used as an early stage template for developingthe other programs.
Code Example 3.1 shows how this would be accomplished in the language of Scratch. Theleft panel shows the code. Because Scratch is an interpreted language the code is executed byclicking on the the green flag above the stage panel shown on the right side of the figure. Theoutcome of this program is shown in the contents of this panel.
Code Example 3.1. Hello World in Scratch
3.1.3 The Scratch command palletProgramming in Scratch starts by selecting and dragging objects known as Sprites onto the stage.The programmer can then give each sprite a separate set of instructions by choosing one of thesprites on stage and then selecting and dragging commands into the Sprite Script window in themiddle of the IDE. These commands sequences will be executed on the program begins. TheScratch language offers the programmer eight types of command each of which are representedby a different color button in the command pallet, as shown in Figure 3.3. A full listing of theScratch commands is given in Appendix B.2.
Figure 3.3: Groups of Scratch Operations
The eight groups of Scratch commands are described below:
Motion: All functions and variables related to the location, speed and direction of thesprite
Looks: All functions and variables related to the appearance of the sprite. A costumechange will result in the use of another graphic to represent the sprite on stage. Useful forsimulating incremental motion in animation.
-
32 CHAPTER 3. SCRATCH PROGRAMMING
Sound: All functions and variables related to the source and volume of audio output. Awide range of sound clips, musical notes and sound effects are supported.
Pen: All functions and variable related to the drawing pen connected to the sprite. Usefulfor recording the path taken by th