Computer Programming - initial version

Page 1

COMPUTER PROGRAMMING PROGRAMMING

A Course Textbook Robert P. Batzinger Payap University Press Chiang Mai 50000, Thailand


COMPUTER PROGRAMMING The Course Textbook

Robert P. Batzinger

Payap University Press Chiang Mai 50000, Thailand


Copyright © 2013 Robert P. Batzinger Payap University Press Amphur Muang Chiang Mai 50000 Thailand 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 XƎLATEX source code which can be compiled to generate a 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 XƎLATEX source for this book is available from the author.


Contents Front matter Table of Contents . . . . . . List of Figures . . . . . . . . List of Tables . . . . . . . . . List of Flowcharts . . . . . . List of Algorithms . . . . . . List of Code Examples . . . . List of Supplemental Material

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

iii iii vi viii ix x xii xiv

Acknowledgements

xvii

Acronyms

xix

1 Introduction 1.1 Why study programming? 1.2 Overview of this course . . 1.3 Organization of this book . 1.4 Features of this book . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

2 Computer Fundamentals 2.1 Main Components of a Computer System . . . . 2.1.1 Hardware . . . . . . . . . . . . . . . . . 2.1.2 Software . . . . . . . . . . . . . . . . . . 2.1.3 Peopleware . . . . . . . . . . . . . . . . . 2.2 Key Ingredients of Good Computer Programming 2.2.1 Algorithms employed . . . . . . . . . . . 2.2.2 Nature of man-computer interaction . . . . 2.2.3 Programming language selected . . . . . . 2.2.4 Data representations . . . . . . . . . . . . 3 Scratch Programming 3.1 Getting started . . . . . . . . . . . . . . . 3.1.1 Interactive Development Enironment 3.1.2 A first program . . . . . . . . . . . 3.1.3 The Scratch command pallet . . . . 3.2 Conditional Operation within Scratch . . . 3.2.1 Combining multiple logic conditions 3.3 Programming Loops in Scratch . . . . . . . 3.3.1 Endless repetition . . . . . . . . . . 3.3.2 Controlled repetitions . . . . . . . . 3.3.3 Nesting of loops . . . . . . . . . . . iii

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . .

1 1 2 4 5

. . . . . . . . .

7 7 8 14 14 17 17 18 18 20

. . . . . . . . . .

29 29 29 30 31 32 34 35 36 39 40


iv

CONTENTS 3.4 Using variables in Scratch . . . . . . . . . . . 3.5 Calling subroutines in Scratch . . . . . . . . . 3.5.1 An extended example using subroutines 3.6 Lists and arrays . . . . . . . . . . . . . . . . .

4 Program Design Tools 4.1 Different methods for describing a process . 4.2 Program design tools . . . . . . . . . . . . 4.2.1 Flow chart . . . . . . . . . . . . . . 4.2.2 Pseudo code . . . . . . . . . . . . . 4.3 Basic programming patterns . . . . . . . . 4.4 Commenting source code . . . . . . . . . .

. . . . . .

5 Basic Concepts of C Programming 5.1 Getting started . . . . . . . . . . . . . . . . 5.2 Basic building blocks . . . . . . . . . . . . . 5.2.1 Variables and constants . . . . . . . . 5.2.2 Operators and precedence . . . . . . . 5.2.3 Comments . . . . . . . . . . . . . . . 5.2.4 Expressions and statements . . . . . . 5.3 Program Flow . . . . . . . . . . . . . . . . . 5.3.1 Conditional execution . . . . . . . . . 5.3.2 Loop structures . . . . . . . . . . . . 5.4 Functions . . . . . . . . . . . . . . . . . . . 5.4.1 Standard Library Functions in stdlib.h 5.4.2 Mathematical Functions in math.h . . 5.4.3 Parameters . . . . . . . . . . . . . . . 5.4.4 Return values . . . . . . . . . . . . . 5.4.5 Local vs Global variables . . . . . . . 5.5 Compiler Directives . . . . . . . . . . . . . 5.5.1 Macro . . . . . . . . . . . . . . . . . 5.5.2 Conditional compiling . . . . . . . . . 5.6 C Programming Examples . . . . . . . . . . 5.6.1 Grade conversion . . . . . . . . . . . 5.6.2 Prime Number Listings . . . . . . . . 6 Composite Data Types 6.1 Array . . . . . . . . . . . . 6.2 String . . . . . . . . . . . . 6.3 Character functions - ctype.h 6.4 User-defined data types . . 6.5 Enumerated data type . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . .

42 43 45 48

. . . . . .

53 53 56 56 58 64 66

. . . . . . . . . . . . . . . . . . . . .

69 69 71 71 72 78 78 80 80 81 82 83 84 84 84 84 84 84 84 84 84 91

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

99 99 108 109 109 111

7 File Processing 7.1 Data stream handles . . . . . . 7.2 Sequential text file input/output 7.3 Formatted input and output . . . 7.4 File open . . . . . . . . . . . . 7.5 Random access file input/output 7.6 Parsing a CSV file . . . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

113 113 114 115 116 117 118

. . . . .


CONTENTS 8 Pointers 8.1 The concept of a pointers . . . . 8.2 Pointers as function parameters . 8.3 Pointers and arrays . . . . . . . 8.4 Arrays of pointers . . . . . . . . 8.5 Pointers of functions . . . . . .

v

. . . . .

. . . . .

. . . . .

. . . . .

9 Software Programming Paradigms 9.1 Software development . . . . . . . . . 9.1.1 Module development . . . . . . 9.1.2 Agile programming . . . . . . . 9.1.3 Debugging and Unit testing . . . 9.1.4 Version control and makefile . . 9.1.5 Conditional compiling . . . . . . 9.2 Program Structure . . . . . . . . . . . 9.2.1 Structured programming . . . . . 9.2.2 Object-oriented programming . . 9.2.3 Parallel/concurrent programming

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . . . . . . . . . . . .

. . . . .

121 121 121 121 121 126

. . . . . . . . . .

127 127 127 129 129 129 129 129 129 129 129

A Software installation 133 A.1 Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 A.2 yEd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 A.3 GNU gcc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 B A Quick Guide to Programming Languages 135 B.1 Keyword list of some popular programming languages . . . . . . . . . . . . . . 135 B.2 Scratch Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 C Comparison between standard Computer Science curriculum 139 C.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. . . 1.2 Sequence of Computer Science Courses in Prerequisite Order . . . . . . . . . .

2 3

2.1 Basic hardware components of electronic computers . . . . . . . . . . . . . . . 2.2 Bus line communications between the microprocessor and internal memory. . . . 2.3 Early electronic computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4 Photomicrograph of Intel 8080 introduced in 1974. . . . . . . . . . . . . . . . . 2.5 Photomicrographs of popular microprocessors produced in 1993. . . . . . . . . . 2.6 A photomicrograph of the Intel iCore7 quad core microprocessor . . . . . . . . . 2.7 47 Years of Moore's Law . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.8 Hardware standards for PC I/O ports . . . . . . . . . . . . . . . . . . . . . . . . 2.9 Successful technology comes with good technical support. . . . . . . . . . . . . 2.10 Children's Product Table at the Apple Store in Singapore . . . . . . . . . . . . . 2.11 Origins of common computer languages . . . . . . . . . . . . . . . . . . . . . . 2.12 Bits can be used to monitor individual sensors or combined to store a number using powers of 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.13 Converting the binary number 101001012 to its decimal equivalent of 165 . . . .

8 9 10 11 12 13 13 15 17 18 19

3.1 Scratch Interactive Development Environment . . . . 3.2 Thai and English view of hello.scr . . . . . . . . . 3.3 Groups of Scratch Operations . . . . . . . . . . . . . 3.4 Flowchart and pseudocode of a script to center the cat . 3.5 Endless loop structures within the Scratch language . . 3.6 Conditional Processing: Stage screen shots . . . . . . 3.7 Controlled loop structures within the Scratch language 3.8 Loop execution . . . . . . . . . . . . . . . . . . . . . 3.9 Pseudocode and outcome of nested loops . . . . . . . 3.10 Sample polygons drawn with Scratch . . . . . . . . . 3.11 Storyboard Frames of the Scratch Screen . . . . . . . 3.12 Interaction between the character subroutines . . . . . 3.13 Costumes of used by the sprites . . . . . . . . . . . . 3.14 Making change for 188 cents . . . . . . . . . . . . . . 3.15 Jumping frogs . . . . . . . . . . . . . . . . . . . . . . 3.16 Solving a maze . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

30 30 31 33 36 38 39 39 40 43 45 46 46 49 52 52

4.1 4.2 4.3 4.4 4.5

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

54 54 55 57 58

Video on cooking a scrabbled egg Recipe for scrambled eggs . . . . Step by step graphic instruction . IBM Flowcharting Template . . . The user interface for yEd . . . .

. . . . .

. . . . .

. . . . . vi

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

21 22


LIST OF FIGURES 5.1 5.2 5.3 5.4

Steps to run a program in the C language . . . . . . . . . . Variables must be declared by type and set to known values. Output of the bitops.c program . . . . . . . . . . . . . . . . Variables must be declared by type and set to known values.

vii . . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

70 71 73 95

6.1 Bitmapped Numerical Digits . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 6.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 2.2 2.3 2.4 2.5 2.6 2.7

Size of memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A Short List of Popular Open-Source Computer Languages . . . . . . . . . . . . Keyword Count of Some Computer Languages . . . . . . . . . . . . . . . . . . Powers of 2 represented by each binary digit of a 32 bit number . . . . . . . . . Binary representation of some signed numbers . . . . . . . . . . . . . . . . . . Bit allocation within an IEEE floating point number . . . . . . . . . . . . . . . . Binary, Octal and Hexidecimal and ASCII Character Representation of Values 0 to 127 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.8 The Thai Character Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

25 26

3.1 3.2 3.3 3.4

Comparison Operators of Scratch . Mathematical Operations of Scratch Truth Table for AND Combinations . Truth Table for OR Combination . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

32 33 35 35

4.1 4.2 4.3 4.4

Flowchart Symbols used in this Course . . . . . . . . . . . . . . . . Common action words used in pseudocodes . . . . . . . . . . . . . . Information to be included in Software Sourcecode . . . . . . . . . . Comparison between the Lyrics of Hey Jude and a Flowchart Version

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

57 59 66 67

5.1 5.2 5.3 5.4

C basic data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Precedence and meaning of C Operators . . . . . . . . . . . . . . . . . . . . . . Bit-wise Outcomes of Bit-wise Operators . . . . . . . . . . . . . . . . . . . . . Comparison of Pseudocode and Flowchart of an Application to Convert Percentages to Letter Grades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

72 72 73

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

9 20 20 22 23 24

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 B.2 B.3 B.4

Keywords of the C language . . . . . Keywords of the Ardunio language . Keywords of the Java language . . . . Keywords of the Processing language

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

135 135 136 136

D.1 Common computer terms in the some languages of the AEC . . . . . . . . . . . 150

viii


List of Flowcharts 3.1 4.1 4.2 4.3 4.4 4.5

Conditional movement . . . . . . Making scrambled eggs . . . . . . Cockpit takeoff warning controller Calculating storage capacity . . . Score to Letter Grade . . . . . . . Line-tracing robot behavoir . . . .

. . . . . .

. . . . . .

ix

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

33 56 60 60 61 63


x

LIST OF FLOWCHARTS


List of Algorithms 3.1 3.2 3.3 4.1 4.2 4.3 4.4 4.5 4.6 8.1 8.2

Conditional movement . . . . . . . . . . . . Pseudocode of a loop . . . . . . . . . . . . . Pseudocode of nested loops . . . . . . . . . . Instructions for making scrambled eggs . . . Pilot warning system . . . . . . . . . . . . . Calculating storage capacity . . . . . . . . . Score to Letter Grade . . . . . . . . . . . . . Robot line following behavior . . . . . . . . Storing information in variables and constants Euclid’s algorithm by iteration . . . . . . . . . . . . . . . . . . Euclid’s algorithm by recursion . . . . . . . . . . . . . . . . . .

xi

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

33 39 40 55 59 60 61 62 64

. . . . . . . . . . . . . . . . . . 125 . . . . . . . . . . . . . . . . . . 125


xii

LIST OF ALGORITHMS


List of Code Examples 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 5.13 6.1 6.2 6.3 9.1 9.2

Hello World in Scratch . . . . . . . . . . . . . . . . . . . . . . Centering the cat: (First try) . . . . . . . . . . . . . . . . . . . Centering the cat: (Corrected version) . . . . . . . . . . . . . . Walking forever . . . . . . . . . . . . . . . . . . . . . . . . . . Conditional Processing: Program code for 2 Sprites . . . . . . . A Scratch program to draw a triangle . . . . . . . . . . . . . . . Scratch program with nested loops . . . . . . . . . . . . . . . . Scratch program to draw a hexagon- . . . . . . . . . . . . . . . A generic polygons drawn with Scratch . . . . . . . . . . . . . Sum of the first 10 integers . . . . . . . . . . . . . . . . . . . . Sum of the first 10 integers: Improved version . . . . . . . . . . An improved version of the code in Figure 3.7 . . . . . . . . . . Main and event-driven scripts of the wizard . . . . . . . . . . . Main and event-driven scripts of the spark . . . . . . . . . . . . Main and event-driven scripts of the Ogre . . . . . . . . . . . . Making change: setup and calculation subroutines . . . . . . . . Making change application . . . . . . . . . . . . . . . . . . . . Hello.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bitops.c: a program to illustrate binary operators . . . . . . . . . increment.c: a program to illustrate ways to increment an integer Comparison between 2 styles of C programming . . . . . . . . . accuracy.c: program to demonstrate floating point errors . . . . Converting a percentage to a letter grade: chained if version . . Converting a percentage to a letter grade: Function version . . . Converting a percentage to a letter grade: Function version . . . Score to Grade Conversion: student submission . . . . . . . . . Printing all the prime numbers less than 50 . . . . . . . . . . . . Finding the prime factors of a number . . . . . . . . . . . . . . Score to Grade Conversion: student submission . . . . . . . . . Finding the prime factors of a number . . . . . . . . . . . . . . Displaying bitmapped digits . . . . . . . . . . . . . . . . . . . Displaying bitmapped digits (Version 2) . . . . . . . . . . . . . Print the longest line . . . . . . . . . . . . . . . . . . . . . . . Parallel processing using fork() . . . . . . . . . . . . . . . . . . An example of switch . . . . . . . . . . . . . . . . . . . . . . .

xiii

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

31 34 35 36 37 40 41 42 42 43 44 44 47 47 48 49 49 70 75 76 76 77 87 88 89 90 91 94 96 97 103 104 112 131 132


xiv

LIST OF CODE EXAMPLES


List of Supplemental Material 1.1 1.2 2.1 2.2 5.1 5.2 5.3 5.4 5.5

Why is the job market for computer programmers growing? . Why study C? . . . . . . . . . . . . . . . . . . . . . . . . . Converting a binary number to a decimal number . . . . . . Addition and Subtraction with binary signed numbers . . . . Why study a language like C? . . . . . . . . . . . . . . . . Avoiding the Six Most Common Programming Errors . . . . Steps to Writing Algorithms . . . . . . . . . . . . . . . . . Six Most Common Programming Errors . . . . . . . . . . . Steps for Writing a Program . . . . . . . . . . . . . . . . .

xv

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

2 4 22 23 79 85 92 95 98


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 do far more abundantly than all 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 ever before. 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 their number grows an ever increasing rate. In fact, it is very difficult to find a career where some application of computers has not had a significant impact. Despite all this development, there is growing need for new solutions and new applications in every field. However, all computer software are limited in part by the nature of its creators particularly in regards to their understanding of the problem, their abilty to quickly develop reliable software and their creativity in providing a meaningful and pleasant user experience. Wile basic understanding of programming might be sufficient to extend the usefulness of some software systems, computer programmers are needed to develop the software to the point where significant increases in speed, reliability and functionality needed to meet the expectation of users. As the global market continues to demand newer, faster and more powerful applications, the need for computer programmers to develop this software continues to grow as well. Computer programming 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 create a career in the location and problem domain of their choosing. Thus, the job market for those who can program is very good and is expected to continues to grow world wide over the new several 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 meet the demand for new software creating a serious world-wide shortage of programmers. At the same time the amount of data online has literately exploded with millions of new photographics uploaded, tens of millions of new webpages created, and billions of tweets and text messages creating a need for new ways to create, transmit and manage this information. In addition, the omputer technology has grown with the development of faster, cheaper processors, 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 each year in the United States.[1] The world-wide shortage is estimated to be closer to 2 million,[2] creating new opportunities for small, local software companies to develop for the international market.

1.2 Overview of this course The purpose of this course is to provide both the background and the skills for developing computer programs that solve problems. The aim is to develop fluency with the major concepts of programming computers that allow one to design, develop and test sequences of steps required to create software that solves problems. As shown in Figure 1.2, this introductory course at Payap University is the first course for Computer Science majors offered by the Computer Science Department and acts a prerequisite to all other courses within the department. Readings, homework problems, lab exercises and programming assignments have been developed to provide understanding the nature of five factors essential to effective computer programming: The problem to be solved: At the heart of all computer programs is a basic problem to be solved. This is true regardless of whether one is playing a game, attempting to develop and transmit an email message, playing a audio-visual media clip, drawing a picture or printing 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 devices like the mouse or the console keyboard to provide the context and parameters of the problem to be solved. Algorithm: The data processing procedures. The computer depends on the programmer to capture and describe the core algorithm as a logical sequence of data transformations required to convert the data input into useful information. Output: The required response. The computer also depends on the program to describe the nature and design of the response. Depending on the application, this may come in the form of printed or displayed reports, or changes in the audio-visual channel output, or by activation of motors, relays and solenoids. The computer programming language: a limited set of instructions (vocabulary) and some basic 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 communicating 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 functions and procedures to process this information to develop a solution which governs the response or output of the computer. This is true regardless of whether the program is just a few commands running on a microprocessor designed to monitor a sensor or as complex as the intensive parallel processing 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 a broad 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 language? 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 history has resulted in optimized compilers and an extensive collection of library functions that produce efficient executable code as well as creating a very large body of source code. 2. C has become something of the lingua franca of programming. The C source code can be very succinct and will compile to executable code that is similar in speed and size of code written in Assembly. 3. C has become the basis for many languages. The C library is used by many languages because compilers for other languages are written in C. 4. The nature of C is very close to that of microprocessors. It is relatively easier to demonstrate and explore techniques that manipulate pointers, bytes, and individual bits. Attempts to optimize applications are more likely to work as expected than applications written in higher level languages. Often constructs of higher level languages do not map closely to the implementation at the machine operation level. 5. C supports a wide range of programming projects. In fact C is the language of choice for developing operating systems, games, device drivers and even for creating 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 logical sequence of events using the limited vocabulary and grammar of a programming language. At the same time, student need to develop the ability to clearly communicate concepts, paradigms and 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 high demand world-wide. To this end, this book will attempt to help students by encouraging and supporting modern techniques used in modern computer education such as active learning techniques, peer programming,[3] and bilingualism.[4] The objective is to help students in non-Anglophone parts of Association of Southeast Asian Nations (ASEAN) to acquire the basic computer programming skills and vocabulary needed to function effectively as professional programmers within ASEAN Economic Community (AEC). This Thai-English Diglot edition is an initial step towards this goal.

1.3 Organization of this book Each chapter of this textbook represents another module in a college course that introduces computer 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 operations of a primitive computer system. The role and purpose of high-level computer languages are also introduced. Chapter 5 - Creating a program: introduces the development of programs as a planned process using the Scratch programming language. Chapter 4 - Program Design Tools: Introduces the art of designing and describing computer programs. Various program design tools are introduced as well as the basic patterns and building blocks of a program. Chapter 5 - Introduction to the C programming language: The basics of programming in C including variables, control structures and subroutines/functions. The emphasis will be on development of software in C as an extension of the software design process. The use of 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 introduced. These will include arrays, strings, user-defined data types such as enumerated data, struct and unions. Chapter 7 - File Processing: Interaction with files will be introduced starting with the establishment of data stream handles. Sequential, random access and block file input/output will be covered. Chapter 8 - Pointers: The concept of address pointers will be introduced as well as their practical application in function parameters, and arrays processing. The definition and use of arrays of pointers of both functions and data will be covered. Chapter 9 - Software Engineering Paradigms: This chapter will take a closer look at the software development process. Various techniques for ensuring rapid development of tested software such as agile programming, module development, and unit testing will be introduced. The use of makefiles and version control software to monitor and encourage progress will also be covered. Structured programming will be contrasted with other program structures such as object-oriented, event-driven and parallel/concurrent programming paradigms. Appendix A - Software installation: This section will cover the downloading and installation of the open-source software introduced in this course. Appendix B - Programming in Scratch: In this section, the contents of Chapter 5 have been adapted for the Scratch programming language to provide a more graphic and visual approach to this material. Appendix C - Quick reference guides to C and Scratch: A concise description of the C and Scratch programming languages have been included as a resource.

1.4 Features of this book In this electronic age of textbooks, students expect a growing range of learning helps and guides to 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 students better understand concepts and provide a richer set of key words for searching in Google. Chapter reviews The key words used in the chapter are listed in this section to help students review the material covered in the chapter. covered. This provides a checklist of the topics covered. Exercises Most of these exercises were designed to build on examples given in the text and provide and opportunity for developing understanding and skill. The questions often appear on exams and in interviews while applying for employment or graduate school. The answers are primarily code fragments and short answers. Lab exercises These are projects that will require a software program to be developed. The benefit of these exercise is maximized when students work on their own and search to find their own solutions. Discussion questions These questions are meant to provide a broader context and application of the topics covered in the chapter. Many of these questions require an essay and/or flowchart to answer. Supplemental Materials Related stories given in parallel text units which are meant to help provide depth in the material presented without interupting the main train of thought. Many of these stories provide additional information from the prespective of history or practical application. Cartoons Line drawings help to provide humor and comic relief for what could be considered a heavy subject. The original line drawings are vector graphics created with Inkscape. Code examples The text is peppered with numerous code fragments to that illustrate a particular programming paradigm or technique. Line numbers have been added to assist in reference specific code expression in the corresponding section of text. Installation of open-source software Appendix 2.9 contains the instructions for downloading and installing software used in this book. Although the instructions were updated at the time of publication, it is possible that newer versions may exist but they should also work well for use in this programming course. See also Section A.1

Cross-references and hypertext links This books makes full use the crossreferences, citations and indexing functions of LATEX. In the PDF version of this document, all references have been converted to hyperlinks making it even easier to find information.

Online exercises, quizzes and activity This course is taught at Payap University using 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 other institution 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 at least 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 and what 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 software applications, 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 is comfortable and feels in control (peopleware). Each of these streams are further explained in the following sections. 7


8

CHAPTER 2. COMPUTER FUNDAMENTALS

2.1.1 Hardware Hardware 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 that can be touched. Figure 2.1 illustrates the 4 basic groups of hardware components that make up a typical computer system. These hardware components can be found even in small mobile computing devices.

Figure 2.1: Basic hardware components of electronic computers Input devices are used to collect and recieve data entering the computer as input. Information is collected using devices like electronic mice, touch pads, keyboards, scanners, barcode readers, 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 is captured and processed before it can be lost. In recent years, computers have equipped with global positioning sensors (GPS), motion sensors, and acclerometers, as well as proximity 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 stream that be read by the processor. In this way, movement of a mouse is understood by the processor as a request for movement of the cursor to a particular location or a keystroke of a key located at a particular row and column on a keyboard is interpreted as the input of a particular character. Output devices are used to display and communicate results to the user in the form of output 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 into signals that trigger the corresponding devices. For example, audio devices translate amplitude into analog signals that drive speakers and video monitors convert values into the amplitude of the primary color circuits for each pixel or dot. Memory is used to store information and is available within a computer system in multiple forms 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 for measuring the quantities of memory. Table 2.1: Size of memory Prefix Symbol bit b nibble byte b word w long word lw kilobyte KB megabyte MB gigabyte GB terabyte TB petabyte PB exabyte EB zettabyte ZB yottabyte YB

Number of bytes 1/8 1/8 1/2 1/2 20 1 1 2 2 2 2 4 210 103 220 106 30 2 109 240 1012 250 1015 60 2 1018 270 1021 80 2 1024

English word one eighth byte one half byte one byte two bytes four bytes thousand bytes million bytes billion bytes trillion bytes quadrillion bytes quintillion bytes sextillion bytes septillion bytes

Central Processing Unit (CPU) is the component that picks up data and manipulates it before transfering the results to other system components according to a pre-established set of instructions.

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 and manipulating 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 data and address buslines of the motherboard of processors provide a means for storing and retrieving gigabytes of information. Processors can also transfer information from memory to and from peripheral memory devices such as hard drives, memory tapdre ives and DVD readers/writers. Hard drives can now manage tetrabytes of information. More recently, processors can address even more data using the banks of memory devices connected to the Internet Cloud, allowing access to petrabytes of information at a rate of speed that is controlled by the bandwidth of the Internet connection.

Colossus Mark 2 codebreaking computer, 19431

ENIAC used for calculating artillery firing tables, 19462

Figure 2.3: Early electronic computers. As shown in Figure 2.3, the electronics of the earliest CPUs occupied several cabinets the size of a room. Colossus Mark was the world's first electronic digital computer. The Colossus computers were used by British codebreakers during World War II to help in the cryptanalysis of the Lorenz cipher. However, programming the Colossus required setting switches and plugging in jumper wires. Data was read from patterns of holes punched in paper tape. The Electronic Numerical Integrator And Computer (ENIAC) was the world's first electronic general-purpose computer launched in 1946 by the United States Army's Ballistic Research Laboratory. The ENIAC was designed to calculate artillery firing tables used to determine the range of projectiles. It was Turing-complete, digital, and capable of being reprogrammed to solve a full range of computing problems. This programmable computer excited scientists and industrialists because of its flexibility to apply tremendous mathematical power to solve a wide range of problems. These early computers used vaccuum tubes to perform all Boolean operations and mathematical calculations. Despite their size, these computers had the ability to address approximately 30 bytes of memory, 2 registers and could support about 100 operations per second from a very a limited setr of operators. (Operations like multiplication and division required special programming.) Today the typical CPU can perform billions of operations per second, address trillions of bytes of information with a wide range of functions. The circuit has been reduced to fit a single microprocessor chip that is less than 5mm across. 1 2

The National Archives Document Record FO850/234, United Kingdom, 1943 K. Kempf, U.S. Army Photo, 1946


2.1. MAIN COMPONENTS OF A COMPUTER SYSTEM

11

Most modern microprocesssors increase performance by using multiple processors working 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 microprocessors. Each patterned segments represents are a collection of various micro digital circuits 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 have been used to improve the preformance. • Reduced instruction set computing (RISC): Microprocessors of this type are really fast 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 generally require less power making them ideal for mobile devices. A photomicrographs of Intel Pentium RISC microprocessor is shown in the left panel of Figure 2.5. • Complex instruction set computing (CISC): Microprocessors of this type have a very large number of functions built into the chip. A photomicrograph of the Motorola 68000 CISC microprocessor is shown in the right panel of Figure 2.5. The purpose is to reduce the number of instructions needed to perform complex operations such as high speed graphics processing, floating point mathematics, data compression, global positioning and other forms of signal processing. While individual commands may be slower than RISC device, the theory is that fewer commands would be required by an application. In the past decade, the trend has been to add multiple processors or cores to the microprocessor chip. While each of these cores have access to all the hardware resources of the computer, they work independantly. The operating system coordinates the allocation of tasks or processes to the individual processors on the chip. Multicore parallel computing greatly improved the hardware support of multitasking allowing users to run more applications simultaneously such as listening to music and uploading pictures to Facebook, while replying to a Facebook message while doing homework in Microsoft Word. Figure 2.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 double nearly every 18-24 months. Moore’s Law states that the density of transistors doubles every 18 to 24months. The actual growth in the number transitors per microprocessor chip are given in Figure 2.7. This has meant that for the past 40 years, processors have nearly doubled in speed and capacity as well while reducing power comsumption. It also has driven the world-wide business practice of replacing computers every 3-5 years creating 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]

9

● ●

8

7

● ●

● ●

● ●

● ● ●

● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ●

● ●

6

● ●

5

● ●

● ●

4

Number of Transistors per chip (Log10)

Increase in the Number of Transistors in a Microprocessor Chip

1970

● ● ● ● ●

1980

1990

2000

Figure 2.7: 47 YearsYear of Moore's Law[6]

2010


14

CHAPTER 2. COMPUTER FUNDAMENTALS

2.1.2 Software Software includes everything that can be held in memory, stored for later use in retrieval. There are 2 basic categories of software: Program code: sequences of instructions. At the machine level, program code is a sequence of binary numbers that correspond to operations that take place within the CPU. Regardless the language used, size or complexity of the program, every program must provide develop a detailed description of the process by which a solution can be found using available information and computing resources. Good programs execute in reasonable time, produce correct responses and are understood by the computer, the users and other programmers. • Boot loader: a series of functions whose purpose is to check the hardware and load an appropriate version of the operating system. This is activated whenever a computer is turned on or reset. • Operating system (OS): a collection of functions that manage processes and applicatons running on a computer. It also provides system calls to the Graphic User Interface (GUI) and the Basic Input/Output Systems (BIOS). Examples of modern operating systems written in C include UNIX, Solaris, Linux, BeOs, Solaris, and Android. • 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 preferences.

2.1.3 Peopleware Peopleware has be used to describe all components and services designed to make the user experience easier to understand and use. It also addresses such issues as developer productivity, teamwork, group dynamics, the psychology of programming, project management, organizational factors, human interface design, and human-machine-interaction.Peopleware generally comes in one the following forms: Awareness campaigns: Various events and services to launch a product and make the benefits and 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 promoters are often seen at trade shows or professional meetings and often carry the job title of Evangelist, Consultant, or Developer. • Providing venues for early adoptors to demonstrate the benefits of using new technology, such as Seminars, Webinars, Road shows, and Show rooms open house • Providing hands-on training in the use of the technology through seminars, workshops, and online user training Standards: attempts to simplify and provide uniformity in the production, use and communication of technology, particularly by establishing common principles that governs the nature and behaviour of the technology. • Hardware standards: designing the physical characteristics of a device in order to limit the possibility for damage to the device to occur because of misconfiguration or by faulty hardware. This includes the use of colors, shapes, and sizes used in the array of input/output ports of computers. The ports on the back of a standard PC desktop computer are shown in Figure 2.8. This design scheme helps users to figure out 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 numerous ways: the size and shape of connectors. the voltages and electrical current requirements of components, the electrical protection mechanisms, pin and lead assignments of all connectors, and the control behavoir and timing of all interaction that takes place on the address and data buslines. • Interface behavior: Users have come to expect particular behaviour from Graphic User Interafaces (GUI). For example, Warning messages are displayed in Red, Buttons are meant to be clicked to activate a function, and tabs of pull down menus are located near the top of screen. Confusion can result if the wrong color, object shape and location is chosen. • Data standards: Because data is often used for multiple applications, data standards are used to facilitate the exchange and sharing of information. XML, CSV, and SQL are commonly used to stored structured data in files. ASCII, TIS620, and UTF8 are commonly used to identify the individual characters of text. Viewers require graphics to conform to on of a limited number of graphics standards such as PNG, JPEG, GIF or SVG. The current trend in software development is to use open data and file standards because these standards are best supported and are upward compatible with future revisions of that standard.


16

CHAPTER 2. COMPUTER FUNDAMENTALS • Software standards: In the past several decades of computer development, there has emerged a concensus on how softare should behave. Each of these standards is meant to preserve user data and minimize data loss due to mistakes or program errors. 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 application terminated unexpectedly. – A backup file is created everytime a file is updated.

Documentation: Software companies publish and distribute resources to provide users and developers with in-depth information about the nature, application and use of the technology. • Installment charts and guides: Simple step by step instructions to help users start using the new software. • User manuals and howto guides: Initially users tend to develop a few essential skills unaware of the bredth of functions that have been designed into the computer software. The purpose of these documents is to provide users with the ability to discover and use the full range of functions provided by the software. • Online support pages: Ongoing support for technology is provided via web pages and video clips. This is often facilitated by contributions from the user community. User Support: development of a satisfied user community by addressing issues that individual users are having with the computer technology. • Active communications: These services provide the user with the ability to communicate with a real people via chat, email, bulletin board or voice. • Services: Occasionally users will require an expert to help them to effect repair or installation of technology. Companies often employ subcontractors to provide support facilities in remote locations. • User community support: User groups tend to be useful and helpful in promoting software and in developing new applications and functions. Software houses like Adobe have discovered that users very creative and effective in motivating other users 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 purposes for which it was not designed. Bug trackers help users to follow the progress of the fixing of reported bugs. In addition, websites are often provided to help distribute official software patches and updates and well as contributions from the user community.


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 Programming The invention of computing devices, computer applications and services have all been driven by a need to solve specific problems. To this end, computer software attempts to provide basic background information and a description of the steps in the process for finding a solution. Good computer programs make effective use of the resources and capabilities of computers as they accept and process input in order to produce some appropriate response. The nature of effective programs is the result of careful and deliberate design choices within each of the areas described in the sections that follows.

2.2.1 Algorithms employed Algorithm provide a description of the sequence of operations needed to solve a problem. In theory, efficient and effective algorithms attempt to use minimum amounts of memory to solve problems in minimum time. but the reality for most problems solved by computers is that there is an inverse relationship between the amount of memory used and the computational time 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 sorting is known for its speed in sorting arrays of items in random order but if the elements in the array are already presorted the performance can be poor. Therefore, programmers need to be able to study an algorthm to identify that the method used is appropriate for the application in that it will produce correct output, in reasonable time while putting reasonable demands on the key computing resources of cpu time and internal memory.

2.2.2 Nature of man-computer interaction The value of a computer program to solve problem depends greatly on the ease by which the problem can be of described and the solution understood. In a similar way, the popularlity of the technology depends on user-friendliness, and the nature and aesthetics of the interaction between man and machine. Both input and output need to be organized in a format and sequence that seems locical to the user even if processing of this information would require a different order. Because a good interface needs to be easy to learn, acts in predictable ways and use conventions that are intuitive and easily understood by the user, end users are often part of the software development team. In fact, companies like Apple and Samsung are famous for using children 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 selected The entire sequence of operations that comprise a computer program must be encoded within the instruction set of a given programming language chosen. There are literally thousands of computer languages in current use and each language was designed for creating a particular range of applications to address problems in specific problem domains. Figure 2.11 shows the origins of the most popular languages in use. Each language represents a different set of instructions and syntax. Although it generally takes a month or two for experienced programmers to become fluent in a new language, most programmers are proficient in 3 or 4 computer languages which they use regularly. The central processing units of computers use binary numbers for all steps of each operations: to determine the addresses of the data and the code of the next operation, the values of the 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 programming languages is to allow the programmer to use a simpler language to express commands that can be translated into the binary language native to the central processing units. Each computer language approaches this process differently. • Compiled languages translate the source code into native code that is saved as an executable 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 of the source code. • Interpreted languages read, interpret and execute the source code expression by expression. This process is repeated until all instructions of the source code have been completed. Applications written in these languages tend to run slower than written languages that compile to native code.. Examples include scripted languages like Perl, Python and Ruby. • Hybrid systems compile source code into the native code for a virtual machine. This compiled code requires an interpretor to execute this code on specific processors. This approach allows software to be compiled once and then used on the range of hardware for which virtual machine interpretors are available. Some languages require the commands to be compiled and saved as native code before it can be run. that can be executed Some of the most popular, open-source computer languages are listed in Table 2.2. The keywords associated with each language establishes the basic vocabulary of that language. 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 C

Description 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 control 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. A LTEX 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 artificial intelligence Octave A matrix oriented mathematical programming language used for engineering applications. PHP A general purpose embedded scripting language used for developing web-based applications. Python a general purpose scripting language often used for developing prototypes 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 including forecasting, graphics, modelling, and statistics. Ruby an object-oriented scripting language used for web site development and computer system programming. generally cannot be redefined to represent variables or methods. Table 2.3 shows the number of keywords for some computer lanugages. Table 2.3: Keyword Count of Some Computer Languages Language Arduino C Java Processing Scratch

Number of keywords 27 32 54 56 80

% Overlap of Keywords Between Languages Processing Scratch Java C Arduino 100 100 100 100 100 -

2.2.4 Data representations All modern computers are designed as binary devices that reduce all processes to sequences of 1's and 0's. Therefore, all data must be represented in some binary format regardless of whether the data is being entered as input, or stored and manipulated internally, or displayed as some output 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 using powers of 2. as parallel printer port status shown in Figure 2.12. A single byte is capable of monitoring 8 bits 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 a increasing different power of 2. The sum of the bit value times its corresponding value of its corresponding power of 2 is used to is represent numbers as shown in Figure 2.13. Table 2.4 gives a list of the values of the powers of 2 for each column of a binary number that is 32 bits long. In addition different bit patterns of binary numbers can be used to represent the different numerical data types. The following sections describe the primitive numerical data types directly supported 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 larger power of 2. Thus a system with unsigned integers n bits long can respresent a range of numerical values between 0 and 2n−1 . 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 165 The basic process of converting between binary numbers and decimal numbers requires creating the sum of the products between the decimal value of each binary digit and its binary value (either 0 or 1). V alue =

n ∑

digitvaluei × bitvaluei

i=0

Figure 2.13 illustrates the mathematics of this with the conversion of an 8 bit number into its decimal equivalent. Bit values: 1 Powers 27 of 2:

0 26

1 25

1 101001012 0 2 1×1 = 1 0×2 = 0 1×4 = 4 0×8 = 0 0 × 16 = 0 1 × 32 = 32 0 × 64 = 0 1 × 128 = 128 Sum: 16510

0 24

0 23

1 22

0 21

Table 2.4: Powers of 2 represented by each binary digit of a 32 bit number Exp 0 1 2 3 4 5 6 7

Value Exp Value Exp Value Exp Value 1 8 256 16 65,536 24 16,777,216 2 9 512 17 131,072 25 33,554,432 4 10 1,024 18 262,144 26 67,108,864 8 11 2,048 19 524,288 27 134,217,728 16 12 4,096 20 1,048,576 28 268,435,456 32 13 8,192 21 2,097,152 29 536,870,912 64 14 16,384 22 4,194,304 30 1,073,741,824 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 systems start with the byte containing the least significant bits. The value of the bits of a 8 bit number are 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 number and 1 is a negative number. Positive numbers are represented as unsigned integers. Negetative numbers are represented as 2s complement of the unsigned number. Signed numbers n bits long can represents a range of number between −2n−1 and 2n−1 . The 16-bit representation of some signed numbers are given below:


2.2. KEY INGREDIENTS OF GOOD COMPUTER PROGRAMMING

23

Supplemental Material 2.2. Addition and Subtraction with binary signed numbers Addition of two numbers is achieved by adding each digit starting with the least significant one. If the result equals 2 the zero is recorded and 1 bit carry is added to the next column. Decimal Addition

Binary Addition

15 + 22 37

00001111 + 00010110 00100101

Binary addition with carries marked 00111100

Decimal equivalents:

(carry values)

00001111 00010110 00100101 32+4+1

= 37

Substraction is achieved by adding the first number to the 2s complement of the second number. The 1s complement is calculated by inverting the zeros and ones of a number. The 2s complement is the result of adding 1 to the 1s complement. Decimal Addition

Addition of 2s Complement

Addition with carries marked 11000000

37 - 22 15

00100101 + 11101010 00001111 Decimal equivalents:

(carry values)

00100101 11101010 00001111 8+4+2+1

= 15

Table 2.5: Binary representation of some signed numbers Positive Numbers Negetative Numbers Decimal Binary Representation Decimal 1s complement 2s complement 1 0000000000000001 -1 1111111111111110 1111111111111111 10 0000000000001010 -10 1111111111110101 1111111111110110 170 0000000010101010 -170 1111111101010101 1111111101010110 255 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 2 raised 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 the floating point representations that exist. Within this standard, e is within the range of Emin to Emax and fractions are generally normalized so that the leading bit equals 1. However, for numbers 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 Table 2.6.


24

CHAPTER 2. COMPUTER FUNDAMENTALS Table 2.6: Bit allocation within an IEEE floating point number Number Sign Bit size bit 32 bits 1 64 bits 1

Exponent bits Emin Emax 8 -126 127 11 -1022 1023

Bias 127 1023

Fraction bits 23 52

Character codes Although most CPUs use integers to represent individual characters, graph processing units and monitor circuits require standards to be able to look up and display the specific shapes associated with characters. In 1963 the American Standards Association published the American Standard Code for Information Interchance which has been abbreviated as ASCII. This standard specifies the code values of 128 character of which 95 are printable characters and 33 are non-printing control characters used to control serial data communications of teleprinters. This quickly became the most common character code standard for Roman characters. Table 2.7 illustates how sequences of bit values can be used to designate the value of binary, octal, hexidecimal and decimal numbers as well as ASCII characters. In 1990 The Thai Industrial Standards Institute published the Thai Industrial Standard 6202533 which is know internationally as TIS-620.[8] This national standard defined an 8-bit standard for encoding Thai characters as an extension of the ASCII character set. The characters are arranged in alphabetical order to facilitate the sorting of Thai words. However, this character set 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 encode multiple multibyte character. Because UTF-8 encodes all of the 1,112,064 code points of the Unicode standard, UTF-8 can be used to encode text files and web pages that contain multiple languages of diverse scripts such as Arabic, Chinese, Japanese, Korean and Russian. Even Hierglyphic Egyptian characters are supported by the Unicode standard. The Thai character code points for both TIS-620 and UTF-8 standards are given in Table 2.8.


Binary 0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001 10010 10011 10100 10101 10110 10111 11000 11001 11010 11011 11100 11101 11110 11111

Oct O0 O1 O2 O3 O4 O5 O6 O7 O10 O11 O12 O13 O14 O15 O16 O17 O20 O21 O22 O23 O24 O25 O26 O27 O30 O31 O32 O33 O34 O35 O36 O37

Hex 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf 0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f

Dec 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

ASCII NUL SOH STX ETX EOT ENQ ACK BEL BS TAB LF VT FF CR SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US

Binary 100000 100001 100010 100011 100100 100101 100110 100111 101000 101001 101010 101011 101100 101101 101110 101111 110000 110001 110010 110011 110100 110101 110110 110111 111000 111001 111010 111011 111100 111101 111110 111111

Oct O40 O41 O42 O43 O44 O45 O46 O47 O50 O51 O52 O53 O54 O55 O56 O57 O60 O61 O62 O63 O64 O65 O66 O67 O70 O71 O72 O73 O74 O75 O76 O77

Hex 0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f 0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3a 0x3b 0x3c 0x3d 0x3e 0x3f

Dec 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

ASCII SPC ! " # $ % & ' ( ) * + , . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?

Binary 1000000 1000001 1000010 1000011 1000100 1000101 1000110 1000111 1001000 1001001 1001010 1001011 1001100 1001101 1001110 1001111 1010000 1010001 1010010 1010011 1010100 1010101 1010110 1010111 1011000 1011001 1011010 1011011 1011100 1011101 1011110 1011111

Oct O100 O101 O102 O103 O104 O105 O106 O107 O110 O111 O112 O113 O114 O115 O116 O117 O120 O121 O122 O123 O124 O125 O126 O127 O130 O131 O132 O133 O134 O135 O136 O137

Hex 0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x48 0x49 0x4a 0x4b 0x4c 0x4d 0x4e 0x4f 0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57 0x58 0x59 0x5a 0x5b 0x5c 0x5d 0x5e 0x5f

Dec 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

ASCII @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _

Binary 1100000 1100001 1100010 1100011 1100100 1100101 1100110 1100111 1101000 1101001 1101010 1101011 1101100 1101101 1101110 1101111 1110000 1110001 1110010 1110011 1110100 1110101 1110110 1110111 1111000 1111001 1111010 1111011 1111100 1111101 1111110 1111111

Oct O140 O141 O142 O143 O144 O145 O146 O147 O150 O151 O152 O153 O154 O155 O156 O157 O160 O161 O162 O163 O164 O165 O166 O167 O170 O171 O172 O173 O174 O175 O176 O177

Table 2.7: Binary, Octal and Hexidecimal and ASCII Character Representation of Values 0 to 127 Hex 0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x6a 0x6b 0x6c 0x6d 0x6e 0x6f 0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77 0x78 0x79 0x7a 0x7b 0x7c 0x7d 0x7e 0x7f

Dec 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

ASCII ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ DEL

2.2. KEY INGREDIENTS OF GOOD COMPUTER PROGRAMMING 25


CHAPTER 2. COMPUTER FUNDAMENTALS 26

TIS 620 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 B2 B3 B4 B5 B6

UTF 16 E01 E02 E03 E04 E05 E06 E07 E08 E09 E0A E0B E0C E0D E0E E0F E10 E11 E12 E13 E14 E15 E16

ก ข ฃ ค ฅ ฆ ง จ ฉ ช ซ ฌ ญ ฎ ฏ ฐ ฑ ฒ ณ ด ต ถ

Character Description Ko Kai Kho Khai Kho Khuat Kho Khwai Kho Khon Kho Rakhang Ngo Ngu Cho Chan Cho Ching Cho Chang So So Cho Choe Yo Ying Do Chada To Patak Tho Than Tho Nangmontho Tho Phuthao No Nen Do Dek To Tao Tho Thung

TIS 620 B7 B8 B9 BA BB BC BD BE BF C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC

UTF 16 E17 E18 E19 E1A E1B E1C E1D E1E E1F E20 E21 E22 E23 E24 E25 E26 E27 E28 E29 E2A E2B E2C

Character Description Tho Thahan Tho Thong No Nu Bo Baimai Po Pla Pho Phung Fo Fa Pho Phan Fo Fan Pho Samphao Mo Ma Yo Yak Ro Rua Ru Lo Ling Lu Wo Waen So Sala So Rusi So Sua Ho Hip Lo Chula

TIS 620 CD CE CF D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DF E0 E1 E2 E3 E4 E5 E6

UTF 16 E2D E2E E2F E30 E31 E32 E33 E34 E35 E36 E37 E38 E39 E3A E3F E40 E41 E42 E43 E44 E45 E46

อ ฮ ฯ ะ ·ั า ·ํา ·ิ ·ี ·ึ ·ื ·ุ ·ู ·ฺ ฿ เ แ โ ใ ไ ๅ ๆ

Table 2.8: The Thai Character Set

ท ธ น บ ป ผ ฝ พ ฟ ภ ม ย ร ฤ ล ฦ ว ศ ษ ส ห ฬ

Character Description O Ang Ho Nokhuk Paiyannoi Sara A Maihanakat Sara Aa Sara Am Sara I Sara Ii Sara Ue Sara Uee Sara U Sara Uu Phinthu Baht E Ae O Ai Maimuan Ai Maimalai Lakkhangyao Maiyamok

TIS 620 E7 E8 E9 EA EB EC ED EE EF F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB

UTF 16 E47 E48 E49 E4A E4B E4C E4D E4E E4F E50 E51 E52 E53 E54 E55 E56 E57 E58 E59 E5A E5B

·็ ·่ ·้ ·๊ ·๋ ·์ ·ํ ·๎ ๏ ๐ ๑ ๒ ๓ ๔ ๕ ๖ ๗ ๘ ๙ ๚ ๛

Character Description

Maitaikhu Maiek Maitho Maitri Maichattawa

Thanthakhat Nikhahit Yamakkan Fongman Zero One Two Three Four Five Six Seven Eight Nine Angkhankhu Khomut


2.2. KEY INGREDIENTS OF GOOD COMPUTER PROGRAMMING

27

Chapter 2 Review Key Terms: algorithm bit byte integer exponent floating point input matissa output precision register signed integer

Discussion Questions: 1. Although the character codes in Thai character set given in Table 2.8 are assigned in alphabetical order, this is insufficient for sorting Thai words in alphabetic order. Describe the 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 of products would they be particularly good test subjects for? If Apple Computers did not use children as part of their test stratgeties do you think their computers would be so easy to 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 these words in ascending sorted order. ,

,

,

,

,

.


28

CHAPTER 2. COMPUTER FUNDAMENTALS

2. Calculate the 8 bit binary equivalents of the following numbers, and their 1s complements and 2s 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 signed and unsigned: Binary number Decimal number fromDecimal number from Binary number an unsigned number a signed number a. 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 started Scratch is a programming language that was designed to teach programming principles in a way that is easy to learn and fun to use. The Interactive Development Environment (IDE) allows the programmer to place objects on a stage and then provide instructions that will govern the reaction of these objects to events that occur. The outcomes of these instructions are animated providing the programmer with instant feedback for evaluating the correctness of the code. While Scratch was primarily designed for 8 to 16 year olds, it is also used by people of all ages, including younger children with their parents as well as freshmen students at various universities around the globe.[9]

3.1.1 Interactive Development Enironment Scratch 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 to be displayed and manipulated on stage. Programming is accomplished graphically by dragging program elements found in the left side of the screnn into the program editor window located in the middle. The Scratch programming language is distributed as an open source product to encourage international participation the development of this product. The designers of the Interactive Development Environment (IDE) for this language have built in support for over 45 languages of the world. By clicking on the globe icon, it is possible to select a different human language for 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 is always the same regardless of the language chosen for the human interface. In addition, the translation of program views does not effect the content of string of text. In this textbook, only the English interface will be used to help students make the transistion to other programming languages covered later in this book. However, some students have found it helpful to use the language change feature to verify the meaning of their program scripts in the early days of their study.

English interface

Thai interface

Figure 3.2: Thai and English view of hello.scr

3.1.2 A first program Ever since the launch of the C language, the starting point for learning a programming language has been centered on a simple problem: The need to demonstrate that it has understood program we 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 special control structures, it is an excellent test of whether the compiler or interpetor has been installed and is working. By tradition, the message is often the greeting "Hello, World!" and the program is often named hello. This hello program can be used as an early stage template for developing the other programs. Code Example 3.1 shows how this would be accomplished in the language of Scratch. The left panel shows the code. Because Scratch is an interpreted language the code is executed by clicking on the the green flag above the stage panel shown on the right side of the figure. The outcome 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 pallet Programming 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 the sprites on stage and then selecting and dragging commands into the Sprite Script window in the middle of the IDE. These commands sequences will be executed on the program begins. The Scratch language offers the programmer eight types of command each of which are represented by a different color button in the command pallet, as shown in Figure 3.3. A full listing of the Scratch 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 the sprite • Looks: All functions and variables related to the appearance of the sprite. A costume change will result in the use of another graphic to represent the sprite on stage. Useful for simulating incremental motion in animation.


32

CHAPTER 3. SCRATCH PROGRAMMING • Sound: All functions and variables related to the source and volume of audio output. A wide 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. Useful for recording the path taken by the sprite. • Control: All operations used to control the execution of individual or groups of script commands. • Sensing: All functions and variables used to detect movement of objects on screen and values of sensors. • Operators: All functions used to compare or manipulate values. • Variable: All functions related to the setting and use of memory used records individual values (known as variables) as well as sequences of values (known as lists).

3.2 Conditional Operation within Scratch The Hello.scb is a very simple program that lists a fixed sequence of 4 commands. Running this script will result in the commands being executed in the order listed in the program. No command is skipped in the process. However, life is full of choices and scripts need a method by which we can instruct the computer how to make right choices for given circumstances. Carrying out conditional operations requires testing for a condition and then executing one of two blocks of code depending on the results obtained. If the test condition turns out positive, the first block of code is executed before proceeding on to the next command. If the test turns out negetative, the code in the block that follows the else label will be executed. If there is no else clause then the program then skips to the next command after if statement. The tests are performed by comparison operations of Scratch which are listed in Table 3.1. These operations return results that are binary in nature, (meaning that the resulting value is either True or False.) Table 3.1: Comparison Operators of Scratch Operation Less than (<) Equal (=) Greater than (>)

Syntax < >

Example 2.1 < 1.4 1.4 = 1.4 2.1 > 1.4

Result False True False

The parameters being compared may be either constant values (like 3.14159), or values of variables, such as x-position), or values returned by various logic, string, or mathematical operations, such as (x-position) - (5). The mathematical operators of Scratch are shown in Table 3.2. As shown by the examples, mathematical operators combine numbers according to the corresponding mathematical function. Numbers are converted between integer and floating point as required by the operation. It is also possible to nest operators within operators such as sqrt((x*x)+(y*y)). The results of nested formula in Scratch are determined by calculating the innermost operations first. As an example, consider developing the Scratch code needed to return the cat to the center of the screen. The diamond shaped block within this figure represents the test which checks


3.2. CONDITIONAL OPERATION WITHIN SCRATCH

33

Table 3.2: Mathematical Operations of Scratch Operation Absolute value Addition Subtraction Multiplication Division Modulus (Remainder) Round Square root Sine Cosine Tangent Arc sine Arc cos Arc tan Natural logarithm Decimal logarithm E power Decimal power

Syntax abs + * / mod round sqrt sin cos tan atan acos atan ln log E^ 10^

Example Result abs(-5.5) 5.500 (2.1)+(1.4) 3.500 (2.1)-(1.4) 0.700 (2.1)*(1.4) 2.940 (2.1)/(3.4) 0.618 (3)mod(2) 1 round(3.4) 3 sqrt(2) 1.414 sin(30) 0.500 cos(30) 0.866 tan(45) 1.000 asin(.5) 30.000 acos(.5) 60.000 45.000 atan(1.0) ln(20) 2.997 log(200) 2.301 E^(2) 7.389 10^(3.3) 199.526

whether the cat is located at the center of the screen. the diamond shaped block within this figure. If the cat is in the middle, the results are cons idered positive and a message would be displayed before proceeding to the end of the program. Otherwise, the results would be considered negative and the cat would be moved back to the middle of the screen before terminating the program. Flowchart 3.1. Conditional movement

Algorithm 3.1. Conditional movement Input: The starting position of the cat 1: if the cat is not in the center then 2: Move the cat to the center 3: else 4: State that there is nothing to do 5: end if

Figure 3.4: Flowchart and pseudocode of a script to center the cat A flowchart and the corresponding pseudocode that describes this process are shown in Figure 3.4. These tools help in the development of the Scratch program by providing a de-


34

CHAPTER 3. SCRATCH PROGRAMMING

tailed, graphic description of the process. (These tools will be described in detail in Chapter 4.) Developing the actual Scratch script involves translating concepts of the design tools into a corresponding sequence of Scratch operations. Code Example 3.2. Centering the cat: (First try)

An initial attempt to implement the program in Scratch is given in Figure 3.2. The conditional operation is captured within the following 3 parts which are contained by the orangecolored if statement in the middle of the script. • The test: The test for centrality is done within the green hexagon block that checks whether the x value equals 0 or not. • The then block of code: The purple line causes the cat to acknowledge that there is nothing to do. This will happen only if x = 0. • The else block of code: The blue line causes the cat to slide back to the middle. This will happen only if x ̸= 0.

3.2.1 Combining multiple logic conditions However, there is a bug in the Scratch script shown in Figure 3.2 that causes the script to work incorrectly. The goal of this script was make the cat return to the center in all cases where the cat is not at in the center. However, the cat will reply that there is nothing to do when the cat is located at (0, 50). The problem arises because the original test only checks the x value and falsely thinks that the cat is in the center because x = 0. This would require testing both the x and the y values and combining the results. When multiple tests are involved, the results of each tests must be combined in predictable and relevant ways. Within the Scratch language there is support for AND and OR combinations of test results. In the case of AND combinations all test results need to positive for the combination to be considered positive. If any or both of the results are false, the combination will be considered false. The truth table representation of AND combinations is shown in Table 3.3. On the other hand, OR combinations will be considered positive only if any or both of the test results are positive. Both tests have to be negative for the combination to be considered negative. The truth table representation of OR combinations is shown in Table 3.4.


3.3. PROGRAMMING LOOPS IN SCRATCH

35

Table 3.3: Truth Table for AND Combinations Scratch AND logic expression

In cases where Gender = Male T Gender = Female F

Age < 25 T T F

Age > 25 F F F

Table 3.4: Truth Table for OR Combination Scratch OR logic expression:

In cases where Gender = Male T Gender = Female F

Age < 25 T T T

Age > 25 F T F

A correct solution for the centering problems would requires testing that both x and y values equal 0. This expanded condition would cover all possible values of x and y. The corrected test condition is shown Scratch script shown in Figure 3.3. Code Example 3.3. Centering the cat: (Corrected version)

3.3 Programming Loops in Scratch Long sequential lists of commands are hard to develop, test and maintain, and also create opportunities for numerous errors to arise. Therefore, it is always better to place repetitive segments of code within a program control structure that can be repeated multiple times within a loop.


36

CHAPTER 3. SCRATCH PROGRAMMING

3.3.1 Endless repetition An endless loop is the simplest form of repetition. Endless loops contain a segment of script code that is repeated forever, or at least until the computer is shutdown or the program aborted. Figure 3.5 is an example of an endless loop in Scratch that attempts to move the cat the right. However, it keeps moving to the right even after the cat has gone off the right side of the screen.

Figure 3.5: Endless loop structures within the Scratch language However this form of loop should be used sparingly because it permenantly commits computer resources which could make the computer run slower and even prevent other functions from working. In addition, errors can arise when the program runs beyond the functional limits of its design. In the endless loop of Code Example 3.4, the cat continues to attempt to move to the right even after it has run off the screen. In short, endless loops should be avoided if it is possible. Code Example 3.4. Walking forever

However, despite the dangers, endless loops could useful for applications that are meant to work continuously until the device or the application is switched off. The scripts in descripts depicts For example, consider developing a simple simulation of the cat walking to the right while footballs roll one at a time in from the right and the cat must jump over the balls as they roll by. In Scratch each sprite is controlled by a separate, corresponding script. Code Example 3.5 contains scripts for both the cat and the ball. At the heart of both scripts are endless loops to control move, rotation and testing proximity between the two objects. Both endless loops conclude with an IF command to prevent the objects from disappearing off the screen by teleporting to back to starting point as soon as the object reaches the far edge of the screen.


3.3. PROGRAMMING LOOPS IN SCRATCH

37

Code Example 3.5. Conditional Processing: Program code for 2 Sprites The script for the cat

The script for the ball

The ball jumping behaviour of the cat is controlled by a sensor operator in an IF statement in the cat script. This operator determines the distance between the ball and the cat. The green line in Figure 3.6 records the path of the cat in the first seconds of execution and clearly demonstrates the ball jumping behavior.


38

CHAPTER 3. SCRATCH PROGRAMMING

Start of the program

Five seconds into the program

Figure 3.6: Conditional Processing: Stage screen shots


3.3. PROGRAMMING LOOPS IN SCRATCH

39

3.3.2 Controlled repetitions A better approach is to restrict the number of times a segment of code is repeated. When the segment is no longer required, processing should skip to the next part of the program. Figure 3.7 shows the controlled loop structures of Scratch.

Repeat until x > 200

Repeat 10 times

Repeat while x < 200

Figure 3.7: Controlled loop structures within the Scratch language However, controlled repetitions require a mechanism to identify if and when the repetition is still needed. Much like the IF operation, controlled repetitions must test if conditions require another repetition of the loop. The status of the loop is tested and updated with each iteration. The repetition continues until the repeated segment of code has completed its task and is no longer needed. Flowchart of a Loop

Algorithm 3.2. Pseudocode of a loop 1: Move to the middle of the screen 2: Count � 1 3: while Count < 3 do 4: Move 5 steps 5: Rotate 120 degrees 6: Increment Count by 1 7: end while

Figure 3.8: Loop execution As shown in Figure 3.8, a controlled repetition to draw a triangle would have the 4 code segments described below. The corresponding Scratch script and output is given in Code Example 3.6. 1. Initial commands describing processes that need to be completed before the loop is started. (Moving to the middle of the screen) 2. A test for the need for another iternation of the repeated segment. (Test for whether count < 3) 3. A group of commands to be repeated. ( Moving a few steps and rotating 120â—Ś 4. An update of the loop status (Add 1 to the count) The corresponding Scratch program is given in Code Example 3.6. By using controlled repetition, this program ends as soon as the triangle has been drawn.


40

CHAPTER 3. SCRATCH PROGRAMMING

Code Example 3.6. A Scratch program to draw a triangle

3.3.3 Nesting of loops In Scratch it is possible to nest repetitions within a script. This allows the programmer to systematically apply a series of multi-step operations to a rangle of value. In Figure 3.9, the task is to draw a small hexagon at every corner of the larger hexagon.

Algorithm 3.3. Pseudocode of nested loops 1: Move the cat to the initial position 2: for all sides of the larger blue hexagon do 3: Draw half of a side of the blue hexagon 4: Find a corner of the smaller red hexagon 5: for all sides of the red hexagon do 6: Draw a side of the red hexagon 7: Turn towards the next red side 8: end for 9: Return to the edge of the blue hexagon 10: Draw the rest of the blueside 11: Turn towards the next blue side 12: end for 13: Move the cat away from the drawing Figure 3.9: Pseudocode and outcome of nested loops The nesting of the loops can be clearly seen in Code Example 3.7. The innermost loop controls the drawing of the smaller red hexagons while the outer loop ensures that this process is repeated for each side of the large blue hexagon.


3.3. PROGRAMMING LOOPS IN SCRATCH

Code Example 3.7. Scratch program with nested loops

41


42

CHAPTER 3. SCRATCH PROGRAMMING

3.4 Using variables in Scratch Constants are useful for specifying values that do not change. Code Example 3.6 draws a triangle by using constants to determine the number of sides and the turning angle. This program can be adjusted to draw a hexagon by changing these key consonants as shown in Code Example 3.8. Code Example 3.8. Scratch program to draw a hexagon-

However, this technique is impractical for drawing a wide range of polygon shapes as it would require editing the program for each and every new polygon. Fortunately, Scratch allows a program to establish variables as named units of memory to store values. These can be used to store information that can be reused through the script. For example, by saving input as a variable, it is relatively easy to convert the triangle drawing program of Code Exampe 3.6 into the generic polygon drawing program shown in Code Example 3.9. Code Example 3.9. A generic polygons drawn with Scratch

In this program, a variable is used to remember the desired number of sides. The number can be used to determine the turning angle and to control the number of repetitions of the procedure


3.5. CALLING SUBROUTINES IN SCRATCH

43

to draw a side. This allow this program to draw a wide rangle of polygons without having to adjust the program. Figure 3.10 shows some polygons drawn by this program.

Figure 3.10: Sample polygons drawn with Scratch In Scratch it is also possible to declare and use multiple variables in the same program. Meaningful variable names should be chosen to avoid confusion. The script shown in Code Example 3.10 uses two variables (count and sum) to calculate the sum of a range of numbers. In this program, the variables are used as memory to store values, parameters in calculations and the control of repetition, and the source of information to be displayed. Code Example 3.10. Sum of the first 10 integers

However, there are often several algorithms or methods for accomplishing the same thing. Mathematics and logic relationships provide numerous shortcuts that can the complexity, size and run time of a program. The problem being solved by the above program is the calculation of the sum of values within an arithmetic series. At the age of 9, Euler derived a simple mathematical formula for this: num 10 (xmin + xmax ) = (1 + 10) = 5 Ă— 11 = 55 2 2 Code Example 3.11 shows the Scratch program implementation of this formula. The resulting program is significantly simpler and faster. In many cases, the performance of a program will depend largely on the algorithm chosen. Efficient algorithms running on slower and older equipment can often outperform slower algorithms running of the fastest and newest CPUs. sum =

3.5 Calling subroutines in Scratch Another way of controlling complexity in a program is to divide the work of the program into segments of code that can be called individually. These segments act as subroutines or functions that carry out a specific process. In Scratch, a subroutine is called by broadcasting its name and this result in the subroutine initiating its work immediately. However, in many cases it is better


44

CHAPTER 3. SCRATCH PROGRAMMING

Code Example 3.11. Sum of the first 10 integers: Improved version

for the calling routine to wait for the subroutine to complete before proceeding and for this purpose Scratch provides a combined command called broadcast and wait. Code Example 3.12. An improved version of the code in Figure 3.7

Code Example 3.7 consists of a single subroutine which is initiated when the green flag is clicked. However, the program code of this subroutine attempts to describe the process for drawing both the large blue hexagon and the smaller red ones. This type of code is harder to understand and to maintain. A better solution would be to break the routine into units that describe a specific process. The code in Code Example 3.12 clearly separates the code into 2 functional units that draw the blue and the red hexagons, respectively. In essence, subroutines allow the programmer to break the overall process of a large program into subroutines that accomplish discrete tasks. There are numerous advantages that come from using subroutines in this way: • The software is easier to test because each subroutine is actually a subprogram that can be tested independantly.


3.5. CALLING SUBROUTINES IN SCRATCH

45

• The software is easier to build because all subroutines could be written initially as a dummy process that does nothing or returns a single constant value. • The software is easier to read and understand because the main subroutine provides an overview of the tasks involved. The details of each task is given in the corresponding subroutine that normally should not exceed a computer screen.

3.5.1 An extended example using subroutines The following example demonstrated the use of Scratch in generating animation. Through the use of sprites with multiple costumes and subroutines, a Scratch program is used to control animated objects on the stage. The main characters of this story are a mean, old wizard and an ogre. The program is started with a click of the green control flag which causes all sprites to return to their initial position and costume. After the initial setup the wizard begins to harass the Ogre. The storyline is described in more detail below and is illustrated as a storyboard in Figure 3.11: 1. 2. 3. 4. 5.

The story begins when the green flag is clicked. A Wizard meets a blue Ogre. Wizard uses his magic wand to fire a spark at Ogre. When the spark hits Ogre, it jumps up into the air. After Wizard has fired the third spark, Ogre looses its patience and chases down Wizard and eats him. 6. Ogre then returns back to its initial position on the screen and contemplates the moral of the story.

Figure 3.11: Storyboard Frames of the Scratch Screen The corresponding program will the use of the green flag and 3 sprites: Wizard, Spark and Ogre. Each of these sprites have subroutines that cause the sprite to act in a particular way. The subroutines in turn call other subroutines forming a chain of programming tasks as shown in Figure 3.12 This Scratch program uses costume changes to render the screen characters in a different pose or orientation. The list of costumes used for each sprite are shown in Program Code 3.13. The scripts of the Wizard are shown in Code Fragment 3.13. While the wizard's wand is pointed at the Ogre a spark is fired. The die subroutine which makes the Wizard disappear is called from a Ogre script near the end of the animation.


46

CHAPTER 3. SCRATCH PROGRAMMING

Figure 3.12: Interaction between the character subroutines

Wizard Spark

Ogre Figure 3.13: Costumes of used by the sprites

The firing of a spark is accomplished by a costume change which makes the spark visible and sends it on its way towards the Ogre. The spark proceeds until it hits the Ogre causing the Ogre to jump. The script and costume for the spark are shown in Code Fragment 3.14. The Ogre reaction to the spark is controlled by the jump subroutine which basically changes the vertical position of the Ogre. Once the Ogre returns to the initial a jump counter is incremented and checked. If patience of the Ogre has been exceeded then the Ogre calls the eat subroutine which chases down and destroys the Wizard The costume and subroutine of the Ogre are shown in Code Fragment 3.15. Together these components make up the Scratch program for this animation. The animation


3.5. CALLING SUBROUTINES IN SCRATCH Code Example 3.13. Main and event-driven scripts of the wizard

Code Example 3.14. Main and event-driven scripts of the spark

will reset and begin every time the green flag on the stage is clicked.

47


48

CHAPTER 3. SCRATCH PROGRAMMING

Code Example 3.15. Main and event-driven scripts of the Ogre

3.6 Lists and arrays Scratch also provides the user with a variable type can be used to hold a list or array of information. List variables represent a collection of spaces for storing information. Once information has been stored within the list, it can be searched, compared or manipulated conveniently within a loop. For example, a Scratch program that can calculate the minimum number coins needed for making change by using a list of the values of the coins. Let us suppose that we have moved to country that mints coins in units of 1,2,5,20, and 50 cents. To make change with the smallest number of coins for a bill with the value of 188 cents, one would have to count the coins starting with the largest denomination first. Therefore, the list of coin values must be set up in order with the largest value first as seen in the setup subroutine in Coin Fragment 3.16 The makechange subroutine uses loops and a list to simplify the change coin count problem. This subroutine does its calculation by determining the largest number of coins of a particular coin denomination that is equal or smaller to the value of the amount to be changed. The value of this collection of coins is subtracted from the amount of change still required. The process is then repeated with the next smaller valued coin until the change has been made in full or all denominations have been tested. The corresponding script for this process can be seen in Code Fragment 3.16. The purpose of the main subroutine is to call the setup and makingchange subroutines each time this application is needed. The script for this can be seen in Code Fragment 3.17. A screen shot of this application is shown in Figure 3.14.


3.6. LISTS AND ARRAYS

Code Example 3.16. Making change: setup and calculation subroutines

Code Example 3.17. Making change application

Figure 3.14: Making change for 188 cents

49


50

CHAPTER 3. SCRATCH PROGRAMMING

Chapter 3 Review

Key Terms: flowchart pseudocode testing debugging

Discussion Questions: 1. If Scratch were to calculate the sum of the first 10,000 integers, how much faster is the algorithm used in Figure 3.11 over that used in Figure 3.10? 2. What changes would be need to the program shown in Code Example 3.7 to make it draw a user defined series of right polygons? What new tasks would be required?

Exercises: 1. Use Scratch to develop a program that uses of lines of random length to create a design like this.


3.6. LISTS AND ARRAYS

51

2. Use Scratch to make the cat draw the following line art.

3. Use Scratch to make the cat draw 3 concentric triangles.

Laboratory Exercises: 1. Use Scratch to write that places a character at the beginning of red line. Write a script that will cause the character to trace the entire red line of the background without ever leaving the red line. Once it touches the blue bar, the character should display the amount of time it took to run the course. The following images show the screen at the beginning and end of the program, respectively.


52

CHAPTER 3. SCRATCH PROGRAMMING 2. Create a version of the conditional file that moves the cat back to the middle of the screen. If the cat is on the right, make the cat reverse direction before moving back to the center. Once the cat is in the middle, force the then for the cat to face to the right. 3. Create a program that makes the cat draw the outline of a five pointed star in red. Add a blue pentagram that connects the tips of each point. 4. Find the sum of all the even numbers between any two positive integers. 5. Adapt the program shown in Figure 3.7 so that the user could choose between 3 triangles on a triangle, 4 squares on a square, 5 pentagons on a pentagon or a circle. 6. Write a program that will cause 3 frogs to take turns jumping over each other to get to an empty lily pad. After 3 rounds of jumps, all frogs should jump up and down together and say "Bye".

Figure 3.15: Jumping frogs 7. Write a Scratch program that will find its way out of a simple maze by tracing the right hand wall until it finds the exit. When it exits, it should display the amount of time taken.

Figure 3.16: Solving a maze


Chapter 4 Program Design Tools

Productivity is never an accident. It is always the result of a commitment to excellence, intelligent planning, and focused effort. Paul J Meyer

If you don't know where you are going, any road will get you there. Lewis Carroll, author

If you only have a hammer, you tend to see every problem as a nail. Abraham Maslow, psychologist

By failing to prepare, you are preparing to fail. Benjamin Franklin, inventor

4.1 Different methods for describing a process The communication of instructions and guidelines is a common phenomena. A wide range of methods have been used to facilitate the transmission and understanding of these instructions between individuals. Five of the more common methods are described below: Video demonstration: Instructional video meant to give a sense of being there. However, there is often no way to quickly skim the material and a review would require watching the whole clip again. In addition, time and focus is often distorted from reality by the movie producer in order to point out specific features and events which would be missed otherwise. 53


54

CHAPTER 4. PROGRAM DESIGN TOOLS

URL: http://www.youtube.com/watch?v=FbLU87PYsZE Figure 4.1: Video on cooking a scrabbled egg Recipe: Step by instructions meant to transfer knowledge in textual form between people with some cooking experience. These descriptions tend to use technical language familar to professionals but would require some training for the average person to understand.

Traditional Scrabbled Eggs Ingredients: 3 Eggs 1 cup Cream A pinch of Salt A dash of black pepper Instructions: • Lightly whisk the eggs, cream and a pinch of salt and pepper together until all the ingredients are just combined and the mixture has one consistency. • Heat a small non-stick frying pan for a minute or so, then add the butter and let it melt. Don't allow the butter to brown or it will discolour the eggs. Pour in the egg mixture and let it sit, without stirring, for 20 seconds. Stir with a wooden spoon, lifting and folding it over from the bottom of the pan. Let it sit for another 10 seconds then stir and fold again. • Repeat until the eggs are softly set and slightly runny in places, then remove from the heat and leave for a few seconds to finish cooking. Give a final stir and serve the velvety scramble without delay.

Figure 4.2: Recipe for scrambled eggs[10]


4.1. DIFFERENT METHODS FOR DESCRIBING A PROCESS

55

Graphic step by step description: Storyboards, page navigation maps a sequence of images meant to illustrate the keypoints of a process.

Figure 4.3: Step by step graphic instruction Pseudocode description: Outlines of instructions meant to provide an overall view of a process including its input parameters, outcomes and control points. Generally each line represents another task. Indentation is used to indicate which lines or tasks control the operation of the other lines/tasks. The indented lines are skipped if the condition of the control line no longer holds. This is a verbal way to express the process being described. Algorithm 4.1. Instructions for making scrambled eggs 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18:

Crack 2 eggs Pour into a mixing bowl. Add milk or water Lightly whip with a wire whisk. Put frying pan on the stove with low heat. Add oil or butter to the frying pan. repeat Wait until the pan is hot enough Pour in the scrambled eggs. repeat repeat Wait until the edges of the eggs begin to stiffen Scrap the cooked eggs towards the center until the eggs are fully cooked Slide the cooked eggs onto a plate Serve.

Flowchart: A detailed railroad track representation of a process meant to detail the sequence and control of the individual tasks of a process. The lines and arrows help to lead the


56

CHAPTER 4. PROGRAM DESIGN TOOLS reader through the required sequence of tasks. Control points are represented by diamond shaped comparisons which determine what the next task will be based on the outcome of the comparison. Loops and repeated segments are gathered at collection points to help the reader follow the iterated sequence of tasks.

Flowchart 4.1. Making scrambled eggs

4.2 Program design tools Program design tools provide an overview of of the purpose and basic functions of the software being developed. The process helps to identify data structures and programming algorithms that will be required by this software. In addition, the process helps to highlight potential problems and areas of confusion and unwanted complexity of the software in a way that can be easily and conveniently corrected and simplified. The resulting design documents also provide a basis for testing and debugging the software. Although there are many tools and methods available for designing software, the following sections will describe the most common software techniques.

4.2.1 Flow chart Flowcharting is a very common and useful tool for describing algorithms graphically. They were first used to describe industrial processes in 1924 and have been widely applied to diverse range of engineering and process development applications. Each symbol represents another step of the process. The symbols are connected by arrows to identify the sequence of the steps and the shape of the symbols represent the nature of the task associated with the step.


4.2. PROGRAM DESIGN TOOLS

57

Figure 4.4: IBM Flowcharting Template However, despite the long history and popularity of using flowcharts to describe algorithms, there is no universal single standard for drawing flowcharts. The flowchart template tool shown in Figure 4.4 was created by IBM in the 1980s for system analysts.[11] It contains over 24 symbols that refer to processes that place in the different cabinets of IBM mainframe computers. However, even among software companies like Borland and Microsoft, there is no uniform standard as to the number of symbols used in their software documentation. The meaning of the 7 symbols used in flowcharts for this textbook are described in Table 4.1. Table 4.1: Flowchart Symbols used in this Course Start: the beginning of a procedure or a segment of code

End: the termination of a program or a segment of code

Decision: conducts a comparison whose outcome selects between 2 sequences of code yo determine which code will be executed next. Processing step: represents one or more operatons needed to complete a particular task. Input: Capturing data for processing. These data are most often collected from the user via the keyboard, mouse, microphone, camera or scanning device. However, they can also come from barcode readers, sensors and even searches conducted on the Internet. Output: Convey the results in some appropriate manner. It may involve displaying or printing characters or images, generation of sounds, creating 3-D objects or even changing the state of activators and switches. Loop connection: a point in the software representing the top of the repeated block of code.


58

CHAPTER 4. PROGRAM DESIGN TOOLS

Because a flowchart is composed of many interconnected graphical elements, insertions and deletions will often result in major changes to the layout. In the days when flowcharts were drawn on paper, even minor changes would often necessiate major redrawing of the diagram. As a pencil and paper execise flowcharts can be very timeconsuming when used to describe practical problems. As a result, flowcharts fell out of use by professional software houses until recently. Fortunately, graphical flowchart editors like yEd[12] have revived the art of flowcharting as a useful and essential technique to describe the software being developed. Their user inteface makes the make editing, correction and reformating of flowcharts faster and more convenient. The instructions for downloading and installing yEd are given in Appendix A.2.

Figure 4.5: The user interface for yEd The interface of yEd is shown in Figure 4.5. This program has several palettes of graphic objects in the upper right window pane to be dragged and dropped into place on the graphic work space in the middle of the screen. Attributes such as text labels, line thickness and colors can be changed in the lower right window. Connections are made by dragging and dropping between pairs of objects. The left window panes allow the user to examine the interconnects between the graphic elements.

4.2.2 Pseudo code Pseudocode is an outline that captures the intent of the programmer in an informal language that helps programmers to describe the algorithms used. Pseudocode is a "text-based" program design method that records the sequence of the procedures to be followed within the program


4.2. PROGRAM DESIGN TOOLS

59

being developed. This description is written in a form that could be included as part of the documentation within the source code. The description starts with a simple description of the problem to be solved and then uses clear and concise language to describe each step of the process needed to effect a solution. Each line should start with an action word. Common action words used in pseudocodes are given in Table 4.2.

Table 4.2: Common action words used in pseudocodes Operation type Input: Output: Compute: Initialize: Increase by one: Select:

Common Keywords READ, OBTAIN, GET PRINT, DISPLAY, SHOW COMPUTE, CALCULATE, DETERMINE SET, INIT INCREMENT, ADD1TO WITH

The rules for writing pseudocode are fairly simple. Indentation is required for all procedural steps that are controlled by loop and condition controllers (such as WHILE, DO, FOR, IF, or SELECT). There are common action words that are often used as keywords within pseudocode. The following 4 examples of pseudocode description of software is given below:

1. Airplane cockpit computers issue various warnings to help pilots fly the airplane. Algorithm 4.2 and Flowchart 4.2 describe a simple warning controller for a small aircraft that checks if the airplane is moving at sufficient speed with enough remaing runway to takeoff safely and issue appropriate abort takeoff warnings when necessary.

Algorithm 4.2. Pilot warning system 1: while airplaneSpeed > 0 AND altitude < 3 do 2: if airplaneSpeed > 120 then Print "Cleared to fly" 3: else if remainingRunway < 200 then Print "Abort takeoff!" 4: else if remainingRunway < 0 then Print "Brace for crash!" 5: end if 6: end while


60

CHAPTER 4. PROGRAM DESIGN TOOLS

Flowchart 4.2. Cockpit takeoff warning controller

2. Calculate the aggregate volume of a series of containers. The input contains the number of containers in the series followed by the volume of each of the individual containers. The program should read this data in and create a list showing the size of each container followed by a line that gives the aggregate total capacity. Algorithm 4.3. Calculating storage capacity 1: SET the ContainerCount to 0 2: SET the TotalVolume to 0 3: INPUT the TotalNumberOfContainers 4: while ContainerCount < TotalNumberOfContainers do 5: READ in the container id width, height, depth 6: SET ContainerVolume to width Ă— height Ă— depth 7: Print container id and ContainerVolume 8: INCREMENT THE TotalVolume by ContainerVolume 9: INCREMENT the ContainerCount by 1 10: end while 11: Print the TotalVolume

Flowchart 4.3. Calculating storage capacity


4.2. PROGRAM DESIGN TOOLS

61

3. An Application to Convert Percentages to Letter Grades

Algorithm 4.4. Score to Letter Grade 1: SETUP variables 2: repeat 3: PROMPT for input 4: INPUT Score value 5: if Score >= 0 then 6: if score = 4 then 7: Grade ← "A" 8: else if score = 3 then 9: Grade ← "B" 10: else if score = 2 then 11: Grade ← "C" 12: else if score = 1 then 13: Grade ← "D" 14: else 15: Grade ← "F" 16: end if 17: DISPLAY Grade 18: end if 19: until Score < 0 20: Print logout message

Flowchart 4.4. Score to Letter Grade

4. A robot that follows a line but go counterclockwise around any obstacle in the way


62

CHAPTER 4. PROGRAM DESIGN TOOLS

Algorithm 4.5. Robot line following behavior 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41:

SET behavoir to LineTrace START at the BeginningSquare repeat if behavoir = LineTrace then if there is an obstacle in front then SET behavoir to AvoidObstacle else if line turns right then TURN right else if line turns left then TURN left else MOVE forward one square end if else if behavoir = AvoidObstacle then while the obstacle is in front do TURN right end while if ostacle is not on the left then TURN Left end if MOVE Forward one square if robot is not on the line then SET behavoir to TraceObstacle end if else if behavoir equals TraceObstacle then if robot is on the line then SET behavoir to TraceLine TURN right else while obstacle is in front do TURN right end while if obstacle is not on the left then TURN LEFT end if MOVE forward one square end if end if until the robot is on the LastSquare STOP the robot SOUND a beep


4.2. PROGRAM DESIGN TOOLS Flowchart 4.5. Line-tracing robot behavoir

63


64

CHAPTER 4. PROGRAM DESIGN TOOLS

4.3 Basic programming patterns Variables and constants act as data containers to hold discrete informate in specific locations in memory which the programmer will reference by name. The most common processes applied to variables is assigning, and retrieving values. Algorithm 4.6. Storing information in variables and constants SET the CurrentMonth to January SET SalaryLevel to 5

Operators, Expressions and Statements provide the ability to combine and manipulate values according to defined functions and subroutines. The new values can be used in comparisons and control tests or can be saved in variables or files. SET Taxes to TaxRate x Salary SET NumOfChildren to Sons + Daughters INCREMENT the CurrentYear by 1 SET Mon to first3char(CurrentMonth) Sequential processes represents a segment of code that define a series of tasks to be completed in order. SET Income to Sum(Salary,Tips,Bonus) SET Taxes to Income * 0.20 SET PayChequeAmount to Income - Taxes PRINT PayCheque Conditional execution allows the programmer to specify a segment of code that is to executed when a test condition succeeds. The programmer also has the option to specify an alternative segment of code if the test condition fails. if PaperOut then TURN ON PaperOutLED PAUSE printing else TURN OFF PaperOutLED RESUME printing end if Loop structures define segments of code to be repeated. Usually there is a condition that needs to be met for the repetition to be allowed. SET counter to 1 while counter < 10 do PRINT the value of the counter and counter2 INCREMENT counter by 1 end while Functions and subprograms allow the programmer to establish blocks of code that can called from other parts of the program. These blocks of code act as functional units that can


4.3. BASIC PROGRAMMING PATTERNS

65

recieve information from the caller in the form of parameters and can be designed to return a value to the caller. Function and subprograms provide a means to hide details of the computation in code segments that can be reused. function Distance(dx,dy) return SQRT(dx2 + dy2 ) end function Calling functions. SET (FrogX,FrogY) to (0,0) SET (BugX,BugY) to (100,100) while Distance(FrogX-BugX,FrogY-BugY) > 2 do INCREMENT BugX by random(-3,3) INCREMENT BugY by random(-3,3) end while Threads and parallel processes allow the programmer to define segments of code that are to be executed at the same time. This commonly used in animation and games. THREAD FrogMovement while Distance(FrogX-BugX,FrogY-BugY) > 2 do if Distance(FrogX-BugX,FrogY-BugY) <20 then INCREMENT FrogX by 5 * (FrogX-BugX) / abs(FrogX -BugX) INCREMENT FrogY by 5 * (FrogY-BugY) / abs(FrogY - BugY) end if end while END THREAD THREAD BugMovement while (do)DistanceFrogX-BugX,FrogY-BugY > 2 if Distance(FrogX-BugX,FrogY-BugY) < 15 then INCREMENT BugX by -2 * (FrogX-BugX) / abs(FrogX -BugX) INCREMENT BugY by -2 * (FrogY-BugY) / abs(FrogY - BugY) else INCREMENT BugX by random(-3,3) INCREMENT BugY by random(-3,3) end if end while END THREAD Using Threads. SET (FrogX,FrogY) to (0,0) SET (BugX,BugY) to (100,100) START FrogMovement START BugMovement


66

CHAPTER 4. PROGRAM DESIGN TOOLS Table 4.3: Information to be included in Software Sourcecode • General Program information: – Name of Program – Programmer and copyrights – Purpose of the program – Pseudocode of the program • Information about each function: – Purpose of the method/function – Pseudocode of the method/function – Precondition: What did you expect to be true before – Post condition: Values to be returned

4.4 Commenting source code Programmer documentation is essential for long-term maintenance and support of software. However, most software is supported by someone other than the original program and even the original programmer will forget the rationale behind all the choices made in putting a program together. Therefore, programmers must write software so that it can be read, understood and supported by others. Good programs will not only work well but they also read well so that others can expand the code to enhance its features. Documentation included within a program should be divided into 2 major parts: the general description of the program and the definitions of the functions and methods. The contents of these sections are listed in Table 4.3. Pseudocode is essential to the development of clear and concise software documentation.

Chapter 4 Review Key Terms: array algorithm variable loop subroutine condition boolean

Discussion Questions:


4.4. COMMENTING SOURCE CODE

67

Key Terms: Discussion Questions: 1. In 1968 the Beetles released their hit single "Hey Jude". Nearly fifty years later a blogger released a flowchart version of the lyrics which went viral despite the errors in the Both versions are shown in Table 4.4. Document the changes needed to correct the flowchart to match the original lyrics. Table 4.4: Comparison between the Lyrics of Hey Jude and a Flowchart Version Lyrics Hey Jude, don't make it bad Take a sad song and make it better Remember to let her into your heart Then you can start to make it better Hey Jude, don't be afraid You were made to go out and get her The minute you let her under your skin Then you begin to make it better Hey Jude, don't let me down You have found her, now go and get her Remember to let her into your heart Then you can start to make it better Hey Jude, don't make it bad Take a sad song and make it better Remember to let her under your skin Then you'll begin to make it Better better better better better better, ohhh. Nah nah nah nah nah nah, nah nah nah, hey Jude, Nah nah nah nah nah nah, nah nah nah, hey Jude, Nah nah nah nah nah nah, nah nah nah, hey Jude, Nah nah nah nah nah nah, nah nah nah, hey Jude, Nah nah nah nah nah nah, nah nah nah, hey Jude.

1

Flowchart Version


68

CHAPTER 4. PROGRAM DESIGN TOOLS

Exercises: 1. Design a program using 2. Use

Laboratory Exercises: 1. Create a version 2. Create a program 3. Find the sum


Chapter 5 Basic Concepts of C Programming

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. Martin Fowler, software engineer

Edison failed 10,000 times before he made the electric light. Do not be discouraged if you fail a few times. Napoleon Hill, business consultant

Christopher Columbus'discovery changed the future. He did not have a complete map but what he had was a bold vision and he was confident that the journey he set out on would be worth it. It was as it lead him to a new world. Gabriel Byrne, Irish actor and director

5.1 Getting started C Programming is widely used in all levels in computer development. Since its first appearance in the late 1970s, C has been used to develop operating systems, system utilities and libraries, and countless applications. The American National Standards Institute (ANSI) standardized the language in the 1980s with the release of ANSI C, further enhancing the portability of software developed in this language. It is widely accepted that the C language has been the inspiration and development environment for the subsequent development of many other programming languages. The source code to script languages like PHP, Perl, and Ruby and operating systems like Linux and Solaris are developed and maintained in C. In addition runtime libraries for many languages are written as well as the libraries and compiled in C. However, C is a compiled language requiring a different process for developing and running program than the IDE and interpretor of Scratch. This process is shown in Figure 5.1 and can be described as follows. The commands of a program to be recorded in a text file in the manner 69


70

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

Figure 5.1: Steps to run a program in the C language shown in Code Example 5.1. Once the source code has been prepared and saved to a file called hello.c, the compiler is then executed with the following command line: > gcc hello.c -o hello.exe This initiates the multi-phase process as shown in Figure 5.1. The GNU C compiler (gcc) can produce output for each stage of this process using command line switches. The first stage involves expansion of macros and compiler directives which is then translated into assembly language source. The assembly code is then translated into machine language and place in binary link objects. The linker then links all the parts together with a run-time language to create the final product which is an executable program. On some operating system , the permission and properties of the executable program must be set to executable before the compiled program can be run. The actual execution is initiated with the following command line. > hello.exe The behaviour of a hello world program in C is very similar to that one written in Scratch. The object is to create and run a program that displays on the screen a simple message (i.e., Hello, World!) The source code for the C version is shown in Code Fragment 5.1. The compiler directive in Line 1 links the program with a standard library of Input and Output functions that links the program to the operating system. Code Example 5.1. Hello.c 1 2 3 4 5 6 7

# include <stdio .h > int main ( void ) { printf (" Hello , World !\ n"); return (0) ; }


5.2. BASIC BUILDING BLOCKS

71

5.2 Basic building blocks The basic units that are used in programming in C are described in the following sections. Together these form the foundations common to software written in C.

5.2.1 Variables and constants The use of memory to store information is a critical and important part of program. In C units of memory can be referenced by name as variables and constants or by address as pointers (which will be covered in detail in Chapter 8 Because the compiler must manage the use of memory, in C, the type of all variables and constants must be declared to ensure that sufficent memory is allocated. Type declarations also ensures that the proper alignment and treatment of information as data is manipulated. For example, integers must converted to floating point numbers before any arithmetric operation with a floating point number.

Figure 5.2: Variables must be declared by type and set to known values. The C language supports six basic data types shown in Table 5.1. Each of these data types is actually a different type of numerical representation as described in an earlier in Section 2.2.4. Because ANSI C language predates the emergence of the Unicode standard, support for world scripts within applications written in C requires third party libraries.


72

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING Table 5.1: C basic data structures Data type char short int long float double

Description character short integer integer long integer floating point double-precision floating point

Size 1 byte 2 bytes 4 bytes 8 bytes 4 bytes 8 bytes

5.2.2 Operators and precedence The operators of the C language are shown in Table 5.2. They have been arranged by level of precedence from the highest to the lowest level of precedence. Both unary and teritary operators (Levels 2 and 13, respectively) are applied within an expression from right to left. All other operators are applied left to right within an expression. Table 5.2: Precedence and meaning of C Operators Level 1

2∗

3 4 5

6

Operator () [] -> . ! ~ ++ -+ * (type) sizeof * / % + << >> < <= > >=

Description Parenthesis Array index marker Data structure field left to right Logical NOT Bit-wise Not Increment by 1 Decrement by 1 Addition Negation Pointer Type casting Data structure size Multiplication Division Modulus Addition Subtraction Bit shift left Bit shift right Less than Less than or equal Greater than Greater than or equal

Level 7 8 9 10 11 12 13∗

14

15 ∗

Operator == != & ^ | && || ?: = += -= *= /= %= &= ^= +|=+ <<= >>= ,

Description Equals Not Equals Bitwise AND Bitwise XOR Bit-wise OR Logical AND Logical OR Conditional operator Assignment Additive assignment Subtractive assignment Multiplicative assignment Division and assignment Modulus and assignment Bitwise AND and assignment Bitwise XOR and assignment Bitwise OR and assignment Left shift and assignment Right shift and assignment Unit separator

Operation of these lefts are applied right-to-left

Table 5.3 shows the expected outcomes of bitwise operations. When applied to integers, these operations are conducted on a bitwise manner. It should be noted that the binary shift left and right are equivalent to multiplying and dividing by the corresponding powers of 2. Thus, x<<3 would be the same as x * 8. Similarly, x>>2 would be the same as x/4.


5.2. BASIC BUILDING BLOCKS

73

Table 5.3: Bit-wise Outcomes of Bit-wise Operators

NOT: (~A) A

AND: (A & B)

T F

OR:

F T

(A | B)

B A

T F

T T F

XOR: (A ^ B)

B F F F

A

T F

T T T

B F T F

A

T F

T F T

F T F

Test of Binary Operators Expression A ~A B A&B A|B A^B A<<2 A>>2

Decimal = 26 = -27 = 15 = 10 = 31 = 21 = 104 = 6

Binary (00011010) (11100101) (00001111) (00001010) (00011111) (00010101) (01101000) (00000110)

Figure 5.3: Output of the bitops.c program Code Fragment 5.2 demonstrates how these binary operators work with 8 bit binary numbers. In this program, the function printNumber() prints a single line that labels the origin and decimal value of the number (Line 7). Since the C language has no built in binary print format, the function printBinary()provides a binary display of the integer value is accomplished by the the loop described in Lines 16-20. The conditional operator was used to prints the corresponding 0 or 1 value of the leftmost bit (Bit7 ) which has the equivalent decimal value of 27 or 128. After this, all the bits are shifted one bit left (in Line 19) and the process is repeated. Line 17 was added to truncate the shifted integer to 8 bits in order to prevent the number from growing too large. This process is repeated 8 times to effect the display of all bits in a single byte integer. This function greatly simplifies the task of displaying bit manipulations of integers in the main() function (Lines 41-44). The program is compiled and executed using the following command shell commands. The output of this program is shown in Figure 5.3. > gcc bitops.c -o bitops.exe > bitops In the C language, the sequence by which an operator would be executed is determined by both its position within the expression and its relative level of precedence. Since all expressions are calculated within the registers of the CPU, the results of the operation are still the register values and available for the next operation regardless of whether the next operation is a calculation, assignment or comparison. However, using this feature of C is often a source of great confusion. On one hand it leads to provides an opportunity to write very terse code but at the


74

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

risk of creating code that is hard to understand because of the endless stream of operators. An example of this can be seen in Line 3 of Code Fragment 5.4. Most C compilers have some form of code optimization. In this way, the compiler rearranges code written by the programmer to result in an executable that runs quickly. This way the Functions obsured() and readable() in Code Fragment 5.4 actually do the same thing and compile to the same code in Assembly language by gcc. However, most readers would agree that the readable() version would be far easier to develop and debug. Writing code that is easy to read and understand will minimize time spent debugging a program. Obfuscated code should be avoided despite the popularity of C puzzle books[13] and international obscure programming contest[14].


5.2. BASIC BUILDING BLOCKS

75

Code Example 5.2. bitops.c: a program to illustrate binary operators 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

/* bitops .c: a program to demonstrate bitwise operators programmed and tested in gcc within MinGW (c) Copyright 2013 by R. Batzinger . All rights reserved */ # include <stdio .h> /* ***** printBinary () ********************** Purpose : to output 8bit binary numbers in Base 2 Parameters : a string label and a value Output : binary digits values */ void printBinary (int x) { int i; for(i = 0; i < 8; i++) // For each bit in a byte .... { x &= 255; // Trunctate to 8 bits printf ("%d" ,(x & 128)? 1 : 0); // leftmost bit digit x <<= 1; // shift number 1 bit to the left } } /* ***** printNumber () ********************** Purpose : to format and print 8bit binary numbers Parameters : a string label and a value Output : a string label , decimal and binary values */ void printNumber (char *msg , int x) { printf ("%10s = %3d (",msg ,x); // label , decimal value printBinary (x); // binary value printf (")\n"); // close the line } int main () { int A = 26;

int B = 15;

//

test values

printf ("\ nTest of Binary Operators \n"); printf ("\ nExpression Decimal Binary \n"); // test cases printNumber ("A", A); printNumber ("~A", ~A); printNumber ("B", B); printNumber ("A&B", A&B); printNumber ("A|B", A|B); printNumber ("A^B", A^B); printNumber ("A<<2", A <<2); printNumber ("A>>2", A >>2); return (0); }


76

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

Code Example 5.3. increment.c: a program to illustrate ways to increment an integer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

# include <stdio .h> void display (int num , expVal , varVal ) { printf ("%3d.%9d%9d\n\n", num ,expVal , varVal ); } int main () { int A; printf ("Test ( Expression ) A\n\n") ; A = 1; display (1, (A = A + 1) ,A); A = 1; display (2, (A += 1), A); A = 1; display (3, (A++) , A); A = 1; display (4, (++A), A); return (0); }

Output: Test (Expression) A 1.

2

2

2.

2

2

3.

1

2

4.

2

2

Code Example 5.4. Comparison between 2 styles of C programming 1 int obsured (int x, y) 2 { 3 return ((((x > 0) ? x : -x) > ((y > 0) ? y : -y))? 4 x + y : x - y); 5 } 6 7 int readable (int x, y) 8 { 9 if (abs(x) > abs(y)) 10 return (x + y); 11 else 12 return (x - y); 13 }


5.2. BASIC BUILDING BLOCKS

77

Code Example 5.5. accuracy.c: program to demonstrate floating point errors 1 2 3 4 5 6 7 8 9 10 11 12 13

# include <stdio .h> int main () { int i; float x = 0.0; for (i = 0; i < 1000; x = x + 0.001; printf ("%f\n", x); return (0); }

i++)


78

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

5.2.3 Comments Comments were used to describe purpose and process of a program works. It provides a record to assist understanding of programmers who will want to make changes. In this way, important documentation becomes part of the source code to provide critical information for ongoing maintenance and development of the program. In ANSI C two forms of comments are supported: comment blocks which consist of everything between the comment block markers /*...*/ and an inline comment that starts with // and continues to the end of the line. Both types of comments were used in Code Fragment 5.2. While there is no one standard for comments, there is a general consensus within the software industry that comments should contain the following information. Copyright notices are also included to provide legal protection. • General information about the program – Program information: Name of Program, programmer and copyrights – Explanations to clarify special issues – Purpose and use of the program – Meaning of the global variables and commandline switches and parameters • Information about the function: – Purpose of the method – Precondition: What did you expect to be true before – Post condition: What values are changed, output or returned – Meaning of the local variables – Pseudocode of the process

5.2.4 Expressions and statements Commands in the C language are parsed and understood in units called expressions. Each expression represents a separate task such as comparison of two numbers, changing a value of a variable, receiving a line of input and printing a line of output.


5.2. BASIC BUILDING BLOCKS

Supplemental Material 5.1. Why study a language like C? Low Level Features: The C programming language models the inner workings of the CPU providing low level features available to Assembly language compilers, such as status of register contents, direct and indirect memory addressing modes, and bitwise operations. Many C compilers can translate C programs into both machine executable sequences and their assembly language code equivalent. This gives the programmer the flexibility and performance of an Assembler within a high language construct. Software Portability: The ANSI Standardization of the C language allows for programmers to develop a single source code for software solutions that can be compiled into machine native executable programs that will run on a wide variety of CPUs, platforms and operating systems. Compiler directives and preprocessor utilities provide additional support for specific features of operating systems and computer equipment. The language is extendable: The C language provides support for user defined data structures and programming macros. Additional refinements can be achieved using conditional compiler directives. In addition, functions can be combined into modules that can be precompiled and linked as needed. Bit Manipulation: C Programs can manipulate specific bits of memory with a variety of bit-wise operators and bit-fields. This also gives C programs the ability to control specific bit ports of hardware. High Level Features: C program allows natural expression of mathematical formula. Output formats support templates. The language also has a built-in macro language. Previous languages have there pros and cons but C Programming collected all useful features of previous languages thus C become more effective language. Modular Programming: The C language has compiler directives that support modular program design. Individual modules can be developed and compiled independantly. The C compiler calls a linker to load all modules together with the runtime librfary to create the completed executable program Efficient Use of Pointers: C pointers provide the ability to determine the address location of data held in memory. These address values can also be incremented and decremented to determine the location of the next and the previous items within an array. Efficient Executable Runtime Code: C compilers are highly optimized to produce runtime versions of the software that execute quickly and use a minimum number of bytes.

79


80

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

5.3 Program Flow 5.3.1 Conditional execution • Teritery operator x = (boolean expression) ? valueIfTrue : valueIfFalse; • Simple condition if (expression) statement; • Control a block of statements if (expression) { Block of statements; } • Choosing between 2 alternatives if (expression) { Block of statements; } else { Block of statements; } • a nested chain of conditions if (expression) { Block of statements; } else if(expression) { Block of statements; } else { Block of statements; } • Switch between multiple alternatives


5.3. PROGRAM FLOW

81

switch( expression ) { case constant-expression1: statements1; [case constant-expression2: statements2;] [case constant-expression3: statements3;] [default : statements4;] }

5.3.2 Loop structures • While loop while (boolean_expression) { Single statement or Block of statements; } • For loop for( expression1; expression2; expression3) { Single statement or Block of statements; } • Do While Loop do { Single statement or Block of statements; }while(expression); • Using Break and Continue #include <stdio.h> void main() { int i; for( i = 0; i <= 10; i ++ ) { if( i == 5 ) continue; if (i == 9 ) break; printf("Value: %d\n", i ); } }

Value: Value: Value: Value: Value: Value: Value: Value: Value:

0 1 2 3 4 6 7 8 9


82

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

5.4 Functions

Functions provide a way to group program statements as a named unit that can be invoked from other parts of a program. It is possible for a function to receive specific values from the calling routine via parameters and to return a value that results from its calculations. The processing within the function is usually done with local variables which are separate from those used in other parts of the program. Names of function must be unique within a C Program and are global to all parts of a C program.

int add(int a, int b) { int sum = a + b; return sum; }


5.4. FUNCTIONS

5.4.1 Standard Library Functions in stdlib.h

atof atoi atol atoll strtod strtof strtol strtold strtoll strtoul strtoull rand srand calloc free malloc realloc abort atexit exit getenv system bsearch qsort abs div labs ldiv llabs lldiv

String conversion Convert string to double Convert string to integer Convert string to long integer Convert string to long long integer Convert string to double Convert string to float Convert string to long integer Convert string to long double Convert string to long long integer Convert string to unsigned long integer Convert string to unsigned long long integer Pseudo-random sequence generation Generate random number Initialize random number generator Dynamic memory management Allocate and zero-initialize array Deallocate memory block Allocate memory block Reallocate memory block Environment Abort current process Set function to be executed on exit Terminate calling process Get environment string Execute system command Searching and sorting Binary search in array Sort elements of array Integer arithmethic Absolute value Integeral division Absolute value Integral division Absolute value Integral division

83


84

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

5.4.2 Mathematical Functions in math.h Function sin(x) cos(x) tan(x) asin(x) acos(x) atan(x) sinh(x) cosh(x) tanh(x) exp(x) log(x) log10(x) pow(x,y) sqrt(x) ceil(x) floor(x) fabs(x) ldexp(x,n) frexp(x, int *ip)

modf(x, double *ip) fmod(x,y)

Description sine of x: sin(x) cosine of x: cos(x) tangent of x: tan(x) arc sine of x: arcsin(x) arc cosine of x: arccos(x) arc tan of x: arctan(x) hyperbolic sine of x: sinh(x) hyperbolic cosine of x: cosh(x) hyperbolic tangent of x: tanh(x) exponential function ex natural logarithm ln(x) base 10 logarithm log 10(x) Power function√xy square root of x smallest integer not less than x, as a double. ⌈x⌉ largest integer not greater than x, as a double. ⌊x⌋ absolute value |x| x × 2n splits xinto a normalized fraction in the interval [1/2, 1] which is returned, and a power of 2, which is stored in *exp. If xis zero, both parts of the result are zero. [0.5 · · · 1] × 2ip splits xinto integral and fractional parts, each with the same sign floating-point remainder of x/y, with the same sign as x. If yis zero, the result is implementation-defined. x mod y

5.4.3 Parameters 5.4.4 Return values 5.4.5 Local vs Global variables

5.5 Compiler Directives 5.5.1 Macro 5.5.2 Conditional compiling

5.6 C Programming Examples 5.6.1 Grade conversion Score Enter Grade Enter Grade

to Grade Convertor Score:100 = A Score:75 = B


5.6. C PROGRAMMING EXAMPLES

Supplemental Material 5.2. Avoiding the Six Most Common Programming Errors • Missing end of expression marker: The lack of a semi-colon will result in the attempt to join two unrelated expressions into one. This simple error may create a long list of other errors: x += 2 y += 4; should be x += 2 ; y += 4; • Syntax errors: Generally appear as typos or a sequence of tokens in the wrong order. prtf[x,y,"(%d,%d)"]; should be printf("(%d,%d)",x,y); • Undeclared or undefined variables: information from variables which have not been declared or defined is bogus. int y,xval = 5; printf("%d %d",x,y); should be int y = 3, x = 5; printf("%d %d",x,y); • Data type mismatch: mistakes arise when variables are referenced by the wrong data type is used. int x = 5.0; printf("%f\n",x); should be float x = 5.0; printf("%f\n",x); • Infinte Loop: the repetition never ends because the loop counter or the loop status never changes. int i = 0; while (i < 10) printf("%d\n",i++); should be int i = 0; while (i < 10) printf("%d\n",i);]; • Off by One Bug: It is easy to miscalculate the beginning and end of loops. int x[] = {1,2,3}; for (i = 1; i < 3; i++) printf("%d\n",x[i]); should be int x[] = {1,2,3}; for (i = 0; i < 3; i++) printf("%d\n",x[i]);

Enter Grade Enter Grade Enter Grade Enter

Score:72 = C Score:78 = B Score:65 = C Score:40

85


86

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

Table 5.4: Comparison of Pseudocode and Flowchart of an Application to Convert Percentages to Letter Grades Pseudocode Display application name Setup variables loop Prompt for input input Score value if Score >= 0 Grade = convert2Grade(Score) display Grade until Score < 0 Display logout message

Grade = F Enter Score:51 Grade = D Enter Score:-1 End of Program

Flowchart


5.6. C PROGRAMMING EXAMPLES

87

Code Example 5.6. Converting a percentage to a letter grade: chained if version 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

# include <stdio .h > int main ( void ) { int score ; char * grade ; printf (" Score to Grade Convertor \n"); do { printf (" Enter Score :"); scanf ("%d" ,& score ); if( score >= 85) else if( score >= else if( score >= else if( score >= else if( score >=

75) 65) 50) 0)

grade grade grade grade grade

= = = = =

printf (" Grade = %s\n", grade ); } while ( score >= 0); printf (" End of Program \n"); exit (0) ; }

"A"; "B"; "C"; "D"; "F";


88

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

Code Example 5.7. Converting a percentage to a letter grade: Function version 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

# include <stdio .h > char * convertor (int { if( score >= 100) else if( score >= else if( score >= else if( score >= else if( score >= else if( score >= else }

score )

85) 75) 65) 50) 0)

return ("X"); return ("A"); return ("B"); return ("C"); return ("D"); return ("F"); return ("X");

int main ( void ) { int score ; char * grade ; printf (" Score to Grade Convertor \n"); do { printf (" Enter Score :"); scanf ("%d" ,& score ); grade = convertor ( score ); if( strcmp ( grade ,"X") != 0) printf (" Grade = %s\n", grade ); } while ( score >= 0); printf (" End of Program \n"); exit (0) ; }


5.6. C PROGRAMMING EXAMPLES

Code Example 5.8. Converting a percentage to a letter grade: Function version 1 char * convertor (int score ) 2 { 3 switch ( number /5) 4 { 5 case 1: case 2: case 3: case 4: case 5: 6 case 6: case 7: case 8: case 9: case 10: 7 return ("F"); 8 9 case 11: case 12: 10 return ("D"); 11 12 case 13: case 14: 13 return ("C"); 14 15 case 15: case 16: 16 return ("B"); 17 18 case 17: case 18: case 19: case 20: 19 return ("A"); 20 21 default : 22 return ("X"); 23 } 24 }

89


90

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

Code Example 5.9. Score to Grade Conversion: student submission 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

# include <stdio .h > int main ( void ) { int number ,i; for(i =0;i <2; i ++) { i - -; scanf ("%d" ,& number ); if( number <=50) printf (" Grade :F\n"); else if( number <=55) printf (" Grade :D\n"); else if( number <=65) printf (" Grade :C\n"); else if( number <=75) printf (" Grade :B\n"); else if( number >=85) printf (" Grade :A\n"); if( number <0) { printf (" End Program "); break ; } } return 0; }


5.6. C PROGRAMMING EXAMPLES

5.6.2 Prime Number Listings Code Example 5.10. Printing all the prime numbers less than 50 1 /* primes .c - displays a list of all prime numbers less than 50 2 developed in gnu C by R Batzinger , Payap University 3 (c) Copyright 2013 by R Batzinger . All rights reserved 4 ********************************************************** */ 5 # include <stdio .h> 6 # define TRUE 1 7 # define FALSE 0 8 # define MAXNUMBER 50 9 /* ********************************************************* 10 isprime - checks if a number is prime or not 11 12 works by checking whether 2 or any odd number less than 13 or equal to the SQRT of the number leaves no remainder 14 15 parameter : number to be tested 16 17 returns : Returns TRUE if the number is prime 18 Returns FALSE if the number is not prime 19 */ 20 int isprime (int number ) 21 { int i = 2; 22 23 while(i * i <= number ) 24 { if (( number % i) == 0) return ( FALSE ); 25 i += (i == 2) ? 1 : 2 ; 26 } 27 return (TRUE); 28 } 29 30 int main(void) 31 { int i; 32 33 printf (" Prime numbers less than %d\n", MAXNUMBER ); 34 35 for (i = 1; i < MAXNUMBER ; i++) 36 if ( isprime (i)) printf ("%3d ", i); 37 38 printf ("\n"); 39 return (0); 40 }

91


92

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

Supplemental Material 5.3. Steps to Writing Algorithms The following guidelines describe steps for effective algorithm development[15]. 1. Understand the problem to be solved: A common mistake is to begin developing an algorithm before the problem to be solved is fully understood. It is critical to understand the main questions associated with the problem, such as • What data does the input contain? • What information will be required by the algorithm? • What data processing will be required to determine the solution? • What is the desired output or result? 2. Devise a plan: Unless one has walked through a series of tasks, it is really hard to write instructions that make sense. Thus, the first step in devising a plan is to personally perform the series of tasks that lead to the solution. This would require: • Write down the specific steps required to convert the input into a solution • For each step, identify the information required and the results obtained • For each piece of information, determine whether it should come directly from the input or from variables that hold results of previous steps 3. Translate the plan into pseudocode: Develop a series of detailed instructions based on the plan develop in the last step. 4. Test the design: Test the algorithm by using appropriate data and following the pseudocode step by step to verify the outcomes. The test data should contain both legitimate examples and serious degenerate cases. As errors are found, the pseudocode must be corrected and updated.

Chapter 5 Review Key Terms: Discussion Questions: Exercises: 1. aaa 2. The code show in Code Fragment 5.12 is an early student draft of the computer application and it has a number of issues:


5.6. C PROGRAMMING EXAMPLES

93

Laboratory Exercises: 1. Write three versions of a program that counts from 1 to 10, using loops controlled by for(){}, while(){} and do {} while();, respectively. 2. Rewrite the following C program, using for() loops to replace all do ... while() loops. #include <stdio.h> void main() { int a[] = {9,8,7,6,5,4,3,2,1}; int N = sizeof(a)/ sizeof(int); int flg, i; do { flg = 0; i = 0; do { if (a[i] > a[i+ 1]) { flg = 1; tmp = a[i]; a[i] = a[i+1]; a[++i] = tmp; } } while (i < N-1); } while (flg); i = 0; do { printf("%d", a[i]); } while (++i < N); }


94

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

Code Example 5.11. Finding the prime factors of a number 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

# include <stdio .h > int main ( void ) { int number ,i, factor ,exp , numfactors ; do { factor =2; numfactors =0; printf (" Enter a positive number : "); scanf ("%d" ,& number ); while ( factor <= number ) { exp =0; while ( number % factor ==0) { exp ++; number = number / factor ; } if(exp >0) { if( numfactors >0) printf ("* "); if(exp >1) printf ("(% d ^ %d) ",factor , exp ); else printf ("%d ", factor ); numfactors ++; } if( factor ==2) factor = 3; else factor += 2; } printf ("\n"); } while ( number > 0); printf (" End of Program \n"); return 0; }


5.6. C PROGRAMMING EXAMPLES

Figure 5.4. Variables must be declared by type and set to known values. Missing end of expression marker: Syntax errors:

Undeclared variables: Data type mismatch: Infinte Loop: Off by One Bug:

95


96

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

Code Example 5.12. Score to Grade Conversion: student submission 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

# include <stdio .h > int main ( void ) { int number ,i; for(i =0;i <2; i ++) { i - -; scanf ("%d" ,& number ); if( number <=50) printf (" Grade :F\n"); else if( number <=55) printf (" Grade :D\n"); else if( number <=65) printf (" Grade :C\n"); else if( number <=75) printf (" Grade :B\n"); else if( number >=85) printf (" Grade :A\n"); if( number <0) { printf (" End Program "); break ; } } return 0; }


5.6. C PROGRAMMING EXAMPLES

Code Example 5.13. Finding the prime factors of a number 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

# include <stdio .h > int main ( void ) { int number ,i, factor ,exp , numfactors ; do { factor =2; numfactors =0; printf (" Enter a positive number : "); scanf ("%d" ,& number ); while ( factor <= number ) { exp =0; while ( number % factor ==0) { exp ++; number = number / factor ; } if(exp >0) { if( numfactors >0) printf ("* "); if(exp >1) printf ("(% d ^ %d) ",factor , exp ); else printf ("%d ", factor ); numfactors ++; } if( factor ==2) factor = 3; else factor += 2; } printf ("\n"); } while ( number > 0); printf (" End of Program \n"); return 0; }

97


98

CHAPTER 5. BASIC CONCEPTS OF C PROGRAMMING

Supplemental Material 5.5. Steps for Writing a Program 1. Analyze the Problem: Understand the problem to be solved, identify the information required and determine the nature of the program output or response. 2. Develop an Algorithm in Pseudocode: Develop a detailed description of the steps required to gather the input and convert it into the required output 3. Translate the Algorithm Pseudocode into Program Code: Using the pseudocode as the initial comments, translate the code line by line and visually vertify the integrity of the program. 4. Test and Debug the Program: Attempt to copile Subject the program to a series of test cases to determine that the program is creating the desired output. Correct any errors discovered. 5. Polish the Program: Revise the program to ensure clearity and consistency in the variable names. Check for bottlenecks and optimize performance. Refractor the coding to improve modularity and readability.


Chapter 6 Composite Data Types 6.1 Array • The concept of an variable. – An efficient way to store lists of data. – Each cell is the same size. – The cells are physically located sequentually in memory – Can be used for looking things up like bitmapped graphics for characters, exchange rates, grades in a course. – Can be used for gathering information to be sorted • Two-dimensional array. • A multi-dimensional array. void bubblesort(int unitcount, int dataset[]) { int i, tmp, flg = 1; while (flg) { flg = 0; for (i = 0; i < unitcount -1; i++) { if (dataset[i] > dataset[i + 1]) { tmp = dataset[i]; dataset[i] = dataset[i + 1]; dataset[i + 1] = tmp; flg = 1; } } unitcount--; } } 99


void combsort(int unitcount, int dataset[]) { int flg, tmp, offset = unitcount / 2; while ((offset > 1) && (flg)) { if (offset < 1) offset = 1; flg = 0; for (i = 0; i + offset < unitcount; i++) { if (dataset[i] > dataset[i + 1]) { tmp = dataset[i]; dataset[i] = dataset[i + offset]; dataset[i + 1] = tmp; flg = 1; } } offset--; } } void quicksort(int dataset[], int leftside, int rightside) { int lft, rt, midval, tmp; lft = leftside; rt = rightside; midval = dataset[(lft + rt)/2]; do { while(dataset[lft] < midval) lft++; while (midval < dataset[rt]) rt--; if (lft <= rt) { tmp = dataset[lft]; dataset[lft] = dataset[rt]; dataset[rt] = tmp; lft++; rt--; } } while (rt > lft); if (leftside < rt) quicksort(dataset,leftside,rt); if (lft < rightside)


quicksort(dataset,lft,rightside); }


int numerals[10][7] = { {// zero 0x3C, // 00111100 0x42, // 01000010 0x42, // 01000010 0x42, // 01000010 0x42, // 01000010 0x42, // 01000010 0x3C // 00111100 }, {// one 0x08, // 00001000 0x18, // 00011000 0x08, // 00001000 0x08, // 00001000 0x08, // 00001000 0x08, // 00001000 0x1C // 00011100 }, {// two 0x3C, // 00111100 0x42, // 01000010 0x02, // 00000010 0x3C, // 00111100 0x40, // 01000000 0x42, // 01000010 0x7E // 01111110 }, {// three 0x3C, // 01111100 0x42, // 00000010 0x02, // 00000010 0x1C, // 00011100 0x02, // 00000010 0x42, // 00000010 0x3C // 01111100 }, {// four 0x0C, // 00001100 0x14, // 00010100 0x24, // 00100100 0x44, // 01000100 0x7E, // 01111110 0x04, // 00000100 0x04 // 00000100 },

{// five 0x7E, // 0x42, // 0x40, // 0x7C, // 0x02, // 0x42, // 0x3C // }, {// six 0x1C, // 0x20, // 0x40, // 0x7C, // 0x42, // 0x42, // 0x3C // }, {// seven 0x7E, // 0x42, // 0x02, // 0x04, // 0x08, // 0x08, // 0x08 // }, {// eight 0x3C, // 0x42, // 0x42, // 0x3C, // 0x42, // 0x42, // 0x3C // }, {// nine 0x3C, // 0x42, // 0x42, // 0x3E, // 0x02, // 0x02, // 0x02 // } };

01111110 01000010 01000000 01111100 00000010 01000010 00111100

00011110 00100000 01000000 01111100 01000010 01000010 00111100

01111110 01000010 00000010 00000100 00001000 00001000 00001000

00111100 01000010 01000010 00111100 01000010 01000010 00111100

00111100 01000010 01000010 00111110 00000010 00000010 00000010


* ** * * * * ***

**** * * * **** * * * ******

**** * * * *** * * * ****

** * * * * * * ****** * *

****** * * * ***** * * * ****

*** * * ***** * * * * ****

****** * * * * * * *

**** * * * * **** * * * * ****

* *

**** * * ***** * * *

**** * * * * * * * * * * ****

Figure 6.1: Bitmapped Numerical Digits

Code Example 6.1. Displaying bitmapped digits 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

# include <stdio .h > # include " digits .h" void display (int x) { int i; for (i =0; i < 8; i ++) { if (x & 0 x80 ) putchar ('*'); else putchar (' '); x <<= 1; } } int main () { int row , col ; char num [] = " 1234567890 "; for ( row = 0; row < 7; row ++) { for ( col = 0; col < 10; col ++) display ( numerals [ num [ col ] - '0'][ row ]); putchar ('\n'); } return (0) ; }


Code Example 6.2. Displaying bitmapped digits (Version 2) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

# include <stdio .h> # include <string .h> # include " numerals .h" int max (int x, int y) { if (x > y) return (x);

else

return (y);

void displaySpace (int size) { while (size -- > 0) putchar (' ');

}

}

void displayVerticalSpace (int size) { size *= 7; while (size -- > 0) putchar (' '); } void displayCharPixel (int x, int mask , int size) { while (size -- > 0) if (x & mask) putchar ('*'); else putchar (' '); } void displayCharVertically (char *line , int chrcnt , int size , int mask) { int row; int index ; if ( chrcnt < strlen (line)) { index = line[ chrcnt ] - '0'; for (row = 6; row >= 0; row --) displayCharPixel ( numerals [index ][ row], mask ,size); } else displayVerticalSpace (size); } void displayVertically (char* line1 , char* line2 , int size) { int row , chr , maxchr ; int index ,i,mask; maxchr = max( strlen (line1 ),strlen ( line2 )); for (chr = 0; chr < maxchr ; chr ++) for (mask = 128; mask > 0; mask >>= 1) for (i=0; i < size; i++) { displayCharVertically (line2 , chr ,size , mask); displaySpace (size); displayCharVertically (line1 ,chr ,size ,mask); putchar ('\n'); } } void displayCharRow (int x, int size) { int mask; for (mask = 128; mask > 0; mask >>= 1) displayCharPixel (x, mask , size); } void displayStringHorizontally (char line [], int size) { int row , chr , i, index ; for (row = 0; row < 7; row ++) for (i = 0; i < size; i++) { for (chr = 0; line[chr ]; chr ++) { index = line[chr] - '0';


** ** ** ** ** ** ** ** ** **

******** ********

** ** ** ** ** ** ** ** ** **

******** ******** ************ ************ ** ** ** ** ** ** ********** ********** ** ** ** ** ** ** ******** ******** * **** ***** * * * * * * * * * * * * * * * * * * * * ** ** ***** **** * * * * * * * * * * * ******* * * * * ** ** *** * * * * * * * * * *** * * * * * * * * * *** ** ** ** ** * * * * * * * * * * * * * * * * * * * * * * * * * ** ** ** ** ** ** * * * * * * * * * * * * * * ******* ****** *

** ** **** **** ** ** ** ** ** ** ** ** ****** ****** ****** ******

** ** ** ** ********** ********** ** ** ** ** ** ** ** ** ******** ********

******** ******** ** ** ** ** ** ** ******** ******** ** ** ** ** ** ** ************ ************ ************ ************ ** ** ** ** ** ** ** ** ** ** ** ** ** **

******** ******** ** ** ** ** ****** ****** ** ** ** ** ** ** ******** ******** ******** ******** ** ** ** ** ** ** ** ** ******** ******** ** ** ** ** ** ** ** ** ******** ******** ** **

**** **** ** ** ** ** ** ** ** ** ** ** ** ** ************ ************ ** ** ** ** ******** ******** ** ** ** ** ** ** ** ** ********** ********** ** ** ** ** ** **

Figure 6.2: Output of Version 2


.file "numerals.h" _numerals: db 60, 66, 66, 66, 66, 8, 24, 8, 8, 8, 60, 66, 2, 60, 64, 60, 66, 2, 28, 2, 12, 20, 36, 68,126, 126, 66, 64,124, 2, 28, 32, 64,124, 66, 126, 66, 2, 4, 8, 60, 66, 66, 60, 66, 60, 66, 66, 62, 2,

%ebp

12(%ebp), %eax

8(%ebp), %eax L3

_max: .file 1 "numerals.c" pushl %ebp LCFI0: movl %esp, %ebp LCFI1: movl 8(%ebp), %eax cmpl 12(%ebp), %eax jle L2 movl jmp L2: movl L3: popl LCFI2: ret _displaySpace: pushl %ebp LCFI3: movl %esp, %ebp LCFI4: subl $24, %esp jmp L5 L6: movl $32, (%esp) call _putchar L5: cmpl $0, 8(%ebp) setg %al decl 8(%ebp) testb %al, %al jne L6 leave LCFI5: ret _displayVerticalSpace: pushl %ebp LCFI6: movl %esp, %ebp LCFI7: subl $24, %esp movl 8(%ebp), %edx movl %edx, %eax sall $3, %eax subl %edx, %eax movl %eax, 8(%ebp) jmp L8 L9: movl $32, (%esp) call _putchar

66, 60, 8, 28, 66,126, 66, 60, 4, 4, 66, 60, 66, 60, 8, 8, 66, 60, 2, 2 ; line 6

; line 7

; line 7 ; line 8

; line 11

; line 12

; line 13

; line 16

; line 17

; line 18

L8: cmpl $0, 8(%ebp) setg %al decl 8(%ebp) testb %al, %al jne L9 leave LCFI8: ret _displayCharPixel: pushl %ebp LCFI9: movl %esp, %ebp LCFI10: subl $24, %esp jmp L11 L13: movl 12(%ebp), %eax movl 8(%ebp), %edx andl %edx, %eax testl %eax, %eax je L12 movl $42, (%esp) call _putchar jmp L11 L12: movl $32, (%esp) call _putchar L11: cmpl $0, 16(%ebp) setg %al decl 16(%ebp) testb %al, %al jne L13 leave LCFI11: ret _displayCharVertically: pushl %ebp LCFI12: movl %esp, %ebp LCFI13: pushl %edi pushl %ebx subl $48, %esp movl 12(%ebp), %ebx movl 8(%ebp), %eax movl $-1, -28(%ebp) movl %eax, %edx movb $0, %al movl -28(%ebp), %ecx movl %edx, %edi repne scasb movl %ecx, %eax notl %eax decl %eax cmpl %eax, %ebx jae L15 movl 12(%ebp), %eax addl 8(%ebp), %eax movb (%eax), %al movsbl %al, %eax subl $48, %eax movl %eax, -16(%ebp) movl $6, -12(%ebp) jmp L16

; line 19

; line 22

; line 23 ; line 24

; line 23

; line 25

; line 28

; line 32

; line 34

L17: movl -16(%ebp), %edx movl %edx, %eax sall $3, %eax subl %edx, %eax addl -12(%ebp), %eax addl $_numerals, %eax movb (%eax), %al movsbl %al, %eax movl 16(%ebp), %edx movl %edx, 8(%esp) movl 20(%ebp), %edx movl %edx, 4(%esp) movl %eax, (%esp) call _displayCharPixel decl -12(%ebp) L16: cmpl $0, -12(%ebp) jns L17 jmp L14 L15: movl 16(%ebp), %eax movl %eax, (%esp) call _displayVerticalSpace L14: addl $48, %esp popl %ebx popl %edi popl %ebp LCFI14: ret _displayVertically: pushl %ebp LCFI15: movl %esp, %ebp LCFI16: pushl %edi pushl %ebx subl $48, %esp movl 12(%ebp), %eax movl $-1, -28(%ebp) movl %eax, %edx movb $0, %al movl -28(%ebp), %ecx movl %edx, %edi repne scasb movl %ecx, %eax notl %eax decl %eax movl %eax, %ebx movl 8(%ebp), %eax movl $-1, -28(%ebp) movl %eax, %edx movb $0, %al movl -28(%ebp), %ecx movl %edx, %edi repne scasb movl %ecx, %eax notl %eax decl %eax movl %ebx, 4(%esp) movl %eax, (%esp) call _max movl %eax, -24(%ebp) movl $0, -12(%ebp) jmp L20

; line 37

; line 36

; line 41

; line 42

; line 45

; line 48

; line 49


L25: movl $128, -20(%ebp) jmp L21 L24: movl $0, -16(%ebp) jmp L22 L23: movl -20(%ebp), %eax movl %eax, 12(%esp) movl 16(%ebp), %eax movl %eax, 8(%esp) movl -12(%ebp), %eax movl %eax, 4(%esp) movl 12(%ebp), %eax movl %eax, (%esp) call _displayCharVertically movl 16(%ebp), %eax movl %eax, (%esp) call _displaySpace movl -20(%ebp), %eax movl %eax, 12(%esp) movl 16(%ebp), %eax movl %eax, 8(%esp) movl -12(%ebp), %eax movl %eax, 4(%esp) movl 8(%ebp), %eax movl %eax, (%esp) call _displayCharVertically movl $10, (%esp) call _putchar incl -16(%ebp) L22: movl -16(%ebp), %eax cmpl 16(%ebp), %eax jl L23 sarl -20(%ebp) L21: cmpl $0, -20(%ebp) jg L24 incl -12(%ebp) L20: movl -12(%ebp), %eax cmpl -24(%ebp), %eax jl L25 addl $48, %esp popl %ebx popl %edi popl %ebp LCFI17: ret

; line 51

; line 49

; line 50

; line 51

; line 57

; line 55

; line 54

; line 53

; line 51

; line 50

_displayStringHorizontally: pushl %ebp LCFI21: movl %esp, %ebp LCFI22: subl $40, %esp movl $0, -12(%ebp) jmp L30 L35: movl $0, -20(%ebp) jmp L31 L34: movl $0, -16(%ebp) jmp L32 L33: movl -16(%ebp), %eax addl 8(%ebp), %eax movb (%eax), %al movsbl %al, %eax subl $48, %eax movl %eax, -24(%ebp) movl -24(%ebp), %edx movl %edx, %eax sall $3, %eax subl %edx, %eax addl -12(%ebp), %eax addl $_numerals, %eax movb (%eax), %al movsbl %al, %eax movl 12(%ebp), %edx movl %edx, 4(%esp) movl %eax, (%esp) call _displayCharRow incl -16(%ebp) L32: movl -16(%ebp), %eax addl 8(%ebp), %eax movb (%eax), %al testb %al, %al jne L33 movl $10, (%esp) call _putchar incl -20(%ebp)

_displayCharRow: pushl %ebp LCFI18: movl %esp, %ebp LCFI19: subl $40, %esp movl $128, -12(%ebp) jmp L27 L28: movl 12(%ebp), %eax movl %eax, 8(%esp) movl -12(%ebp), %eax movl %eax, 4(%esp) movl 8(%ebp), %eax movl %eax, (%esp) call _displayCharPixel sarl -12(%ebp) L27: cmpl $0, -12(%ebp) jg L28 leave LCFI20: ret

; line 73

; line 80

; line 75

; line 78

; line 77

; line 75

; line 73

; line 72

; line 69

; line 66

; line 64

; line 65

; line 64

; line 62

; line 84

; line 82

; line 83 ; line 82

; line 82

; line 72

$-16, %esp $16, %esp ___main $2, 8(%esp) $LC0, 4(%esp) $LC1, (%esp) _displayHorizontally $1, 8(%esp) $LC0, 4(%esp) $LC1, (%esp) _displayVertically $0, %eax

%esp, %ebp

%ebp

.ascii "56789\0" .ascii "01234\0" _main: pushl LCFI27: movl LCFI28: andl subl call movl movl movl call movl movl movl call movl leave LCFI29: ret

LC0: LC1:

; line 97 ; line 98

; line 96

; line 94 ; line 95

; line 94

_displayHorizontally: pushl %ebp LCFI24: movl %esp, %ebp LCFI25: subl $24, %esp ; line 88 movl 16(%ebp), %eax movl %eax, 4(%esp) movl 8(%ebp), %eax movl %eax, (%esp) call _displayStringHorizontally ; line 89 movl 16(%ebp), %eax movl %eax, 4(%esp) movl 12(%ebp), %eax movl %eax, (%esp) call _displayStringHorizontally ; line 90 leave LCFI26: ret

L31: movl -20(%ebp), %eax cmpl 12(%ebp), %eax jl L34 incl -12(%ebp) L30: cmpl $6, -12(%ebp) jle L35 movl $0, -20(%ebp) jmp L36 L37: movl $10, (%esp) call _putchar incl -20(%ebp) L36: movl -20(%ebp), %eax cmpl 12(%ebp), %eax jl L37 leave LCFI23: ret


6.2 String • The concept of the string. H

e

l

l

o

,

0

1

2

3

4

5

Marker \a \b \f \n \r \t \v

6

W o

r

l

d

!

7

9

10

11

12

8

Definition Marker alert (bell) character \\ backspace \? formfeed \' newline \" carriage return \0oo horizontal tab \xhh vertical tab

\n \0 13

14

Definition backslash question mark single quote double quote octal number hexadecimal number

• Functions related to string processing. Table 6.1: String manipulation functions char *strcpy (char *dest, char *src) - Copy the source string string into the destination string. char *strncpy(char *string1, char *string2, int n) - Copy first n characters of string2 to stringl. int strcmp(char *string1, char *string2) - Compare string1 and string2 to determine alphabetic order. int strncmp(char *string1, char *string2, int n) - Compare first n characters of two strings. int strlen(char *string) - Determine the length of a string. char *strcat(char *dest, const char *src) - Concatenate string src to the string dest. char *strncat(char *dest, const char *src, int n) - Concatenate n chracters from string src to the string dest. char *strchr(char *string, int c) - Find first occurrence of character c in string. char *strrchr(char *string, int c) - Find last occurrence of character c in string. char *strstr(char *string2, char *string1) - Find first occurrence of string string1 in string2. char *strtok(char *s, const char *delim) - Parse the string s into tokens using delim as delimiter.


6.3 Character functions - ctype.h int isalnum(int c) - The function returns nonzero if c is alphanumeric int isalpha(int c) The function returns nonzero if c is alphabetic only int iscntrl(int c) - The function returns nonzero if c is a control chracter int isdigit(int c) - The function returns nonzero if c is a numeric digit int isgraph(int c) - The function returns nonzero if c is any character for which either isalnum or ispunct returns nonzero. int islower(int c) - The function returns nonzero if c is a lower case character. int isprint(int c) - The function returns nonzero if c is space or a character for which isgraph returns nonzero. int ispunct(int c) - The function returns nonzero if c is punctuation int isspace(int c) - The function returns nonzero if c is space character int isupper(int c) - The function returns nonzero if c is upper case character int isxdigit(int c) - The function returns nonzero if c is hexa digit int tolower(int c) - The function returns the corresponding lowercase letter if one exists and if isupper(c); otherwise, it returns c. int toupper(int c) - The function returns the corresponding uppercase letter if one exists and if islower(c); otherwise, it returns c. #include <stdio.h> void main() { int c while ((c = getchar()) != EOF) putchar(c); return 0; }

6.4

User-defined data types

• The purpose of creating a new data type (Building New Types). • Basic data types (Basic Data Types). • The type of data that is created (New Data Types). • Types of data structures (Structures). • An array of data structures (Arrays of Structures).


• Data type Union (Unions). struct point { int x; int y; long color; };

struct point makepoint(int x, int y, long c) { struct point temp; temp.x = x; temp.y = y; temp.color = c; return temp; } void main() { struct point pt; pt = makpoint( 100, 20, 0xff000000); printf("(%d, %d) \n", pt.x, pt.y); }

typedef char *String; String p, lineptr[MAXLINES]; int strcmp(String a, String b); p = (String) malloc(100);

typedef struct tnode *Treeptr; typedef struct tnode { char *word; int count; struct tnode *left; struct tnode *right; } Treenode;


6.5 Enumerated data type • The name of the new data types.

Chapter 6 Review Key Terms: Discussion Questions: Exercises: Laboratory Exercises:


Code Example 6.3. Print the longest line 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

# include <stdio .h > # define MAXLINE 1000 int getline ( char line [] , int maxline ); void copy ( char to [] , char from []) ; int main () { int len , max ; char line [ MAXLINE ], longest [ MAXLINE ]; max = 0; while (( len = getline (line , MAXLINE )) > 0) if ( len > max ) { max = len ; copy ( longest , line ); } if ( max > 0) printf ("%s", longest ); return 0; } int getline ( char s[] , int lim ) { int c; int i = 0; while (i < lim -1 && (c= getchar ()) != EOF && c!= '\n') s[i ++] = c; if (c == '\n') s[i ++] = c; s[i] = '\0 '; return i; } void copy ( char to [] , char from []) { int i = 0; while (( to [i] = from [i]) != '\0 ') i ++; }


Chapter 7 File Processing 7.1 Data stream handles Constants FILE

a datatype which holds the information about an open file stream. EOF the value returned to indicate that end-of-file has been reached. (traditionally set to -1). NULL set to the value of the null or missing pointer (constant 0) BUFSIZ an integer constant specifing an appropriate size for file I/O buffers.

Value 0

Name stdin

1

stdout

2

stderr

Description Standard input typed on the keyboard or redirected from a file Standard output displayed on the console monitor or redirected to a file Standard error stream normally displayed on the console monitor

113


7.2 Sequential text file input/output #include <stdio.h> int main() { int c; while ((c = getchar()) != EOF) putchar(c); return 0; }

#include <stdio.h> int main() { char buffer[BUFSIZ]; while ((c = getchar()) != EOF) putchar(c); return 0; } int fclose(FILE *stream) Closes the stream. All buffers are flushed. int fflush(FILE *stream) Flushes the output buffer of a stream. int remove(const char *filename) int rename(const char *old_filename, const char *new_filename)

char *tmpnam(char *str) int feof(FILE *stream) int ferror(FILE *stream) int getchar(void) int fgetc(FILE *stream) char *gets(char *str)

Deletes the given file longer accessible. Causes the filenam old_filename to new_filename. Generates and returns name which does not e

Tests for the end-of-file indicator for the given stream. Tests the error indicator for the given stream. Gets a character from stream. Reads a line from stdin and stores it into the string pointed to by str.

char *fgets(char *str, int n, FILE *stream) int putchar(int char) Writes a character (an unsigned char) specified by the argument char to stdout. int fputc(int char, FILE *stream) int puts(const char *str) Writes a string to stdout up to but not including the null character. A newline character is appended to the output. int fputs(const char *str, FILE *stream)


7.3 Formatted input and output

int printf(const char *format, ...) int fprintf(FILE *stream, const char *format, ...) int sprintf(char *str, const char *format, ...)

Sends formatted output to stdout.

int scanf(const char *format, ...) int fscanf(FILE *stream, const char *format, ...) int sscanf(const char *str, const char *format, ...)

d,i o x,X

u c s

f e,E

g,G

p 138 %

integer; displayed as a decimal number integer; displayed as an unsigned octal number (without a leading zero) integer; displayed as unsigned hexadecimal number (without a leading 0x or 0X), using abcdef or ABCDEF for the numbers 10 through 15. unsigned integer; displayed as an decimal number integer; displayed as single character corresponding to a character char pointer; print ther characters from the string start until a '\0' or the number of characters given by the precision. double; [-] m.dddddd, where the number of d's is given by the precision (default 6). double; Scientific notation [-] m.dddddd e +/- xx or [-] m.dddddd E+/- xx, where the number of d 's is given by the precision (default 6). double; use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f . Trailing zeros and a trailing decimal point are not printed. pointer; representation of a pointer no argument is converted; print a %

Reads formatted input from stdin.


printf(":%s:\n", "A string") :A string: printf(":%11s:\n", "A string") : A string: printf(":%-11s:\n", "A string"); :A string : printf(":%d:\n", 77); :77: printf(":%11d:\n", 77); : 77: printf(":%011d:\n", 77); :0000000077: printf(":%-011d:\n", 77); :77 : printf(":%c:\n", 77); :M: printf(":%x:\n", 77); :4d: printf(":%X:\n", 77); :4D: printf(":%11x:\n", 77); : 4d: printf(":%-11x:\n", 77); :4d : printf(":%o:\n", 77); :115: printf(":%11o:\n", 77); : 115: printf(":%f:\n", -12.34); :-12.340000: printf(":%.3f:\n", -12.34); :-12.340: printf(":%11f:\n", -12.34); :-12.340000: printf(":%11.3f:\n", -12.34); : -12.340: printf(":%-11f:\n", -12.34); :-12.340000: printf(":%-11.3f:\n", -12.34); :-12.340 : printf(":%-.3f:\n", -12.34); :-12.340: printf(":%11.3e:\n", -12.34); :-1.234e+001: printf(":%11.3E:\n", -12.34); :-1.234E+001: printf(":%11.3g:\n", -12.34); : -12.3: printf(":%11.3G:\n", -12.34); : -12.3: A warning: printf uses its first argument as a template that specifies the format of the output.

7.4 File open p = fopen(name, mode); r w

open an existing text file to read the contents. open a text file to write data starting at the beginning of the file. Existing data is discarded. a open or create a texrt file to write data at end of text file. r+ open an existing file for reading and writing, starting at the beginning of the file. w+ open a text file for reading and writing, starting at the beginning of the file. Existing data is discarded. a+ open a file to read and write data starting at the end of file. rb open for reading as a file of binary data wb open for writing as a file of binary data from the beginning of the file. Existing data is discarded. ab open for appending binary data to the end of the file


#include <stdio.h> #include <stdlib.h> int main() { char ch, source_file[20], target_file[20]; FILE *source, *target; printf("Enter name of file to copy\n"); gets(source_file); if(!( source = fopen(source_file, "r"))) { printf("Unable to open input file: %s\n", source_file); exit(EXIT_FAILURE); } printf("Enter name of target file: "); gets(target_file); if(!(target = fopen(target_file, "w"))) { fclose(source); printf("Unable to open output file: %s\n", target_file); exit(EXIT_FAILURE); } while( ( ch = fgetc(source) ) != EOF ) fputc(ch, target); printf("File copied successfully.\n"); fclose(source); fclose(target); return 0; }

7.5 Random access file input/output void rewind(FILE *stream) int fseek(FILE *stream, long offset, int whence) long ftell(FILE *stream) Predefined Whence Values

rewind sets the file position indicator fo stream to the beginning of the file. sets the file position indicator for stream returns the current file position for stream.


SEEK_CUR SEEK_SET SEEK_END

file offset computed from the current position in the file. file offset is computed from the beginning of the file. file offset is computed from the end of the file.

7.6 Parsing a CSV file #include <stdio.h> #include <stdlib.h> #include <string.h> int readlines(char *filename,char *lines[],int maxlines) { FILE *fp; int linecount = 0; char buffer[BUFSIZ]; if ((fp = fopen(filename,"r")) == NULL) { perror("Input file unknown\n"); exit(1); } while ((linecount < maxlines) && (fgets(buffer,BUFSIZ,fp) != NULL)) { if (buffer[strlen(buffer) - 1] == '\n') buffer[strlen(buffer) - 1] = '\0'; lines[linecount] = (char *) malloc(strlen(buffer) + 1); strcpy(lines[linecount++], buffer); } return(linecount); } int separatefields(char *line, char *fields[], int maxfields) { char *pstart, *pend, *pfield; pstart = line; int fieldcnt = 0; while((fieldcnt < maxfields) && { pend = pstart; while (*pend && (*pend != ',')) pend++;

(strlen(pstart) > 0))

pfield = (char *) malloc(1 + (int)(pend - pstart));


fields[fieldcnt] =

pfield;

while (pstart < pend) *pfield++ = *pstart++; *pfield = '\0'; while ((isspace(*pstart)) || (*pstart == ',')) pstart++; fieldcnt++; } return(fieldcnt); } int main() { int linecount; int i,fcnt, cnt; char *lines[1000]; char *fields[20]; linecount = readlines("amphur.csv",lines,1000); cnt = 0; for (i = 0; i < linecount; i++) { fcnt = separatefields(lines[i], fields,20); if (fcnt < 7) { printf("%d %s\n", fcnt, fields[0]); cnt++; } // puts(lines[i]); } printf("%d / %d \n", cnt, linecount); return(0); }

Chapter 7 Review


Key Terms: Discussion Questions: Exercises: Laboratory Exercises:


Chapter 8 Pointers

A great lathe operator commands several times the wage of an average lathe operator, but a great writer of software code is worth 10,000 times the price of an average software writer. Bill Gates, CEO, Microsoft

Complexity kills. It sucks the life out of developers, it makes products difficult to plan, build and test, it introduces security challenges, and it causes end-user and administrator frustration. Ray Ozzie

8.1 The concept of a pointers 8.2 Pointers as function parameters 8.3 Pointers and arrays 8.4 Arrays of pointers void combination(char *p, char *s) { int i,j, k; char *newp, *news; if (! *s) { puts(p); } else { for (i=0; i < strlen(s); i++) 121


{ news = (char *) malloc(strlen(s) -1); newp = (char *) malloc(strlen(p) + 1); k = 0; for (j = 0; j < strlen(s); j++) { if (j != i) news[k++] = s[j]; else { strcpy(newp,p); newp[strlen(p)] = s[j]; newp[strlen(p) + 1] = '\0'; } } news[k] = '\0'; combination(newp,news); free(news); free(newp); } } } typedef struct node { int value; struct node *leftp; struct node *rightp; } Node; Node * createNode(int val) { Node *newnode = (Node *) malloc(sizeof(Node)); newnode->value = val; newnode->leftp = NULL; newnode->rightp = NULL; return(newnode); } Node * createNode(int val) { Node *newnode = (Node *) malloc(sizeof(Node)); newnode->value = val; newnode->leftp = NULL; newnode->rightp = NULL; return(newnode); }


void addListNode(Node **root, Node *newnode) { Node* p = *root; Node* lastp = NULL; if (p == NULL) { *root = newnode; return; } while ((p != NULL) && { lastp = p; p = p -> rightp; }

(p->value < newnode->value))


if (lastp == NULL) { newnode->rightp = *root; *root = newnode; } else { newnode->rightp = lastp->rightp; newnode->leftp = lastp; lastp->rightp = newnode; } } void printList(Node *node) { while(node != NULL) { printf("%d ", node -> value); node = node->rightp; } puts("\n"); } void addTreeNode(Node **root, Node *newnode) { Node* p = *root; Node* lastp = NULL; if (p == NULL) { *root = newnode; return; } while (p != NULL) { if (p->value > newnode->value) { if (p ->leftp == NULL) { p ->leftp = newnode; p = NULL; } else p = p -> leftp; } else {


if (p ->rightp == NULL) { p->rightp = newnode; p = NULL; } else p = p -> rightp; } } }

void printTree(Node *node) { if (node != NULL) { printTree(node->leftp); printf("%d ", node -> value); printTree(node->rightp); } }

Figure 8.1: Comparsion between iteration and recursion version of the Euclid GCD algoirithm Algorithm 8.1. Euclid’s algorithm by iteration 1: procedure Euclid(a, b) 2: r ← a mod b 3: while r ̸= 0 do 4: a←b 5: b←r 6: r ← a mod b 7: end while 8: return b 9: end procedure

Algorithm 8.2. Euclid’s algorithm by recursion 1: procedure Euclid(a, b) 2: if b = 0 then 3: return a 4: else 5: Euclid(b, a mod b) 6: end if 7: end procedure

Figure ?? compares between iterative and recursive versions of Euclid's algorithm to determine the greatest common divisor between 2 numbers. In Algorithm 8.1, the loop control statement in Line 3 is used to drive the process until a remainder can no longer be obtained. The remainding number is the greatest common divisor. Similarly, in Algorithm 8.2, as long as the second number does not equal zero, the parameters are adjusted before executing a recursive call in Line 5. When the process has completed, the first number is returned as the GCD. Although both versions will result in the same number of repetitions resulting in the same answer, there are significant differences in the process used.


8.5 Pointers of functions Chapter 8 Review Key Terms: Discussion Questions: Exercises: Laboratory Exercises:


Chapter 9 Software Programming Paradigms

A good designer must rely on experience, on precise, logic thinking; and on pedantic exactness. No magic will do. Niklaus Wirth, Emeritus Professor of Informatics, University of Zurich

The function of good software is to make the complex appear to be simple. Grady Booch

Good programmers use their brains, but good guidelines save us having to think out every case. Francis Glassborow

Good code is its own best documentation. Steve McConnell

9.1 Software development 9.1.1 Module development While modern computers can address terabytes of information, application programs using this much data will run very slowly useles the programmer has broken the most applications employ data structures to greatly facilitate the development, use and maintenance of information. In a similar way, the development, testing, use and maintenance of software is greatly aided by dividing software projects into a collection of modules. The C language itself has been designed as a collection of modules that divide the task of parsing and compiling into smaller functional units. In addition, the ANSI C library functions extend the capabilities of the standard C through function declarations and type and macro definitions. The functions, types and macros of the ANSI standard C library are declared in standard headers described in Table 9.1. A header file have been used in C to specify the basic macros, constants and data types of a module, as well as the parameters and data types of the declared functions. Thus, the header material is included in both the source files of the module where the corresponding functions 127


Table 9.1: Header files of the ANSI C Library Header File Description assert.h a standard macro function for testing and debugging. ctype.h Macros to identify character types and functions to convert between data types. errno.h Macro to track system errors as integer. float.h Constants specifying the characteristics of floating number types. limits.h Constants specifying the size of data types. locale.h Constants useful for localization specific settings, such as culture-specific date formats or country-specific currency symbols. math.h Functions to compute common mathematical operations. setjmp.h Macros and functions to allow the program providing the means to perform long jumps that preserve the calling environment. signal.h Macros and functions for interpreting the signals generated by the underlying operating system, such as error messages performed by the program code, or a request to interrupt the program. stdarg.h Macros for accessing the individual arguments of a list of unnamed arguments whose number and types are not known to the called function. stdio.h Input/Output functions and standard data stream definitions. stdlib.h General purpose functions that support common programming tasks, including dynamic memory management, random number generation, communication with the environment, integer arthmetic, as well as data searching, sorting and converting functions. string.h Functions to manipulate C strings and arrays. time.h Data structures and functions used to read and manipulate date and time information.

are defined and in the modules which use those functions. This is accomplished by using the following line of code.

#include <header>

Modules are linked at the time of compile.


9.1.2 Agile programming 9.1.3 Debugging and Unit testing 9.1.4 Version control and makefile 9.1.5 Conditional compiling

9.2 Program Structure 9.2.1 Structured programming 9.2.2 Object-oriented programming • Visual programming • Event driven programming

9.2.3 Parallel/concurrent programming

Chapter 9 Review: Key Terms: • Process

• Object-oriented programming (OOP)

• Process identifier

• Objects

• Child process

• Object identifier

• Parent process

• Class

• Fork

• Attributes

• Thread

• Methods • Inheritance

• Sequential processing

• Polymorphism

• Event driven processing • Concurrent processing

Discussion Questions: Exercises: • Tic-Tac-Toe Game - provides a console input for a player to play against the computer. • Scissor-Paper-Stone - provides a console input and display for multiple (3-4) players to play against each other or the computer.


• Game of Life - a simulation of the growth of a forest using Conway's Game of life; to be displayed on the monitor • Towers of Hanoi Game - a console game in which a human operator attempts to solve the puzzle Afterwards the computer will show how to solve the puzzle. • HangMan - Allows users to play hangman in English from a list of at least 20,000 words. • Cannon Target Practice - A console game to allow the user to tilt a cannon, specify the amount of gunpowder and shoot a cannon to hit a target on the screen. The console must display the path of the cannonball. • Automatic sentence Writer - Allows the computer to calculate English word sequences from an essay or novel and then write its own English sentences based on those sequences. • Automatic music maker - Allows the computer to determine sequence of notes in music and then writes its own music based on those sequences. • QWERTY Keyboard piano - Uses the standard keyboard to work as single finger music keyboard • ASEAN Coin changer - Accepts a collection of coins in one currency of ASEAN and returns the equivalent collection of coins in the target currency. • Map of Thailand with geoposition of zipcodes: Plots the position of postal zipcodes on a map of Thailand • Map of Thailand with geoposition of Amphur - Plots the postion of Amphurs on a map of Thailand • Distances between Thai zipcode zones - Allows the user to type 2 postal zipcode and will return the distance between the postal areas. • Two player car race using the console keyboard and monitor: Allows two users to play a game on the console of computer. • Map color for Changwats of Thailand - calculates the minimal color scheme to be used in a map of Thailand so that no two neighboring Changwat have the same color. • Simulator for traffic controller for two roads with pedestrian crosswalk • English Crossword maker: Creates a crossword from a list of 100 words • Maze maker and solver: A program to create and display a maze and then show its solution. A program to plot histogram on a console: reads a list of values from a file and creates a normalize histogram. • Grocery store barcode lookup: Scans a barcode and looks up the corresponding product data, i.e. name, price and manufacturer.

Laboratory Exercises:


Code Example 9.1. Parallel processing using fork() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

# include # include # include # include # include # include

< unistd .h > <sys / types .h > <errno .h > <stdio .h > <sys / wait .h > < stdlib .h >

int dowork ( char *s, int x, int *y, int diff ) { *y += diff ; printf ("\n %s Process :: i = [% d]\n", s, x, y); } int main ( void ) { pid_t childPID ; int val = 0; int i; childPID = fork (); if( childPID >= 0) // fork was successful { if( childPID == 0) // child process { for (i =0; i < 10; i ++) val = dowork (" Child ", i, &val , -5); } else // Parent process { for (i =0; i < 10; i ++) val = dowork (" Parent ", i, &val , 10) ; } } else { printf ("\n Fork failed , quitting !!!!!!\ n"); return 1; } return 0; }


Code Example 9.2. An example of switch 1 /* This is a test */ 2 for (int i =0; i < 10; i ++) 3 switch (i %4) 4 { 5 case 0: printf (" --- %d\n",i); 6 case 1: printf ("*-- %d\n",i); 7 case 2: printf ("** - %d\n",i); 8 case 3: printf (" *** %d\n",i); 9 } 10 }

break ; break ; break ; break ;


Appendix A Software installation

A.1

Scratch

This course requires access to a working copy of Scratch. Version 1.4 can be downloaded1 and installed as follows: 1. Go to http://scratch.mit.edu/scratch_1.4/ 2. Choose and download the appropriate version of Scratch 1.4 (See Table A.1) 3. Install the program on the local computer 4. Run the Scratch program Table A.1: The Scratch program is available for Mac Os-X, Windows and Linux Scratch 1.4 For Mac OS X Compatible with Mac OSX 10.4 or later Download the file: MacScratch1.4.dmg Scratch 1.4 for Windows Compatible with Windows 2000, XP, Vista, 7, and 8 Download the file: ScratchInstaller1.4.exe Scratch 1.4 for Debian / Ubuntu Compatible with Ubuntu 12.04 or later Install Scratch using the Debian/Ubuntu Software Center

Alternatively, Scratch 2.0 can be used online following these steps: 1. Use a browser to go http://scratch.mit.edu 1

Scratch Version 2.0 download version is scheduled for release in July 2013. Assignments for this course can be done with either version.

133


2. Sign up for membership 3. Login and choose the CREATE button 4. Create and save your software online or try out one of the projects within its collection such as this online version of the extended example given in Section 3.5.1.

http://scratch.mit.edu/projects/2393008/ Figure A.1: The Online Version of the Wizard vs Ogre Example from Section 3.5.1

A.2

yEd by yWorks

yEd Graph Editor was designed to as an application to generate diagrams. The interface allows diagrams to be entered manually, or imported from spreadsheet files. The program has functions to analyze connections, layouts and can even arrange large data sets with just the press of a button. The community edition of this software runs on all major platforms: Windows, Unix/ Linux, Mac OS X and Java virtual machines. The installers for this software is freely available from http://www.yworks.com/en/products_yed_download.html. Examples, tutorials and documentation can be found at http://www.yworks.com/en/products_yed_about. html

A.3

GNU gcc

GNU gcc is a popular open-source c and c++ compiler that supports and implements ANSI C. This compiler is availablecan be found on a wide range of hardware is distributed with Linux and Apple OSX as part of the standard system development utilities for these systems. MinGW a contraction of Minimalist GNU for Window) provides a complete Open Source programming tool set for MS Windows. This allow programmers to develop software using the GNU Compiler Collection (gcc). The MinGW gcc is a native Windows port of the compilers, libraries and headers to produce native MS-Windows applications that run on 32 and 64 bit systems, without depending on 3rd-party C-Runtime DLLs.2 Additionally, a freely distributable DLL is provided as part of MinGW for shipping with threaded applications.

2

It should be noted however that MinGW gcc does depend on a number of standard and critical components of the Window operating system which are supplied by Microsoft. An example of this is MSVCRT.DLL, the Microsoft C runtime library.


Appendix B A Quick Guide to Programming Languages B.1 Keyword list of some popular programming languages

Table B.1: Keywords of the C language auto break case char const continue default

do goto double if else int enum long extern register float return for short

signed sizeof static struct switch typedef union

unsigned void volatile while

Table B.2: Keywords of the Ardunio language array boolean break byte case char

const continue do double else float

for goto if int long return

135

short volatile static while string word switch unsigned void


Table B.3: Keywords of the Java language abstract assert boolean break byte case catch char class const

continue for default if do goto double implements else import enum instanceof extends int final interface finally long float native

new package private protected public return short static strictfp super

switch synchronized this throw throws transient try void volatile while

Table B.4: Keywords of the Processing language abstract assert boolean break byte case catch char class const continue

default do double else enum extends final finally float for goto

if implements import instanceof int interface long native new null package

private protected public return short static strictfp super switch synchronized this

throw throws transient try void volatile while


B.2 Scratch Language Motion functions

Control functions

move 10 steps turn y 15 degrees turn x 15 degrees point in direction 90 point towards mouse-pointer go to x: 0 y: 0 go to mouse-pointer glide 1 sec to x: 0 y: 0 change x by 10 set x to 0 change y by 10 set y to 0 if on edge, bounce (x position) (y position) (direction)

when flag clicked when space key pressed when Sprite1 clicked wait 1 secs loop forever ◃ ... ▹ repeat 10 times ◃ ... ▹ broadcast message broadcast message and wait when I receive message forever if < boolean exp > ◃ ... ▹ if < boolean exp > ◃ ... ▹ if < boolean exp > ◃ ... ▹ else ◃ ... ▹ wait until < boolean exp > repeat until < boolean exp > ◃ ... ▹ stop script stop all

Sensing functions <touching mouse-pointer ?> <touching color ?> <color is touching ?> ask What's your name? and wait (answer) (mouse x) (mouse y) <mouse down?> <key space pressed?> (distance to mouse-pointer ) reset timer (timer) ( x position of Sprite1 ) (loudness) <loud?> ( slider sensor value) <sensor button pressed ?>

Sound functions play sound meow play sound meow until done stop all sounds play drum 48 for 0.2 beats rest for 0.2 beats play note 60 for 0.5 beats set instrument to 1 change volume by -10 set volume to 100 % (volume) change tempo by 20 set tempo to 60 bpm (tempo)


Looks functions

Operators functions

switch to costume2 next costume (costume #) say Hello! for 2 secs say Hello! think Hmm… for 2 secs say Hmm… change color effect by 25 set color effect to 0 clear graphic effects change size by 10 set size by 100 % (size) show hide go to front go back 1 layers

( + ) ( − ) ( ∗ ) ( / ) pick random 1 to 10 ( < ) ( = ) ( > ) << boolean exp > and < boolean exp >> << boolean exp > or < boolean exp >> < not < boolean exp >> (join hello world ) (letter 1 of world ) (length of world ) ( mod ) (round ) ( sqrt of 10 )

Variables functions

Pen functions

(var) set (var) to 0 change (var) by 1 show variable (var) hide variable (var) (list) add thing to (list)

clear pen down pen up set pen color to change pen color by 10 set pen color to 0 change pen shade by 10 set pen shade to 50 change pen size by 1 set pen size to 1 stamp

delete 1 of (list) insert thing at |fbox1 of (list) replace item 1 of (list) with thing item 1 of (list) length of (list) <(list) contains thing >


Appendix C Comparison between standard Computer Science curriculum ACM/IEEE CS2008 Programming Fundamentals (PF)[16] (47 core hours) • Fundamental Constructs: 9 hrs • Algorithmic Problem Solving: 6 hrs • Data Structures: 10 hrs • Recursion: 4 hrs • Event Driven Programming: 4 hrs • Object Oriented: 8 hrs • Foundations Information Security: 4 hrs • Secure Programming: 2 hrs Fundamental Constructs Minimum core coverage time: 9 hours Topics:0 • Basic syntax and semantics of a higher-level language • Variables, types, expressions, and assignment • Simple I/O • Conditional and iterative control structures • Functions and parameter passing • Structured decomposition Learning Objectives: 1. Analyze and explain the behavior of simple programs involving the fundamental programming constructs covered by this unit. 2. Modify and expand short programs that use standard conditional and iterative control structures and functions. 3. Design, implement, test, and debug a program that uses each of the following fundamental programming constructs: basic computation, simple I/O, standard conditional and iterative structures, and the definition of functions. 4. Choose appropriate conditional and iteration constructs for a given programming task. 5. Apply the techniques of structured (functional) decomposition to break a program into smaller pieces. 6. Describe the mechanics of parameter passing. AlgorithmicProblemSolving Minimum core coverage time: 6 hours Topics: • Problemsolving strategies • The role of algorithms in the problem-solving process • Implementation strategies for algorithms • Debugging strategies • The concept and properties of 139


algorithms Learning Objectives: 7. Discuss the importance of algorithms in the problemsolving process. 8. Identify the necessary properties of good algorithms. 9. Create algorithms for solving simple problems. 10. Use pseudocode or a programming language to implement, test, and debug algorithms for solving simple problems. 11. Describe strategies that are useful in debugging. DataStructures Minimum core coverage time: 10 hours Topics: • Representation of numeric data • Range, precision, and rounding errors • Arrays • Representation of character data • Strings and string processing • Runtime storage management • Pointers and references • Linked structures • Implementation strategies for stacks, queues, and hash tables • Implementation strategies for graphs and trees • Strategies for choosing the right data structure Learning Objectives: 1. Describe the representation of numeric and character data. 2. Understand how precision and round-off can affect numeric calculations. 3. Discuss the use of primitive data types and built-in data structures. 4. Describe common applications for each data structure in the topic list. 5. Implement the user-defined data structures in a high-level language. 6. Compare alternative implementations of data structures with respect to performance. 7. Write programs that use each of the following data structures: arrays, strings, linked lists, stacks, queues, and hash tables. 8. Compare and contrast the costs and benefits of dynamic and static data structure implementations. 9. Choose the appropriate data structure for modeling a given problem. Recursion Minimum core coverage time: 4 hours Topics: • The concept of recursion • Recursive mathematical functions • Simple recursive functions • Divide-and-conquer strategies • Recursive backtracking Learning Objectives: 1. Describe the concept of recursion and give examples of its use. 2. Identify the base case and the general case of a recursively defined problem. 3. Compare iterative and recursive solutions for elementary problems such as factorial. 4. Describe the divide-and-conquer approach. 5. Implement, test, and debug simple recursive functions and procedures. 6. Determine when a recursive solution is appropriate for a problem. EventDrivenProgramming Minimum core coverage time: 4 hours Topics: • Event-handling methods • Event propagation • Exception handling Learning Objectives: 1. Explain the difference between event-driven programming and command-line programming. 2. Design, code, test, and debug simple event-driven programs that respond to user events. 3. Develop code that responds to exception conditions raised during execution. ObjectOriented Minimum core coverage time: 8 hours Topics: • Object-oriented design • Encapsulation and information-hiding • Separation of behavior and implementation • Classes and subclasses • Inheritance (overriding, dynamic dispatch) • Polymorphism (subtype polymorphism vs. inheritance) Learning Objectives: 1. Justify the philosophy of object-oriented design and the concepts of encapsulation, abstraction, inheritance, and polymorphism. 2. Design, implement, test, and debug simple programs in an objectoriented programming language. 3. Describe how the class mechanism supportsencapsulation and information hiding. 4. Design, implement, and test the implementation of “is-a” relationships among objects using a class hierarchy and inheritance. 5. Compare and contrast the notions of overloading and overriding methods in an object-oriented language. FoundationsInformationSecurity Minimum core coverage time: 4 hours Topics: • Role and purpose of computer and network security • Security goals: confidentiality, integrity,


availability triad • Security standards and policies • Security mindset • Defense in depth • Common threats: worms, viruses, trojans, denial of service • Risk assessment and costbenefit analyses • Security versus usability, time, and/or money tradeoffs Learning Objectives: 1. Explain the objectives of information security 2. Analyze the tradeoffs inherent in security 3. Explain the importance and application of eachof confidentiality, integrity, and availability 4. Understand the basic categories of threats to computers and networks 5. Discuss issues for creating security policy for a large organization 6. Defend the need for protection and security, and the role of ethical considerations in computer use 7. Add a very simple risk-assessment learning outcome here

SecureProgramming Minimum core coverage time: 2 hour Topics • Important of checking for and avoiding array and string overflows • Programming language constructs to avoid and alternatives • How attackers use overflows to smash the run-time stack Learning Objectives: 1. Rewrite a simple program to remove a simple vulnerability 2. Explain why or why not a buffer overflow is possible in the programming language you know best 3. Explain why one or more language constructs may lead to security problems such as overflows.

C.1 ACM CC2001 Programming Fundamentals ACM CC2001 Programming Fundamentals[17] (38 core hours)

• Fundamental programming constructs (9)

• Algorithms and problem-solving (6)

• Fundamental data structures (14)

• Recursion (5)

• Event-driven programming (4)

Programming fundamentals


Concept Data models

Description Standard structures for representing data; abstract (described by a model) and concrete (described by an implementation) descriptions Control struc- Effects of applying operations to protures gram objects; what an operation does (described by a model); how an operation does it (described by an implementation) Order of exe- Standard control structures: secution quence, selection, iteration; function calls and parameter passing

Associated activities Read and explain values of program objects; create, implement, use, and modify programs that manipulate standard data structures Read and explain the effects of operations; implement and describe operations; construct programs to implement a range of standard algorithms

Make appropriate use of control structures in the design of algorithms and then implement those structures in executable programs Encapsulation Indivisible bundling of related enti- Use existing encapsulated components in ties; client view based on abstraction programs; design, implement, and docuand information-hiding; implementer ment encapsulated components view based on internal detail Relationships The role of interfaces in mediating in- Explain and make use of inheritance and among en- formation exchange; responsibilities interface relationships; incorporate inhercapsulated of encapsulated components to their itance and interfaces into the design and components clients; the value of inheritance implementation of programs Testing and de- The importance of testing; debugging Design effective tests; identify and correct bugging strategies coding and logic errors


Appendix D C Reference Card This material was adapted from the C Reference Card (ANSI)1 developed by Joseph H. Silverman[18] with some additional material added to better support the GNU C compiler, gcc. Program Structure/Functions # include <stdio .h>

1 2 3 4 5 6

int main(void) { printf (" Hello world \n"); }

function prototype global variable declaration main routine declarations statements exit function terminate execution C Preprocessor include library file include user file replacement text replacement macro Example define max(A,B) ((A)>(B) ? (A) : (B))

undefine quoted string in replace concatenate args and rescan conditional execution line continuation char Data Types/Declarations character (1 byte) integer real number (single, double precision) short (16 bit integer) long (32 bit integer) double long (64 bit integer) positive or negative non-negative modulo 2m pointer to int, float,‌ enumeration constant constant (read-only) value declare external variable internal to source file local persistent between calls no value structure create new name for data type Initialization initialize variable initialize array initialize char string

1

January 2007 version 2.2. Copyright Š 2007 Joseph H. Silverman. The permission for the original was granted to make and distribute copies of this card provided the copyright notices and this permission notice are preserved on all copies. Send comments and corrections to J.H. Silverman, Math Dept., Brown Univ, Providence, RI 02912 USA (mailto://jhs@math.brown.edu)

143



Bibliography [1] Code.org. Every student in every school should have the opportunity to learn to code. Video clips are available at http://www.code.org, December 2012. [2] Stuart Zweben. Computing degree and enrollment trends: From the 2011-2012 cra taulbee survey. Technical report, Computing Research Association, Washington, DC., January 2013. [3] Adair Dingle and Carol Zander. Assessing the ripple effect of cs1 language choice. J. Comput. Sci. Coll., 16(2):85--93, Oct 2000. [4] Gong Ailing and Liu Tingrui. Practical ways of college bilingual teaching. In Proceedings of the 2009 First International Workshop on Education Technology and Computer Science, Volume 01, ETCS 2009, pages 40--42, Washington, DC, USA, 2009. IEEE Computer Society. [5] Kristina Grifantini. Moore's law. MIT Technology Review, December 2008. [6] Intel Corporation. Moore's law 40th anniversary. available online at http://www.intel. com/pressroom/kits/events/moores_law_40th/, 2012. [7] Pascal Rigaux. Programming languages study page. available online at http://rigaux. org/language-study/diagram.html, January 2007. [8] National Electronics and Computer Technology Center (NECTEC). รหัสสําหรับอักขระ ไทยทีใช้กบั คอมพิวเตอร์ (Standard for Thai Character Codes for Computers). มอก.620-2533 available online at http://www.nectec.or.th/it-standards/std620/std620.htm, 1990. [9] Mitch Resnick. Let's teach kids to code. available online at http://www.ted.com/ talks/mitch_resnick_let_s_teach_kids_to_code.html, Nov 2012. [10] Bill Granger. Scrambled eggs. available online at http://www.bbcgoodfood.com/ recipes/1720/perfect-scrambled-eggs, March 2003. [11] IBM. Flowcharting template. The graphic image for Part Number GX20-8020-1 is available online at http://en.wikipedia.org/wiki/File:Flowchart-template. jpg, 1980. [12] yWorks. yed in 90 seconds. http://www.youtube.com/watch?v=OmSTwKw7dX4, 2013. [13] Alan R Feuer. C Puzzle Book. Addison-Wesley, 2nd edition, 1999. [14] Leo Broukhis, Simon Cooper, and Landon Curt Noll. The international obfuscated c code contest. online at http://www.ioccc.org, 2013. 145


146

BIBLIOGRAPHY

[15] Matthew Halloway. Classroom handouts for iusb cs201 (computer programming). unpublished class notes, 2009. [16] ACM/IEEE CS2001 Interim Review Task Force. Computer science curriculum 2008: An interim revision of cs 2001 report from the interim review task force. Technical Report CS2008, Association of Computing Machinery/IEEE Computer Society, available online at http://www.acm.org/education/curricula/ComputerScience2008.pdf, December 2008. [17] The Joint Task Force on Computing Curricula. Computing curriculum 2001 - computer science: Final report. Technical report, IEEE Computer Society and Association for Computing Machinery, available online at http://www,acm.org/education/education/ educations/curric_vols/cc2001.pdf, December 2001. [18] Joseph H. Silverman. C reference card (ansi). available online at http://www.math. brown.edu/~jhs/ReferenceCards/CRefCard.v2.2.pdf, January 2007. [19] Alexander King and Hans Fromhertz. German-English Chemical Terminology: An Introduction to Chemistry in English and German. Thomas Murby & Co, London, 2 edition, 1951. [20] Hans Fromhertz and Alexander King. Englische und Deutsche Chemische Fachausdrücke: Ein Leitfaden der Chemie in englischer und deutcher Sprache. Thomas Murby & Co, London, zweite edition, 1951. [21] Peter J. Denning. Is computer science science? Commun. ACM, 48(4):27--31, Apr 2005. [22] Allen B. Downey, Jeff Elkner, and Chris Meyers. How To Think Like a (Functional) Programmer: OCaml Version. Green Tea Press, Wellesley, MA, 2002. [23] Allen B. Downey. Think Python: How To Think Like a Computer Scientist. Green Tea Press, Needham, MA, 2012. [24] Gérard Swinnen. Apprendre à programmer avec Python. O'Reilly, Paris, 2009. [25] Allen B. Downey. How To Think Like a Computer Scientist: C++ Version. Green Tea Press, Wellesley, MA, 2002. [26] Allen B. Downey. Think Java: How To Think Like a Computer Scientist. Green Tea Press, Wellesley, MA, 2012. [27] TeX Users Group. XeTeX on the Web. posted online at http://tug.org/xetex, Dec 2012. [28] Michel Goossens, Frank Mittelbach, and Alexander Samarin. The LaTeX Companion. Addison-Wesley, Reading, Massachusetts, 1993. [29] Jonathan Kew. XƎTEX, the Multilingual Lion: TEX meets Unicode and smart font technologies. TUGboat, 26(2):115--124, 2005.


Index algorithm, 3 and, 34 array, 48

Programming Job prospects, 1 Overview, 3

C language, 4 Central processing unit, 9

quotes Bill Gates, 1 Jeff Wilke, 1

fork(), 129 Hardware, 8 if, 32 inheritance, 129 Input, 8 input, 3 Integers, 21 Interactive development environment, 29

Scratch programming, 31 software, 14 subroutines, 43 thread, see process variables, 42

กา, 129 การทํางาน, 129

loops, 35 Memory, 8 Object-oriented programming, 129 objects, 129 attributes, 129 class definitions, 129 id, 129 methods, 129 OOP, see Object-oriented programming operators, 32 or, 34 Output, 8 output, 3 Peopleware, 14 polymorphism, 129 processes, 129 child, 129 id, 129 parent, 129 processing concurrent, 129 event driven, 129 sequential, 129 147



About this Book Colophon Much of the inspiration for this book comes from a second hand book the author acquired decades ago in Baltimore, Maryland. The book was the 1951 revision of a bi-lingual basic Chemistry textbook written in both English and German in the 1934. It had the English name German-English Terminology: An Introduction to Chemistry in English and German written by Alexander King and Hans Fromhertz.[19, 20] This edition dates back to a time when the field of Chemistry was so dominated by German publications and reference books that Australian, British and American chemists of that generation were required to develop literacy in German in order to be able to use the leading chemistry references. Figure D.1 shows a copy of the English and German versions of the first chapter of this book. Language

Text

English Version

German Version

Figure D.1: A Bilingual Introduction to Chemistry[19] In the same way, computer science has become an internationally popular, academic discipline with an exceptional growth rate. Computer Science world-wide is very anglo-centric as there is a heavy dependence on English key terms to communicate key concepts. Because computer science continues to expand and grow faster than human languages evolve naturally, the common practice within the member countries of the Association of Southeast Asian Nations (ASEAN) has been to either phonetically transcribe key terms into the local scripts or to coin new concepts from ancient root words. The result is that students fail to understand the 149


150

ABOUT THIS BOOK

imagery and often lack clarity in their understanding of key concepts. When these concepts are communicated internationally, misunderstandings easily arise, especially when even common computer terms like computer, input and output are represented in such diverse ways even within ASEAN languages, as shown in Table D.1. Table D.1: Common computer terms in the some languages of the AEC

Language

Lao Indonesian

Output Output เอาท์พุต ້ບທ ຄອມພ ິວເຕ ີ ວ ັດສະດຸ ປ້ ອນ ຜ ົນໄດ້ ຮ ີ komputer masukan keluaran

Tamil

கணினி

உள்ளீடு

உற்பத்தி

电脑

输入

产量

máy tính computer

đầu vào input

đầu ra pagbubuhos

English Thai

Chinese (Simplified Script) Vietnamese Tagalog

Computer Input Computer Input คอมพิวเตอร์ อินพุต

However, as the ASEAN Economic Community actively moves towards creating a common market, English communication will play an important role in forging partnerships and collaboration needed to attracting new global clientel of local software development services. With recent trend towards globalization, the local software industry already expects students to be familiar with English concepts enough to be able to provide effective service to international customers as well as understand the growing number of new technologies emerging world-wide. These trends greatly increase the need for fluency in English among students aspiring to become computer scientists. There is a need for resources that encourage the development of functional literacy of English computer terminology among university students within the Region. This Thai - English edition is an attempt to simultaneously expose freshmen to the basic computer terms in their mother tongue and in English thereby serving both as an introductory computer programming textbook as well as contextual dictionary of terminology. The cover design attempts to depict these rapid developments and growth of computing. Like this book, the tree has its roots in hardware and grows in unexpected ways to produce a wide range of new applications and technologies. The idea of a tree circuit came from by the graphics that accompanied the original printing of the thought provoking ACM editorial of the IT Profession that explored the question "Is Computer Science Science?".[21] As the green color implies, computer science is not static and there is much room for even more growth. This is an experiment has been developed as open courseware in hopes to stimulate collaboration with other universities other language groups within the Region to make this resource available to other students of other language groups. The model for this project comes from How to Think Like a Computer Scientist[22, 23] written by Allen B. Downey as a textbook for an advanced placement course The idea was to develop a electronic textbook that students could download from the Internet or could purchase in hardcopy. The project was so successful that the book has been translated into several lanugages of the world[24] as well as adopted for use in teaching other computer languages[25, 26] The source text for textbook was developed in XƎLATEX[27]: an open-source typesetting


151 system which combines the powerful document management capabilities of LATEX2e[28] with the multilingual support for Unicode using OpenType.[29] This system provided support for the simultaneous development of the Thai and English versions of this textbook. It can also be easily adapted for supporting other language combinations in the future. About the Author Dr Robert Batzinger has research interests that include using artificial intelligence and statistical computing for data mining, natural language processing in pre-publication processings and web technologies to support education and software engineering. Ever since the age of 12, Dr. Batzinger has a passion for developing computer systems that solve real world problems. At the same time, he enjoys teaching computer science to undergraduates as it gives him an opportunity to help students to discover for themselves the joy of creating software while building their skills towards a rewarding career. This book is the draft of the bilingual version of the textbook used his freshmen programming course in the Department of Computer Science at Payap University.




Computer Programming: A Course Textbook

In the current world economy, information has become the critical commodity that is collected, gathered, analysed, shared and traded. The majority of success stories in the news owe their success to the speed and accuracy in which data can be captured and processed in order to produce and share important and critical information. This is as true in business as it is on the battlefield, in space missions and even in game parlors and cybercafes around the globe. Programmers have become rock stars in this global economy as they build applications, games and software that interact with information and impact our lives. Every software application we use started by applying a few basic computer programming concepts and developing a sequence of commands that solves problems and impacts our lives. This book introduces students to the basic building blocks and concepts that programmers use to build useful software and develop the foundation for pursuing an exciting career in software programming.

Payap University Press Chiang Mai, Thailand http:\www.payap.ac.th

ISBN: 012-345678901-2


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.