Vous êtes sur la page 1sur 276

I NTRODUCTI ON TO COMPUTER

PROGRAMMI NG WI TH C#
Version 1. 0 I SBN 1- 932576- 18- 5
ii
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
ABOUT MI CROSOFT CORPORATI ON
Microsoft is committed to supporting students to pursue their interests in
technology. With the support of partners like DigiPen Institute of Technology,
students are able to learn programming using world-class development tools like
Microsoft Visual Studio.NET. Through programs like MSDN Academic Alli-
ance, theSpoke, and Imagine Cup, students can explore the opportunity that
software provides.
ABOUT DI GI PEN I NSTI TUTE OF TECHNOLOGY
DigiPen Institute of Technology, located in Redmond, Washington, is a
college dedicated to the field of digital interactive entertainment technology.
With specialized degrees in computer science, computer engineering, and
production animation, DigiPen is considered one of the top schools for those
seeking a serious career in the industry. For more information about DigiPen,
please visit http://www.digipen.edu.
iii
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
TABLE OF CONTENTS
I NTRODUCTI ON ....... ....... ........ ....... ....... ........ ....... ....... ........ ....... .... 1
An Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Course Component s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Prerequisit es t o Taking t his Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Soft ware Requirement s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Hardware Requirement s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
SEQUENCE OF TOPI CS..... ........ ....... ....... ........ ....... ....... ........ ....... ..... 2
Part 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Part 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Part 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
A BRI EF SUMMARY OF THE CHAPTERS - WHAT WI LL I LEARN? . . . . . . . 3
Chapt er 1 - Comput er Graphics Basic Concept s. . . . . . . . . . . . . . . . . . . . . . . . . . 3
Chapt er 2 - An Overview of t he C# Programming Language. . . . . . . . . 3
Chapt er 3 - C# Value Types & Reference Types . .. . .. . .. .. . .. . .. .. . .. . .. . 4
Chapt er 4 - Variables and Paramet ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Chapt er 5 - I nput and Out put . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Chapt er 6 - Expressions and Operat ors . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . .. . 5
Chapt er 7 - Funct ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Chapt er 8 - Flow Cont rol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Chapt er 9 - Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Chapt er 10 - Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Chapt er 11 - St ruct ures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
USI NG THE COURSE MATERI ALS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Purpose of t he Direct I mplement at ion Sect ions . .. . .. . .. .. . .. . .. .. . .. . .. . 8
Layout of t he Direct I mplement at ions Sect ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Benefit s of t he Direct I mplement at ions Sect ions.. . .. . .. .. . .. . .. .. . .. . .. . 9
GAME EXAMPLES AND PRACTI CE EXERCI SES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Text - Based Game. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Windows Game. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
DigiPen Proj ect FUN Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
PRESENTATI ON OF THE EXERCI SES ...... ........ ....... ....... ........ ....... ... 13
EXAMPLE # 1 - Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
EXAMPLE # 2 - Physics Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
EXAMPLE # 3 - Chemist r y Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
QUI CK REFERENCE SUMMARY OF EXERCI SES. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
CHAPTER 1
COMPUTER GRAPHI CS: BASI C CONCEPTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.1 REAL- TI ME I NTERACTI VE SI MULATI ON ( RTI S) . . . . . . . . . . . . . . . . . . . . . . . 28
1. 1. 1 Mot ion Pict ures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1. 1.2 Mot ion Pict ures Versus Games .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . . 28
1. 1. 3 Real Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1. 1. 4 I nt eract ive. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1. 1. 5 Simulat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1. 2 GAME ELEMENTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1. 2. 1 I mages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1. 2. 2 I nst ruct ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1. 2. 3 Game Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.3 COMPUTERS ....... ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 33
1. 3. 1 Hist ory of Comput ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1. 3. 2 Dumb Machines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1. 3. 3 Analog Versus Digit al . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
iv
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1. 3. 4 General- Purpose Comput ers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1. 3. 5 Dedicat ed Comput ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
1. 3. 6 Comput er Organizat ion/ Graphics Syst em . . . . . . . . . . . . . . . . . . . . . . . . 37
1. 3. 6. 1 Out put Devices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1. 3. 6. 2 I nput Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
1. 3.7 Operat ing Syst em .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . . 41
1.4 NUMBERS... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 42
1. 4. 1 I nt roduct ion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1. 4. 2 Binary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1. 4. 2. 1 I nt roduct ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1. 4. 2. 2 Binary Numbers Operat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1. 4. 2. 2. 1 Binary Addit ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1. 4. 2. 2. 2 Binary Subt ract ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1. 4. 2. 2. 3 Binary Mult iplicat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1. 4. 2. 2. 4 Binary Division . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1. 4.2. 3 Signed Binary Numbers .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . . 46
1. 4. 2. 4 Convert ing from Binary t o Decimal . . . . . . . . . . . . . . . . . . . . . . 49
1. 4. 2. 5 Convert ing from Decimal t o Binary . . . . . . . . . . . . . . . . . . . . . . 49
1. 4. 3 Oct al . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1. 4. 3. 1 I nt roduct ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1. 4. 3. 2 Convert ing from Oct al t o Decimal . . . . . . . . . . . . . . . . . . . . . . . 50
1. 4. 3. 3 Convert ing from Decimal t o Oct al . . . . . . . . . . . . . . . . . . . . . . . 51
1. 4. 4 Hexadecimal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
1. 4. 4. 1 I nt roduct ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
1. 4. 4. 2 Convert ing from Hexadecimal t o Decimal . . . . . . . . . . . . . 52
1. 4. 4. 3 Convert ing from Decimal t o Hexadecimal . . . . . . . . . . . . . 52
1.5 LOGI C GATES ..... ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 53
1. 5. 1 NOT ( I nvert er) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
1. 5. 2 NOR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
1. 5. 3 OR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
1. 5. 4 NAND. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
1. 5. 5 AND. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
1. 5. 6 XNOR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
1. 5. 7 XOR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
1. 5.8 Combining Logic Gat es . .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . . 56
1.6 LANGUAGES ....... ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 57
1. 6. 1 Low- Level Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1. 6.1. 1 Machine Language . . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . . 58
1. 6. 1. 2 Assembly Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1. 6. 2 High- Level Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1. 6. 2. 1 Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1. 6. 2. 2 I nt erpret ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1. 6. 2. 3 Translat or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1. 6. 2. 4 Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
1. 6. 3 I nt roduct ion t o C# : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
1. 6. 3. 1 What I s a Programming Language?. . . . . . . . . . . . . . . . . . . . . 60
1. 6.3. 2 What I s a Pseudocode?. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . . 60
1. 6.3. 3 My First C# Program . . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . . 61
DI SCUSSI ON QUESTI ONS........ ....... ....... ........ ....... ....... ........ ....... ... 65
EXERCI SES....... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 66
v
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
CHAPTER 2
COMPUTER PROGRAMMI NG OVERVI EW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
2.1 OVERVI EW . ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 71
2. 2 THE SMALLEST C# PROGRAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
2. 3 DI SPLAYI NG A MESSAGE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
2. 4 COMMENTS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
2.5 MULTI PLE I NSTRUCTI ONS PROGRAM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
2.6 FUNCTI ONS WI TH ARGUMENT RETURNI NG A VALUE. . . . . . . . . . . . . . . 75
2.7 VARI ABLES ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 77
2.8 USER I NPUT ....... ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 78
2. 9 CONDI TI ONAL EXPRESSI ON. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
2.10 LOOPS...... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 80
2. 11 ONE- DI MENSI ONAL ARRAY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
2.12 STRUCTURE...... ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 82
2. 13 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
2. 13. 1 Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
2. 13. 2 Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
2. 13. 3 Comput er Science Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
2. 13. 4 Chemist ry Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
2. 13. 5 Chemist ry Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
2. 13. 6 Physics Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
2. 13. 7 Physics Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
2. 13. 8 Physics Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
CHAPTER 3
C# TYPES .. ....... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 95
3.1 VALUE TYPES ..... ....... ........ ....... ....... ........ ....... ....... ........ ....... ... 95
3. 1. 1 byt e. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3. 1. 2 char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3. 1. 3 bool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3. 1. 4 decimal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
3. 1. 5 double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
3. 1. 6 enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3. 1. 7 float . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3. 1. 8 int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3. 1. 9 long . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3. 1. 10 sbyt e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3. 1. 11 short . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3. 1. 12 st ruct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
3. 1. 13 uint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
3. 1. 14 ulong . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
3. 1. 15 ushort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
3. 2 REFERENCE TYPES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
3.3 VOI D ... ....... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 102
3.4 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
3. 4. 1 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
3. 4. 2 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
3. 4. 3 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
3. 4. 4 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
3. 4. 5 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
3. 4. 6 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
3. 4.7 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 115
3. 4. 8 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
3. 4. 9 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
vi
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3.5 THE TEXT- BASED GAME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
3.6 TYPES USED I N THE TEXT- BASED GAME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
3.7 THE WI NDOWS- BASED GAME: BRI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
3.8 TYPES USED I N THE BRI X GAME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
3.9 I NTRODUCTI ON TO FUN EDI TOR. NET. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3.10 THE FUN EDI TOR GAME: CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3. 10. 1 Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3. 10. 2 High Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3. 10.3 Minimum Syst em Requirement s . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 125
3. 10. 4 Plot Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
3. 11 TYPES USED I N CAVES OF DOOM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
3. 11. 1 Adding Global Dat a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
3. 11. 2 Edit ing Global Dat a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
3. 11.3 Accessing Global Dat a .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 133
3. 11. 4 Delet ing Global Dat a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
3. 11. 5 Referencing Global Dat a. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
3. 11.6 Global Dat a in t he Game .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 134
3. 12 ADDI NG CODE TO CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
CHAPTER 4
VARI ABLES ...... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 137
4.1 CATEGORI ES OF VARI ABLES I N C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4. 1. 2 St at ic Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4. 1. 3 I nst ance Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4. 1. 3 Array Element s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4. 1. 4 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4. 1.5 Value Paramet ers .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 137
4. 1. 6 Reference Paramet ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
4. 1. 7 Out put Paramet ers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
4.2 DEFAULT VALUES ...... ........ ....... ....... ........ ....... ....... ........ ....... . 138
4.3 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
4. 3.1 English Language Problem . . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 138
4. 3.2 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 139
4. 3.3 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 139
4. 3. 4 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
4. 3. 5 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
4.4 VARI ABLES USED I N THE TEXT- BASED GAME. . . . . . . . . . . . . . . . . . . . . . . . 140
4.5 VARI ABLES USED I N THE BRI X GAME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
4.6 VARI ABLES USED I N CAVES OF DOOM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
4. 6.1 Global I nt eger Variables . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 142
4. 6. 2 Global Boolean Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
4. 6. 3 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
4. 6. 4 FUN Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
4. 7 ADDI NG CODE TO CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
4. 8 ADDI NG CODE TO BRI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
vii
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
CHAPTER 5
I NPUT AND OUTPUT. ....... ........ ....... ....... ........ ....... ....... ........ ....... . 148
5. 1 THE CONSOLE CLASS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
5. 2 OUTPUT: THE CONSOLE. WRI TE METHOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
5.3 OUTPUT: THE CONSOLE. WRI TELI NE METHOD . . . . . . . . . . . . . . . . . . . . . . . 149
5.4 I NPUT: THE CONSOLE. READ METHOD. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
5.5 I NPUT: THE CONSOLE. READLI NE METHOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
5.6 GDI + ... ....... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 149
5.7 A GDI + CLASS: THE GRAPHI CS CLASS...... ....... ....... ........ ....... . 149
5. 7. 1 DrawI mage Met hods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
5. 7.2 DrawSt ring Met hods.. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 151
5.8 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
5. 8.1 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 152
5. 8. 2 Game Design Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
5. 8. 3 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
5. 8. 4 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
5. 8.5 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 153
5. 8.6 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 153
5.9 I NPUT AND OUTPUT I N THE TEXT- BASED GAME. . . . . . . . . . . . . . . . . . . . 153
5.10 I NPUT AND OUTPUT I N THE BRI X GAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
5. 10. 1 I nput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
5. 10. 2 Out put . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
5.11 I NPUT AND OUTPUT I N CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
5. 11.1 I nput : The Keyboard Class .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 156
5. 11. 2 Game I nput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
5. 11. 3 Out put : The Text Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
5. 11.4 Text Obj ect s in Caves Of Doom . . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 160
5.12 TEXT- BASED GAME EXERCI SE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
5. 13 ADDI NG CODE TO CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
5. 14 ADDI NG CODE TO BRI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
CHAPTER 6
EXPRESSI ONS, OPERATORS .... ....... ....... ........ ....... ....... ........ ....... . 166
6.1 CLASSI FI CATI ON OF EXPRESSI ON .. ........ ....... ....... ........ ....... . 166
6.2 OPERATORS ....... ....... ........ ....... ....... ........ ....... ....... ........ ....... . 166
6. 2. 1 Operat or Precedence and Associat ivit y. . . . . . . . . . . . . . . . . . . . . . . . . . . 167
6. 2.2 Operat or Overloading . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 167
6. 3 FUNCTI ON MEMBERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
6. 3.1 The New Operat or .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 168
6.4 UNARY OPERATORS .. ........ ....... ....... ........ ....... ....... ........ ....... . 168
6.5 ARI THMETI C OPERATORS . ....... ....... ........ ....... ....... ........ ....... . 169
6.6 SHI FT OPERATORS.... ........ ....... ....... ........ ....... ....... ........ ....... . 171
6.7 RELATI ONAL AND TYPE TESTI NG OPERATORS . . . . . . . . . . . . . . . . . . . . . . 172
6.8 LOGI CAL OPERATORS........ ....... ....... ........ ....... ....... ........ ....... . 172
6. 8. 1 Condit ional Operat or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
6. 8. 2 Assignment Operat ors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
6. 8.3 Simple Assignment Operat or . . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 173
6. 8. 4 Boolean Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
6.9 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
6. 9. 1 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
6. 9. 2 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
6. 9. 3 Game Design Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
6. 9. 4 Game Design Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
6. 9. 5 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
viii
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6. 9.6 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 175
6. 9.7 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 175
6. 9.8 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 176
6.10 OPERATORS I N THE TEXT- BASED GAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
6.11 OPERATORS I N THE BRI X GAME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
6.12 OPERATORS I N CAVES OF DOOM... ........ ....... ....... ........ ....... . 179
6.13 TEXT- BASED GAME EXERCI SE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
6. 14 ADDI NG CODE TO CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
6. 15 ADDI NG CODE TO BRI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
CHAPTER 7
FUNCTI ONS...... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 185
7.1 DEFI NI TI ON ....... ....... ........ ....... ....... ........ ....... ....... ........ ....... . 185
7.2 SCOPE . ....... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 185
7.3 CALLI NG A FUNCTI ON ....... ....... ....... ........ ....... ....... ........ ....... . 185
7. 4 RETURN STATEMENT EXAMPLE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
7.5 CALL BY VALUE FUNCTI ON ARGUMENTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
7.6 CALL BY REFERENCE FUNCTI ON ARGUMENTS. . . . . . . . . . . . . . . . . . . . . . . . 187
7.7 FUNCTI ON RETURNI NG VALUE EXAMPLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
7. 7. 1 Ret urning an I nt eger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
7.8 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
7. 8. 1 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
7. 8. 2 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
7. 8. 3 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
7. 8. 4 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
7. 8.5 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 190
7. 8.6 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 191
7. 8.7 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 193
7. 8.8 Physics Problem . . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 193
7.9 FUNCTI ONS I N THE TEXT- BASED GAME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
7.10 FUNCTI ONS I N THE BRI X GAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
7. 11 FUNCTI ONS I N CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
7.12 TEXT- BASED GAME EXERCI SE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
7. 13 ADDI NG CODE TO CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
7. 14 ADDI NG CODE TO BRI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
CHAPTER 8
FLOW CONTROL ....... ....... ........ ....... ....... ........ ....... ....... ........ ....... . 205
8.1 THE WHI LE STATEMENT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
8.2 THE DO- WHI LE STATEMENT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
8.3 THE FOR LOOP ... ....... ........ ....... ....... ........ ....... ....... ........ ....... . 206
8.4 THE FOREACH, I N STATEMENT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
8. 5 THE JUMP STATEMENT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
8. 5. 1 Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
8. 5. 2 Cont inue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
8. 5. 3 Got o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
8. 5. 4 Ret urn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
8.6 THE SWI TCH STATEMENT .. ....... ....... ........ ....... ....... ........ ....... . 210
8.7 I F- ELSE ...... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 211
8.8 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
8. 8. 1 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
8. 8. 2 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
8. 8. 3 Mat h Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
8. 8. 4 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
ix
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8. 8. 5 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
8. 8. 6 Chemist ry Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
8.9 FLOW CONTROL I N THE TEXT- BASED GAME . . . . . . . . . . . . . . . . . . . . . . . . . . 219
8.10 FLOW CONTROL I N THE BRI X GAME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
8.11 FLOW CONTROL I N CAVES OF DOOM ..... ....... ....... ........ ....... . 221
8.12 TEXT- BASED GAME EXERCI SE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
8. 13 ADDI NG CODE TO CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
8. 14 ADDI NG CODE TO BRI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
CHAPTER 9
CLASSES ... ....... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 230
9.1 DEFI NI TI ON OF A CLASS... ....... ....... ........ ....... ....... ........ ....... . 230
9.2 CLASS DECLARATI ON ........ ....... ....... ........ ....... ....... ........ ....... . 230
9. 2. 1 Class Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
9. 2. 2 Abst ract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
9. 2. 3 Sealed Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
9. 2. 4 Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
9. 3 MEMBERS OF A CLASS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
9. 3. 1 I nherit ance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
9. 3. 2 Access Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
9. 3. 3 St at ic & I nst ance Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
9. 3. 4 Nest ed Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
9. 3. 5 Reserved Member Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
9.4 CONSTANTS ....... ....... ........ ....... ....... ........ ....... ....... ........ ....... . 234
9.5 FI ELDS ....... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 234
9. 5. 1 St at ic and I nst ance Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
9. 5. 2 Readonly Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
9.6 METHODS ... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 234
9. 6. 1 Met hod Paramet ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
9. 6.2 Value Paramet ers. .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 235
9. 6. 3 Reference Paramet ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
9. 6. 4 Out put Paramet ers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
9. 6. 5 St at ic and I nst ance Met hods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
9. 7 PROPERTI ES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
9. 7.1 St at ic and I nst ance Propert ies .. .. . .. . .. . .. .. . .. . .. . .. .. . .. . .. .. . .. . 235
9. 7. 2 Virt ual, Sealed, Override, and Abst ract Accessors. . . . . . . . . . . . 236
9.8 EVENTS ...... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 236
9.9 I NDEXERS .. ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 236
9.10 OPERATORS ..... ....... ........ ....... ....... ........ ....... ....... ........ ....... . 237
9. 11 I NSTANCE CONSTRUCTORS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
9. 12 STATI C CONSTRUCTORS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
9.13 DESTRUCTORS . ....... ........ ....... ....... ........ ....... ....... ........ ....... . 238
9.14 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
9. 14. 1 Chemist ry Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
9. 14. 2 Chemist ry Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
9.15 CLASSES I N THE TEXT- BASED GAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
9.16 TEXT- BASED GAME EXERCI SE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
9. 17 ADDI NG CODE TO CAVES OF DOOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
CHAPTER 10
ARRAYS..... ....... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 248
10.1 I NTRODUCTI ON ...... ........ ....... ....... ........ ....... ....... ........ ....... . 248
10.2 ARRAY TYPES... ....... ........ ....... ....... ........ ....... ....... ........ ....... . 248
x
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
10. 3 ARRAY CREATI ON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
10. 4 ARRAY ELEMENT ACCESS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
10. 5 ARRAY MEMBERS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
10.6 ARRAY I NI TI ALI ZERS...... ....... ....... ........ ....... ....... ........ ....... . 249
10. 7 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
10. 7. 1 Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
10. 7. 2 Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
10. 7. 3 Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
10. 7. 4 Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
10. 7. 5 Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
10. 7. 6 Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
10. 7. 7 Physics Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
10. 7. 8 Physics Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
10. 8 ARRAYS I N THE TEXT- BASED GAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
10. 9 ARRAYS I N THE BRI X GAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
10. 10 ADDI NG CODE TO BRI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
CHAPTER 11
STRUCTURES.... ........ ....... ........ ....... ....... ........ ....... ....... ........ ....... . 255
11. 1 DEFI NI TI ON OF A STRUCT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
11.2 STRUCT DECLARATI ON.... ....... ....... ........ ....... ....... ........ ....... . 255
11.3 MEMBERS OF A STRUCT... ....... ....... ........ ....... ....... ........ ....... . 255
11.4 CLASS AND STRUCT DI FFERENCES ........ ....... ....... ........ ....... . 255
11. 5 DI RECT I MPLEMENTATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
11. 5. 1 Mat h Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
11. 5. 2 Comput er Science Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
11. 5. 3 Social Sciences Problem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
11. 6 STRUCTURES I N THE TEXT- BASED GAME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
11. 7 STRUCTURES I N THE BRI X GAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
11. 8 ADDI NG CODE TO BRI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
APPENDI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
xi
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
HOW TO USE THI S DOCUMENT
This e-Textbook has been distributed electronically using the Adobe Portable
Document Format (PDF) format. More than just a converted text file, this doc-
ument was designed to take advantage of this medium so that both instructors
and students, using freely distributed Adobe Acrobat version 6.0 or 7.0, can create
personalized versions of the document. They can easily search, highlight text,
and add comments. This section will cover how to use this document and pro-
vides tips on the best practices.
On the left side of the document there are tabs. If you click on the bookmark
tab, you will see the different chapters of the book in Red. If you click on them
they will take you to that part of the book. You can expand the bookmarks by
clicking the plus sign next to each bookmark to see the different sections of that
particular chapter.
BOOKMARKS
The sections are color-coded
as follows:
BLUE Sub-sections of
content for a given
chapter.
RED Vocabulary words:
The definitions to
these words can be
read by rolling over the
word with your cursor.
The definition will
appear in red on the
left margin.
ORANGE Examples are orange
and are identified by a
light-bulb icon.
xii
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
APPENDI X
The Appendix, located at the
end of the document contains
the answers to the example
questions.
SEARCHI NG THE DOCUMENT
This document makes it easy for users to
search through the document for specific
words or phrases.
To access this feature:
Press CTRL+F
Or
Click the Edit in the top menu
and click Search.
Or
Click on the icon on the toolbar.
This will open up the search dialogue
box on the right side of the screen.
Simply type in the word or phrase and
choose the options that best fit your
search and click Search. To hide the
dialogue box, click the Hide button in
the top right-hand corner.
xiii
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
COMMENTI NG
One of the most useful functions available to users is the ability to use Adobe
Acrobat Reader version 6.0 or 7.0 to highlight important sections of text and to
add personal comments to the users copy of this PDF. Much like how students
will use a highlighter or scribble comments in the margin, this function
enhances the PDF to be a functional study resource. In addition, this functional-
ity allows the instructor to highlight specific sections of the text that you want
your students to pay special attention to or add notes to give students additional
instruction or guidance as they study this textbook.. The instructor can then
save these changes and distribute a copy to students for them to import into their
PDFs.
Click the Commenting icon or in the top menus, click Tools and scroll down
to Commenting. In the scroll down menu that appears, select Show Commenting
Toolbar.
You will notice that there are a few options to choose from. The tools you will be
primarily concerned with are the Note Tool and the Highlighter.
Not es
The Note Tool allows you to place sticky notes anywhere you wish in the
document. Simply click on this icon and click anywhere in the document. A
small text window will open for the user to enter comments.
For the instructor, this is a good tool to identify important concepts a student
should learn or even identify questions that a student should answer for a given
section.
Comment/Notes can be minimized or left open. Minimized notes can be opened
again by double clicking the icon of the note you wish to open.
xiv
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
In the tabs on the left of the screen is the Comments tab. This allows the user
to view all of the comments. This section allows the user to print/import/export
the comments. Instructors can use the import/export function to provide their
notes to their students. In the top right corner of the Comments window is
Options under which selected comments can be imported or exported.
Hi ghl i ght i ng
The Highlighter allows a user to highlight sections of text
Cust om i zi ng t he Hi ghl i ghi ng/ Comm ent i ng Feat ur e
To further customize these features open the Properties Toolbar by either press-
ing CTRL+E or clicking View in the top menu, scrolling down to Toolbars and
click Properties Bar.
xv
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
The Properties Toolbar allows you to choose the color, transparency and icons
that appear when you use the commenting tools.
To change the properties of a note or highlighted section after it is already
placed, right click on the icon or section and select Properties. You will be able to
change the color, transparency, the icon, or the Author name.
Having different colors and icons can set your comments apart from those of
your student and make them easier to find. For example, instead of using the
default yellow for commenting, an instructor can choose to use red so that
students can distinguish between the instructors comments and their own.
OTHER FUNCTI ONALI TY
Snapshot Tool
Another useful tool in this document is the Snapshot Tool. This allows a user to
take a picture of a section of the screen and paste it into PowerPoint presenta-
tions, Word documents and other programs.
To use this tool, click on the Snapshot Tool icon and drag an area select win-
dow around the section of the document you wish to put onto the clipboard for
pasting into another program.
I nt roduct ion 1
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
I NTRODUCTI ON
An Over vi ew
This computer science course provides a unique curriculum for instructors to
teach Microsofts C# programming language through the implementation of
computer games. Computer games are used to illustrate C# programming con-
cepts because they are an ideal medium to present complicated subjects in a for-
mat that is engaging to students. Other advantages of using games are:
Students can relate to games because games are a part of students' lives.
They can realistically simulate natural phenomena and real-life events.
They react in real-time.
They are story-based simulations requiring a plot where game objects must
interact intelligently with each other.
The curriculum provides instructors with the materials to give students a solid
foundation and clear understanding of the fundamental concepts of the C# pro-
gramming language. In addition, after working through the exercises and direct
implementations, students should be able to effectively apply C# programming
concepts in various fields of study including mathematics and physics. These
fields were purposely chosen to illustrate the extensive application of C#.
The following goals were addressed in the development of this curriculum:
To introduce the C# programming language to college students in the easiest
possible way through the implementation of games.
To provide a guide to teaching and learning the C# programming language
through the use of graphic and non-graphic applications.
To present C# topics in a non-traditional way that is more engaging to stu-
dents by using computer game programming and development as a solid
base.
To develop students thinking and problem solving skills by providing prac-
tical, hands-on examples.
To show how C# concepts can be effectively used and demonstrated in real-
istic simulations.
To integrate C# into high school academic programs.
Ultimately, the programming language should not be regarded as one whose sole
purpose is strictly for computer science. Instead, DigiPen has tried to demon-
strate clearly the usefulness and convenience of the language across all domains.
It is DigiPens intention that instructors gain a general and practical knowledge
of C# that will enable integration of programming skills into everyday life.
DigiPen welcomes your comments and suggestions.
Please email us at: csharp@digipen.edu
I nt roduct ion 2
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
Cour se Component s
There are a number of folders that accompany this curriculum including:
The folder Brix contains the Windows-based game.
The folder Caves Of Doom contains the FUN Game.
The folder Exercises contains the solutions for all the exercises.
The folder Text Based Game contains the text-based game.
Pr er equi si t es t o Tak i ng t hi s Cour se
Ideally, students should have a general idea about computer programming. To
get the most out of this course, students should at least have good knowledge of a
Windows-based Operating System. It is also helpful if students are familiar with
Microsoft Visual Studio.net.
For the Caves of Doom example, students should be familiar with the DigiPen
ProjectFUN Editor, an application developed by DigiPen to facilitate game
development training.
Sof t w ar e Requi r ement s
C# 2005 Express Edition
DigiPen FUN Editor.net
Microsoft Windows 2000 or XP
Har dw ar e Requi r ement s
A Pentium III-based (or better) PC
Keyboard
Mouse
Speakers
Sound card
SEQUENCE OF TOPI CS
The book has three parts that comprise the 11 chapters.
Par t 1
Chapter 1 provides a general guide to computer science. This chapter covers top-
ics like numbers, logic gates, and languages. It also contains a background his-
tory of computer development.
Chapter 1 Computer Graphics Basic Concepts
I nt roduct ion 3
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
Par t 2
Chapter 2 provides a brief general overview of the C# programming language. It
answers common questions about C# and offers a platform from which to con-
tinue with the rest of the course. Each topic mentioned is dealt with in more
depth in the dedicated chapters.
Chapter 2 An Overview of the C# Programming Language
Par t 3
Chapters 3 through 11 cover the core of C# concepts. Each chapter deals with a
specific topic in detail. Each chapter assumes the knowledge of the previous
chapters.
Chapter 3 C# Value Types & Reference Types
Chapter 4 Variables & Parameters
Chapter 5 Input & Output
Chapter 6 Expressions & Operators
Chapter 7 Functions
Chapter 8 Flow Control
Chapter 9 Classes
Chapter 10 Arrays
Chapter 11 Structures
A BRI EF SUMMARY OF THE CHAPTERS -
WHAT WI LL I LEARN?
Chapt er 1 - Comput er Gr aphi cs Basi c Concept s
We begin with motion pictures, comparing them to games, and explaining what
Real-Time Interactive Simulation means. We will then talk about game elements,
the history of computers, number representation and bases, and logic gates. The
last section of this chapter covers computer languages: high-level and low-level
languages, their differences, and the relationship between them. Discussion
questions at the end of the chapter review the chapters contents and assess what
the reader really understood. A set of exercises is provided to test students
knowledge about the covered topics. This introductory chapter serves as a basis
for the rest of the curriculums materials.
Chapt er 2 - An Over vi ew of t he
C# Pr ogr ammi ng Language
Chapter 2 provides an introduction to the C# programming language. It briefly
covers the major topics in the C# language. Subsequent chapters expand on each
of these topics.
The smallest C# program, which does nothing but run correctly
with no errors.
How to write the famous Hello World program in C#
Two kinds of comments used in C#
I nt roduct ion 4
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
A multiple instructions program
A program that returns a value
Variables and their use
User input and how it is interpreted
Conditional expression, loops arrays, and structures
The chapter review exercises in the final section are gathered from various field
of study.
Chapt er 3 - C# Val ue Ty pes & Ref er ence Ty pes
This chapter is extremely important and contains a lot of information. Students
of this curriculum should take their time to read the chapter in its entirety and
understand all the details and new ideas covered within the chapter. A key step in
understanding what is going on in the three games is to open the code for each
game and try to follow through the code and understand the logic behind it.
Topics covered include:
Value types
Reference types
Void
Exercises
Direct Implementation
Text-based games and the types used
The Windows-based game Brix and the types used
Caves of Doom using the FUN Editor
Chapt er 4 - Var i abl es and Par amet er s
In Chapter 4 we first categorize the C# variables as static variables, instance vari-
ables, array elements, local variables, value parameters, reference parameters,
and output parameters. We then discuss default values. The Direct Implementa-
tions section is followed by sections describing the variables used in the three
games and a section explaining how to add related code to Caves Of Doom. The
last section deals with adding code to Brix.
Chapt er 5 - I nput and Out put
This chapter deals with input and output in C#. We begin our discussion of input
and output in C# with the Console class. This class has four basic methods: Read
and ReadLine (for input), and Write and WriteLine (for output). The Console
class is useful when writing a console application with no Windows interface.
Next we talk about GDI+, an Application Programming Interface (API) for Win-
dows programmers. In GDI+, the Graphics class provides methods for drawing
lines, curves, figures, images, and text. The most important and frequently used
method in the Graphics class is the DrawImage method, which enables image-
drawing in the window. Another important method in the Graphics class is the
DrawString method, which enables text string display in various formats. The
Direct Implementations section deals with a physics problem that converts tem-
perature from Celsius to Fahrenheit and a game design problem that determines
whether a game character should make a punch or a kick. We also discuss input
I nt roduct ion 5
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
and output in the three games, and we add more code to an incomplete version
of Caves Of Doom.
This chapter introduces a new Text-Based Game Exercise section. In this section,
we start building the text-based game step-by-step. We begin by finishing a small
section of the game. In chapters 6, 7, 8, and 9, we add increasingly more code in
this code section until the game is almost finished. The last section deals with
adding code to Brix.
Chapt er 6 - Ex pr essi ons and Oper at or s
Chapter 6 is dedicated to expressions and operators. We talk about the classifica-
tion of expressions (a value, a variable, a namespace, a type, a method group, a
property access, an event access, an indexer access, or nothing). We then talk
about operators: operator precedence and associativity, operator overloading,
unary operators, and so forth. After the Direct Implementations section, in
which there are two math problems and two game design problems to solve, we
talk about how operators are used in the three games. Finally, we add more code
to the incomplete version of Caves Of Doom. In the Text-Based Game Exercise
section, we take up where we stopped in the last chapter and add more code. The
last section deals with adding code to Brix.
Chapt er 7 - Funct i ons
Chapter 7 deals with the C# functions: function definition, function scope, call-
ing a function, return statement, call by value function arguments, and call by
reference function arguments. The Direct Implementations section contains a
math problem that calculates the volume of several three-dimensional shapes.
Finally, students will learn how functions are implemented in the three games,
and add code to Caves Of Doom. The Text-Based Game Exercise begins from
where we stopped in the last chapter and add more code to it. The last section
deals with adding code to Brix.
Chapt er 8 - Fl ow Cont r ol
Chapter 8 deals with about flow control: the While statement, the Do-while
statement, the For loop, the "foreach, in" statement, the Jump statement, the
break statement, the continue statement, the goto statement, the return state-
ment, the switch statement, and the if-else statement. The Direct Implementa-
tions section has three math problems to solve. The last section talks about flow
control in the three games, as well as how to add code to Caves Of Doom. The
Text Based Game Exercise section adds more code to it. The last section deals
with adding code to Brix.
Chapt er 9 - Cl asses
Chapter 9 focuses on C# Classes: the definition of a class, class declaration, class
modifiers, members of a class, constants, fields, methods, properties, events,
indexers, operators, instance constructors, default constructors, static construc-
tors, and destructors. There is also a section about how classes are used in the
I nt roduct ion 6
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
text-based game, and another section about adding code to Caves Of Doom. The
Text Based Game Exercise section adds code.
Chapt er 10 - Ar r ay s
Chapter 10, first provides an introduction to arrays and then a discussion about
array types, array creation, array element access, array members, and array ini-
tializers. The Direct Implementations section contains ten math problems.
Finally, we discuss how to use arrays in the text-based and Windows-based
games. The last section deals with adding code to Brix.
Chapt er 11 - St r uct ur es
Chapter 11 is about the C# structure: definition of a struct, struct declaration,
members of a struct, and differences between class and struct. In the Direct
Implementations section, there is a math problem, a computer science problem,
and a social science problem. Two sections talk about how to use structures in
the text-based and Windows-based games. The last section deals with adding
code to Brix.
I nt roduct ion 7
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
USI NG THE COURSE MATERI ALS
This course is available electronically in two versions to give instructors the
option as to what approach they wish to take in teaching the course:
Full Instructor Version (recommended)
MS_DP_C_Sharp_Course_INSTRUCTOR.pdf
By providing this version to students, students have direct access to the
solutions appendix to verify their understanding of the content. Of course,
it is expected that instructors would need to devise alternative assessment
mechanisms, such as assigning a programming task related but not
specifically defined within the course materials.
Student Version
MS_DP_C_Sharp_Course_STUDENT.pdf
For instructors who do not wish students to have access to the solutions
appendix, this version has had the appendix removed.
Each chapter is subdivided into topics with examples given to further clarify
ideas. In addition, diagrams, illustrations, screenshots, and tables support the
text. This is a brief explanation of the formatting used in the document:
I nt roduct ion 8
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
The layout of the chapters is structured as follows:
Each chapter begins with a short explanation.
Every key term is highlighted and supported by a definition that can be used
as a reference.
Near the end of the chapter, a Direct Implementations section puts into
practice what has just been learned. This section presents different prob-
lems that relate to various fields, including mathematics, computer science,
physics, chemistry, english, and social sciences. The solutions can be found
in the Appendix.
Pur pose of t he Di r ect I mpl ement at i on Sect i ons
Direct Implementation sections can be found near the end of each chapter.
These sections are an integral part of the curriculum and have been designed
specifically to show the power of the C# programming language in solving prob-
I nt roduct ion 9
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
lems of various disciplines found in typical high school courses. In addition,
each problem is related to the content of the chapter in which it appears. For
example, in Chapter 6 Expressions and Operators, the direct implementation
exercises put that theory into practice. A new programming concept in Chapter
3 is put into practice. After Chapter 4, the information from both chapters 3 and
4 relate in a new C# program.
Lay out of t he Di r ect I mpl ement at i ons Sect i on
Each problem is followed by an example of what the output should look like. A
sample is shown below:
Only the programs output is shown, not the C# code. The C# code is provided in
the accompanying folder that has the same name as the exercise. For example,
the exercise given in section 3.4.2 will be found in a folder called Exercise3.4.2.
Students do not need to provide the exact output shown in the sample. What
matters is that the result of the program is the same. In the above case, it is the
final equation y=0.5x+2.5 that matters.
Benef i t s of t he Di r ect I mpl ement at i ons Sect i ons
Direct Implementations sections are beneficial for students in the following
ways:
The problems are related to common high school subjects, such as math and
physics, and are therefore very relevant.
Students will be able to see how effective the C# programming language is in
solving problems that are presented by more familiar subjects like math and
physics.
This section is the link between C# as a programming tool and high school
subjects.
By working through all the sections, students will ready themselves to use
C# to face and solve problems related to high school courses.
I nt roduct ion 10
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
GAME EXAMPLES AND PRACTI CE EXERCI SES
The final part of each chapter shows how each topic discussed in that chapter
can be implemented in a real game. Three different games illustrate this.
A text-based game, Fun City;
A Windows-based game, Brix;
A ProjectFUN game, Caves of Doom.
By using three different game genres, students will be able to see and learn how
each C# concept can apply differently in distinct types of games. The examples
are intended as exactly that, examples, and should not be assumed as the only
way concepts can be understood and mastered.
Tex t - Based Game
The game environment of Fun City virtually simulates the FUN Editor environ-
ment. The idea and main aim of Fun City is to be able to successfully build and
run a game with all the required assets, just as in the actual FUN Editor applica-
tion. It is a simple text-based game that accepts one or two words, such as GoTo
Game, as input. The first letter of every word is in uppercase (GameAssets and
SpritesCity). When the program recognizes a word, it displays a text message
depending on the location of the player at that moment. The input is a combina-
I nt roduct ion 11
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
tion of specific verbs and nouns that the computer recognizes and responds to.
Users enter the input through the keyboard; a mouse is not used. Another term
for text-based games is parser-based games. These games are very useful for
learning C# for a variety of reasons:
No graphics are needed for this type of game, so students can immediately
focus on direct programming techniques.
Programmers with little experience can learn how to create a game using C#
without having to worry about how to manipulate graphical objects.
Text or parser-based games are the origin of all video games created before
Windows and other common platforms. Before programming with graph-
ics, it is a good idea to become familiar with games using DOS.
Text-based games can be played from the DOS prompt and programmed
under DOS and under Windows; therefore, students do not need to under-
stand Graphical User Interfaces (GUIs) or the architecture behind them at
this stage.
Wi ndow s Game
Windows-based games came after the era of text-based games. As the name
implies, a Windows game runs in the Windows Operating System. Programming
a game that runs on Windows is vastly different from programming a game that
runs on DOS (a text-based game). Some of the main differences include:
Windows games are programmed under the Windows Operating System.
Text-based games can be programmed under the Disk Operating System
(DOS), while Windows games cannot.
Windows has a Graphical User Interface (GUI) that should be used in Win-
dows games.
Text-based games are programmed without a GUI.
Windows games run in a window while text-based games run under the
DOS prompt.
Windows games have backgrounds, images, and actors that make the game
more appealing and visually interesting.
Text-based games rely on the players imagination there are no graphics.
GDI+ or Direct X are needed to program and run Windows games.
Text-based games run without the need for applications such as GDI+ and
Direct X.
By definition, Windows games are more interactive than text-based games.
In addition to these differences, certain C# features (for example, some Classes)
are only used in either text-based or Windows-based games. The Graphics and
Bitmap classes are only used with C# Windows programming.
Brix is the Windows game used as an example in this curriculum. It is a classical
bricks game where the player manipulates a paddle that moves horizontally.
Players move the paddle right and left using the right and left arrow keys. A ball
rests on the paddle until the Spacebar is pressed. The ball then begins moving
and bouncing until it hits a group of bricks. When the ball hits a brick, the brick
reflects the ball and vanishes. When all the bricks have been hit, the game ends.
From the player's point of view, Brix is a simple and classical game, but from the
I nt roduct ion 12
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
designer's point of view, it represents a big challenge; the designer has to start
from scratch. All the game logic and design must be built step-by-step.
Di gi Pen Pr oj ect FUN Game
ProjectFUN Editor is the visual-aid tool that helps users develop games that run
with the FunEngine. This can be accomplished in a short period of time with
minimal hassle, even for those who have only basic programming skills. FUN
games, however, can be fully developed without the need to install or use this
tool. Given its simplicity, ProjectFUN helps beginning programmers to enjoy
producing 2D games that look and feel like those games produced by profes-
sional game developers.
Think of the editor as the intermediary between you (as a developer) and the
FunEngine. It simply provides the different tools that help to define a game in
terms of FUN objects. It produces code required by the engine to run. It also
saves a lot of time specifying countless coordinates needed to move objects or to
define collision points by providing visual tools that facilitate this. Many other
features offered by this tool make game development much more fun. From a
learning point of view, it is the ideal way to learn C# concepts.
I nt roduct ion 13
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
PRESENTATI ON OF THE EXERCI SES
Each C# example is presented in a frame containing the code. The actual C# code
is written in Courier New.
I nt roduct ion 14
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
The following three sections examine three types of problems that we deal with
in the Direct Implementations section found in most of the chapters.
1. We state the problem.
2. We offer a flow chart detailing how the problem can be solved logically.
3. We provide a list of items needed to complete the task.
4. We describe how the problem should be approached.
5. We describe each keyword appearing in the problem to ensure clear
understanding of the problem before it is attempted.
6. A step-by-step method shows exactly how the problem should be
dealt with.
7. We show how to use the C# approach to deal with the problem from
a programming point of view.
These three sections illustrate and emphasize why C# is an efficient program-
ming tool for solving academic problems. We need only to understand the prob-
lem and implement the solution using the C# approach.
EXAMPLE # 1 - Math Problem
Find the least common multiple of 3 and 20, that is, LCM(3,20).
Fl ow Char t
I nt roduct ion 15
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
A calculator
A ruler
Pre-calculus math book
Appr oach
An efficient way of approaching a problem such as this is to analyze the termi-
nology and thoroughly understand of each term. The three key terms in this
problem are least, common, and multiple. Before going into a detailed explana-
tion of each term, you have to remember that the least common multiple (LCM)
of two integers is also an integer. Therefore, our task shortly consists of finding
one number, the least common multiple. Let us look at each key term separately.
Least
Least means the smallest. Using this term leads us to think that the LCM will be
found by comparison with other numbers that will simply end up being greater.
Common
Common means a number belonging equally to two parties, which are, in this
case two sets of numbers.
Multiple
A multiple of an integer is an integer resulting from the multiplication of this
integer by another one. Thus, each of the two sets of numbers mentioned above
contains the multiples of an integer.
After this comprehensive clarification of the key terms, gathering all the previous
information helps deduce that the required number is a number common
between two sets, each one consisting of the multiples of a certain integer. More-
over, since you may find more than one number in common, the LCM happens
to be the smallest number among all the common multiples that you may find.
Sol ut i on
1. Find the first 10 multiples of 3, that is, multiply 3 by 1, 2, 3, , 10. The num-
bers you get will form the set M
3
of multiples of 3.
2. Find the first 10 multiples of 20, that is, multiply 20 by 1, 2, 3, , 10. The num-
bers you get will form the set M
20
of multiples of 20.
3. Check if there are any common numbers between the sets M
3
and M
20
.
4. If the check is positive (if you find any numbers in common) then the smallest
one is the least common multiple of 3 and 20.
I nt roduct ion 16
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
5. If the check is negative (there are no numbers in common) find the next 10
multiples of 3 and include them in M
3
.
6. Find the next 10 multiples of 20 and include them in M
20
.
7. Go to step 3.
Lessons Lear ned
After solving this problem:
I learned a simple, step-by step method of finding the least common
multiple of two integers.
I can implement this method in a computer programming algorithm.
I developed the skill of finding the least common multiple of two integers.
I can accomplish the task of finding the LCM more easily because it was
broken down into several simple steps.
I will remember this method faster because it was described verbally and
visually.
The C# Appr oach
The above mathematical problem was solved using a purely mathematical
approach. Now we will solve it using the C# approach. The following C#
program solves the above problem:
I nt roduct ion 17
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
EXAMPLE # 2 - Physics Problem
Write a program that takes as input the initial velocity (magnitude and direction)
of a projectile and returns the maximum height (H) that it will reach from its ini-
tial position and the time (t
0
) it needs to get back again to its initial height.
Note: Drag force is not considered.
Fl ow Char t
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
Dynamics physics book
Appr oach
In order to approach this problem, it is essential to understand a particular form
of two-dimensional motion called projectile motion.
Ignoring air resistance, an object thrown into the air follows a parabolic path that
originates at the point where it was thrown and ends when an external agent,
I nt roduct ion 18
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
such as the ground or a barrier, interrupts its motion. The object undergoes pro-
jectile motion when the only force field acting on it is gravity. A familiar example
of a projectile motion is a basketball shot toward a hoop.
Describing projectile motion using a two-dimensional graph, makes under-
standing easier. We assume that the body is initially placed at the origin of a 2D
frame. Once given an initial velocity, it follows the parabola shown in the figure.
Under the effect of gravity, this body accelerates downward, but no horizontal
acceleration occurs.
Knowing the initial velocity (its magnitude v
0
and its angle with the horizontal,
), the horizontal acceleration and the vertical acceleration is enough to deter-
mine the velocity components along each of the axes and the x and y coordinates
of the mobile at any instant t.
To visually aid the understanding of a game concept or idea, snapshots of the
game are integrated within the text.
Motion in a vertical direction
The acceleration in a vertical direction is equal to g (-9.8 m/s
2
). The laws of
dynamics allow us to express the vertical velocity, v
y
, and the ordinate, y, of the
mobile in function of time.
0
9 8 sin
y
v . t v o = +
2
0
4 9 sin y . t v t o = +
Motion in a horizontal direction
According to Newtons third law of dynamics, since no horizontal acceleration is
assigned to the object, this object will keep moving at the same initial horizontal
velocity (v
0x
) during the whole period of motion. The laws of Dynamics again
imply the following relations:
0
cos
x
v v o =
( )
0
cos x v t o =
I nt roduct ion 19
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
You now have all the tools you need to start solving the problem and determin-
ing the required unknowns.
As you may notice in the figure above, when the object reaches the maximum
height, the vertical component of velocity becomes zero. In other words, the
velocity becomes horizontal. This allows us to determine by what time (t
1
) this
happens. All we have to do is to solve the equation v
y
= 0.
1 0
9 8 sin 0 . t v o + =
0
1
sin
9 8
v
t
.
o
=
If you replace t
1
in y, you get H, the maximum height the projectile reaches.
( )
2 2 2
2 0 0
1 1 0 1
sin sin
H 4 9 sin 4 9
9 8 9 8
v v
y t . t v t .
. .
o o
o
| |
= = + = +
|
\ .
On the other hand, the mobile reaches its initial level again when its ordinate is
equal to zero. This is demonstrated in the figure below. To find out the time at
which y becomes equal to zero, we have to solve the equation y = 0. It is a qua-
dratic equation that has two solutions. One of them is obviously equal to zero
because it is where the motion begins and the other is given by the equation.
Algebra easily proves what we have just said:
( )
2
0 0
0
0
0
4 9 sin 0 4 9 sin 0
sin
4 9
i
t
. t v t t . t v
v
t
.
o o
o
=

+ = + =

Sol ut i on
Given the magnitude (v
0
) of the velocity and its direction by means of the angle
that it makes with the horizontal () the problem can be solved as follows.
1. Find the velocitys y-component as a function of time, which is given by
v
y
(t) = -gt + v
0
sin where g = 9.8 m/s
2
is the gravitational acceleration.
2. Solve the equation v
y
(t) = 0, that is, -gt + v
0
sin = 0. This is a linear equation
in t and its solution (t
1
) is given by:
0
1
sin v
t
g
o
=
3. Find the positions y-component as a function of time, which is given by:
y(t) = -0.5gt
2
+ v
0
sint
4. To find the maximum height, replace t
1
in y(t). In other words, H = y(t
1
).
5. To find the time that the projectile needs to get back to its initial position,
solve the quadratic equation y(t) = 0. This equation will engender two solu-
I nt roduct ion 20
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
tions such that one of them is equal to zero and the other, which is the
required one, is given by
q
0
0
2 sin v
t
g
o
=
.
What di d I acqui r e f r om t hi s ex per i ment ?
After solving this problem:
I became familiar with projectile motion, which is an important physical
phenomenon.
I learned a simple, step-by step method of finding the maximum height that
a projectile thrown with a certain initial velocity reaches.
I can know how much time this projectile takes to get back to the height at
which it was initially thrown.
I recognize how the velocity components of a projectile change with respect
to time.
I am able to determine the position of a projectile at any time.
I developed the skill of finding the maximum height of a projectile and the
time it needs to get back to its initial height.
I discovered that the time a projectile takes to reach its maximum height
from the initial height is the same time that it needs to get back from its
maximum height to the initial height.
This method can be implemented in a computer programming algorithm.
I will remember this method faster because it was described verbally
and visually.
I nt roduct ion 21
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
The C# appr oach
We solved the physics problem above by using a purely scientific approach. Now
we will solve it using the C# approach. Next is a C# program that solves the above
problem:
For now, you can take this program as is, without the need to understand every
detail of it. Our intention is to show that using a C# program is more efficient
when solving such problems. The difference between the two ways of approach-
ing the same problem is clear: in the traditional method, you have to follow
methodical steps and the process is longer. On the other hand, using C# is more
direct and takes less time to reach the same result.
I nt roduct ion 22
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
EXAMPLE # 3 - Chemistry Problem
Write a program that takes as input the number of electrons in an atom (up to
20) and returns the number of electrons it has on its peripheral electronic layer.
Fl ow Char t
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
A calculator
A ruler
General chemistry book
I nt roduct ion 23
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
Appr oach
Tackling a chemistry problem like this one requires that you first have the struc-
ture of an atom and its constituents clearly in mind.
Structure of an atom
An atom consists of a nucleus surrounded by a cloud of electrons. The nucleus of
an atom contains two types of subatomic components: protons and neutrons.
The electron cloud consists of many electrons, a type of subatomic element that
undergoes a circular motion around the nucleus. This creates the electron cloud
that surrounds the nucleus.
Constituents of an atom
Protons
Protons are positively charged components that exist in the nucleus of an atom.
Their mass is negligible with respect to that of neutrons.
Neutrons
These components coexist with the protons inside the nucleus, and as their name
reflects, they are neutral, that is, they do not carry any electric charge. Being
extremely massive with respect to other subatomic components, neutrons con-
tribute to an atoms real mass.
Electrons
Symbolized by e

, electrons carry negative electric charges. They rotate around


the nucleus to form an electron cloud that neutralizes the positive charge created
by the proton within the nucleus; therefore, they stabilize the atomic structure.
Electrons do not rotate arbitrarily around the nucleus. Instead, they are distrib-
uted into atomic layers and sub-layers. Each of the layers may contain a certain
number of electrons. The first layer has room for two electrons at most while the
others have room for eight electrons at most. Moreover, for the first 20 elements
in Mendeleevs periodic table, these layers are filled up with electrons by increas-
ing order of closeness from the nucleus; that is, the closest layer to the nucleus is
first filled up with 2 electrons, the next with eight, and so on. For instance, con-
sider the oxygen atom that has a total of 8 electrons. First, two electrons find
their place in the first layer, and the six remaining electrons in the second layer,
which happens to be the outer layer in this case. This leaves the second layer with
enough room for two more electrons, the fact that urges an atom of oxygen to
relate to other atoms and form chemical compounds called molecules.
I nt roduct ion 24
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
When you know the atomic number of an atom, it should be easy for you to dis-
tribute the electrons into the different atomic layers and subsequently find how
many of them lie on the outer (peripheral) layer.
Sol ut i on
1. Determine Z, the atomic number of the atom you wish to find the peripheral
number of electrons.
2. If Z is less than or equal to 2, then the number of peripheral electrons is Z
itself. The problem ends here. On the other hand, if Z is greater than 2, move
forward to step 3.
3. Find K = Z 2.
4. Calculate n = K%8, that is, the remainder of the division of K by 8.
5. If n is different than zero, then n is itself the number of peripheral electrons
required.
6. If n = 0, then the number of peripheral electrons is 8.
Lessons Lear ned
After solving this problem:
I learned a simple, step-by step method of finding the number of peripheral
electrons of several atoms.
I recognized the structure of an atom, its different components, and their
distribution within the structure of the atom.
I am aware that the first principal layer of any atom may contain 2 electrons
at most, while each one of the other layers may contain 8 electrons at most.
I can implement this method in a computer programming algorithm.
I developed the skill of finding the number of peripheral electrons of several
atoms.
I nt roduct ion 25
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
I can accomplish the task of finding the number of peripheral electrons
more easily because it was broken down into several simple steps.
I will remember this method faster because it was described verbally and
visually.
The C# appr oach
The above chemistry problem was solved using a purely scientific approach.
Now we will solve it using the C# approach. The following C# program solves the
above problem:
I nt roduct ion 26
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
I
QUI CK REFERENCE SUMMARY OF EXERCI SES
This table can be used as a quick reference to find the type of problems and how
many are given in each chapter. For example, if you are working with Chapter 6,
you can easily see that there are two math and two game design problems in that
chapter.
Chap
2
Chap
3
Chap
4
Chap
5
Chap
6
Chap
7
Chap
8
Chap
9
Chap
10
Chap
11
Total
Math 2 6 - - 2 1 3 - 6 1 21
Physics 3 1 2 3 3 4 - - 2 - 18
Chemistry 2 2 2 2 1 3 3 2 - - 17
English - - 1 - - - - - - - 1
Computer
Science
1 - - - - - - - - 1 2
Game Design - - - 1 2 - - - - - 3
Social
Sciences
- - - - - - - - - 1 1
Total 8 9 5 6 8 8 6 2 8 3
1
COMPUTER GRAPHI CS:
BASI C CONCEPTS
Comput er Graphics: Basic Concept s 28
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
COMPUTER GRAPHI CS: BASI C CONCEPTS
This chapter covers the basic concepts related to the world of computer graphics.
It contains four main parts: game concept, computer hardware, binary concept,
and application programs. As an introduction, you are going to discover the
characteristics and elements of games. No one can fully understand game pro-
gramming without basic knowledge of computer hardware and how each part
functions. Computers are made of electronic circuitries and have their own digi-
tal presentation for numbers. Any programmer must understand binary num-
bers (and the conversions between binary and decimal) and logic gates.
1.1 REAL- TI ME I NTERACTI VE SI MULATI ON ( RTI S)
1.1.1 Mot i on Pi ct ur es
Movies are also known as motion pictures. When you go to a movie, what you
actually see is a linear sequence of static images. What does that mean? Linear
sequence means in a straight line, and static images means images that are not
moving. Therefore, a motion picture is actually a set of non-moving pictures.
However, the brain is tricked into thinking that they are moving because each
image is slightly different from the previous one and the images are flashed onto
the eye so fast that they are interpreted as motion.
Modern motion pictures move at a constant speed of 24 frames per second. This
means that during the course of one second, 24 static pictures flash in sequence
in front of your eyes. That means it takes almost 1.5 feet of film for each second
of a movie that you watch. This means that the reels of film are usually very large.
Look at the stick figure below to see how a kick would look as a series of static
frames:

The above image is twelve frames divided into two sets of six frames each. That
would be about half a second of a movie since a movie uses 24 frames per sec-
ond. At this speed, the eye does not perceive each individual image, instead, it
paints a moving image on the brain. The same rules apply in video games. We
use single frames to act as each static image of a character in a game; we connect
a sequence of them together to create motion. In games, we refer to the motion
described as animation.
1.1.2 Mot i on Pi ct ur es Ver sus Games
Games are also composed of pictures that are displayed sequentially. However,
the images used in games to create the illusion of motion cannot be taken in
advance. Why can the pictures not be taken in advance? Each player plays the
Comput er Graphics: Basic Concept s 29
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
game differently. For example, player A might start moving toward the left while
player B might start moving toward the right. Consequently, each time some-
body plays the game, different scenarios will take place. With this fact, we can
conclude that the images used to create the motion effect in a game have to be
constructed while playing the game in order to reflect the players decision.
Movies display 24 images per second while games usually display 60 images per
second. This means that we have to construct and display 60 separate images per
second. A game is a Real-Time Interactive Simulation application. Each word is
explained below.
1.1.3 Real Ti me
The application (or game) must react according to the players input. For exam-
ple, if the player presses the right arrow key to move right, then the application
will instantly respond by moving the character to the right. Real-time applica-
tions require real-time mathematical computations in order to calculate the data
needed to reflect the players input. Real time is also used to react to events other
than the users input. For example, when a ball touches the ground, using the law
of cosine and vectors, we compute the new direction in real time.
1.1.4 I nt er act i v e
The game is interactive by definition, since it allows the player to interact with
the application by using input devices such as keyboard, mouse, or joystick.
1.1.5 Si mul at i on
By definition, a game is an interactive environment that imitates a physical pro-
cess through a program that causes a computer to respond mathematically to
data and changing conditions. The game uses the science of mathematics and
physics to calculate the simulated object data. Then it uses the science of pro-
gramming languages and computer hardware to implement or visualize the data
acquired by the previous step.
1. 2 GAME ELEMENTS
Images or objects controlled by instructions make games.
1.2.1 I mages
Images represent the game background and game objects. The game objects are
displayed or placed on top of the background. Game objects are composed of
images, which are rectangular bitmaps. How can we display a ball (game object)
that has a circular shape? We use the concept of transparency. If you look closely
at the set of frames found in the motion pictures section, you will notice that the
object is surrounded by green pixels. When we display the game objects (also
known as the sprites), we draw all the picture elements (pixels) except the green
ones. The green pixels have been assigned a transparency property.
Comput er Graphics: Basic Concept s 30
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Ex ampl e:
The balls image is surrounded by green pixels used as the trans-
parency color. When the game is running, the green background
is not displayed, resulting in round image (the ball.)
A rectangular background
image represents the game
background, and the game
object, which is the ball, is
represented by a different
rectangular image.
This game screenshot rep-
resents a ball bouncing.
However, it is actually
composed of two objects:
the game background and
the game object.
1.2.2 I nst r uct i ons
The instructions specify the actions that we need to apply to the background or
the sprites. For example, an instruction to change the map position along the y-
axis will scroll the map. Similarly, an instruction that reads the keyboard input
will allow us to specify the sprite interactivity.
1.2.3 Game Loop
The looping concept helps to implement the simulation. A loop is defined as a
sequence of instructions that repeats a specified number of times. Since a games
frame rate is usually 60 frames per second, we have to loop 60 times per second.
In other words, each game loop can have up to 1/60 (16.66 ms) second to com-
plete. The game is divided into two parts: handling and displaying.
Handling
The handling part reads the input, finds the collision status between the sprites,
finds the new position of all the sprites, and executing the sprite behavior. It then
constructs the final picture.
Displaying
The displaying part draws the images constructed in the handling section. Since
the game displays 60 frames per second, we need to handle and display the game
objects 60 times a second, or each 16.66 ms.
Comput er Graphics: Basic Concept s 31
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Ex ampl e:
To show a ball moving over a background, we first calculate the new position of
the ball, then display the ball at its new position. One game loop makes the cal-
culations and displays the game objects in their new positions. By repeating the
game loop 60 times per second, the ball appears to be moving.
At game loop n, we have a ball on a background positioned P(x,y) where x=100,
and y=300.
The handling of the ball consists of calculating the new position based on a vec-
tor V(3,0). Vector V means that the balls position is incremented by 3 along the
x-axis and by 0 along the y-axis.
At game loop n+1, the balls position is P(103,300)
At game loop n+2, the balls position is P(106,300)
At game loop n+3, the balls position is P(109,300)
At game loop n+4, the balls position is P(112,300)
At game loop n+5, the balls position is P(115,300)
And so forth.
At the beginning of each game loop, the display screen is deleted. Then the back-
ground is displayed; then the ball is displayed according to its new position on
top of the background.
Game Loop n
P( 100,300)
Game Loop
n+ 1
Game Loop
n+ 2
Game Loop
n+ 3
Comput er Graphics: Basic Concept s 32
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
If we do not delete the display screen we will get the following:
These steps are repeated at every game loop 60 times per second.
Maintaining the frame rate
What happens if the handling and displaying need more than 16.66 ms to be
completed? The game frame rate will drop since we can no longer construct and
display 60 images per second. What would happen if the handling and displaying
need less than 16.66 ms to be completed? In this case, more images will be dis-
played. When more images than expected are displayed in one second, the ani-
Comput er Graphics: Basic Concept s 33
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
mation or the images in motion will appear to be animated faster. For example, a
car traveling at a speed of 100 miles per second will travel farther than it should.
1.3 COMPUTERS
1.3.1 Hi st or y of Comput er s
In the 19
th
century, the British mathematician Charles Babbage designed the first
true analytical machine based on principles similar to those used in modern dig-
ital computers. However, he never got this analytical engine working properly,
because technology in those days could not produce the high precision parts that
were needed.
The First Generation (1945-1955) Vacuum Tubes and Plug boards
Until the mid-1940s, little progress was made in constructing digital computers.
Around that time, several people in the United States and Europe all succeeded
in building calculating engines. The first ones used mechanical relays with cycle
times measured in seconds, but they were very slow. Later, vacuum tubes
replaced relays. These large machines filled up whole rooms with thousands of
vacuum tubes. Even so, the cheapest computer available today is millions of
times faster than those large machines used to be.
Those days, a single group of people designed, built, programmed, operated, and
maintained each machine. This was often done by wiring up plug boards (a
board where users plug cables into sockets) to control the machines basic func-
tioning. Since programming languages and even assembly language was
unknown, all programming was done in machine language. Very nearly all prob-
lems were straightforward calculations, such as tables of sines, cosines, and loga-
rithms.
With the introduction of punched cards by the early 1950s, the routine
improved. It was now possible to write programs on cards and read them in
instead of using plug boards.
The Second Generation (1955-1965) Transistors and Batch Systems
In the mid-1950s, the picture changed significantly when transistors were intro-
duced. Computers had become very reliable and could be sold to customers who
banked on getting some useful work done with their help. For the first time, the
difference between people who designed, built, and operated computers was
clear. These machines, called mainframes, were hidden away in climate-con-
trolled rooms with qualified staff to run them. Mainframes though were very
expensive, and only large companies, government agencies, and universities
could afford them. To do a job, the programmer first wrote the program on
paper (using assembler or FORTRAN), and then punched it on cards. The deck
was sent to the input room and given to the operator. When the output was
ready, the operator tore it off and took it to the output room for the programmer
to collect. Later, the programmer took one of the card decks and read it in. Much
time was wasted while operators walked around the machine room.
Comput er Graphics: Basic Concept s 34
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
In an effort to cut down on wasted time, the batch system was introduced where
a tray full of jobs was collected in the input room and then read onto a magnetic
tape using a small computer, such as the IBM 1401. After a while of collecting a
batch of jobs, the operator rewound the tape and took it to the machine room to
be mounted on a tape drive. Next, the operator loaded a special program (the
precursor of todays operating system) that read the first job from the tape and
ran it. Instead of being printed, the output was written on a second tape. After
each job, the operating system automatically read the next job and started run-
ning it. When the entire batch had finished, the operator removed the input and
output tapes. The input tape was replaced with a new batch while the output tape
was then taken to a 1401 for printing. These large second-generation computers
were used for scientific and engineering calculations.
The Third Generation (1965-1980) ICs and Multiprogramming
By the 1960s, there were two vastly different product lines on the market. On one
hand there were word-oriented, large-scale scientific computers that were used
for numerical calculations in science and engineering. On the other hand, there
were character-oriented, commercial computers that were used for tape sorting
and printing, mainly by insurance companies and banks. Due to the immense
cost involved needed to develop and maintain two totally different product lines,
IBM decided to introduce the System/360, which solved these problems. This
series of software-compatible machines only differed in price and performance,
and could handle both scientific and commercial computing. In addition, the
360 series used Integrated Circuits, (ICs) which provided a huge price/perfor-
mance advantage over second-generation machines. These days, successors of
these machines are used to handle huge databases, or as servers for Internet web-
sites, where thousands of requests must be processed in seconds.
An important key technique in third-generation computers was multiprogram-
ming, where memory was partitioned into several pieces with a different job in
each partition. Another feature present in third-generation computers was the
ability to read jobs from cards on the disk as soon as they were brought to the
computer room. This is called spooling. A variant of multiprogramming is time-
sharing, in which each user has an online terminal. For example, if 10 people are
logged in but only 3 of them are actively working, the CPU can be allocated, in
turn, to the three jobs that want service.
The Fourth Generation (1980-Present) Personal Computers
The age of the personal computer dawned with the development of LSI (Large
Scale Integration) circuits, chips that contain thousands of transistors on a
square inch of silicon. It was now possible for single individuals to have their
own personal computers. In the early 1980s, IBM designed the IBM PC. DOS
(Disk Operating System) was used. Later, Bill Gates sold IBM a revised version of
DOS called MS-DOS (Microsoft Disk Operating System), and they quickly dom-
inated the IBM PC market. Even though the initial version of MS-DOS was
primitive, later versions included more advanced features. Other operating sys-
tems (including MS-DOS) for early microcomputers all relied on users typing in
commands through the keyboard, but when Doug Engelbart invented the GUI
Comput er Graphics: Basic Concept s 35
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
(Graphical User Interface) all that changed. A GUI is an environment that repre-
sents programs, files, and options by means of icons, menus, windows, and dia-
log boxes on the screen. MS-DOS successor, a GUI-based system called
Windows, originally ran on top of MS-DOS and was more of a shell than a true
operating system. After about 10 years, Microsoft released a freestanding version
called Windows 95. Subsequently, the company released Windows 98; both con-
tain a large amount of 16-bit Intel assembly language. Another Microsoft oper-
ating system, Windows NT, is a full 32-bit system. After several versions of NT,
version 5 was renamed Windows 2000 in early 1999. Other versions have been
released since then. Another major player in the personal computer world is
UNIX, which is strongest on workstations and network servers.
A recent development has been networks of personal computers running on net-
work operating systems and distributed operating systems. In a network operat-
ing system, users can log in to remote machines and copy files from one
computer to another. Network operating systems are not vastly different from
single-processor operating systems. A distributed operating system, however,
seems like a traditional uniprocessor system but is actually composed of multiple
processors.
1.3.2 Dumb Machi nes
Computers need to be instructed to perform tasks. In addition, computers do
not think. On the other hand, computers are fast, accurate, and reliable. For
example, they can perform accurately 1,000 divisions per second.
Ex ampl e:
Instructing a computer to alert the user every five hours exactly, the com-
puter is very reliable even over a long period of time.
Compare the time required to compute Factorial 1000000 by hand and by
using a computer. It takes a long time to get the result by hand while using a
computer, it only takes few seconds.
Divide 3937188242534.972575 by 4257896.245 multiply the result by
7845521 then subtract it from 96321457447. The computers results are fast
and accurate.
Computers are machines that execute predefined instructions to perform tasks
such as numerical computations very rapidly. A sequence of instructions created
for a specific purpose is called a program. Computers have a vocabulary of
instructions that they know how to execute. Programmers create programs, but
it is difficult to work with the vocabulary of computers, so different vocabularies
that are easier to use have been invented. These are called programming lan-
guages, and C# is one of these programming languages. Special programs have
been created to translate a particular programming language into a particular
computer vocabulary. The physical equipment that makes up a computer is
called hardware, and programs that run on the hardware are called software.
Comput er Graphics: Basic Concept s 36
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
1.3.3 Anal og Ver sus Di gi t al
While in real life information is analog, in computers information is digital.
Since computers are made from electronic circuitries, only two states can be
formed: current is present or current is not present. The presence of current is
translated to 1, and the absence of current is translated to 0. For example, the
analog information of value 3 becomes 11 in digital presentation. Binary system
numbers, or numbers in base 2, are perfect for computers to understand since
they only have two states.
Analog input and output take on a continuous range of values. Analog values
represent quantities of the real world such as sound and temperature.
Digital systems represent input and output with discrete values. The number of
possible digital output values for any digital device is finite. The advantage of
digital systems is their inherent ability to deal with electrical signals that have
been degraded by transmission through circuits. Consequently, digital logic is
used for algorithm control and data manipulation.
The following figure shows the difference between analog and digital systems, a
typical output waveform. The x-axis is time, and the y-axis is the measured volt-
age.
Ex ampl e: Modems
Modems are used to interchange data between two computers over telephone
lines.
Comput er Graphics: Basic Concept s 37
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
The modem is connected to the computer and to the telephone line. The
modem converts the digital computer data to analog data in order to send it
through the telephone line.
Your ISP (Internet Service Provider) will use the modem to reverse the con-
version from analog (telephone line) to digital (the computer).
The two computers will interchange the data through telephone lines using
the modems.
Ex ampl e: Recording
Tape recording will save the analog waves onto tapes.
Digital recording will convert the voice from analog waves to digital data (to
numbers 0 and 1s).
Over time, the tape will lose its quality while digital recording will always
have the same quality because the 0s and 1s stay unchanged.
1.3.4 Gener al - Pur pose Comput er s
General-purpose computers are reprogrammed and used for various jobs:
Businesses
Airline agencies
Banks
Hotels
Homes, etc.
1.3.5 Dedi cat ed Comput er s
Dedicated computers perform specific tasks:
Cars
Microwave ovens
Toys
Phones
Cameras, etc.
1.3.6 Comput er Or gani zat i on/ Gr aphi cs Sy st em
The figure below shows a graphic system:
Comput er Graphics: Basic Concept s 38
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Central Processing Unit
CPU stands for central processing unit. In desktop computers, CPU refers to the
primary microchip, which performs the computations and is the main control of
the computers functionality. It is also called the microprocessor. Most desktop
computers running Microsoft Windows use a Pentium microprocessor made by
Intel. The microprocessor contains, among other things, some special memory
units called registers, which are used to temporarily store data for computations.
The CPU is the control and arithmetic logical unit.
To complete the process of a logical or arithmetical operation, the CPU uses the:
Bus unit (this includes includes the data bus, address bus, and control bus)
in order to link to the other components.
Instruction unit to carry instructions from the memory to the instruction
unit.
Execution unit to control the execution unit.
Addressing unit used to access the instruction for execution. How does it do
this? The CPU reads instructions (adding numbers, moving, inputting, and out-
putting data) from the program memory via the data bus. This part of the mem-
ory is given an address that is calculated by the processor using the ALU. Once
the data manipulations are complete, the results are transferred to the output of
the computer.
Memory
The program memory tells the CPU what to do and stores the instructions list
(program). In addition, the instructions list manipulates information called data.
The area where a computer machine stores its data is called a memory. A com-
puter machine memory is an array of consecutively numbered (or addressed)
memory cells holding a bit value. Every byte in a machine memory has a unique
number or address.
For example, if we have a memory with a size of 8 bytes, memory address 0 will
point to the first byte, memory address 1 will point to the second byte, and mem-
ory address 7 will point to the last byte, byte number 8. This is how the empty
memory looks:

Addr essCont ent
000000000( 8 bit s)
100000000( 8 bit s)
200000000( 8 bit s)
300000000( 8 bit s)
400000000( 8 bit s)
500000000( 8 bit s)
600000000( 8 bit s)
700000000( 8 bit s)

Below is how the memory will look after we store value 7 in address 1, value 3 in
Comput er Graphics: Basic Concept s 39
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
address 2, value 8 in address 5 and value 255 in address 6.
Addr essCont ent
000000000( 8 bit s)
100000111( 8 bit s)
200000011( 8 bit s)
300001000( 8 bit s)
400000000( 8 bit s)
500001000( 8 bit s)
611111111( 8 bit s)
700000000( 8 bit s)
Frame buffer
A picture is produced as an array of picture elements, called pixels. The pixels are
stored in a part of memory called the frame buffer. Consequently, the number of
pixels in the frame buffer determines the details of the image. In addition, the
depth of the frame buffer determines the number of colors that can be repre-
sented on the system. For example, a depth of one bit only allows two colors. A
depth of eight bits allows 2
8
= 256 colors.
1.3.6.1 Out put Devi ces
Cathode-ray tube
What is a cathode-ray tube (CRT)? A cathode-ray tube is the basis of the com-
puters display screen. A CRT display is built around a vacuum tube containing
one or more electron guns whose electron beams sweep horizontally across the
inside of the front surface of the tube, which is coated with a phosphor that glows
when irradiated. Electrons strike the phosphor coating on the tube. Then light is
emitted for a short period of time. The direction of the beam is controlled by two
pairs of deflection plates (x and y). The output of the computer is converted by a
digital-to-analog converter. In other words, the output of the computer is con-
verted to voltages across the x and y deflection plates. The beam can move along
the x and y directions. However, the intensity of the beam can be turned off, and
it is turned off during the H-blank and the V-blank. The H-blank is needed to
raster the next row, and the V-blank is needed between the last pixel of the last
row and the first pixel of the first row. In order to see a steady image, the same
path must be refreshed by the beam at least 50 times a second. Colored CRTs
have three different colored phosphors: red, green, and blue. Consequently, there
are three electron beams.
Liquid-crystal display (LCD)
This type of display uses a liquid compound having a polar molecular structure,
placed in between two transparent electrodes. An LCD screen does not emit
light of its own. An electric field causes the molecules to line up in a way that
alerts their optical properties. Unfortunately, many LCDs are difficult to read in
sunlight or other strong light. Many portable computers now use backlit LCDs,
which are brighter and easier to read.
Comput er Graphics: Basic Concept s 40
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Printers
Printers take information from the CPU and transfer it to paper (called hard
copy). There are different types of printers available.
Dot Matrix Printers
Dot Matrix printers are inexpensive and reliable, but they are
noisy and slow.
The printer head is made up of pins which push out to give
different patterns.
A 9-pin printer produces poorer quality printouts compared to a
24-pin printer.
Inkjet Printers
Inkjet printers work like dot matrix printers in that the print out is made up
of dots.
The printer head has many tiny holes in it through which ink is forced out
onto the paper.
Inkjet printers are much quieter than dot matrix printers, and because the
holes can be very tiny, they can produce images and text of much higher
quality.
Laser Printers
Laser printers produce very high quality print outs and can do
so very quickly.
They are often faster than inkjet printers, though are more expensive and
the toner cartridge costs more than the ink cartridges for inkjet printers.
Laser printers are useful for volume printing because of their speed.
Laser printers use a combination of laser and copying technology to make
very clear copies.
1.3.6.2 I nput Devi ces
Keyboard
The keyboard is a device that returns character codes, like the American Stan-
dard Code for Information Interchange (ASCII). Since computers can only
understand binary numbers, the character set is represented by numbers. For
example, the number 65 in base 1, which is 01000001 in binary, represents the
uppercase character A. The ASCII character code tables contain the decimal val-
ues of the extended ASCII (American Standards Committee for Information
Interchange) character set. The extended character set includes the ASCII char-
acter set and 128 other characters for graphics and line drawing, often called the
IBM

character set.
Mouse
A mouse has a small ball underneath it and is attached with a cord to the system
unit. When rolled on the table top, the mouse directs the location of the cursor
or pointer on the computer screen. The pointer can be used to draw pictures or
point to a particular instruction. Selection buttons on the mouse are used to
issue commands. Sometimes no flat surface is available and in such cases, a
Comput er Graphics: Basic Concept s 41
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
mouse-like device with a ball is attached to the side of the computer. The device
stays in one place, but the user can operate the ball with his or her thumb to
guide the cursor.
Touch screen
A touch screen is a particular kind of monitor covered with a plastic layer.
Behind this layer are crisscrossed invisible beams of infrared light. This arrange-
ment enables users to select actions or commands by touching the screen with a
finger. Touch screens are easy to use, especially when people need information
quickly. You are likely to see touch screen input devices used in airports, hotels,
banks, and in applications that do not use a mouse.
1.3.7 Oper at i ng Sy st em
An operating system is a program that acts as an intermediary between com-
puter users and computer hardware. The purpose of an operating system is to
provide an environment in which users can execute programs. The primary goal
of an operating system is to make the computer system convenient and easy to
use. A second goal is to use the computer hardware in an efficient manner.
An operating system is an important part of almost every computer system. A
computer system can be divided into four components: The hardware, the oper-
ating system, the application programs, and the users.
Comput er Graphics: Basic Concept s 42
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Hardware, software, and data constitute the components of a computer system.
The operating system provides the means for the proper use of these resources in
the operation of the computer system. The operating system performs no useful
function by itself. It simply provides an environment within which other pro-
grams can do useful work.
1.4 NUMBERS
1.4.1 I nt r oduct i on
What is the difference between a digit and a value? A digit is a character between
0 and 9 while a number has a value.
What is a base of a number? The base of the number specifies the set size of dig-
its of the numbering system. There are four numbering systems in computing:
hexadecimal, decimal, octal, and binary.
Ex ampl e: Decimal numbers (base 10) digits set is 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
The base of a number is written as a subscript on the right of the number. Exam-
ple: value 10 is written:
10
16
in base 16 (Hexadecimal)
10
10
in base 10 (Decimal)
10
8
in base 8 (Octal)
10
2
in base 2 (Binary)
Information representation in computers uses two numbers (0 and 1). Real-life
information is analog, while computer information is digital. Since computers
are made from electronic circuitries, only two states can be formed: current is
present or current is not present. The presence of current translates to 1, and the
absence of current translates to 0. For example, the analog information of value 3
becomes 11 in digital presentation. Consequently, binary system numbers, or
numbers in base 2, are perfect for computers to understand since they only have
two states.
A bit is the smallest memory element holding a binary value (0 or 1), and a set of
8 bits is called a byte.
Ex ampl es:
A bit is either 0 or 1:
Bit
0
1
Comput er Graphics: Basic Concept s 43
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Combining two bits:
Bit1 Bit2 Value
0 0 0
0 1 1
1 0 2
1 1 3
Combining three bits:
Bit1 Bit2 Bit3 Value
0 0 0 0
0 0 1 1
0 1 0 2
0 1 1 3
1 0 0 4
1 0 1 5
1 1 0 6
1 1 1 7
When combining 8 bits (1 byte), you can represent 256 values ranging from 0 to
255:
00000000 = 0
00000001 = 1
00000010 = 2
00000011 = 3
. . .
11111110 = 254
11111111 = 255
1.4.2 Bi nar y
1.4.2.1 I nt r oduct i on
The CPU consists of transistors that switch digitally between the on and off
conditions. This leads to a binary, or a two-value representation, of the informa-
tion. A binary digit is one of the characters 0 or 1.
Most humans use base 10 numbers. Computers use base 2 numbers. Conse-
quently, we need to understand how to convert from base 10 to base 2 and from
Comput er Graphics: Basic Concept s 44
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
base 2 to base 10. The natural input needs to be converted to binary in order to
be executed, and the output of the execution needs to be converted to decimal in
order to be understood. In addition, we need to learn how to convert from hexa-
decimal and vice versa since reading and stating hexadecimal values is easier
than binary numbers. For example, 255 is FF in hexadecimal and 11111111 in
binary.
Binary digital systems form the basis of just about all hardware systems in exist-
ence today where the 0 bit is represented by a low voltage, and the 1 bit is rep-
resented by a high voltage. A binary number is therefore a sequence of 0 bit and 1
bit. For example, 111 represents the number 7. A set of 8 bits or one byte can rep-
resent 256 numbers from 0 to 255.
1.4.2.2 Bi nar y Number s Oper at i on
1.4.2.2.1 Bi nar y Addi t i on
In the binary number system, we have the following additional table:
Bit 1 Bit 2 Sum Carry
0 0 0
0 1 1
1 0 1
1 1 0 1
Example: (5) 101
2
+ (3) 11
2
= 0111
2
(the step-by-step process is shown below):
1 0 1 5
+ 0 1 1 3
1 1 1 Carry
1 0 0 0 Result
1.4.2.2.2 Bi nar y Subt r act i on
The following subtraction table summarizes the strategy of subtraction numbers
in a binary system:
Bit 1 Bit 2 Sub Borrow
0 0 0
0 1 1 1
1 0 1
1 1 0
Comput er Graphics: Basic Concept s 45
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Ex ampl e: Using this table, we can subtract (52) 110100
2
from (95)
1011111
2
to get 0101011
2
(43).
1 0 1 1 1 1 1 95
- 0 1 1 0 1 0 0 52
1 Borrow
0 1 0 1 0 1 1 Result
1.4.2.2.3 Bi nar y Mul t i pl i cat i on
Multiplication in the binary number system is very simple. The following table
summarizes the strategy of multiplication numbers in a binary system:
Bit 1 Bit 2 Multiplication
0 0 0
0 1 0
1 0 0
1 1 1
Ex ampl e: Multiply (7) 111
2
with (3) 11
2
to get 10101
2
(21).
1 1 1 7
* 0 1 1 3
1 1 1
+ 1 1 1
1 0 1 0 1 Result
1.4.2.2.4 Bi nar y Di v i si on
Binary division is also similar to decimal division, and the division by zero is
meaningless. There are two cases.
Bit 1 Bit 2 Division
0 1 0
1 1 1
Comput er Graphics: Basic Concept s 46
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Ex ampl e:
1 0 1)1)1)0)0)1) 101
1 0 1 100101
0 0 0 1
0 0 0
1 1
0 0
1 1 0
1 0 1
0 0 1 0
0 0 0
1 0 1
1 0 1
0
1.4.2.3 Si gned Bi nar y Number s
We use 2s complement notation when signed numbers are required. A byte is
formed from 8 bits. Bits are numbered from 0 to 7:
Bit 0 is the least significant bit (LSB).
Bit 7 is the most significant bit (MSB).
Bit 0 would be the 1s place.
Bit 1 would be the 2s place.
Bit 2 would be the 4s place.
Bit 3 would be the 8s place.
Bit 4 would be the 16s place.
Bit 5 would be the 32s place.
Bit 6 would be the 64s place.
Bit 7 would be the 128s place.
Bit 7 is the sign bit.
The sign bit identifies whether the number is positive or negative. A 0 in the sign
bit position means the number is positive, and a 1 in the sign bit position means
the number is negative. Since bit 7 is used for the sign, 7 bits from 0 to 6 are left
to represent numbers. Consequently, 128 = 2
7
values could be represented when
using 7 bits. The set of positive numbers ranges from 0 to 127 and the set of neg-
ative numbers ranges from 1 to -128. If the sign bit is negative, the register
would hold the 2s complement form of that number.
For example,
-1 in 2s complement form is 11111111.
-128 in 2s complement form is 10000000.
We can also convert negative numbers to 2s complement form. How do we do
this?
Invert all the bits, then
Add 1.
Comput er Graphics: Basic Concept s 47
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Ex ampl e: 127
10
= 01111111
2

Invert all bits: 10000000
2
Add 1: 10000001
2
= (-127
10
)
Why does inverting and adding 1 work? Inverting and adding one might sound
like a strange thing to do, but it is actually just a mathematical shortcut of a
rather straightforward computation: borrowing and subtracting.
Borrowing and Subtracting
Remember the old trick we learned in first grade of borrowing ones from
future tens places to perform a subtraction? As an example, we will subtract
58,358 from 93,702:

93702
- 58358

What is the answer to this computation? We will start at the least significant
digit, and subtract term by term. We cannot subtract 8 from 2, so we will borrow
a digit from the next most significant place (the tens place) to make it 12 minus
8. 12 minus 8 is 4, and we note a 1 digit above the tens column to signify that we
must remember to subtract by one on the next iteration.
1
93702
- 58358
35344
So 58,358 from 93,702 is 35,344.
Borrowing and Its Relevance to the Negative of a Number
When we want to find the negative of a number, we take the number and sub-
tract it from zero. Now, suppose we act like a computer, and instead of simply
writing a negative sign in front of a number A when we subtract A from 0, we
actually go through the steps of subtracting A from 0.
Take the following idiotic computation of 0 minus 3:
0000
- 3
10
0000
- 3
7
110
0000
- 3
97
1110
0000
- 3
997
1111
00000
0-
30
99970
We will end up with a number composed of a 7 in the one's digit and a 9 in every
digit more significant than the 10's place.
Comput er Graphics: Basic Concept s 48
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
The Same in Binary
We can do more or less the same thing in binary. In this example, we use 8 bit
binary numbers, but the principle is the same for both 8 bit binary numbers
(chars) and 32 bit binary numbers (ints). We take the number 75 (in 8 bit binary
that is 01001011
2
) and subtract that from zero.
Sometimes we are in the position where we are subtracting 1 from zero, and also
subtracting another borrowed 1 against it.
00000000
- 01001011
1
00000000
- 01001011
1
11
00000000
- 01001011
01
111
00000000
- 01001011
101
1111
00000000
- 01001011
0101
11111
00000000
- 01001011
10101
111111
00000000
- 01001011
110101
1111111
00000000
- 01001011
0110101
11111111
00000000
- 01001011
10110101
If we wanted we could go further, but there would be no point. Inside of a com-
puter, the result of this computation would be assigned to an eight bit variable, so
any bits beyond the eighth would be discarded.
With the fact that we will simply disregard any extra digits in mind, what differ-
ence would it make to the end result to have subtracted 01001011 from
100000000 (a one bit followed by 8 zero bits) rather than 0? There is none. If we
do that, we end up with the same result:
11111111
100000000
- 01001011
010110101
To find the negative of an n-bit number in a computer, subtract the number from
0 or subtract it from 2
n
. In binary, this power of two will be a one bit followed by
n zero bits. In the case of 8-bit numbers, it will work just as well if we subtract
our number from (1 + 11111111) rather than 100000000.
1
+ 11111111
- 01001011
In binary, when we subtract a number A from a number of all 1 bits, what we are
doing is inverting the bits of A. So the subtraction operation is the equivalent of
inverting the bits of the number. Then we add one.
To the computer, taking the negative of a number (subtracting a number from 0)
is the same as inverting the bits and adding one, which is where the trick comes
from.
Comput er Graphics: Basic Concept s 49
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Binary Values for Signed 8-Bit Integers
BitsValue
0 1 1 1 1 1 1 1 127
0 1 1 1 1 1 1 0 126
0 1 1 1 1 1 0 1 125
0 1 1 1 1 1 0 0 124
: :
0 0 0 0 0 0 1 0 2
0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 - 1
1 1 1 1 1 1 1 0 - 2
1 1 1 1 1 1 0 1 - 3
1 1 1 1 1 1 0 0 - 4
: :
1 0 0 0 0 0 1 0 - 126
1 0 0 0 0 0 0 1 - 127
1 0 0 0 0 0 0 0 - 128
1.4.2.4 Conver t i ng f r om Bi nar y t o Deci mal
The position of a digit in a binary number determines its value. Starting from
right to left, the decimal value of the first digit is 2
0
times the digit value; the
value of the second digit is 2
1
times the digit value; the value of the third digit is
2
2
times the digit value; and the value of the n
th
digit is 2
n-1
times the digit value.
In order to convert a binary number to decimal, the values of all the operations
must be added.
Ex ampl e: Converting 111
2
111
2
= (2
2
*1) + (2
1
*1) + (2
0
*1) = 4+2+1=7
10
Ex ampl e: Converting 1001
2
1001
2
= (2
3
*1) + (2
2
*0) + (2
1
*0) + (2
0
*1) = 8+0+0+1 = 9
10
Ex ampl e: Converting 1010
2
1010
2
= (2
3
*1) + (2
2
*0) + (2
1
*1) + (2
0
*0) = 8+0+2+0 = 10
10
1.4.2.5 Conver t i ng f r om Deci mal t o Bi nar y
Decimal numbers have 10 digits, and binary numbers have 2 digits. The number
must be converted from 10-digits to 2-digit representation. How?
Divide the decimal number by two.
Save the remainder.
If the result of the division is divisible by two, repeat the process.
Comput er Graphics: Basic Concept s 50
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
The binary number is formed by writing the remainders of all the divisions start-
ing from the last.
Ex ampl e: Converting 7
10
7/2 = 3 Remainder = 1
3/2 = 1 Remainder = 1
1/2 = 0 Remainder = 1(last remainder)
Decimal 7
10
= 111
2
binary
Ex ampl e: Converting 9
10
9/2 = 4 Remainder = 1
4/2 = 2 Remainder = 0
2/2 = 1 Remainder = 0
1/2 = 0 Remainder = 1(last remainder)
Decimal 9
10
= 1001
2
binary
Ex ampl e: Converting 10
10
10/2 = 5 Remainder = 0
5/2 = 2 Remainder = 1
2/2 = 1 Remainder = 0
1/2 = 0 Remainder = 1(last remainder)
Decimal 10
10
= 1010
2
binary
1.4.3 Oct al
1.4.3.1 I nt r oduct i on
The octal numbering system can only use the following 8 digits: 0, 1, 2, 3, 4, 5, 6,
and 7. Operations on octal numbers are the same as operations on decimal num-
bers, excluding the digits 8 and 9.
The first 10 octal numbers starting from 0 are:
0
8
, 1
8
, 2
8
, 3
8
, 4
8
, 5
8
, 6
8
, 7
8
, 10
8
, and 11
8
.
5
8
+ 5
8
= 12
8
1.4.3.2 Conver t i ng f r om Oct al t o Deci mal
The position of a digit in an octal number determines its value. Starting from
right to left, the decimal value of the first digit is 8
0
times the digit value; the
value of the second digit is 8
1
times the digit value; the value of the third digit is
8
2
times the digit value; and the value of the n
th
digit is 8
n-1
times the digit value.
In order to convert an octal number to decimal, the values of all the operations
must be added.
Ex ampl e: Converting 7
8
7
8
= (8
0
*7) = 7 = 7
10
Comput er Graphics: Basic Concept s 51
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Ex ampl e: Converting 10
8
10
8
= (8
1
*1) + (8
0
*0) = 8+0=8
10
Ex ampl e: Converting 234
8
234
8
= (8
2
*2) + (8
1
*3) + (8
0
*4) = 128+24+4=156
10
1.4.3.3 Conver t i ng f r om Deci mal t o Oct al
Octal numbers have 10 digits, while binary numbers have 2 digits. The number
must be converted from 8 digits to 2 digits representation. How?
Divide the decimal number by eight.
Save the remainder.
If the result of the division is divisible by eight, repeat the process.
The binary number is formed by writing the remainders of all the divisions start-
ing from the last.
Ex ampl e: Converting 7
10
.
7/8 = 0 Remainder = 7(last remainder)
Decimal 7
10
= 7
8
octal
Ex ampl e: Converting 8
10
8/8 = 1 Remainder = 0
1/8 = 0 Remainder = 1(last remainder)
Decimal 8
10
= 10
8
octal
Ex ampl e: Converting 156
10
156/8 = 19 Remainder = 4
19/8 = 2 Remainder = 3
2/8 = 0 Remainder = 2(last remainder)
Decimal 156
10
= 234
8
octal
1.4.4 Hex adeci mal
1.4.4.1 I nt r oduct i on
When dealing with large numbers, representing numbers using 0s and 1s is not
easy. A combination of 4 bits is called a nibble. With 4 bits, it is possible to have
16 unique digits. In addition to the normal digits 0 to 9, we add an additional six
hexadecimal digits 10 to 15. The letters A(10) to F(15) are used.
Hexadecimal numbers consist of 16 digits:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.
Comput er Graphics: Basic Concept s 52
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Operations on hexadecimal numbers is the same as operations on decimal num-
bers, but including the A, B, C, D, E, and F digits. The first 20 hexadecimal num-
bers starting from 0 are:
0
16
, 1
16
, 2
16
, 3
16
, 4
16
, 5
16
, 6
16
, 7
16
, 8
16
, 9
16
, A
16
, B
16
, C
16
, D
16
, E
16
, F
16
, 10
16
, 11
16
,
12
16
, and 13
16
.
5
16
+ 5
16
= 12
16.
7
16
+ 8
16
= F
16.
1.4.4.2 Conver t i ng f r om Hex adeci mal t o Deci mal
The position of a digit in a hexadecimal number determines its value. Starting
from right to the left, the decimal value of the first digit is 16
0
times the digit
value; the value of the second digit is 16
1
times the digit value; the value of the
third digit is 16
2
times the digit value; the value of the n
th
digit is 16
n-1
times the
digit value. In order to convert a hexadecimal number to decimal, the values of
all the operations must be added.
Ex ampl e: Converting 7
16
7
16
= (16
0
*7) = 7 = 7
10
Ex ampl e: Converting 10
16
10
16
= (16
1
*1) + (16
0
*0) = 16+0=16
10
Ex ampl e: Converting A3C
16
A3C
16
= (16
2
*10) + (16
1
*3) + (16
0
*12) = 2560+48+12=2620
10
1.4.4.3 Conver t i ng f r om Deci mal t o Hex adeci mal
Hexadecimal numbers have 16 digits, while binary numbers have 2 digits. The
number must be converted from 16 digits to 2 digits representation. How?
Divide the decimal number by 16 and
Save the remainder
If the result of the division is divisible by 16, repeat the process.
The binary number is formed by writing the remainders of all the divisions start-
ing from the last.
Ex ampl e: Converting 7
10
7/16 = 0 Remainder = 7(last remainder)
Decimal 7
10
= 7
16
hexadecimal
Ex ampl e: Converting 16
10
16/16 = 1 Remainder = 0
1/16 = 0 Remainder = 1(last remainder)
Decimal 8
10
= 10
16
hexadecimal
Ex ampl e: Converting 2620
10
Comput er Graphics: Basic Concept s 53
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
2620/16 = 163 Remainder = C
163/16 = 10 Remainder = 3
10/16 = 0 Remainder = A(last remainder)
Decimal 156
10
= A3C
16
hexadecimal
1.5 LOGI C GATES
We use CMOS (complementary metal oxide semiconductor) technology to cre-
ate digital circuitry. In addition, CMOS circuits consume very little energy. It is
possible to design circuits with very large numbers of logic gates and produce
them on a single chip.

Circuits used to process digital signals are called logic gates. Digital signals are
supplied as Low Voltage (0V) or High Voltage (5V).
Low Voltage, 0 Volts, Zero (0), and False have the same value.
High Voltage, 5 Volts, One (1), and True have the same value.
Logic gates receive input and produce output. There are seven basic logic gates:
Inverter, NOR, OR, NAND, AND, XNOR, and XOR.
1.5.1 NOT ( I nv er t er )
The Inverter is the simplest logic gate. The circuit has one input and one output.
When a high voltage is applied at the input, the output voltage is low. When a
low voltage is applied at the input, the output voltage is high. The output is the
opposite of the input.
Truth table:
Input Output
0 1
1 0
Logic symbol diagram:
Comput er Graphics: Basic Concept s 54
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
1.5.2 NOR
The logic circuit has two inputs and one output. Whenever at least one of the
inputs is high, the output voltage will be low. If both inputs are low, then the out-
put voltage will be high.
Truth table:
Input1 Input2 Output
0 0 1
0 1 0
1 0 0
1 1 0
Logic symbol diagram:
1.5.3 OR
The logic circuit has two inputs and one output. Whenever at least one of the
inputs is high, the output voltage will be high. If both inputs are low, then the
output voltage will be low.

Truth table:
Input1 Input2 Output
0 0 0
0 1 1
1 0 1
1 1 1
Logic symbol diagram:
1.5.4 NAND
The logic circuit has two inputs and one output. Whenever at least one of the
inputs is low, the output voltage will be high. If both inputs are high, then the
output voltage will be low.
Comput er Graphics: Basic Concept s 55
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Truth table:
Input1 Input2 Output
0 0 1
0 1 1
1 0 1
1 1 0
Logic symbol diagram:
1.5.5 AND
The logic circuit has two inputs and one output. Whenever at least one of the
inputs is low, the output voltage will be low. If both inputs are high, then the out-
put voltage will be high.
Truth table:
Input1 Input2 Output
0 0 0
0 1 0
1 0 0
1 1 1
Logic symbol diagram:
1.5.6 XNOR
Truth table:
Input1 Input2 Output
0 0 1
0 1 0
1 0 0
1 1 1
Logic symbol diagram:
Comput er Graphics: Basic Concept s 56
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
1.5.7 XOR
The logical circuit has two inputs and one output. Whenever only one of the
inputs is high, the output voltage will be high. If both inputs are low, then the
output voltage will be low.
Truth table:
Input1 Input2 Output
0 0 0
0 1 1
1 0 1
1 1 0
Logic symbol diagram:
1.5.8 Combi ni ng Logi c Gat es
Digital systems are composed of combinations of logic gates. Logic gate combi-
nations can be described by:
Truth table
Boolean expression
Logic-symbol diagram
Ex ampl e: Water Tanks
We have the following resources:
Two water tanks
A water pump
Water tank 1 located at level 0, and water tank 2 located at level 7. When tank 2 is
empty and tank 1 is full, the system should turn on the water pump.
Truth table:
Input1 will be high (1) when tank 1 is full.
Input1 will be low (0) when tank 1 is empty.
Input2 will be high (1) when tank 2 is full.
Input2 will be low (0) when tank 2 is empty.
Output will be low (0) when the water pump is off.
Output will be high (1) when the water pump is on.
Input1 Input2 Output
0 0 0
0 1 0
1 0 1
1 1 0
Comput er Graphics: Basic Concept s 57
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
Converting truth table to Boolean expression:
Locate the high output (1).
ANDs the inputs.
If the input is low (0), invert it.
Input1 AND Not Input2 = 1.
Converting Boolean expression to logic-symbol diagram:
1.6 LANGUAGES
The instruction vocabulary of a particular microprocessor is called its instruc-
tion set. A program in the form of a microprocessor's instruction set is called
machine code. As mentioned previously, each microprocessor model has a vocab-
ulary of instructions that it understands. This vocabulary is called the micropro-
cessor's instruction set. Since everything that a computer deals with is in the
form of numbers, an instruction code number represents each instruction. A
program in the form of a sequence of instructions based on the microprocessor's
instruction set is called machine code.
Since it is very tedious to write programs in machine code, most programmers
write programs in a programming language, such as C++, which has been
designed to be easy to use. However, a computer will not be able to recognize and
execute programming language instructions. A program written in a program-
ming language must be translated into machine code by a translating program
called a compiler. A program written in a programming language is also referred
to as source code because it is the source from which the final executable pro-
gram is generated. The final executable program containing machine code is also
referred to as executable code.
Comput er Graphics: Basic Concept s 58
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
1.6.1 Low - Lev el Language
1.6.1.1 Machi ne Language
It is the language actually read and understood by the computer. It is made up of
binary numbers, which can be interpreted by a computers processor. A proces-
sor has a built-in micro-program that decodes and executes machine language
using hardware signals.
Ex ampl e: MOVE AL, 5
10110000 00000101
1.6.1.2 Assembl y Language
Assembly language is just one level higher than machine language. Since
machine language is not easy to decipher, assembly language was created to
make programming easier. There are a number of assembly languages, each spe-
cific to a processor family. A programming language uses word-like commands
to give precise instructions to the computer. Then the assembler translates this
into numerical binary codes (machine language) that the computer can translate
into operations. It is mostly used for systems software such as device drivers. In
addition, it is also used whenever code optimization is needed. A program con-
verts word-based assembly language into numerical machine language.
1.6.2 Hi gh- Level Languages
High-level languages such as C#, C, Pascal, and FORTRAN cannot be under-
stood by the computer. In order to execute programs written in a high-level lan-
guage, the program needs to be converted. The following sections define the
different converters.
1.6.2.1 Compi l er s
A compiler is a computer program translates high-level programming languages
such as C# or Java into machine language. The computer can then execute the
generated machine language program.
1.6.2.2 I nt er pr et er s
An interpreter is a program translator that translates and runs the program at the
same time. Basic and Java are interpreters.
1.6.2.3 Tr ansl at or
A translator translates one high-level language into another high-level language.
For example, a translator can translate a script into the C# language.
1.6.2.4 Li nk er
A linker combines the 'obj' files produced by the compiler along with the librar-
ies needed to produce an executable file. A library includes header files, each of
which provides definitions and declarations for a group of related facilities
(functions). These functions are not part of a particular program. They need to
be linked to a program in order to use them.
Comput er Graphics: Basic Concept s 59
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
1.6.3 I nt r oduct i on t o C# :
C# (pronounced see-sharp) is a simple, modern, object-oriented, and type-safe
programming language developed expressly for Microsoft's .Net platform. C# is
derived from C, C++, and Java programming languages. The language was
designed to balance power (the C++ influence) with swift development (the
Visual Basic, Delphi programming language, and Java influences). The language
features allow interoperation with subroutines written in other programming
languages, including other .NET languages, Component Object Model (COM)-
based objects and C-style Application Programming Interfaces (APIs) exported
from Dynamic Link Libraries (DLLs). C# provides the features that are the most
important to programmers: object-orientation, graphics, GUI components, and
Internet-based client/server networking and distributed computing. In addition,
C# eliminates many of the difficulties that developers often face when program-
ming in C and C++. C# is a programming language that has broad applications.
The world of C# starts from the existence of an original object class called
Object. In C# you create all subsequent objects as children of the original object.
Each child inherits the capabilities initializing, deleting, and so forth of the
original object. The children of the children will continue this inheritance.
Therefore, the C# program is a collection of children created from Object.
For the compiler to know where to start the program, one of the objects should
contain a method that must be named "Main." In such a case, the compiler will
locate the entry point. This method is responsible for calling all the other func-
tions of the program. However, it is possible to define more than one main. This
results in ambiguity. In such a case, it is the duty of the programmer to dictate to
the compiler which main is the real starting point.
The Main method is the entry point of your program, where the program control
starts and ends. It is declared inside a class or struct and must be static. It can
either have a void or int return type. The Main method is where you create
objects and invoke other methods. It can be declared with or without parame-
ters. The first form allows your program to read command-line arguments. The
static modifier denotes a member that belongs to the class itself, not any instance
of the class.
The following diagram shows how all created classes inherit and are directly or
indirectly derived from the base class Object:
Comput er Graphics: Basic Concept s 60
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
In the diagram above, Class1, Class2, to ClassN are all classes created by the
programmer with no base class. Despite this fact, they all indirectly inherit from
the base class "Object." Class11 is derived from Class1; Class12 is derived from
Class2; ; and Class1N is derived from ClassN. All these derived classes also
inherit from the base class "Object."
We can conclude that no matter how we create our classes, they all inherit from
the base class "Object." In addition, all available classes in the .NET Framework
are derived from Object, and every method defined in the Object class is avail-
able in all objects in the system.
1.6.3.1 What I s a Pr ogr ammi ng Language?
Programming a computer means instructing the computer what to do. A lan-
guage enables a programmer to precisely specify what data a computer will act
upon, how this data will be stored/transmitted, and precisely what actions to take
under various circumstances. A programming language consists of keywords
and grammar rules. The programming language comes with a translator (com-
piler) that translates the program into code. This code is readable by the machine
so that the machine can execute the instructions. C# allows the manipulation of
bits, bytes, and words, which are the basic elements with which the computer
functions.
The C# programming language supports the concept of data types. These define
a set of values that a variable can store along with a set of operations that can be
performed on that variable. Data types have the ability to section off and hide
from the rest of the program all the information and instructions necessary to
perform a specific task.
1.6.3.2 What I s a Pseudocode?
Pseudocode is the name used to describe the English-like words that are then
assembled and compiled into machine code. Computers do not understand the
English pseudocode words that you type. The compilers job is to translate them
into a series of 0s and 1s that the computer understands.
Comput er Graphics: Basic Concept s 61
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
1.6.3.3 My Fi r st C# Pr ogr am
If you are a beginner to C# programming and you have never created and run a
C# program, this step-by-step tutorial will show you how to open the C# pro-
gramming environment, create a new application, and run it.
1. Locate the C# environment called Visual C# 2005 Express Edition Beta. It can
usually be found on the "Start" menu or under "All Programs", as shown
below:
Comput er Graphics: Basic Concept s 62
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
You can also find the C# programming environment packaged with Visual Stu-
dio 2005. Once you locate and run the environment, you will see something very
similar to the following:
A console application is an application that does not depend on Windows
features or classes. Console applications perform all their input and output at
the command line.
2. To create a Console Application, On the File menu, click New and then
click Project.
Comput er Graphics: Basic Concept s 63
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
The New Project dialogue box appears. This lists the various default applica-
tion types that Visual C# Express can create.
3. Select Console Application as your project type.
4. Change the name of your application to "FirstProject." The default location
should be fine, but you can always use a different path if you wish.
Click OK.
Comput er Graphics: Basic Concept s 64
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
A new folder is created for your project named after the project title:
For now, we have created a complete C# console application that is ready to be
run.
5. To run the application without debugging, hold down the Ctrl key and press
F5. In either case you will not see any output because the application you just
created has no output to show. When you close the solution, you will be asked
if you want to save your project. In normal conditions you would save the
project, but for this demo project just choose to "Discard" it.
Comput er Graphics: Basic Concept s 65
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
1
DI SCUSSI ON QUESTI ONS
The answers for these questions are available in the appendix.
1. What is the main difference between a motion picture and a game?
2. What would happen if there was no handling in the procedure of the Game
Loop?
3. Why is transparency used in computer graphics?
4. How can the game maintain the frame rate?
5. Can we guarantee that a game will not exceed a certain number of frames?
6. Can we guarantee that a game will not drop below a certain number of frames?
7. Name three analog devices and three digital devices.
8. Is the position of a standing person a digital or analog value? Explain why.
9. Name the tasks that the CPU performs.
10. Is the memory address accessed randomly?
11. How will the memory look if we store value 5 in address 1, value 10 in
address 3, and value 250 in address 5?
12. What would the depth of a sixteen bit frame buffer be?
13. Represent 8
10
in binary (use 8 bits).
14. Represent 300
10
in binary (use 8 bits).
15. Represent -5
10
in binary number (use 8 bits).
16. Represent a new logic symbol diagram for the NOR gate.
17. Draw the truth table of the following logic symbol diagram.
Exercises 66
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
E
EXERCI SES
The solutions for these exercises are available in the Appendix.
1. Add the following two numbers:
a. 10010011
2
and 01000100
2

b. 10101010
2
and 01010101
2

c. 111111110
2
and 00000001
2

d. 11010111
2
and 11001101
2

e. 00010001
2
and 00000101
2

f. 10111010
2
and 01000101
2

g. 11011011
2
and 00100100
2

h. 11111011
2
and 00000100
2

i. 10101010
2
and 10101010
2

j. 11110011
2
and 01000110
2

2. Subtract the following two numbers:
a. 00001110
2
and 00000101
2

b. 11010111
2
and 11001100
2
c .11011111
2
and 01101100
2
d. 00101010
2
and 00100101
2
e. 11010011
2
and 01010100
2

f. 00011011
2
and 01000111
2

g. 10001011
2
and 01011101
2

h. 10110010
2
and 11110100
2

i. 11010010
2
and 01100000
2

j. 10110001
2
and 11001100
2

3. Multiply the following two numbers:
a. 00110011
2
and 0100
2
b. 00001010
2
and 0001
2
c. 00101110
2
and 0100
2
d. 11011011
2
and 0010
2
e. 00101010
2
and 0101
2
f. 11101010
2
and 1001
2
g. 00101110
2
and 1100
2
h. 00111011
2
and 0101
2
i. 01111010
2
and 1101
2
j. 00111011
2
and 1111
2
Exercises 67
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
E
4. Divide the following two numbers:
a. 10111010
2
and 01011101
2
b. 10010010
2
and 0000100
2

c. 10101010
2
and 000101
2

d. 11101010
2
and 000111
2
e. 01101011
2
and 0101
2
f. 11101110
2
and 10100
2
g. 01111010
2
and 01001
2
h. 11101110
2
and 00011101
2
i. 101111011
2
and 011001
2
j. 11011011
2
and 1001
2

5. Find the 2s complement of the following binary numbers:
a. 10010101
b. 10110111
c. 11011010
d. 11111011
e. 11001001
f. 01011110
g. 11111110
h. 10101111
i. 10011101
j. 11011011
6. Convert the following decimal numbers to their 1 byte binary form:
a. -115
b. 127
c. -128
d. 85
e. -50
f. 11
g. 250
h. -250
i. 144
j. -32
Exercises 68
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
E
7. Convert the following unsigned binary numbers to decimal:
a. 10010011
b. 10101010
c. 00100111
d. 11011011
e. 00100100
f. 11111011
g. 11001010
h. 10011001
i. 11011111
j. 01110011
8. Convert the following octal numbers to their 1 byte binary form:
a. 200
b. 57
c. 66
d. 255
e. 25
f. 55
g. 210
h. 325
i. 67
j. 771
9. Convert the following binary numbers to octal:
a. 01001001
b. 10101010
c. 00100111
d. 00110110
e. 01110100
f. 00110000
g. 10100110
h. 11110111
i. 01100100
j. 01010101
10. Convert the following hexadecimal numbers to their 1 byte binary form:
a. FF
b. AD
c. 1F
d. F6
e. AA
f. 5B
g. 6C
h. CD
i. B1
j. 99
Exercises 69
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
E
11. Convert the following binary numbers to hexadecimal:
a. 1100100110101010
b. 10101010 00100111
c. 0011011010101010
d. 1010101010101010
e. 1011111010101110
f. 1110101010101011
g. 1011100010100010
h. 1110100010100010
i. 1011101010001010
j. 0010001010111011
12. Using the following given:
We have the following resources:
Two water tanks.
A water pump.
Two channel sensors used to read the water level.
Water tank1 located at level0.
Water tank2 located at level7.
When tank2 is empty and tank1 is full or half full, the system should turn on the water pump.
Truth table
Input1 will be high (1) when the first half of tank1 is full.
Input1 will be low (0) when the first half of tank1 is empty.
Input2 will be high (1) when the second half of tank1 is full.
Input2 will be low (0) when the second half of tank1 is empty.
Input3 will be high (1) when tank2 is full.
Input3 will be low (0) when tank2 is empty.
Output will be low (0) when the water pump is off.
Output will be high (1) when the water pump is on.
Input1 Input2 Input3 Output
0 0 0 0
0 0 1 0
1 0 0 1
1 0 1 0
1 1 0 1
1 1 1 0
a) Convert the truth table to its Boolean expression
b) Convert the Boolean expression to its logic-symbol diagram
2
C# PROGRAMMI NG
OVERVI EW
C# Programming Over view 71
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
COMPUTER PROGRAMMI NG OVERVI EW
This chapter presents a brief introduction to the the most important aspects of
the C# language. Those aspects will be dealt with in detail in later chapters. Our
intention is to introduce the features that we will need for every C# program.
Since most of the language's topics are interdependent, we need to discuss each
of them in brief before dealing with them in detail. It is important to get the gen-
eral feeling about C# by reading and understanding this chapter.
2.1 OVERVI EW
C# is a new, simple, programming language based on and similar to the older
programming language called C++. In this chapter we might use some instruc-
tions or expressions without explaining their meaning. These materials will be
covered in later chapters.
2.2 THE SMALLEST C# PROGRAM
The Main function is the entry point of a C# program where the program starts
and ends. All standard C# programs start by executing the content of the Main
function. One of the objects must contain a method named Main, where the
compiler will locate the entry point. This function is responsible for calling all
the other functions of the program. However, it is possible to define more than
one Main, which results in ambiguity. In this case the programmer must indi-
cate to the compiler which Main is the real starting point.
The Main method is declared inside a class or struct and must be static. It can
either have a void or int return type. The Main method is where you create
objects and invoke other methods. The Main method can be declared with or
without parameters. The first form allows your program to read command-line
arguments. The static modifier denotes a member that belongs to the class itself,
not any instance of the class.
Like all functions in C#, the Main function should belong to a class. However,
this program does not do anything because the Main function does not have
instructions.
Facts:
An opening and closing parenthesis is placed after the
function name.
Parentheses are used to hold the function arguments.
C# Programming Over view 72
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
The type of the value returned by the function is specified before the func-
tion name.
The C# language uses classes to package code.
All executable C# code must be contained in a class.
Void is a C# type specifying a typeless type.
The body of the function is written within the function block specified by
the open and closed curly braces.
A class is the fundamental data type from which all C#
programs are constructed.
The C# program must contain a Main method, in which
control starts and ends.
The C# programming language is a free-format language.
2.3 DI SPLAYI NG A MESSAGE
The canonical hello, world program can be written as follows:
using System;
class Hello
{
static void Main() {
Console.WriteLine("hello, world");
}
}
The source code for a C# program is typically stored in one or more text files
with a file extension of .cs, for example, hello.cs. Using the command-line com-
piler, such a program can be compiled with the command line directive csc
hello.cs which produces an application named hello.exe. The output produced by
this application when it is run is:
hello, world
The using System; directive references a namespace called System. This
namespace contains the Console class referred to in the Main method.
Namespaces provide a hierarchical means of organizing the elements of one or
more programs. A using directive enables unqualified use of the types that are
members of the namespace. The hello, world program uses Console.WriteLine
as shorthand for System.Console.WriteLine. (For the sake of brevity, most exam-
ples in this specification omit the using System; directive.)
The Main method is a member of the class Hello. The entry point for an applica-
tionthe method that is called to begin executionis always a static method
named Main.
The hello, world output is produced using a class library. The language does
not itself provide a class library. Instead, it uses a class library that is also used by
other programming languages.
How does the "hello, world" program work? The following flowchart illustrates
the step-by-step execution of the program:
C# Programming Over view 73
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
The above flowchart gives a general idea about how a C# program is executed.
C# Programming Over view 74
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
2.4 COMMENTS
Two forms of comments are supported: single-line comments and delimited
comments. Single-line comments start with the characters // and extend to the
end of the source line. Delimited comments start with the characters /* and end
with the characters */. Delimited comments may span multiple lines.
Comments do not nest. The character sequences /* and */ have no special mean-
ing within a // comment, and the character sequences // and /* have no special
meaning within a delimited comment.
The following example includes a delimited comment.
/* Hello, world program
This program writes hello, world
to the console
*/
class Hello
{
static void Main() {
Console.WriteLine("hello, world");
}
}
The following example shows several single-line comments.
// Hello, world program
// This program writes hello, world
to the console
//
class Hello // any name will do for this class
{
static void Main() { // this method must benamed "Main"
Console.WriteLine("hello, world");
}
}
2.5 MULTI PLE I NSTRUCTI ONS PROGRAM
A function is a block of code written to perform a specific task (function) and
packaged in a unit so that it can be executed at desired points in a program.
Dividing a program into separate functions makes the program more manage-
able and easier to understand.
Facts:
The program contains three user functions.
Functions need to be defined before being used or executed.
The Main function contains three function calls or three statements.
User functions are declared outside the Main function.
Functions can be called many times.
The program starts by executing the first instruction in Main, which is the
DisplayHello function.
C# Programming Over view 75
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
When the DisplayHello function is called, the execution flow changes to the
first instruction within the function definition of DisplayHello.
When the last instruction (which is also the first instruction) of the function
DisplayHello is executed, the execution returns to the next instruction after
the DisplayHello function call, which is DisplayWorld.
2.6 FUNCTI ONS WI TH ARGUMENT RETURNI NG A VALUE
A function contains the parameters and the return type. The parameters provide
data needed by the function to do its job. For each parameter, specify its name
and data type; if no parameters are needed, specify the keyword void inside the
parentheses.
The return type specifies the data type of the data that is returned by the func-
tion. Some functions do not return any data; in this case specify the keyword
void as the return type.
Ex ampl e:
void foo();
void foo(int i);
int foo();
C# Programming Over view 76
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
We have used the WriteLine method to write to the console. The method has
two arguments. The first is a string, and the second is a function call returning a
value that C# will convert to a string for display. The format specifier, {0}, indi-
cates the position where the second argument will appear in the string.
To output more than one number, we use additional format specifiers, {0}, {1},
{2}, and so on. For each specifier, we include an argument to replace it in the out-
put string. Thus, if number1 is 5 and number2 is 10, the statement
Console.WriteLine("The number is {0} and twice it is {1}.",
number1, number2);
will output:
The number is 5 and twice it is 10.
We can output the data in any order. For example,
Console.WriteLine("Twice the number is {1} and the number is
{0}",
number1, number2);
Facts:
int is a C# type specifying whole or integral numbers.
int means integer.
The function prototype specifies that the function takes two integer argu-
ments and returns an integer.
When a function has more than one argument, a comma is used to separate
the arguments.
When a function with arguments is called, the arguments are received as
parameters by the function where the functions
instructions are specified.
When arguments are passed to the parameters, the order of the arguments is
respected. In our case, x would be equal to 3, and y
would be equal to 5.
The last statement of the function definition returns the result of the arith-
metic expression x + y.
C# Programming Over view 77
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
x and y are called variables. A variable is a name assigned to a data storage
location.
The variables x and y are defined in the parameter list of the function: (int x,
int y).
In C#, a variable must be defined before it can be used.
A variable definition specifies its name and type.
The compiler uses the type in order to know how much memory to allocate.
2.7 VARI ABLES
Facts:
Two integer variables i and j are declared and defined.
By declaration, we mean that the rest of the function Main knows about the
presence and type of i and j.
In other words, the scope and type of i and j is within the body of function
Main.
Then, an assignment operator is used in order to assign the value 3 and 5 to
i and j respectively.
The function Add is used by having two variables as arguments, while in the
previous example the arguments were constants.
C# Programming Over view 78
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
2.8 USER I NPUT
Instead of using the assignment operator to assign value to the variables, the
input function ReadLine is used.
Facts:
The ReadLine() method belongs to the Console class.
The ReadLine() method reads the next line of characters from the standard
input stream.
The Parse() method belongs to the Int32 structure.
The Parse() method converts the string representation of a number to its 32-
bit signed integer equivalent.
In C# arithmetic, the addition (+) operator is evaluated from left to right.
The multiplication operator (*) has a higher order of precedence than the
addition operator.
C# Programming Over view 79
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
2.9 CONDI TI ONAL EXPRESSI ON
Facts:
i>100 is the Boolean expression that evaluates to true or false.
If the expression is true, then the statement (or the block of statements
enclosed between opening and closing curly braces)
following the condition is executed.
If the expression is false, then the statement following the condition is
skipped.
The statement following the else is executed only when the conditional
expression is false.
In other words, only one of the WriteLine statements will be executed.
The conditional statement starts with the keyword if followed by an opening
parenthesis, followed by a Boolean expression,
followed by a closing parenthesis, followed by an instruction.
if(Boolean expression)
instruction;
Notice that there is no semicolon after the closing parenthesis of the Bool-
ean expression because the conditional statement has not ended yet.
C# Programming Over view 80
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
2.10 LOOPS
Facts:
The for loop form is:
for(expression1;expression2;expression3)
statement
The loop is initialized through expression1 i=0;
Expression2 specifies the test made before each iteration i<10;
If expression2 is true,
The statement Console.Write("{0} ",i); is executed, then
Expression 3 i=i+1 is executed.
The loop iterates until expression2 is false.
If expression2 is false, the for loop will exit, and the control is transferred to
the statement following the statement in question.
Expression3 is evaluated after each iteration.
Any or all of the three for expressions may be omitted, but the semicolon
must remain.
The while loop form is:
while (expression)
statement
If expression i<10 is true, the statement is executed until expression becomes
false.
In our case the statement is made from a block enclosed between curly
braces:
{
Console.WriteLine("{0} ",i);
i=i+1;
}
If expression is false, the execution resumes at the following statement. In
our case, the following statement is the end of the
program.
The expression is evaluated before the statement is executed.
When the expression is false from the first time, the statement will never be
executed.
C# Programming Over view 81
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
2.11 ONE- DI MENSI ONAL ARRAY
Facts:
It is a collection of variables of the same type that are referred to by the same
name.
In our case, int[] A = new int[10]; reserved 10 integers.
Array elements are accessed through an index, in our case the index is i.
The first element is accessed by index 0 A[0].
The highest address corresponds to the last element, and it is accessed by
index (total number of elements 1), in our case it is A[9].
The amount of storage required to hold an array depends on the type and
the total number of elements; in our case it is 10 * 4=40,
since each integer is 4 bytes.
The C# compiler does not perform index range checking.
The array element is accessed by indexing the array name.
It is done by writing the index enclosed between brackets placed after the
array name.
arrayName[index] A[i]=i;
C# Programming Over view 82
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
2.12 STRUCTURE
class test
{
struct point
{
public int x;
public int y;
};
static void Main()
{
int deltaX;
p1.x=2; p1.y=1;
p2.x=7; p2.y=3;
Console.WriteLine(Distance(p1,p2));/* will print
5.3851648071345 */
}
static double Distance(point p1,point p2)
{
int deltaX, deltaY;
deltaX=p2.x - p1.x;
deltaY=p2.y - p1.y;
return Math.Sqrt(deltaX*deltaX + deltaY*deltaY);
}
}
Output
5.3851648071345
Facts:
A structure is an object consisting of a sequence of named members of vari-
ous types.
A structure is a collection of variables referenced under one name.
The collection of variables is logically related.
A structure provides a convenient way to keep related information together.
A structure is declared by typing the keyword struct, followed by the struc-
ture name, followed by the structure members enclosed
between curly braces. For example:
struct point
{
public int x, y;
}
Once a structure is declared, variables having the structure type could be
declared by typing the structure name followed by the
variable name. For example:
point p1, p2;
The dot "." operator is used to access the structure member.
First write the structure variable name, followed by a dot, followed by a
member. For example:
deltaX=p2.x - p1.x;
The function Distance requires a square root calculation.
The square-root function Sqrt is defined in the namespace called Math.
The function Distance declares and defines two variables: deltaX and deltaY.
Remember that variables declared inside a function are only available while
executing the function.
deltaX and deltaY are used to hold the difference between the first and the
second point.
C# Programming Over view 83
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
In C# arithmetic, the multiplication * operator is evaluated from left to right.
The multiplication operator has a higher order of precedence than the addi-
tion operator.
This is why deltaX*deltaX is evaluated first to 25.
Next deltaY*deltaY is evaluated to 4.
Then 25 and 4 are added evaluating to 29.
Then the square root of 29 is evaluated to 5.3851648071345.
2.13 DI RECT I MPLEMENTATI ONS
2.13.1 Mat h Pr obl em
Write a program that finds the Determinant (Delta) of the second-degree equa-
tion.
Equation: a
*
x
2
+ b
*
x + C = 0
Delta = b
2
4
*
a
*
c
The output should be similar to the following:
2.13.2 Mat h Pr obl em
Write a C# program that accepts an integer number into a variable, and then tests
the variable against 100. If the value of the variable is less than one hundred,
multiply the variable by 10 and finally display the variable.
The output should be similar to the following:
2.13.3 Comput er Sci ence Pr obl em
Write a program that allows the user to enter the 10 integers to an array. The pro-
gram should output the integers entered by the user.
The output should be similar to the following:
C# Programming Over view 84
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
2.13.4 Chemi st r y Pr obl em
One molecule of a certain gas is placed into a balloon of volume V. A manometer
reads the pressure P inside the balloon. Write a program that takes as input V
and P and returns the temperature T of the gas.
The output should be similar to the following:
2.13.5 Chemi st r y Pr obl em
The combustion of an alkane of general formula C
n
H
2n+2
pro-
duces carbon dioxide and water according to the reaction:
( )
2 2 2 2 2
3 1
C H O CO 1 H O
2
n n
n
n n
+
+
+ + +

Write a program that takes as input the number of carbon atoms
in the alkane, n, and returns the number of oxygen molecules
(O
2
) that one molecule of this alkane needs in order to be
burned.
The output should be similar to the following:
C# Programming Over view 85
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
2.13.6 Phy si cs Pr obl em
Write a program that takes as input the height of an object and returns the time
that it would need to hit the ground when it is released at this height.
Fl ow Char t

C# Programming Over view 86
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
Dynamics physics book
Appr oach
Faced with a free-fall problem, your best friends are:
The three laws of motion established by Sir Isaac Newton.
A good knowledge of kinematics.
A frame of reference to position the body.
These will help you to comprehend all the facts involved in the problem.
The section of classical mechanics, called kinematics, describes the motion of an
object in terms of time and space, regardless of what causes the motion. Briefly,
kinematics studies the position of a moving object as a function of time, its
velocity (the rate of change of the position as a function of time), and its acceler-
ation (the rate of change of the velocity as a function of time.)
Newtons laws of motion are as follows:
First Law:
Consider a body with no external forces acting on it. If the body is at rest, it will
stay at rest. If it is moving at constant velocity, it will keep moving at the same
velocity.
Second Law:
The sum of external forces acting on a body is equal to its mass times its acceler-
ation.
Third Law:
For each action, there is a reaction. That is, when two bodies interact, the first
body exerts a force F1 on the second, and the second exerts a force F2 on the first
that is equal in magnitude and opposite in direction to F1.
Newtons laws care about the cause of motion. Coupling kinematics and New-
tons laws will provide a good base for you to understand free-fall motion.
C# Programming Over view 87
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
Consider now an object released at a certain height. Set your frame of reference
(graph) as follows:
A vertical axis pointing upward and
passing by the release point.
A horizontal axis parallel to the
ground level.
An origin at the ground level.
The observation of the phenomenon
clearly says that the position of the object
changes with time, and its speed increases,
which means that there is a force causing
this object to accelerate.
In fact, the cause of this motion is the gravitational force field of the Earth, which
exerts on any body of mass m, a force directed towards the center of the Earth
equal to mg, that is, the product of the mass and the gravitational constant g =
9.81 m/s
2
. This force is known as the weight of the body. Therefore, a body
released at a certain height falls under the action of its own weight.
Consequently, if the only force acting on the body is its weight, mg, Newtons
Second Law allows us to write the following
-mg = ma a = -g = -9.81 m/s2
The minus sign is due to the downward direction of the force, opposite to the
positive direction of the y-axis usually adopted.
In this problem, we are only concerned with the vertical motion because the
body does not move horizontally. This is why we search only for the vertical
component of velocity and the height, which is the vertical component of posi-
tion.
We know that the body accelerates downward at a rate of 9.81 m/s
2
and the verti-
cal component of the velocity as a function of time (the anti-derivative of the
acceleration) is given by:
v = -9.81t + v
0
v
0
is the initial velocity of the body. Which, happens in this case, to be equal to
zero, since the body was released. Therefore, the equation is reduced to:
v = -9.81t
The height of the body is the anti-derivative of the velocity, given by:
2
0
1
g
2
h t h = +
h
0
is the initial height of the object, that is, where the body is released.
C# Programming Over view 88
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
As you can see, the body reaches the ground level when its height becomes zero.
Therefore, to find out the time at which the body hits the ground, all you have to
do is solve for t the equation h(t) = 0.
Sol ut i on
1. Set the coordinate system having the vertical axis perpendicular to the ground,
its origin at the ground level, and its horizontal axis parallel to the ground, as
the figure below shows:
2. Find the coordinates of the release point with respect to xOy, that is, find how
far the release point is from the vertical axis and the horizontal axis.
3. Find the grounds ordinate, y
0
, that is, the distance between the ground level
and the x-axis. The x-axis is taken to be parallel to the ground level.
4. When the ball is released, its height changes with respect to time. Find the
equation of the balls height as a function of time, h(t), in xOy.
5. Find t
0
the solution of the equation y0 = h(t).
6. t
0
is the time required for the ball to reach the ground level.
Lessons Lear ned
After solving this problem:
I recognized how gravity makes objects undergo free-fall motion.
I learned a simple, step-by-step method of finding the time that an object
needs, when released from a certain height above ground level, to hit the
ground.
I can implement this method in a computer programming algorithm.
I developed the skill of finding the height of a falling object at any time dur-
ing its motion.
I can now accomplish the task of finding the time that a falling object needs
to reach the ground more easily because it was broken down into several
simple steps.
I will remember this method faster because it was described verbally and
visually.
C# Programming Over view 89
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
The C# Appr oach
The above physics problem was solved using a purely scientific approach. Now
you need to solve it using C#.
The output should be similar to the following:
2.13.7 Phy si cs Pr obl em
The speed of light in vacuum is c = 310
8
m/s. Write a program that takes as
input v, the speed of light in a certain medium, and returns the index of refrac-
tion of the medium.
The output should be similar to the following:
C# Programming Over view 90
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
2.13.8 Phy si cs Pr obl em
Write a program that takes as input the position of an object placed in front of a
concave mirror and the focal length f (f > 0) of the mirror, and returns how far
the image will be from the mirror and to which side.
Fl ow Char t
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
Optics physics book
Appr oach
This is a classical problem in geometric optics. In fact, all you need to know to
solve these problems is the characteristics of a concave mirror (spherical mirror)
and the mirror equation.
C# Programming Over view 91
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
Characteristics of a concave mirror
A concave mirror has a spherical shape as if it were cut from a sphere. Its reflect-
ing face is the inner part of the sphere.
A concave mirror is characterized by its:
Radius of curvature, R
The radius of the sphere from which the mirror was made.
Center of curvature, C
The center of the sphere from which the mirror was made.
Center of the spherical segment, V
The vertex of the mirror or the midpoint of the arc.
Principal axis
The axis passing by the center of curvature and the center of the spherical seg-
ment.
Focal point, F
The midpoint of the center of curvature and the center of the spherical segment.
Focal length, f
The distance between the focal point and the center of curvature. This is half the
radius of curvature.
The Mirror Equation
Consider a point object, O, (a very small source of light reduced to a point)
placed in front of a concave mirror. The distance VO is known as the object dis-
tance and named p. The image I, of O given by the concave mirror is placed on
the principal axis. The distance VI is known as the image distance and named q.
C# Programming Over view 92
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
One should note that p, q, R, and f are algebraic distances, that is, they are signed.
When the object is placed in front of the mirror, then the distance p is positive.
Also, if the image is formed in front of the mirror, then the distance q is positive.
p and q are negative in the other case. Since the focal point and the center of cur-
vature of a concave mirror are placed in front of the mirror, then they are both
positive.
The geometry of the figure allows us to find a relation between p, q, and R called
the Mirror Equation. We do not derive this formula here, yet we state it directly.
1 1 2 1
p q R f
+ = =
After this brief introduction on concave mirrors, you should be able to find the
image of any object given by a concave mirror. For example, if a point object is
placed at the center of curvature, then p = R. In this case, the Mirror Equation is
1 1 2 1 2 1 1
q R
R q R q R R R
+ = = = =
Consequently, when you place an object at the center of curvature of a concave
mirror, the image of the object will coincide with the object itself.
Sol ut i on
1. Find the position p in meters of the object, that is, the distance from the
vertex of the mirror to the bottom of the object on the principal axis of the
mirror. This is represented by OP on the above figure.
2. Find the focal length of the mirror, which is the distance from the vertex to
the focus, F, of the mirror that lies on the principal axis. The focal length is
the distance OF on the figure above.
C# Programming Over view 93
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
2
3. Using the mirror equation, calculate q, the position of the image that is the
distance from the vertex to the bottom of the image on the principal axis.
On the figure, this distance is OQ.
4. Check the sign of q.
5. If q is positive, the image is real in front of the mirror. Otherwise, the image
is virtual in the back of the mirror.
Lessons Lear ned
After solving this problem:
I understood how a spherical mirrors function.
I learned a simple, step-by-step method of finding the position of the image
of a certain object placed in front of a spherical mirror.
I can implement this method in a computer programming algorithm.
I developed the skill of finding the position of the image given by a spherical
mirror of an object placed in front of the mirror.
I can accomplish the task of finding the position of the image more easily
because it was broken down into several simple steps.
I will remember this method faster because it was described verbally and
visually.
The C# Appr oach
The above physics problem was solved using a purely scientific approach. Now
you need to solve it using C#.
The output should be similar to the following:
3
C# TYPES
C# Types 95
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
C# TYPES
In C#, types are divided into two categories: value types and reference types. Value
types directly contain their data, and reference types store references to their
data. A third category of types called pointers, is available only in unsafe code.
This pointer type will not be discussed in this document.
3.1 VALUE TYPES
In C#, a value type can be either a struct or an enumeration. C# contains a set of
predefined struct types called the simple types. These simple types are identified
through reserved words. All value types implicitly inherit from a class called
object. Also, no type can derive from a value type. It is not possible for a value
type to be null (null means nothing or no value). Assigning a variable of a
value type creates a copy of the value. This is different from assigning a variable
of a reference type, which copies the reference and not the object identified by
the reference.
3.1.1 by t e
The byte type denotes an integral type that stores values ranging from 0 to 255.
Its size is 8-bit. A byte can be declared and initialized as follows:
byte b = 117;
In the preceding declaration, 117 is implicitly converted from int to byte. If the
integer literal exceeds the range of byte, a compilation error will occur, as with
the following assignment statement:
byte c = a + b; // Error: conversion from int to byte
To fix this problem, use an explicit cast:
byte c = (byte)(a + b); // OK
3.1.2 char
The char type is used to declare a Unicode character in the range 0 to 65535.
Unicode characters are 16-bit characters used to represent most of the written
languages throughout the world. The following statement declares a char vari-
able and initialize it with the character D:
char c = 'D';
3. 1. 3 bool
The bool type represents boolean quantities. There can be two possible values of
type bool: true and false. There is no standard conversion between bool and
other types. Such conversions are accomplished by comparing an integral value
to zero or comparing an object to null. A boolean value can be assigned to a bool
variable; for example:
bool MyBool = true;
You can also assign an expression that evaluates to a bool variable; for example:
bool b = (i > 66);
C# Types 96
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Conversions
No conversion exists between the bool type and other types. For example, the
following if statement:
int i = 101;
if (i)
{

}
is not allowed in C#.
To test an int type, you have to explicitly compare it to a value, as follows:
int i = 13;
if (i == 13)
{
// do something
}
Ex ampl e:
In this example, you enter a character from the keyboard, and the program
checks if the input character is a letter.
public class test
{
static void Main()
{
Console.Write("Enter a character: ");
char ch = (char) Console.Read();
if (Char.IsLetter(ch))
Console.WriteLine("It is an
alphabetic character.");
else
Console.WriteLine("It is not an
alphabetic character.");
}
}
Output
Enter a character: A
It is an alphabetic character.
3.1.4 deci mal
The decimal type denotes a 128-bit data type. The decimal type has a greater pre-
cision and a smaller range than the floating-point type, which makes it suitable
for financial and monetary calculations. To make sure that a numeric real num-
ber is treated as a decimal, use the suffix m or M:
decimal dec = 710.88m;
Without the suffix m, the number is treated as a double, and the expression gen-
erates a compilation error.
C# Types 97
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Ex ampl e:
public class test
{
static void Main ()
{
decimal dec = 12.4m;
int i = 33;
Console.WriteLine(dec * i); // Here the result is con-
verted to decimal
}
}
Formatting Decimal Output
You can format the results by using the String.Format method, or through the
Console.Write method, which calls String.Format(). The currency format is
specified using the standard currency format string "C" or "c", as shown below.
Ex ampl e:
In this example, the output is formatted using the currency format string.
public class test
{
static void Main ()
{
decimal dec1 = 0.987m;
decimal dec2 = 5454335566m;
Console.WriteLine("{0:C}", dec1);
Console.WriteLine("{0:C}", dec2);
}
}
Output:
$0.99
$5,454,335,566.00
3.1.5 doubl e
The double type denotes a simple type that stores 64-bit floating-point values. By
default, a real numeric literal on the right-hand side of the assignment operator
is treated as double. However, if you want an integer number to be treated as
double, use the suffix d or D; for example:
double x = 44D;
Numeric integral types and floating-point types can be mixed in an expression.
In this case, the integral types are converted to floating-point types.
Ex ampl e:
class test
{
static void Main()
{
float f = 8.66f;
int i = 123;
double d = 22.1E+2;
Console.Write("{0}", f + i + d);
C# Types 98
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
}
}
3.1.6 enum
The enum type is used to declare an enumeration, which is a distinct type con-
sisting of a set of constants called the enumerator list. Every enumeration type
has an underlying type, which can be any integral type except char. The default
type of the enumeration elements is int. By default, the first enumerator has the
value 0, and the value of each successive enumerator is increased by 1. For exam-
ple:
enum WeekDays {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
In this enumeration, Sun is 0; Mon is 1, and so forth. Enumerators can have ini-
tializers overriding the default values, as the following example shows:
enum WeekDays {Sun=1, Mon, Tue, Wed, Thu, Fri, Sat};
In this enumeration, the sequence starts from 1.
An enum En has a default value, which is the value produced by the expression
(En)0. The enumeration type specifies how much storage is allocated. However,
an explicit cast is needed to convert from enum type to an integral type.
Ex ampl e:
In this example, an enumeration, weekDays, is declared. Two enumerators are
explicitly converted to int and assigned to int variables.
public class test
{
enum WeekDays {Sun=1, Mon, Tue, Wed, Thu, Fri, Sat};
static void Main()
{
int i1 = (int) WeekDays.Tue;
int i2 = (int) WeekDays.Thu;
Console.WriteLine("Tuesday is day {0}", i1);
Console.Write("Thursday is day {0}", i2);
}
}
Output
Tuesday is day 3
Thursday is day 5
3.1.7 f l oat
The float type denotes a type that can store 32-bit floating-point values. A real
numeric literal on the right-hand side of the assignment operator is by default
treated as a double. Therefore, to initialize a float, use the suffix f or F, for exam-
ple:
float f = 68.77F;
You will get a compilation error if you do not use the suffix because you are
attempting to store a double value into a floating-point variable. You can mix
numeric integral types and floating-point types in an expression. In this case, the
integral types are converted to floating-point types.
C# Types 99
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Ex ampl e:
class test
{
static void Main()
{
int i = 14;
float f = 68.25f;
Console.Write("{0}", i-f);
}
}
3.1.8 i nt
The int type denotes an integral type storing 32-bit values. It ranges from -
2,147,483,648 to 2,147,483,647. The type int is declared and initialized like this:
int i = 441;
3.1.9 l ong
The long type denotes an integral type that stores 64-bit values. It ranges from
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. The type long is
declared and initialized like this:
long myLong = 23940043;
When an integer literal has no suffix, its type is the first of the following types in
which its value can fit: int, uint, long, ulong. The suffix L can be used with the
long type like this:
long myLong = 990085665543L;
When you use the suffix L or l, the literal integer's type is either long or ulong
according to its size.
A predefined implicit conversion exists from long to float, double, or decimal. In
other cases, a cast must be used. For example, the following statement:
int i = 21L;
will produce a compilation error without an explicit cast. There is an implicit
conversion from sbyte, byte, short, ushort, int, uint, or char to long. Also, there is
no implicit conversion from floating-point types to long. For example, the fol-
lowing statement generates an error:
long l = 31.23;
3.1.10 sby t e
The sbyte type denotes an integral type that stores signed 8-bit integer values
ranging from -128 to 127. An sbyte can be declared and initialized like this:
sbyte mySbyte = 100;
100 is implicitly converted from int to sbyte. If the integer literal exceeds the
range of sbyte, a compiler error will occur. A predefined implicit conversion
exists from sbyte to short, int, long, float, double, or decimal. Also, there is no
implicit conversion from floating-point types to sbyte.
3.1.11 shor t
The short type denotes an integral data type that stores signed 16-bit integer val-
ues ranging from -32,768 to 32,767. A short is declared and initialized like this:
C# Types 100
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
short s = 30201;
30201 is implicitly converted from int to short. If the integer literal does not fit
into a short storage location, a compiler error will occur. A predefined implicit
conversion exists from short to int, long, float, double, or decimal. You cannot
implicitly convert non literal numeric types of larger storage size to short. Also
there is no implicit conversion from floating-point types to short.
3.1.12 st r uct
A struct is a value type. It can contain constructors, constants, fields, methods,
properties, indexers, operators, and nested types. The struct type is suitable for
representing objects such as Point, Rectangle, and Color. When creating a struct
object using the new operator, it gets created, and the appropriate constructor is
called. Structs can be instantiated without using the new operator. If you do not
use new, the fields will remain unassigned and the object cannot be used until all
of the fields are initialized.
You cannot declare a class using the struct type. Classes and structs are semanti-
cally different. A struct is a value type, while a class is a reference type.
Ex ampl e:
public struct Point
{
public int x, y;
}
Ex ampl e:
This example creates a point object without using the new operator.
public struct Point
{
public int x, y;
}
class test
{
static void Main()
{
Point p1;
}
}
3.1.13 ui nt
The uint type denotes an integral type that stores unsigned 32-bit integer values
ranging from 0 to 4,294,967,295. A uint can be declared and initialized like this:
uint myUint = 4294967288;
The suffix u or U can be used, like this:
uint myUint = 112U;
If you use the suffix U or u, the literal type is determined to be either uint or
ulong according to its size. In this example, it is uint. A predefined implicit con-
version exists from uint to long, ulong, float, double, or decimal. For example:
C# Types 101
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
float myFloat = 4294967289;
Also, there exists a predefined implicit conversion from byte, ushort, or char to
uint. Otherwise you must use a cast. There is no implicit conversion from float-
ing-point types to uint.
3.1.14 ul ong
The ulong type denotes an integral type that stores unsigned 64-bit integer values
ranging from 0 to 18,446,744,073,709,551,615. A ulong is declared and initialized
like this:
ulong myUlong = 92854775806;
When using L or l as a suffix, the type of the literal integer will be either long or
ulong according to its size. There is an implicit conversion from ulong to float,
double, or decimal, but there is no implicit conversion from ulong to any integral
type.
3.1.15 ushor t
The ushort type denotes an integral data type that stores unsigned 16-bit integer
values ranging from 0 to 65,535. ushort can be declared and initialized like this:
ushort myUShort = 65535;
65535 is implicitly converted from int to ushort. A compiler error will occur if
the integer literal exceeds the range of ushort. A predefined implicit conversion
exists from ushort to int, uint, long, ulong, float, double, or decimal. Also, there
is a predefined implicit conversion from byte or char to ushort. Otherwise a cast
must be used. There is no implicit conversion from floating-point types to ush-
ort.
3.2 REFERENCE TYPES
A reference type is one of the following: a class, an interface, an array, or a dele-
gate. A reference type value is a reference to an instance of the type. null is com-
patible with all reference types and indicates the absence of an instance.
Class Types
A class defines a data structure containing data members (constants and fields),
function members (methods, properties, events, indexers, operators, instance
constructors, destructors and static constructors), and nested types.
The Object Type
The object class type is the ultimate base class of all other types. Every type in C#
directly or indirectly derives from the object class type.
The String Type
The string type inherits directly from class object.
Interface Types
An interface defines a contract. A class implementing an interface must adhere to
its contract.
C# Types 102
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Array Types
An array is a data structure containing a number of variables that are accessed
through indices. The variables contained in an array are called the elements of
the array. They are all of the same type, and this type is called the element type of
the array.
3.3 VOI D
When used as the return type for a method, the void type specifies that the
method does not return a value. A void is not allowed in a methods parameter
list. A method with no parameters and returning no value is declared as follows:
void MyMethod();
C# Types 103
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.4 DI RECT I MPLEMENTATI ONS
3.4.1 Mat h Pr obl em
Write a program that takes as input the equation of a parabola and returns as
output the coordinates of its vertex, the direction of its concavity, and the coordi-
nates of its intersection with the x-axis if there exists any.
Fl ow Char t
If a z 0
If a = 0
Input a, b, and c, the
coefficients of the
quadratic function
f(x) = ax
2
+ bx + c
The coordinates of the vertex
are
2
2 2 2
b b b
,a b c
a a a







The intersections with the x-axis are
0
2
b
,
a

'



and 0
2
b
,
a

'



This is not a
quadratic
function
If a > 0 If a < 0
Calculate
' = b
2
4ac
If '< 0 If ' > 0
Concavity
Upward
Concavity
Downward
No intersections
with the x-axis
If '< 0
The intersection
point with the x-
axis is
0
2
b
,
a



Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
Precalculus math book
C# Types 104
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Appr oach
In order to deal easily with these kinds of problems, you need to be familiar with
quadratic functions and their behavior. Also, being able to solving quadratic
equations will help you in determining the different characteristics of a parabola,
which is the graph of a quadratic function.
The quadratic function is of the form f(x) = ax
2
+ bx + c, where a, b, and c are
real numbers and a is not zero. The domain of a quadratic function is the whole
set of real numbers. The quadratic function may have one of two behaviors
according to the sign of a.
If a is positive, then the value of f(x) decreases when x increases from - to x =
b/2a where f(x) reaches a minimum, then it increases as x increases from b/2a
to . The table below shows some of the values that f(x) = 2x
2
4x + 1 takes
around x = b/2a = 1.
x f(x) = 2x2 4x + 1
0.1 0.62
0.2 0.28
0.3 -0.02
0.4 -0.28
0.5 -0.5
0.6 -0.68
0.7 -0.82
0.8 -0.92
0.9 -0.98
1 -1
1.1 -0.98
1.2 -0.92
1.3 -0.82
1.4 -0.68
1.5 -0.5
1.6 -0.28
1.7 -0.02
1.8 0.28
1.9 0.62
2 1
C# Types 105
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Notice that the function in the table reaches a minimum value equal to -1
when x = 1. We can use the table to draw the graph of this quadratic equation
called a parabola:
The graph reflects the behavior of its function and shows a minimum at x = 1.
If a is negative, then the value of f(x) increases when x increases from - to x =
b/2a where f(x) reaches a maximum, then it decreases as x increases from b/2a
to . The table below shows some of the values that f(x) = 2x
2
+ 4x 1 takes
around x = b/2a = 1.
x f(x) = 2x2 + 4x 1
0.1 -0.62
0.2 -0.28
0.3 0.02
0.4 0.28
0.5 0.5
0.6 0.68
0.7 0.82
0.8 0.92
0.9 0.98
1 1
1.1 0.98
1.2 0.92
1.3 0.82
1.4 0.68
1.5 0.5
1.6 0.28
1.7 0.02
1.8 -0.28
1.9 -0.62
2 -1
C# Types 106
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Again, let us plot this function and see how its graph reflects its behavior:
In both cases, the function reaches an extreme value (either a minimum or a
maximum) that is represented graphically by a point called the vertex of the
parabola having an abscissa x = b/2a and an ordinate y = f(b/2a).
You probably noticed that a parabola is concave in some direction. This is why
we define the direction of the parabolas concavity. In fact, the sign of a contrib-
utes to the concavitys direction. If a is positive, as it is the case in the first exam-
ple, then the concavity is directed upward. When a is negative, as the second
example shows, it is directed downward.
In order to find if the parabola intersects with the x-axis (horizontal axis) and to
determine the coordinates of the intersection points, we need to introduce the
method of solving a quadratic equation. The solution of the quadratic equation
f(x) = 0 supplies us with the abscissas of the intersection points with the x-axis
when they exist and tells us when no such intersection points exist. The ordi-
nates of the intersection points with the x-axis are equal to zero.
Solution of a quadratic equation ax
2
+ bx + c = 0
First, solving an equation means determining the values of the unknown(s) that
validates the equation. In this case, some simple algebra tricks may serve us well
in finding the value(s) of x that verifies ax
2
+ bx + c = 0 when they exist.
ax
2
+ bx + c = 0 ax
2
+ bx = c (subtracting c from both sides)


x
b
a
x
c
a
2
+ =

(dividing both sides by a)
x
b
a
x
b
a
c
a
b
a
2
2 2
2 2
+ +

= +

(add
b
a 2
2

to

both sides) x
b
a
b ac
a
+

=

2
4
4
2
2
2
(the left side being of the form a
2
+ 2ab + b
2


can be written as (a+b)
2
).
The left hand side of the form above is nonnegative (being squared); therefore,
this form of the equation cannot be legal unless the right hand side is
C# Types 107
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3

nonnegative, that is, if b
2
4ac 0. Notice that if a
2
= b a b = because
b b b
( )
=
( )
=
2 2
.
Then x
b
a
b ac
a
x
b
a
b ac
a
x
b b ac
a
+ =

=

=

2
4
4 2
4
2
4
2
2
2
2 2
Consequently, under the condition that b
2
4ac 0, we have two values of x that
serve as solutions for the quadratic equation. In the special case where b
2
4ac =
0, both solutions will be equal to b/2a. On the other hand, if b
2
4ac < 0, then
the equation has no solution.
The question now is how can we translate the solution of the quadratic equation
f(x) = 0 into a geometric data about the intersection of the curve of f(x) with the
x-axis. This task is very easy. One of three cases may arise.
Case 1: b
2
4ac > 0
The parabola intersects with the x-axis in
two points: and .
Case 2: b
2
4ac = 0
The parabola intersects with the x-axis in one point: .
Case 3: b
2
4ac < 0
The parabola does not intersect with the x-axis.
Now you are ready to solve any problem that is similar to this one. Moreover, you
can execute a graphical interpretation of the solution that you get.
Sol ut i on
1. Determine the coefficients a, b, and c of the quadratic equation
f(x) = ax
2
+ bx + c.
2. Check if a is different than zero. If this is true, you may continue. Otherwise,
the equation you are dealing with is not a quadratic equation.
3. Calculate the coordinates of the vertex of the parabola, which are given by:

b
a
a
b
a
b
b
a
c
2 2 2
2
, .
4. Check the sign of a to find whether the concavity of the parabola is directed
upward or downward. If a is positive, then the parabolas concavity is directed
upward.
+

b b ac
a
2
4
2
0 ,

b b ac
a
2
4
2
0 ,

b
a 2
0 ,
C# Types 108
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
5. Calculate the discriminant = b
2
4ac.
6. If is positive, then there are two intersection points with the x-axis:

+

b
a

2
0 ,
and

b
a

2
0 ,
.
7. If = 0, the only intersection point with the x-axis is the vertex .

b
a 2
0 ,
8. If < 0, then the parabola does not intersect with the x-axis.
Lessons Lear ned
After solving this problem:
I can recognize the characteristics of a parabola.
I know the relation between a quadratic equation and a parabola.
I learned a simple, step-by step method of determining the characteristics of
a parabola.
I can implement this method in a computer programming algorithm.
I developed the skills of finding the vertex of a parabola, its intersection
point(s) with the x-axis (if any exist), and the direction of the parabolas
concavity.
I can accomplish the task of finding the characteristics of a parabola is easier
more easily because it was broken down into several simple steps.
I will remember this method faster because it was described verbally and
visually.
The C# appr oach
The above math problem was solved using a purely scientific approach. Now you
need to solve it using C#. The output should be similar to the following:
3.4.2 Mat h Pr obl em
Find a method to find the equation of a line passing by two points A(xA,yA) and
B(xB,yB). Write a program that implements your method. The output should be
similar to the following:
C# Types 109
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.4.3 Mat h Pr obl em
Find a method to give the equation of a line passing by a point A(xA,yA) and
having a slope m. Write a program that implements your method.
Fl ow Char t
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
Precalculus math book
Appr oach
Some solve this problem automatically by applying the formula, but if you would
like to understand the concept behind the solution, you should have a good
understanding of the slope of a straight line is indispensable.
The equation of a straight line that emphasizes the slope is of the form y = ax + b.
However, the slope of a straight line represents the response of the line to a
change of one unit in the independent variable x. In other words, when x
increases by 1 (from x0 to x0 + 1), y responds by changing from a certain value
y0 to another value y0 + m.
C# Types 110
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
We will try to determine the relation between the coordinates of the points that
belong to a line of slope m that passes through the point (xA,yA). This relation
turns out to be the equation of a straight line:
Let M(x,y) be an arbitrary point on the line. To get from point A to point M, we
move x xA units to the right. As a result of this change, y will increment by m(x
xA) units. It is a linear relation: if for every unit y changes to y + m, then for
every x units, y changes to y + mx.
As a result, y = yA + m(x xA) = mx + yA mxA. Since the point M(x,y) is arbi-
trary, then it can represent any point on the line and the relation between x and y
(the coordinates of M) may represent the relation between the coordinates of any
point on this line. As a consequence, the relation that we just established is the
equation of the line having a slope m that passes through the point (xA,yA).
You are now ready to tackle the problem more easily and effectively because you
understand the real meaning of the problem and are no longer simply a user of
the formula. This will also help you in solving any similar problem.
Sol ut i on
1. Find the slope m of the line.
2. Find a point having the coordinates (xA,yA) that belongs to the line.
3. Write the equation y = mx mxA + yA, and simplify it.
4. The simplified form of the equation above represents a simple form of the
equation of the line passing by (xA,yA) and having a slope m.
Lessons Lear ned
After solving this problem:
I recognized what the slope of a straight line is.
I know how to find the equation of a straight line when I have a point on the
line and the slope of the line.
C# Types 111
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
I learned a simple, step-by-step method of determining the equation of a
straight line of slope m that passes through the point (xA,yA).
I can implement this method in a computer programming algorithm.
I can accomplish the task of finding the equation of a straight line of slope m
and passing by the point (xA,yA) more easily because it was broken down
into several simple steps.
I will remember this method faster because it was described verbally and
visually.
The C# appr oach
The above math problem was solved using a purely scientific approach. Now you
need to solve it using C#. The output should be similar to the following:
3.4.4 Mat h Pr obl em
Write a program that takes an angle in degrees as input and trans-
forms it to radians. The output should be similar to the following:
3.4.5 Mat h Pr obl em
Write a program that takes an angle in radians as input and transforms it to
degrees. The output should be similar to the following:
C# Types 112
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.4.6 Mat h Pr obl em
Write a program that takes the length of two sides of a right triangle, chooses the
greatest one to be the hypotenuse, and generates the length of the third side.
Fl ow Char t
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
Euclidean geometry math book
Appr oach
Although the application of the Pythagorean theorem in a right triangle is easy
to perform, it is important to understand how to prove this theorem. This will
remind you of some important geometric rules and prevent you from feeling that
such a theorem has to be applied blindly.
C# Types 113
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Consider a square S. Inscribe in S another square S:
Consider the two upper right triangles shown in the figure above.
1. Their respective hypotenuses are equal because they are both edges of the
inner square.
2. + = 90
+ = 90
+ = 90
+ = + = and + = + = .
The triangles have an side and two equal angles; therefore, they are congruent.
This leads us to conclude that a = d and b = c. By the same logic, all four right tri-
angles are congruent. The figure can be set as follows:
On one hand, the area of the square is equal to the area of the small square plus
the areas of the four right-angled triangles, and equal to (a + b)
2
on the other

hand. The area of each of the four right triangles is equal to
a b
2
, and the area of
the inner square is equal to s
2
.
Consequently,
a b
a b
s + ( ) =

+
2
2
4
2
a b ab ab s
2 2 2
2 2 + + = +
a b s
2 2 2
+ =
C# Types 114
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3

Therefore, we proved the Pythagorean theorem.
At the same time, you are now able to deal with any problem involving a right
triangle with a missing sides length.
Sol ut i on
1. Find the length of each of the two sides.
2. Compare them to find the longest one.
3. Set the longest one to be the hypotenuse of the right triangle.
4. Apply the Pythagorean theorem in right triangles to find the length
of the third side.
Lessons Lear ned
After solving this problem:
I recognized the Pythagorean theorem.
I know how to find the length of the third edge of a right-angled triangle
once I know the length of each of the other two edges.
I learned a simple, step-by-step method of calculating the length of the third
edge of a right triangle once I know the length of each of the other two sides.
I can implement this method in a computer programming algorithm.
I can accomplish the task of finding the length of the third edge of a right
triangle once I know the length of each of the other two edges more easily
because it was broken down into several simple steps.
I will remember this method faster because it was described verbally and
visually.
The C# appr oach
The above Math problem was solved using a purely scientific approach. Now you
need to solve it using C#. The output should be similar to the following:
C# Types 115
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.4.7 Phy si cs Pr obl em
Write a program that takes as input the speed and mass of a certain moving body
and returns its kinetic energy and its momentum. The output should be similar
to the following:
3.4.8 Chemi st r y Pr obl em
The combustion of an alkene of general formula C
n
H
2n
produces carbon dioxide
and water according to the reaction:
C H O CO H O
n n
n
n n
2 2 2 2
3
2
+ + . Write a program that takes as input the

number of carbon atoms in the alkene, n, and returns the number of oxygen
molecules (O
2
) that one molecule of this alkene needs in order to be burned. The
output should be similar to the following:
3.4.9 Chemi st r y Pr obl em
The combustion of an alkyne of general formula C
n
H
2n-2
produces carbon diox-
ide and water according to the reaction:

C H O CO H O
n n
n
n n
2 2 2 2 2
3 1
2
1

+

+ ( )
. Write a program that takes as input

the number, n, of carbon atoms in the alkyne and returns the number of oxygen
molecules (O
2
) that one molecule of this alkyne needs in order to be burned. The
output should be similar to the following:
C# Types 116
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.5 THE TEXT- BASED GAME
Game Design Overview
The game environment is a virtual city that simulates the FUN Editor environ-
ment. The goal is to be able to successfully build and run a game with all the
required assets, just as in the actual FUN Editor.
This is a simple text-based game that accepts one or two words, such as GoTo
Game, as input. When a word is recognized by the program, a textual message is
displayed depending on the location of the player at that moment. Input is
strictly through the keyboard. The first letter of every word is in uppercase
(GameAssets and SpritesCity).
The player will start the game having an amount of money of $1500 and should
build a game and run it before spending the whole amount. The money will
decrease by a certain amount according to the action completed:
Buying a frame will cost $30.
Buying a background will cost $60.
Every create or add action will cost $40.
Taking a taxicab will cost $50.
Taking a train will cost $100.

Below is a sample game run:
<GoTo GameAssets>
You are in GameAssets.
You can go to: BackgroundsStore, FramesStore, ActorRoom.
Or you can take a taxicab to Game, and this will cost you $50.
Your current balance is $1450.
<GoTo Game>
You are in Game.
You can go to: LevelTrainStation, RunCenter. Or you can take a taxicab to Game-
Assets, and this will cost you $50.
Your current balance is $1400.
An inventory, contains the following items over the course of the game:
BackgroundImageMap
FrameImageMapCollision
MoneySprite
ActorsAnimation
AnimationsCollision
FramesEffect
FrameCollisionsDisplacement
The parser will understand the following inputs:
GoToBuy
CreateAdd
LookRun
InventoryHelp
C# Types 117
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Locations:
Start = Game
GameAssets
FramesStore
BackgroundsStore
ActorRoom
AnimationRoom
FrameRoom
CollisionRoom
RunCenter
LevelTrainStation
SpritesCity
AnimationBld
CollisionBld
EffectsBld
DisplacementsBld
MapsCity
MapCollision
Gameplay Design Instructions
Here are the details for the text and options available, at each location:
Game:
Look = You are in Game
You can go to: LevelTrainStation, RunCenter.
Or you can take a taxicab to GameAssets, and this will cost you $50.
GoTo GameAssets
GoTo RunCenter
GoTo LevelTrainStation
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Add, Run and List
GameAsset s:
Look = You are in GameAssets.
You can go to: BackgroundsStore, FramesStore, ActorRoom.
Or you can take a taxicab to Game, and this will cost you $50.
GoTo BackgroundsStore
GoTo FramesStore
GoTo ActorRoom
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Add, Run and List.
C# Types 118
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Fr amesSt or e:
Look= You are in FramesStore.
You can go to: GameAssets
Or you can buy some frame images for $30 each.
GoTo GameAssets
Buy FrameImage
List Frames
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Create, Add and Run.
Back gr oundsSt or e:
Look= You are in BackgroundsStore.
You can go to: GameAssets
Or you can buy some background images for $30 each.
GoTo GameAssets
Buy BackgroundImage
List Backgrounds
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Create, Add and Run.
Act or Room:
Look = You are in ActorRoom.
You can go to: GameAssets or AnimationRoom.
Creating an actor will cost $40.
GoTo GameAssets
GoTo AnimationRoom
Create Actor (You enter the name of the actor)
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Add, Run and List.
Ani mat i onRoom:
Look = You are in AnimationRoom.
You can go to: ActorRoom or FrameRoom.
Creating an animation will cost $40.
GoTo ActorRoom
GoTo FrameRoom
Create Animation (You enter the name of the animation)
C# Types 119
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Add, Run and List.
Fr ameRoom:
Look = You are in FrameRoom.
You can go to: AnimationRoom or CollisionRoom.
Adding a frame will cost $40.
GoTo AnimationRoom
GoTo CollisionRoom
Add Frame (you should have a FrameImage)
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Run and List.
Col l i si onRoom:
Look = You are in CollisionRoom.
You can go to: FrameRoom or ActorRoom.
Adding a collision data will cost $40.
GoTo FrameRoom
GoTo ActorRoom
Add Collision
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Run and List.
RunCent er :
Look = You are in the RunCenter.
You can go to the Game.
You can run the game when it is complete.
GoTo Game
Run Game
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Add and List.
Level Tr ai nSt at i on:
Look = You are in LevelTrainStation.\nYou can go to: Game, SpritesCity or Map-
sCity for $100.
GoTo Game
GoTo SpritesCity
C# Types 120
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
GoTo MapsCity
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Add, Run and List.
MapsCi t y :
Look = You are in MapsCity.
You can go to: CollisionBld or LevelTrainStation for $100.
GoTo CollisionBld
GoTo LevelTrainStation
Create Map (you should have a FrameImage)
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Add, Run and List
MapCol l i si on:
Look = You are in MapCollision.
You can go to: MapsCity. ANY COST?
GoTo MapsCity
Add Collision
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Run and List.
Spr i t esCi t y :
Look = You are in SpritesCity.
You can go to: AnimationBld, CollisionBld, EffectsBld, DisplacementBld or Level-
TrainStation for $100.
GoTo AnimationBld
GoTo CollisionBld
GoTo AnimationBld
GoTo AnimationBld
Create Sprite
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Add, Run and List.
Ani mat i onBl d:
Look = You are in AnimationBld.
You can go to: SpriteCity or CollisionBld.
Adding an animation will cost $40.
C# Types 121
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
GoTo SpriteCity
GoTo CollisionBld
Add Animation
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Run and List.
Col l i si onBl d:
Look = You are in CollisionBld.
You can go to: SpriteCity, AnimationBld or EffectsBld.
Adding a collision data will cost $40.
GoTo SpriteCity
GoTo AnimationBld
GoTo EffectsBld
Add Collision
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Run and List.
Ef f ect sBl d:
Look = You are in EffectsBld.
You can go to: SpriteCity, CollisionBld or DisplacementBld.
Adding a reflection effect will cost $40.
GoTo SpriteCity
GoTo CollisionBld
GoTo DisplacementBld
Add Effect
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Run and List.
Di spl acement Bl d:
Look = You are in DisplacementBld.
You can go to: SpriteCity or EffectsBld.
Adding a speed and a vector direction will cost $40 each.
GoTo SpriteCity
GoTo EffectsBld
Add Displacement
Inventory = [list inventory]
Help = [list parser commands]
Invalid parser commands: Buy, Create, Run and List.
C# Types 122
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Scr eenshot of t he Ci t y :
3.6 TYPES USED I N THE TEXT- BASED GAME
In this game, we have used several C# types according to the game's needs:
enum: We have two enumerations: the verbs enumeration and the nouns enu-
meration.
int: We have many integer declarations, the most important are:
int VERBSIZE = 8;
int NOUNSIZE = 36;
bool solved=false;
struct: We have only one structure:
public struct sInventory
{
public int values;
public bool available;
public String name;
};
char: We have only one char declaration in this game:
char[] sep = {' '};
string: Mainly we have five strings defined as follows:
1. String inputBuffer = null, token1 = null, token2 = null;
2. String[] verb = {"GoTo","Buy","Create",
"Add","Look","Run","Inventory","Help"};
3. String[] noun =
C# Types 123
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
{
"Invalid","GameAssets","FramesStore",
"BackgroundsStore","ActorRoom","AnimationRoom",
"FrameRoom","CollisionRoom","Game","RunCenter",
"LevelTrainStation","MapsCity","CollisionBld","SpritesCity",
"EffectsBld","DisplacementBld","BackgroundImage",
"FrameImage","Money","Actor","Animation","Frame",
"Collision","FrameCollision","Backgrounds","Frames",
"Map","MapCollision","Sprite","sAnimation","sCollision",
"sEffect","sDisplacement","AnimationBld","Effect",
"Displacement"
};
Where Can I Find the Text-Based Game?
This game is available in a folder named Text Based Game. In this folder, the
complete game is available in a subfolder: TBG Complete. The Text Based
Game folder also includes five other subfolders named TBG Part1, TBG Part2,
TBG Part3, TBG Part4, and TBG Part5. Each of these subfolders contains an
incomplete version of the game. In later chapters you will add code to these ver-
sions as part of the exercises provided.
3.7 THE WI NDOWS- BASED GAME: BRI X
Game Design Overview
As its name implies, this is a Windows-based game named Brix. It is a classic
bricks game where the player manipulates a pad that moves horizontally. The
pad can move right and left using the Right and Left arrow keys. The ball rests on
the pad. When the Spacebar is pressed, the ball begins moving. When the ball
hits a brick, the brick reflects the ball and vanishes. When all the bricks are hit,
the game is over.
C# Types 124
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
From the player's point of view, it is a simple, classic game, but from the
designer's point of view, it represents a big challenge. The designer has to start
from scratch. All the game logic and design must be built step-by-step. A screen
shot of the final game is shown below:
3.8 TYPES USED I N THE BRI X GAME
Several basic C# types are needed in this game, namely:
int: int left1, right1, bricksNb;
bool: bool free, one, gameOver;
float: float xdirection, ydirection, ballSpeed, padSpeed;
struct:
public struct line
{
public int x1, x2, y1,y2;
}
public struct rect
{
public line top, right, bottom, left;
public bool active;
}
The use of each variable will be explained in detail in the next chapter.
Where Can I Find the Brix Game?
This game is available in a folder named Brix.
C# Types 125
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.9 I NTRODUCTI ON TO FUN EDI TOR.NET
As a game development tool, FunEditor.Net has two major components:
FunEngine and FunEditor. FunEditor is the visual aid tool that helps users
develop games that will run with the FunEngine. This can be accomplished in a
short period of time with minimal hassle and without the need to acquire
advanced programming skills. Given its simplicity, FunEditor.Net aids non-tech-
nical users to enjoy producing 2D games that look and feel like games produced
by professional game developers. Think of the Editor as the intermediary
between you (the developer) and the FunEngine. It simply provides the tools that
help to define a game in terms of FUN objects. It produces code required by the
engine to run. It also saves a lot of time by providing visual tools that will facili-
tate specifying countless coordinates needed for moving objects or for defining
the collision points.
Many other features offered by this tool make game development much more
fun.
3.10 THE FUN EDI TOR GAME: CAVES OF DOOM
3.10.1 Pur pose
In this side-scrolling shoot-em-up game, you play a space pilot who must evade
and destroy an alien horde, bypass an electrical field, and defeat the final master
spaceship to save a planet from destruction.
Along with enjoying the exciting action of playing the game, we will teach you
how to develop games like this where you learn how to:
Detect movement patterns to evade enemies.
Shoot electrodes to disable electrical fields.
Create enemies that take multiple hits to destroy.
Get secret cheats to gain finite invulnerability after your ship is first destroyed.
Set collision.
Apply movement patterns.
Use streamed sound.
Caves Of Doom shows you how to create very large vanquishing-the-enemy and
flying-in-space games and teaches you the programming and design skills to cre-
ate enemies of various strengths. You will also learn how to make your enemies
behave in various ways to confuse your players and add replay ability to increase
their desire to complete your games.
3.10.2 Hi gh Concept
Side-scrolling shooter where you must destroy as many enemies as possible and
then defeat the evil one.
3.10.3 Mi ni mum Sy st em Requi r ement s
FunEditor, DirectX8 compatible 16-bit video card or higher, 128 MB of RAM, 20
MB of hard disk space.
C# Types 126
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.10.4 Pl ot Over vi ew
This game follows the further adventures of the intrepid space pilot Trask Van
Der Veer and his trusty ship Cowboy. Trask has now made it through the surface
of the planet and is headed deep within its interior in an attempt to defeat the
alien overlord.
In the very beginning, Trask has to eliminate


The fleet
of Mutants,

followed by
several
formations
of Landers.
The conquest does not stop here, but it continues

with an
invasion of
Baiters.


As the
invasion
ends, laser
barriers
designed to
prevent any
intrusion
will inter-
cept the
heros
advance.
C# Types 127
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
If our hero overcomes the laser barriers



the fearless Swarmer
knights will defend the
evil one with their lives.


After abolishing the
Swarmers, Trask is up
against the evil one in
the ultimate duel.


This
changes
your design
aspects as
now you
are more
interested in
making sure
that your
players can
see on the
horizontal
axis rather
than the
vertical.
Game Design Overview
In this game we will be dealing with a scrolling shooter; we will approach side-
scrollers as opposed to top-down scrolling shooter games.
C# Types 128
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Side-scrolling games have some similarities to top-down games, but also with
significant differences. First, your players perspective for the game is different:


instead of looking at
the roof of the ship they
are now looking at the
side view.
Another aspect of side-scrollers covered in this game is the tactic of creating
enemy groups that can swarm an opponent. By creating movement patterns that
follow pre-determined paths, we can create the illusion of alien ships following
orders as formations instead of acting independently. This is a trick to give our
games the appearance of artificial intelligence while not requiring the coding
skill to accomplish this.
Along with the aspects of ship movement patterns and various levels of alien
intelligence, in designing side-scrollers you will also learn how to introduce mul-
tiple levels into your games. For Caves Of Doom we will be using four levels.
(When we refer to levels we are talking about the way FunEditor handles differ-
ent areas in your game.)
The introduction level (Level 1) shows you once again how to begin your games
for your players. In Level 1, we will deal with player input with only two sprites:
Exit and Start. The player can toggle between these two sprites to select the
option required.
The Up and Down arrow keys manage toggling. If the player chooses the Start
option, the game will jump to the playing level. If the player chooses the Exit
option, the game will exit. This will show you how to allow your players to easily
exit the game if they wish.

Level 1: The
Introduction
Level
C# Types 129
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
In the playing level (Level 2), the player has to destroy all the enemies that are
trying to shoot and destroy him.

Level 2:
The Playing
Level
The actual playing level contains two aspects regarding the manipulation of
maps: the wrapping map moves at a certain speed to produce a parallax effect;
the main map is not visible.
Why do we create two different maps that move at different speeds? This gives
the players the illusion of depth in our game. Run the game and play it for a
while notice how it feels like the planet you see in the background is very far
away compared to Trasks space ship.
This is how arcade games achieve this effect. Multiple maps are also widely used
in fighting games to make it look like the area that the opponents are in is larger
than it really is. They also allow us to make it look like the world is three-dimen-
sional when in reality it is just a flat two-dimensional representation.
The success level (Level 3) shows you how to reward your players with informa-
tion upon the completion of a particular level.


Level 3: The
Success Level
C# Types 130
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
In addition, a table indicates the number of Mutants, Landers, Baiters, and
Swarmers destroyed as well as the number of points scored. Finally, the players
total score is shown.
Scores are important to players so they can boast about how well they did on
your game and compare their skills with each other. Having a table encourages
players to come back to replay your game to see if there is any way to increase the
number of each enemy type they destroyed.
An advanced trick that you might want to try on your own is to create what is
called a par list of scores. This means that you, as the designer, determine and
list the average number of each enemy that should be destroyed. If a player gets
over this par number, reward him or her with extra points.
C# Types 131
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Level 4 is the Game Over level and consists of only two sprites: Exit and Start.
The player can toggle between these two sprites to select the option required.
The Up and Down arrow keys manage toggling. If the player chooses the Start
option, the game will jump to the introduction level. If the player chooses the
Exit option, the game will exit.

Level 4:The
Game Over Level
Now let us talk about some additional concepts to build on the initial levels of
Caves Of Doom to increase the challenge and playability of the game.
One component to shooter games (especially in space) is the concept of shields.


Shields are an important
balancing component.
The number of shields that you give to a player can be used to balance the diffi-
culty of a level. Too tough? More shields can be a quick fix. But remember: it is
still a quick fix. It is better to balance the number of opponents so that shields
can be saved for the bosses at the end of your levels.
Another tactic to consider is grouping opponents together in sets to create
waves of enemies attacking your player. As you can see, all the opponents that
attack in waves require the same number of normal hits to explode, but give dif-
ferent numbers of points to the player as a reward. Why? As a designer you want
to weigh the difficulty of an opponent and reward your players with more points
for enemies that are harder to hit because of either speed or maneuverability.
C# Types 132
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
Now let us discuss how to handle the barriers. If players get through these with-
out getting hit by one of them, then they will be granted a bonus that will restore
all the health, lives, and shields to their maximum capacity.
Why give such a large reward for simply surviving? This is an example of a nav-
igational puzzle in an arcade game. A navigational puzzle is where the designer
creates a maze that the player must fly through that is filled with danger. Since it
is so difficult, successful completion should be rewarded.


Now what about the
Big Boss?
First some statistics about the Big Boss. This sprite has an up and down move-
ment pattern. It shoots two different kinds of weapons: a laser beam for a certain
amount of time, as well as two bombs that follow the jetfighter sprite, which will
explode after 80 hits. Every hit increments the score by 100. When the boss
blows up, the score will increment by 1000.
Bosses should be tougher to kill than the first enemies players face. However,
remember that they must not be impossible to kill or nobody will want to play
your game. Once again, as a designer, balancing the various strengths and weak-
nesses of the enemies that players will face is important so players will enjoy your
game.
Another trick to know about is invisible sprites. An invisible sprite is used by the
designer to set key points where magic effects or events happen to the player.
This programming trick allows the designer to reward the player without a visual
cue.
This concludes our introduction to Caves Of Doom. The designer has a tough
task with this style of game, but the payoff is that your players will want to come
back again and again for the challenges that you design for them to overcome.
3.11 TYPES USED I N CAVES OF DOOM
Before talking about the types used in this game, let us have a look on a FUN
Editor concept called global data. As the name implies, this is a section under
FUN Editor dedicated to creating and implementing global data types:
C# Types 133
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.11.1 Addi ng Gl obal Dat a
There are two ways to add global data under FUN Editor:
Project Resources
1. Right-click the Global Data icon in the tree.
2. Select Add.
The Global Data Properties dialog box will appear.
Project Toolbar
1. In the toolbar, click Global Data.
The Global Data Properties dialog box will appear.
3.11.2 Edi t i ng Gl obal Dat a
To edit global data:
1. Assign a name to the global data object.
2. Set the type of this global data object, as follows:
Variable:
Normal variable:
Set the type of the variable: char, int, float,.
Set the initial value.
Array:
Click the Array checkbox.
Set the Type of the variable: char, int, float,.
Set the Dimensions (a maximum of 3).
Structure:
Set the Name of the structure.
Set the Body of the structure.
Class:
Set the Name of the class.
Set the Body of the structure.
Remember to place the function definition inside the class definition;
in other words, use the in-line member functions technique.
3.11.3 Accessi ng Gl obal Dat a
There are two ways to access global data:
Right-click
1. Right-click the desired global data in the game tree.
2. Select Properties.
Double-click
1. Double-click the desired global data in the game tree.
2. The Properties dialog box will appear.
C# Types 134
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.11.4 Del et i ng Gl obal Dat a
To delete a global data item:
1. Right-click the desired global data in the game tree.
2. Select Delete.
3.11.5 Ref er enci ng Gl obal Dat a
To reference a global data type, type the word GlobalData followed by a dot .
followed by the name of the global data (Example: GlobalData.bonus).
3.11.6 Gl obal Dat a i n t he Game
Many C# types are used in the game:
Integer: the integer type is a very popular and used type; almost any application
or game uses this type.
Boolean
Structure
Where Can I Find Caves Of Doom?
This game is available in a folder named Caves Of Doom. The folder includes
eight subfolders:
Caves Of Doom Complete: Contains the game in its final and
complete version.
Chapter3: Contains an incomplete version of the game, which is used in Chap-
ter 3 within a section named Adding Code to Caves Of Doom.
Chapter4: Contains an incomplete version of the game. This version is used in
Chapter 4 within a section named Adding Code to Caves Of Doom.
Chapter5: Contains an incomplete version of the game. This version is used in
Chapter 5 of this document, within a section named Adding Code to
Caves Of Doom.
Chapter6: Contains an incomplete version of the game, which is used in Chap-
ter 6 of this document within a section named Adding Code to
Caves Of Doom.
Chapter7: Contains an incomplete version of the game. This version is used in
Chapter 7 of this document within a section named Adding Code to
Caves Of Doom.
Chapter8: Contains an incomplete version of the game, which is used in Chap-
ter 8 of this document within a section named Adding Code to
Caves Of Doom.
Chapter9: Contains an incomplete version of the game. This version is used in
Chapter 9 of this document within a section named Adding Code to
Caves Of Doom.
C# Types 135
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
3
3.12 ADDI NG CODE TO CAVES OF DOOM
In this section, we will add code to an unfinished version of Caves Of Doom and
then run it to see the changes taking effect.
1. With FunEditor.Net, open the file called CavesOfDoomChapter3.fun.
Note: This version is not a working version of the game. Attempting to run
it as is before adding the appropriate code will generate errors.
2. After opening the game under the Project Resources window, right click
Global Data, and from the pop-up menu select Add
A Global Data Properties New window will open.
3. In Name type planeY You must type the name exactly as is.
4. For Type, select int.
5. Type 0 for Initial Value.
6. Click OK to save and close the window. A new global data called planeY
is added under Global Data in the Project Resources window.
7. Click the Run icon, then click Yes.
The game will run.
4
VARI ABLES
Variables 137
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
VARI ABLES
In C#, a variable represents a storage location. A variable has a type that deter-
mines what values can be stored in this variable. Because C# is a type-safe lan-
guage, the C# compiler guarantees that values stored in variables are always of the
appropriate type. The value of a variable is changed through the assignment opera-
tor and through the use of the ++ and -- operators. A variable must be
definitely assigned before its value can be obtained: variables are either
initially assigned or initially unassigned. An initially assigned variable has a well-
defined initial value, while an initially unassigned variable has no initial value.
4. 1 CATEGORI ES OF VARI ABLES I N C#
C# has seven categories of variables: static variables, instance variables, array ele-
ments, value parameters, reference parameters, output parameters, and local vari-
ables. The following sections describe each of these categories.
4.1.2 St at i c Var i abl es
A variable, declared with the static keyword, is a static variable. The initial value of
a static variable is the default value of the variables type. A static variable is initially
assigned.
4.1.3 I nst ance Var i abl es
A variable declared without the static keyword is an instance variable. An instance
variable of a class exists when a new instance of that class is created and ceases to
exist when there are no references to that instance and the instances destructor (if
any) has executed. The initial value of an instance variable of a class is the default
value of the variables type. An instance variable of a class is initially assigned.
4.1.3 Ar r ay El ement s
Array elements exist when an array instance is created and cease to exist when
there are no references to that array instance. The initial value of each of the ele-
ments of an array is the default value of the type of the array elements. An array
element is initially assigned.
4.1.4 Local Var i abl es
A local variable is declared within a block, a for-statement, a switch-statement, or a
using-statement. The lifetime of a local variable is implementation-dependent. For
example, the compiler could generate code that results in the variables storage hav-
ing a shorter lifetime than its containing block. A local variable is not automati-
cally initialized and it has no default value. A local variable is initially unassigned.
It is a compile-time error to refer to the local variable in a position that precedes its
declaration.
4.1.5 Val ue Par amet er s
A parameter declared without a ref or out modifier is a value parameter. A value
parameter is initially assigned.
Variables 138
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
4.1.6 Ref er ence Par amet er s
A parameter declared with a ref modifier is a reference parameter. A reference
parameter represents the same storage location as the variable given as the argu-
ment in the function member invocation. Therefore, the value of a reference
parameter is always the same as the underlying variable. A variable has to be def-
initely assigned before it can be passed as a reference parameter in a function
member invocation. A reference parameter is considered initially assigned
within a function member.
4.1.7 Out put Par amet er s
An output parameter is a parameter declared with an out modifier. An output
parameter represents the same storage location as the variable given as the argu-
ment in the function member invocation. Therefore, the value of an output
parameter is always the same as the underlying variable. A variable does not
need to be definitely assigned before it can be passed as an output parameter in a
function member invocation. An output parameter is initially unassigned within
a function member.
4.2 DEFAULT VALUES
Static variables, instance variables of class instances, and array elements are auto-
matically initialized to their default values. The default value of a variable
depends on the type of the variable.
4.3 DI RECT I MPLEMENTATI ONS
4.3.1 Engl i sh Language Pr obl em
Write a program that takes as input these three parameters.
A string // used to store the target string
A char // denotes the character that needs to be changed
A char // denotes the replacing character
The program changes all the characters denoted by the second parameter to the
character denoted by the third parameter. The program should then output the
result of the operation. The output should be similar to the following:
Variables 139
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
4.3.2 Phy si cs Pr obl em
A uniformly accelerating car starts its
trip from rest with a constant accelera-
tion a. How far will the car have
traveled by the time it reaches the
velocity v?
Write a program that takes as input the
acceleration, the velocity that we wish
to reach, and gives the distance traveled as output. The output should be similar
to the following:
4.3.3 Phy si cs Pr obl em
Write a program that takes as input the height
and mass of a certain body and returns its
potential energy. The output should be simi-
lar to the following:
4.3.4 Chemi st r y Pr obl em
One molecule of a certain gas is placed into a
balloon of volume V. The thermometer reads the
temperature T inside the balloon. Write a pro-
gram that takes as input V and T and returns the
pressure P inside the balloon. The output should
be similar to the following:
4.3.5 Chemi st r y Pr obl em
Write a program that takes as input the concentration of a solution in
H
+
ions and returns the pH of the solution. The output should be similar to
the following:
Variables 140
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
4.4 VARI ABLES USED I N THE TEXT- BASED GAME
In this game, we have used various C# types according to the game's needs:
enum: We have two enumerations: the verbs enumeration and the nouns
enumeration, as follows:
enum verbs {GoTo,Buy,Create,Add,Look,Run,Inventory,Help};
enum nouns
{
Invalid,GameAssets,FramesStore,BackgroundsStore,Actor-
Room,AnimationRoom,FrameRoom,CollisionRoom,Game,Run-
Center,LevelTrainStation,MapsCity,CollisionBld,SpritesCity,E
ffectsBld,DisplacementBld,BackgroundImage,FrameImage,Money,A
ctor,Animation,
Frame,Collision,FrameCollision,Backgrounds,Frames,Map,Map-
Collision, Sprite,sAnimation,sCollision,sEffect,sDisplace-
ment,AnimationBld,Effect,
Displacement
};
int: We have many integer declarations, the most important are:
1. int VERBSIZE = 8;
Defines the number of verbs.
2. int NOUNSIZE = 36;
Defines the number of nouns.
3. bool solved=false;
States whether or not the game is solved: as long as this variable is
false, the game is not yet solved.
struct: The struct type is vital in this game. We have only one structure:
public struct sInventory
{
public int values;
public bool available;
public String name;
};
The first member of the structure is an integer called values. This member
defines the actual value of the specified structure. For example, it defines
the value of the money structure, in other words, how much money we
actually have.
The second member is a Boolean called available. This member indicates
whether this specific structure is available or not.
The third member is a String called name. It defines the name of the struc-
ture. From this structure, we are defining 36 instances:
sInventory[] inventory = new sInventory[NOUNSIZE];
char: We have only one char declaration in this game:
char[] sep = {''};
Variables 141
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
This variable serves as follows: when the parser reads a command in a form
of a string, it removes any duplicate(s) of the space character by comparing
the string's characters to this variable.
string: Strings play a key role in this game. Mainly we have five strings
defined as follows:
1. String inputBuffer = null, token1 = null, token2 = null;
The inputBuffer string receives the input command that the player
enters.
The token1 string gets the first word that the player enters.
The token2 string gets the second word (if any) that the player enters.
2. String[] verb = {"GoTo","Buy","Cre-
ate","Add","Look","Run","Inventory","Help"};
The verb string contains the eight verbs that can be used.
3. String[] noun =
{
"Invalid","GameAssets","FramesStore","BackgroundsStore",
"ActorRoom", "AnimationRoom", "FrameRoom", "Collision-
Room","Game","RunCenter", "LevelTrainStation", "MapsCity",
"CollisionBld", "SpritesCity", "EffectsBld", "Displacement-
Bld","BackgroundImage","FrameImage", "Money","Actor","Anima-
tion","Frame","Collision","FrameCollision", "Backgrounds",
"Frames", "Map", "MapCollision", "Sprite", "sAnimation",
"sCollision","sEffect","sDisplacement","AnimationBld",
"Effect","Displacement"
};
The noun string contains all the nouns that the player can use.
4.5 VARI ABLES USED I N THE BRI X GAME
int: int left1, right1, bricksNb;
left1: This integer is used to know when the pad is moving left.
right1: This integer is used to know when the pad is moving right.
bricksNb: This integer is used to know the number of bricks remaining.
bool: bool free, one, gameOver;
free: This Boolean value is used to know if the ball is resting on the paddle
or is moving freely.
float: float xdirection, ydirection, ballSpeed, padSpeed;
In 2D space, the ball will move according to an x-direction (horizontal) and
a y-direction (vertical).
xdirection determines the ball's horizontal direction as follows:
If xdirection is positive, the ball is moving from left to right.
If xdirection is negative, the ball is moving from right to left.
The ydirection determines the ball's vertical direction as follows:
If ydirection is positive, the ball is moving upward.
Variables 142
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
If ydirection is negative, the ball is moving downward.
ballSpeed: Controls and stores the current speed of the ball.
padSpeed: Controls and stores the current speed of the pad.
struct:
public struct line
{
public int x1, x2, y1,y2;
}
The line structure is used to define a line in 2D space. As we know, a line is
defined by two points: p1(x1,y1) and p2(x2,y2).
public struct rect
{
public line top, right, bottom, left;
public bool active;
}
The rect structure defines a rectangle in 2D space. It uses the line structure
to define four lines that form a rectangle. The rect structure defines the rect-
angle that represents a brick. This structure is used to know when the ball hits
a brick. After a ball hits a brick, the brick disappears; that is why we need the
active Boolean to mark the brick as inactive after it is hit.
public rect[,] r;
This array of rectangles represents the 20 bricks available in the game.
public rect ballRect, padRect;
ballRect represents the ball's rectangle.
padRect represents the pad's rectangle.
public Bitmap ballBitmap, padBitmap, brickBitmap;
A Bitmap consists of the pixel data for a graphics image and its attributes.
A Bitmap object is an object used to work with images defined by pixel data.
ballBitmap is the image representation of the ball.
padBitmap is the image representation of the pad.
brickBitmap is the image representation of the brick.
4.6 VARI ABLES USED I N CAVES OF DOOM
4.6.1 Gl obal I nt eger Var i abl es
When one of the arrow keys is pressed, the position of the ship updates, which
means that the x and/or y position of the ship should change. For example, when
the Right arrow key is pressed, the ship should advance right; in other words, the
y-coordinate should be incremented by a specific amount. To keep track of how
Variables 143
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
the ship's position should change at the next game loop, we need two global inte-
ger variables:
planeX: Changes the x-coordinate of the ship. Its initial value is 0. When
the Right arrow key is pressed, its value increments by 3, and when the Left
arrow key is pressed, its value decrements by -3.
planeY: Changes the y-coordinate of the ship. Its initial value is 0. When the
Down arrow key is pressed, its value increments by 3, and when the Up
arrow key is pressed, its value decrements by -3.
Before the ship's position is updated, a check is made to ensure that the ship will
remain in a specified rectangle within the visible window.
In this game, many enemies come to attack the ship. When the ship hits an
enemy, a global integer variable attached to the specific enemy is incremented.
When the game finishes, the value of those variables is totaled to give a final
score. Those variables are:
ld: Stores the points that the player scores for killing the lander enemy. Its
initial value is 0.
mt: Stores the points that the player scores for killing the mutant enemy. Its
initial value is 0.
sw: Stores the points that the player scores for killing the swarmer enemy. Its
initial value is 0.
bt: Stores the points that the player scores for killing the baiter enemy. Its
initial value is 0.
4.6.2 Gl obal Bool ean Var i abl es
Only one Boolean global variable is used the bonus variable. This variable
states whether or not a bonus is allowed. Its initial value is true, which means
that at the start of the play level, bonus is allowed. When the ship collides with
the barrier sprite or when the ship bypasses a certain threshold y-position, the
bonus Boolean becomes false, meaning that no bonus is allowed.
4.6.3 Local Var i abl es
Sometimes we need to store a value for local use. The role of local variables
includes:
Within the state machine of the bigBoss enemy, the value of the current
frame's delay is needed, so a local integer variable called delay is created as
follows:
int delay = This.Delay;
Where This.Delay denotes the delay value of the bigBoss enemy.
Within the function responsible for updating the position of the swarmer
enemy, a local integer variable is needed to hold the difference between the
position of two sprites:
int k = (int) (This.MapPositionY() - sp.MapPositionY());
Where This.MapPositionY() is the y-position of the swarmer sprite, and
sp.MapPositionY() is the y-position of the ship.
Variables 144
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
4.6.4 FUN Var i abl es
FUN variables are global variables only in the level where they are defined. All
the objects in the same level as the variable will be able to access it.
Add
To add a variable:
1. Right-click the Variables icon in the Game tree in the Project Resources
dialog box.
2. Select the Add command.
The Properties dialog will appear.
Edit
Set the type of the variable (Text, Number).
Set a unique name for the variable.
Set the initial value of the variable.
Behavior
To set the Variable Object behavior:
1. Click on the button.
A dialog box will appear.
2. Click the button to add or remove a State Machine or an
Object Function.
3. Click on the OK button to validate the changes.
4. Click on the Cancel button to discard the changes.
Access
To access a variable:
Right-click:
Right-click the desired Variable Object.
From the pop-up menu, select Properties.
or
Double-click the Variables Object.
The Properties dialog will appear.
Delete
To delete a Variable Object:
Right-click the Variable Object.
On the menu, click Delete.
Under Level1, the play level, we have two variables:
stopUpdate: This integer variable lets the bigBoss know to start mov-
ing and attacking after reaching a certain position. Its initial value is 0,
meaning that the bigBoss enemy cannot attack yet.
shieldCounter: When the score reaches 3500, the ship can be sur-
rounded by a shield by pressing Ctrl-K. Also, when the ship bypasses an
invisible sprite called invisible, the shield option is enabled. All this work
is done using the shieldCounter variable. Also, this integer variable
changes the animation of the shield sprite, which gives us the status of
Variables 145
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
the shield. Its initial value is 0, meaning that no shielding is allowed in
the beginning.
4.7 ADDI NG CODE TO CAVES OF DOOM
In this section, we will add some code to an unfinished version of Caves Of
Doom and then run it to see the changes taking effect.
1. With FunEditor.net, open the file CavesOfDoomChapter4.fun.
Note: This version is not a working version of the game. Attempting to run
it as is before adding the appropriate code will generate errors.
2. Open the game under the Project Resources window.
3. Right-click Global Data, and on the menu, click Add
A Global Data Properties New window will open.
4. In the Name Box, type: bonus
5. For Type, select bool.
6. Type true for Initial Value.
7. Click OK
A new global data called bonus is added under Global Data in the Project
Resources window.
8. Click the Run icon, and then click Yes.
If you have done this correctly, the game will run.
4.8 ADDI NG CODE TO BRI X
In this section, we will add code to an unfinished version of Brix and then run it
to see the changes taking effect.
1. With Visual C#.Net, locate and open the project /Brix/Brix Chapter4/
Brix.csproj.
Note: This version is an incomplete version of the game.
2. Locate and open the file called Form1.cs.
3. Under the method
"public class Form1 : System.Windows.Forms.Form"
replace the line:
private bool free, one;
with the line:
private bool free, one, gameOver;
We have now added a new boolean variable called gameOver.
4. Under the method
public Form1()
and after the line:
one = true;
add the following line:
gameOver = false;
Variables 146
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
4
5. Under the method
private void timer3_Tick(object sender,
System.EventArgs e)
and before the line:
timer3.Enabled = false;
add the following line:
gameOver = true
6. Under the method
private void Form1_Paint(object sender, System.Win-
dows.Forms.PaintEventArgs e)
replace the line:
if (false)
with the following line:
if (gameOver)
7. Save and run the game.
When all the bricks are hit, the game can now end by displaying the correct
message.
5
I NPUT and
OUTPUT
I nput and Out put 148
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
I NPUT and OUTPUT
Input devices, like the keyboard and mouse, let a user send input to the computer.
Input is essential when the user wants to give some information to an application
or wants to choose an item from a list of available choices. In a game, input can be
the direction of the player, a gunshot, or an order to jump. In our example, input is
taken from the keyboard only.
Output usually gives the result of an operation in a calculation program, or gives
the visual outcome of a game, reflecting all changes made by the game play. Out-
put devices essentially include the screen and the printer. In this curriculum, we
deal with the screen as the output device.
5.1 THE CONSOLE CLASS
This class represents the standard input, output, and error streams for console
applications. The console class provides support for applications that read charac-
ters from, and write characters to, the console. Data from the console is read from
the standard input stream, while data to the console is written to the standard out-
put stream. The console class contains methods that read individual characters or
entire lines from the console. The console class contains many write methods that
write the formatted string to the console.
5.2 OUTPUT: THE CONSOLE.WRI TE METHOD
The console.write method writes the specified information to the standard output
stream. By default, the output stream is the computer's screen.
Overload List (most-used methods):
Writes a Boolean value to the standard output stream:
public static void Write(bool);
Writes a Unicode character value to the standard output stream:
public static void Write(char);
Writes an array of Unicode characters to the standard output stream:
public static void Write(char[]);
Writes a Decimal value to the standard output stream:
public static void Write(decimal);
Writes a double-precision floating-point value to the standard output stream:
public static void Write(double);
Writes a 32-bit signed integer value to the standard output stream:
public static void Write(int);
Writes a 64-bit signed integer value to the standard output stream:
public static void Write(long);
Writes a floating-point value to the standard output stream:
public static void Write(float);
Writes a string value to the standard output stream:
public static void Write(string);
I nput and Out put 149
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
5.3 OUTPUT: THE CONSOLE.WRI TELI NE METHOD
The console.writeline method writes the specified data followed by the current
line terminator, to the standard output stream. The only difference between this
method and the console.write method is the line terminator (the cursor) auto-
matically goes one line down after calling this method. This method has the
same overload list as the console.write method.
5.4 I NPUT: THE CONSOLE.READ METHOD
The console.read method reads the next character from the standard input
stream:
public static int Read();
The return value is the next character from the input stream or negative one (-1)
if no more characters are available. This method does not return until the read
operation is terminated, for example, by the user pressing the return key.
Ex ampl e:
int i;
i = Console.Read ();
Console.WriteLine ("{0}", (char) i);
5.5 I NPUT: THE CONSOLE.READLI NE METHOD
The console.readline method reads the next line of characters from the standard
input stream:
public static string ReadLine();
The return value is the next line from the input stream or a null reference if no
characters are available. The returned string does not contain the terminating
character(s).
5.6 GDI +
GDI+ is an application programming interface (API) for Windows program-
mers. It enables applications to use graphics and formatted text on both the
video display and the printer. Instead of accessing the graphics hardware directly,
GDI+ interacts with device drivers on behalf of applications based on the
Microsoft Win32 API. GDI+ can be used in all Windows-based applications.
5. 7 A GDI + CLASS: THE GRAPHI CS CLASS
The graphics class provides methods for drawing lines, curves, figures, images,
and text. A graphics object stores attributes of the display device and attributes of
the items to be drawn.
I nput and Out put 150
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
5.7.1 Dr aw I mage Met hods
The most important and most used method in the graphics class are the Draw-
Image methods. These methods enable the drawing of images inside the window.
Following is a list of the most used methods:
Status DrawImage(Image *image, const Point *destPoints, INT count);
Parameters:
image: a pointer to an image object that specifies the source image.
destPoints: a pointer to an array of point objects that specifies the area, in a
parallelogram, in which to draw the image.
count: an integer that specifies the number of elements in the destPoints
array.
Return Value:
If the method succeeds, it returns Ok.
If the method fails, it returns InvalidParameter.
1. The value of the count parameter must equal 3 to specify the three
corners of the parallelogram.
2. The fourth corner of the parallelogram is calculated using the vectors of
the first and second coordinates and the first and third coordinates.
3. The image is scaled to fit the parallelogram.
Status DrawImage(Image *image, INT x, INT y);
Parameters:
image: a pointer to an image object that specifies the image to be drawn.
x: an integer that specifies the x-coordinate of the upper-left corner of the
rendered image.
y: an integer that specifies the y-coordinate of the upper-left corner of the
rendered image.
Return Value:
If the method succeeds, it returns Ok.
Otherwise, it returns one of the other elements of the Status enumeration.
Status DrawImage(Image *image, INT x, INT y, INT width, INT height);
Parameters:
image: a pointer to an image object that specifies the source image.
x: an integer that specifies the x-coordinate of the upper-left corner of the
destination rectangle at which to draw the image.
y: an integer that specifies the y-coordinate of the upper-left corner of the
destination rectangle at which to draw the image.
width: an integer that specifies the width of the destination rectangle at
which to draw the image.
height: an integer that specifies the height of the destination rectangle at
which to draw the image.
I nput and Out put 151
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
Return Value:
If the method succeeds, it returns Ok.
Otherwise, it returns one of the other elements of the Status enumeration.
5.7.2 Dr aw St r i ng Met hods
Another important method in the graphics class are the DrawString methods.
They enable the user to display text strings in different formats. Following is a
list of the most used methods:
Status DrawString(const WCHAR *string, INT length, const Font *font,
const RectF &layoutRect, const StringFormat *stringFormat, const Brush
*brush);
Parameters:
string: a pointer to a wide-character string to be drawn.
length: an integer that specifies the number of characters in the string
array. The length parameter can be set to 1 if the string is null terminated.
font: a pointer to a font object that specifies the font attributes (the family
name, the size, and the style of the font) to use.
layoutRect: a reference to a rectangle that bounds the string.
stringFormat: a pointer to a StringFormat object that specifies text layout
information and display manipulations to be applied to the string.
brush: a pointer to a brush object that is used to fill the string.
Return Value:
If the method succeeds, it returns Ok.
Otherwise, it returns one of the other elements of the Status enumeration.
Status DrawString(const WCHAR *string, INT length, const Font *font,
const PointF &origin, const Brush *brush);
Parameters:
string: a pointer to a wide-character string to be drawn.
length: an integer that specifies the number of characters in the string
array. The length parameter can be set to 1 if the string is null terminated.
font: a pointer to a font object that specifies the font attributes (the family
name, size, and style of the font) to use.
origin: a reference to a PointF object that specifies the starting point for the
string.
brush: a pointer to a brush object that is used to fill the string.
Return Value:
If the method succeeds, it returns Ok, which is an element of the status
enumeration.
Otherwise, it returns one of the other elements of the Status enumeration.
I nput and Out put 152
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
5.8 DI RECT I MPLEMENTATI ONS
5.8.1 Phy si cs Pr obl em
Write a program that converts from Fahrenheit to Celsius,
knowing that the formula to convert from Fahrenheit to Celsius
is:
Celsius = (Fahrenheit 32)*5/9
The program takes your input Celsius value, calculates its
equivalence in Fahrenheit, and displays
the following:
Celsius Fahrenheit
c-value f-value
The output should be similar to the following:
5.8.2 Game Desi gn Pr obl em
In your game design, the main character can only perform two offensive moves
initiated by the number of times you right-click and left-click your mouse. Let n
l

be the number of right-clicks and n
r
be the number of left-clicks. If the sum n
l
+
n
r
is even, the character punches; if the sum is odd, it kicks. Write a program that
takes two integer numbers as inputs and tells you whether their sum is even or
odd. This will help in knowing which move your character is going to perform.
The output should be similar to the following:
5.8.3 Chemi st r y Pr obl em
Write a program that takes as input the number of molecules of
a chemical compound and the volume of water in which it is
dissolved and returns as output the concentration of the solu-
tion formed.
The output should be similar to the following:
I nput and Out put 153
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
5.8.4 Chemi st r y Pr obl em
Write a program that takes as input the mass and volume of a
certain chemical compound and returns as output its density.
The output should be similar to the following:
5.8.5 Phy si cs Pr obl em
Write a program that takes as input the
distance that a car travels and the time
that its trip takes and returns its average
velocity.
The output should be similar to the following:
5.8.6 Phy si cs Pr obl em
Two balls are heading toward each other,
moving along the same straight path. One
has mass m
1
and speed v
1
, and the other has
mass m
2
and speed v
2
. Assume they
undergo a perfectly elastic collision.
Write a program that takes as input m
1
, v
1
,
m
2
, and v
2
and returns v
1
and v
2
, the new
velocities of the balls.
The output should be similar to the following:
5.9 I NPUT AND OUTPUT I N THE TEXT- BASED GAME
The text-based game depends entirely on input and output. Through the output,
the game sends information to the player, and through the input the player can
actually play, interact, and send information and data to the game. The game
then responds accordingly.
I nput and Out put 154
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
At the very beginning, the game tells the player the following:
Your location is: Game
You can go to: LevelTrainStation, RunCenter
Or you can take a taxicab to the GameAssets, and this will cost you $50.
Your starting balance is $1500.
This information is delivered through the use of the WriteLine method:
Console.WriteLine("Your location is: Game\n");
Console.WriteLine("You can go to: LevelTrainStation, RunCenter\nOr you can
take a taxicab to the GameAssets, and this will cost you $50.\n");
Console.WriteLine("Your starting balance is $1500\n\n");
After this information is output on the screen, the player should type some input
data to the game. The game takes this input through the use of the Readline
method:
inputBuffer = Console.ReadLine();
Where inputBuffer is a string variable that will store the input line that the
player typed. The input/output cycle is repeated during the game many times.
5.10 I NPUT AND OUTPUT I N THE BRI X GAME
Input and output in Brix are different from input and output in the text-based
game. In Brix the input and output is done through the windows interface, as fol-
lows:
5.10.1 I nput
Two special functions, Form1_KeyDown and Form1_KeyUp, are called by the sys-
tem when a keyboard key is pressed down or up:
private void Form1_KeyDown(object sender, System.Win-
dows.Forms.KeyEventArgs e)
private void Form1_KeyUp(object sender, System.Win-
dows.Forms.KeyEventArgs e)
Where sender is the source of the event, and e is a KeyEventArgs specifies the
key the user pressed and whether any modifier keys (CTRL, ALT, and SHIFT)
were pressed at the same time which is passed with each KeyDown or KeyUp
event.
The KeyDown event occurs when the user presses any key. The KeyUp event
occurs when the user releases the key. Duplicate KeyDown events occur each time
the key repeats or if the key is held down, but only one KeyUp event is generated
when the user releases the key.
A KeyPress event also occurs when a key is depressed. A KeyPressEventArgs is
passed with each KeyPress event and specifies the character that was composed
as a result of each key press.
I nput and Out put 155
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
In our game, input works as follows:
When a key is pressed, the Form1_KeyDown function is called. Inside this func-
tion, some processing is done. If the key pressed is the Spacebar and the ball is
resting on the pad, it is released. If the key pressed is the Left or Right arrow key,
the pad will move left or right accordingly until it reaches the window's border.
When a key is released, the Form1_KeyUp function is called. If the key released is
the Left key, the pad will stop moving left. If the key released is the Right key, the
pad will stop moving right.
5.10.2 Out put
In a windows game, all output is shown inside the window. This window is
drawn (or painted) within a function called Form1_Paint:
private void Form1_Paint(object sender, System.Win-
dows.Forms.PaintEventArgs e)
This function has the same arguments as the Form1_KeyDown function (men-
tioned in the previous section) and is called by the system whenever the win-
dows needs to be redrawn.
Note: We can force the system to call this function by calling the Invalidate()
function.
Within the paint function:
To draw the background image and the sprites (ball, pad, and bricks), we use
the DrawImage() function as follows:
e.Graphics.DrawImage(ballBitmap, ballRect.top.x1, ball-
Rect.top.y1,
ballBitmap.Width, ballBitmap.Height);
e.Graphics.DrawImage(padBitmap, padRect.top.x1,
padRect.top.y1,
padBitmap.Width, padBitmap.Height);
for (int i = 0;i<2;i++)
for (int j = 0;j<10;j++)
{
if (r[i,j].active)
e.Graphics.DrawImage(brickBitmap, r[i,j].top.x1,
r[i,j].top.y1, brickBitmap.Width,
brickBitmap.Height);
}
To output a text message, we use the DrawString() function as follows:
// Create string to draw.
String drawString = "Game Over!";
// Create font and brush.
Font drawFont = new Font("Arial", 50);
SolidBrush drawBrush = new SolidBrush(Color.White);
// Create point for upper-left corner of drawing.
float x = 200.0F;
float y = 200.0F;
I nput and Out put 156
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
// Draw string to screen.
e.Graphics.DrawString(drawString, drawFont, drawBrush, x,
y);
5.11 I NPUT AND OUTPUT I N CAVES OF DOOM
5.11.1 I nput : The Key boar d Cl ass
FUN Editor.Net provides a special class for keyboard input: the keyboard class.
Through the use of this class, we can check whether a keyboard key is pressed or
triggered. The most important members of this class are:
static bool IsPressed(KeyboardKey key);
This method allows the pressed key on the keyboard to be detected. The
IsPressed method returns true when the specified key is pressed. Key-
boardKey" is an enumeration that holds all the available keys.
static bool IsNotPressed(KeyboardKey key);
This method detects if the key is not pressed. The IsNotPressed method
returns true when the specified key is not pressed.
static bool IsTriggered(KeyboardKey key);
This method detects if the key is triggered. The IsTriggered method
returns as true when the key status changes from not pressed to pressed.
static bool IsNotTriggered(KeyboardKey key);
This method detects if the key is not triggered. The IsNotTriggered method
returns as true when the key is not triggered.
5.11.2 Game I nput
In Caves Of Doom, the player input works as follows:
In the first level, the Intro level, we have two options: either start the game or
exit the game. The player can switch between these two options by pressing
the Up and Down arrow keys:
return Keyboard.IsTriggered(KeyboardKey.K_UP);
return Keyboard.IsTriggered(KeyboardKey.K_DOWN);
Where K_UP and K_DOWN tell the computer that we are asking about the
Up and Down arrow keys. These options also apply to the GameOver and
Success levels.
Also in the Intro level, to submit our choice between playing or exiting the
game, we need to press the ENTER key:
if (Keyboard.IsTriggered(KeyboardKey.K_RETURN))
{

}
In the play level Level1, the ship can move left, right, up, or down. This is
done by checking if the specified keys are pressed in the state machine that
controls the ship's behavior (JFMovementSM):
I nput and Out put 157
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
return Keyboard.IsPressed(KeyboardKey.K_RIGHT);
return Keyboard.IsPressed(KeyboardKey.K_LEFT);
return Keyboard.IsPressed(KeyboardKey.K_UP);
return Keyboard.IsPressed(KeyboardKey.K_DOWN);
The ship can fire by pressing the Spacebar:
if (Keyboard.IsPressed(KeyboardKey.K_SPACE))
{
//Create the ship's bullets
}
Additionally, if the shield option is available, the ship can be shielded by
pressing CTRL-K:
if (sv.Value >= 1 &&
(Keyboard.IsTriggered(KeyboardKey.K_RCONTROL) ||
Keyboard.IsTriggered(KeyboardKey.K_LCONTROL)))
{
// Turn into the shielded state
}
5.11.3 Out put : The Tex t Cl ass
The Text class provides means to display texts and numbers on the screen as out-
put. The text object will always be displayed on top or below all the other sprites
and maps. It is only present in the level where it is defined.
Operations
To add a text object:
1. Right-click on the Text Objects icon under Game in the projects tree.
2. Click Add.
A Text Properties dialog will appear.
To delete a text object:
1. Right-click on the text object desired.
2. Click Delete.
To access a text object:
1. Right-click on the text object.
2. Click Properties.
A Text Properties dialog will appear.
or
Double-click on the desired text object.
A Text Properties dialog will appear.
Properties
To define a text object, the user has to set the properties of the created text.
a. General
Name: Sets a unique name for the text.
Type: Specifies the type of the text object. It can be a text (string) or a
number. Once the number type is chosen, the Only Integer Part is
enabled.
I nput and Out put 158
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
Visible: Specifies whether or not the text is visible. By default, it is visible
(checked).
Unused: Specifies whether or not the text will be used. If it is checked, the
text will not be used, and all its behavior (state machines, functions, and
actions) are disabled. By default, the text object is used (unchecked).
Paused: Specifies whether or not the text is paused. If it is checked, the
text will freeze, and all its behavior and its effects are disabled. By default,
it is not paused (unchecked).
Deactivate Beyond Viewport: Specifies whether or not the text outside
the viewport is activated. It will be enabled once the Fixed In Viewport
in the Position Property is unchecked. By default, it is disabled.
Only Integer Part: Specifies whether or not the integer part of the num-
ber or the whole number, is the chosen number type. If the number is a
float, checking this flag will show only the integer part of the float num-
ber. Otherwise, the whole float number is shown. By default, it is dis-
abled
Local Data: Chooses a local data (from a list of all the defined local data),
which the text can use.
b. Format
1. Font:
Choose Font: Specifies the font type, style, and size.
Color: Changes the color of the text.
Width: Specifies the width of the font.
Height: Specifies the height of the font.
Weight: Specifies the weight of the font.
2. Paragraph Format:
Style: Specifies the style of the paragraph. There are five types of styles:
Wrap With Complete Words: A word having no spaces and
reaching the border of the bounding rectangle will be moved to
a new line.
Wrap With Incomplete Words: A word having no spaces and
reaching the border of the bounding rectangle will be
divided and continued on a new line.
Horizontal Scrolling: Allows the paragraph to scroll right and
left. For that reason, only the Left and Right key
assignments in the Scrolling property are enabled.
Vertical Scrolling: Allows the paragraph to scroll up and down.
For that reason, only the Up and Down key
assignments in the Scrolling property are enabled.
Horizontal/Vertical Scrolling: Allows the paragraph to scroll
in all directions (up, down, left, and right). For that
reason, all the key assignments in the Scrolling property are
enabled.
Top Margin: This is used to set the margin at the top of the
paragraph.
Left Margin: Sets the margin of the left side of the paragraph.
Line Spacing: Sets the spaces between lines of the paragraph.
I nput and Out put 159
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
Character Spacing: Sets the spaces between the characters of the para-
graph.
Suppress Leading Spaces: Sets whether or not the spaces at the begin-
ning of each line of the paragraph are to be disregarded. Every line of
the paragraph will start from the left specified margin.
Initial Value: Sets an initial value for the text object. It can be set manu-
ally or taken from a file whose path is specified by the user.
c. Position
1. Belongs To Map: Specifies whether or not the text object belongs to a
map. Once it is checked, the list box is enabled, allowing the user to
choose a map.
2. Bounding Rectangle: Defines the rectangle's bounding box surrounding
the text object.
Left, Top, Right, and Bottom: Sets the dimensions of the rectangle.
Fixed In Viewport: This is used to specify whether or not the texts
position is fixed inside the viewport. Once it is unchecked, the Center
In Viewport flag is disabled. The Deactivate Beyond Viewport flag in
the General property is enabled.
Center In Viewport: Specifies whether or not the texts position is cen-
tered in the viewport. Once it is unchecked, the Fixed In Viewport flag
is disabled.
Show: Specifies whether or not the rectangle is shown. If it is checked,
the Color button is enabled.
Color: Allows the user to choose the color of the rectangle. By default,
the color is white.
d. Effects
1. Scrolling: Enabled when the paragraph format style is set as Horizontal
Scrolling, Vertical Scrolling, or Horizontal/Vertical Scrolling.
Keys Assignment: Allows the user to use the keyboard keys to scroll
the text left, right, up, and down. By default, the arrow keys are chosen.
Size: Sets the size of the arrows, which appear at the right-bottom cor-
ner of the text bounding rectangle. It shows the user the direction that
the text can be scrolled. By default, the size's value is 16.
Color: Sets the color of the arrows at the bottom-right corner of the text
bounding rectangle mentioned earlier. By default, the color is black.
Move Horizontally/Move Vertically: Sets the number of characters
scrolled horizontally and/or vertically each time the user presses the
keys.
Continuous Scrolling: Specifies whether or not the text keeps scrolling
as long as one of the keys ispressed.
2. Style: Sets the style of the text effect.
Normal: The text has no effect.
Character By Character: The text is displayed on the screen, character
by character, with a delay between each character. This effect uses one
delay between the display of each character.
I nput and Out put 160
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
Line By Line: The text is displayed on the screen, line by line, with a
delay between each line. This effect uses one delay between the display
of each character.
ASCII Effect: Continually and randomly changes the ASCII values of
all the characters of the text, due to atime delay (delay2) set for the
number of text changes, and another delay (delay1) used between each
text display. When the number of changes reaches the delay's value, the
effect stops.
Random Decoding: This effect continually and randomly changes the
value of the characters of the text, due to a time delay (delay2) set for
the number of text changes, before one character (chosen randomly)
stops changing, and another delay (delay1) used between each text dis-
play. The effect stops when all the characters stop changing.
Sequential Decoding: Continually and randomly changes the value of
the characters of the text, due to a time delay (delay2) set for the num-
ber of text changes, before one character (sequentially chosen starting
from the beginning of the text) stops changing, and another delay
(delay1) used between each text display. The effect stopswhen the last
character stops changing.
Delay1/Delay2: Sets the delays of the specified effect's style. Some of
the effects need one delay and others need two delays.
Sound Effect: Specifies whether or not a sound effect is set to the text.
If it is checked, the user has to choose the sound effect from the list box
showing all the defined sound effects.
e. Behavior
This property allows the user to specify the state machine and the function
that describe the behavior of the text. Once the state machine or function
flag is checked, the user can assign a state machine or function by choosing
from the list boxes that show all the defined state machines and functions.
The Edit button allows the user to edit the chosen state machine or func-
tion, so that it will be suitable for the text. The user can add state machines
and object functions to the behavior.
The behavior is the brain of every FUN Object. Through the behavior,
the user can assign reactions and behaviors to the objects.

To add state machines and functions:
1. Click the button; a dialog will appear.
2. Click the button to add or remove a state machine or object function.
3. Click OK
5.11.4 Tex t Obj ect s i n Caves Of Doom
Under Level1, the only visible text object is score, which displays the
player's score. This text object is a number.
Under the Success level, many text objects are used:
I nput and Out put 161
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
mutantNumber displays the number of mutant enemies killed during
game play.
mutantPoints displays the points that the player gets by killing the
mutant enemies.
landerNumber displays the number of lander enemies killed during
game play.
landerPoints displays the points that the player gets by killing the
lander enemies.
baiterNumber displays the number of baiter enemies killed during game
play.
baiterPoints displays the points that the player gets by killing the baiter
enemies.
swarmerNumber displays the number of swarmer enemies killed during
game play.
swarmerPoints displays the points that the player gets by killing the
swarmerenemies.
total sums up and displays the player's total score.
5.12 TEXT- BASED GAME EXERCI SE
(The complete solution of the exercise is available in the Appendix.)
Write the appropriate code to read two words (two strings: the first is a verb, and
the second is a location) and then display a text.
When running the program, first your initial location is displayed, then you
enter the new destination, and then the program displays some information.
Ex ampl e:
Your location is: Game
You can go to LevelTrainStation or you can take a taxi to
GameAssets.
Taking a taxi costs $50.
Input:GoTo GameAssets
Output:Your new location is: GameAssets.
You can take a taxi to Game. Taking a taxi costs $50.
Verbs:GoTo (used to go from a place to another)
Help (used to list all the verbs. In this assignment type, Help with ?
i.e. Help ?)
Locations:
Game (Initial location)
GameAssets
LevelTrainStation
MapsCity
SpritesCity
I nput and Out put 162
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
Steps
1. Display (Console.WriteLine) a text showing your initial location.
2. Enter (Console.Readine) two strings and save them in token1 and token2
(token1=a verb and token2=a location).
3. Compare token1 with the verbs and token2 with the locations.
4. Display (Console.WriteLine) information of the new location.
To compare two strings, you may use the equals method:
String.Equals Method (String)
Return Value
Return true if the value of the value parameter is the same as this instance
otherwise, return false.
Output Example
I nput and Out put 163
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
5.13 ADDI NG CODE TO CAVES OF DOOM
In this section, we will add code to an unfinished version of Caves Of Doom and
then run it to see the changes taking effect.
1. With FunEditor.Net, open the file CavesOfDoomChapter5.fun.
Note: This version is not a complete version of the game.
2. In the Project Resources window, under Level_1, right-click on Text
Objects and on the menu, click Add
A Text Properties New window will open.
In the Name box, type score 1.
3. For Type, select Number.
4. On the Format tab, click the Choose Font button.
In the Font window:
For Font Style, choose Bold.
For Size, choose 22.
For Color, choose Black.
Click OK
5. Under Font, click on the button next to Color.
In the Color window:
Choose the Maroon color.
Click OK
6. For Initial Value, type 0.
7. On the Position tab, under Bounding Box, type 240 for Left, 12 for Top,
340 for Right, and 52 for Bottom.
8. Click OK to save, and close the Text Properties window. A new text
object called score is added under Level_1 in the Project Resources win-
dow.
9. Click the Run icon and then click Yes.
The game will run and the score will be displayed under Level_1.
I nput and Out put 164
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
5.14 ADDI NG CODE TO BRI X
In this section, we will add code to an unfinished version of Brix and then run it
to see the changes taking effect.
1. With Visual C#.Net, open the project /Brix/Brix Chapter5/Brix.csproj.
Note: This version is an incomplete version of the game.
2. Open the file called Form1.cs.
3. Under the method
private void Form1_KeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)

and before the line:
if (e.KeyData == Keys.Left)

add the following lines:
if (e.KeyData == Keys.Space)
{
free = true;
}
Save and run the game. When the Spacebar is pressed, the ball leaves the pad and
starts moving around.
6
EXPRESSI ONS,
OPERATORS
Expressions, Operat ors 166
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
EXPRESSI ONS, OPERATORS
What is an expression? It is a sequence of operators and operands. It specifies
computation of a value, or it designates a variable or constant. The operators of
an expression indicate which operations to apply to the operands.
6.1 CLASSI FI CATI ON OF EXPRESSI ON
An expression is classified as one of the following:
Value
Variable
Namespace
Type
Method group
Property access
Event access
Indexer access
Nothing
The final result of an expression cannot be one of the following:
Namespace
Type
Method group
Event access
These categories are intermediate constructs. They are only permitted in certain
contexts.
Values of expressions
If the expression denotes a property access, an indexer access, or a variable, the
value of the property, indexer, or variable is implicitly substituted:
The value of a variable is simply the value currently stored in the storage
location identified by the variable.
The value of a property access expression is obtained by invoking the get-
accessor of the property.
The value of an indexer access expression is obtained by invoking the get-
accessor of the indexer.
6.2 OPERATORS
Expressions are constructed from operands and operators. Operators of an
expression indicate which operations to apply to the operands. We can find three
types of operators:
Unary operators: Take one operand. They use either prefix notation (i) or
postfix notation (i++).
Binary operators: Take two operands. They all use infix notation (i + j).
Ternary operator: Takes three operands and uses infix notation
(z? x: y).
Expressions, Operat ors 167
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
Operands in an expression are evaluated from left to right. Certain operators can
be overloaded. This permits user-defined operator implementations to be speci-
fied for operations where one or both of the operands are of a user-defined class
or struct type.
6.2.1 Oper at or Pr ecedence and Associ at i vi t y
When an expression contains multiple operators, the precedence of the operators
controls the order in which the individual operators are evaluated. For example,
the expression a + b * c is evaluated as a + (b * c) because the * operator has
higher precedence than the + operator. The precedence of an operator is estab-
lished by the definition of its associated grammar production.
When an operand occurs between two operators with the same precedence, the
associativity of the operators controls the order in which the operations are per-
formed. All binary operators are left-associative, except for the assignment oper-
ators, meaning that operations are performed from left to right. Assignment
operators and conditional operator (?:) are right-associative, which means that
operations are performed from right to left. Precedence and associativity can be
controlled using parentheses.
6.2.2 Oper at or Over l oadi ng
User-defined implementations can be introduced by including operator declara-
tions in classes and structs. User-defined operator implementations always take
precedence over predefined operator implementations. Only when no applicable
user-defined operator implementations exist will the pre-defined operator
implementations be considered.
The overloadable unary operators are:
+ - ! ~ ++ -- true false
The overloadable binary operators are:
+ - * / % & | ^ << >> == != > < >= <=
When a binary operator is overloaded, the corresponding assignment operator
(if any) is also implicitly overloaded. For example, an overload of operator + is
also an overload of operator +=.
The assignment operator (=) cannot be overloaded. An assignment performs a
bit-wise copy of a value into a variable. Element access, such as Ar[x], is not an
overloadable operator.
User-defined operator declarations always require at least one of the parameters
to be of the class or struct type that contains the operator declaration. User-
defined operator declarations cannot modify the syntax, precedence, or associa-
tivity of an operator. For example, the / operator is always a binary operator,
always has the precedence level specified in, and is always left-associative.
Expressions, Operat ors 168
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
6.3 FUNCTI ON MEMBERS
Function members contain executable statements. They are always members of
types and cannot be members of namespaces. C# defines the following categories
of function members:
Methods
Properties
Events
Indexers
User-defined operators
Instance constructors
Static constructors
Destructors
Statements contained in function members are executed through function mem-
ber invocations. The argument list of a function member invocation provides
actual values or variable references for the parameters of the function member.
6.3.1 The New Oper at or
The new operator is used to create new instances of types. There are three forms
of new expressions:
Object creation expressions are used to create new instances of class types
and value types.
Array creation expressions are used to create new instances of array types.
Delegate creation expressions are used to create new instances of delegate
types.
The new operator implies creation of an instance of a type. Instances of value
types require no additional memory beyond the variables in which they reside.
6.4 UNARY OPERATORS
The unary operators are +, -, !, ~, *, ++, --, and cast operators.
The + operator: The predefined plus operators are:
int operator +(int x);
uint operator +(uint x);
long operator +(long x);
ulong operator +(ulong x);
float operator +(float x);
double operator +(double x);
decimal operator +(decimal x);
For each of these operators, the result is simply the value of the operand.
The - operator: The predefined negation operators are:
Integer negation:
int operator (int x);
long operator (long x);
The result is computed by subtracting x from zero.
Expressions, Operat ors 169
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
Floating-point negation:
float operator (float x);
double operator (double x);
The result is the value of x with its sign inverted.
Decimal negation: decimal operator (decimal x);
The result is computed by subtracting x from zero. Decimal negation is
equivalent to using the unary minus operator of type decimal.
Logical negation operator: There is only one predefined logical negation
operator: bool operator !(bool x);
This operator computes the logical negation of the operand: if the oper-
and is true, the result is false; if the operand is false, the result is true.
Bitwise complement operator: The bitwise complement operators are:
int operator ~(int x);
uint operator ~(uint x);
long operator ~(long x);
ulong operator ~(ulong x);
Prefix increment and decrement operators:
pre-increment-expression: ++ unary-expression
pre-decrement-expression: -- unary-expression
The value returned by the operator becomes the result of the operation.
The ++ and -- operators also support postfix notation.
Cast expressions
A cast-expression is used to explicitly convert an expression to a given type.
Cast-expression:
( type ) unary-expression
6.5 ARI THMETI C OPERATORS
The *, /, %, +, and operators are called the arithmetic operators.
multiplicative-expression:
unary-expression
multiplicative-expression * unary-expression
multiplicative-expression / unary-expression
multiplicative-expression % unary-expression
additive-expression:
multiplicative-expression
additive-expression + multiplicative-expression
additive-expression multiplicative-expression
Multiplication operator
- Integer multiplication:
int operator *(int x, int y);
Expressions, Operat ors 170
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
uint operator *(uint x, uint y);
long operator *(long x, long y);
ulong operator *(ulong x, ulong y);
- Floating-point multiplication:
float operator *(float x, float y);
double operator *(double x, double y);
- Decimal multiplication:
decimal operator *(decimal x, decimal y);
Division operator
- Integer division:
int operator /(int x, int y);
uint operator /(uint x, uint y);
long operator /(long x, long y);
ulong operator /(ulong x, ulong y);
- Floating-point division:
float operator /(float x, float y);
double operator /(double x, double y);
- Decimal division:
decimal operator /(decimal x, decimal y);
Remainder operator
- Integer remainder:
int operator %(int x, int y);
uint operator %(uint x, uint y);
long operator %(long x, long y);
ulong operator %(ulong x, ulong y);
- Floating-point remainder:
float operator %(float x, float y);
double operator %(double x, double y);
- Decimal remainder:
decimal operator %(decimal x, decimal y);
Addition operator
- Integer addition:
int operator +(int x, int y);
uint operator +(uint x, uint y);
long operator +(long x, long y);
ulong operator +(ulong x, ulong y);
- Floating-point addition:
float operator +(float x, float y);
double operator +(double x, double y);
- Decimal addition:
decimal operator +(decimal x, decimal y);
- Enumeration addition:
E operator +(E x, U y);
E operator +(U x, E y);
Expressions, Operat ors 171
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
- String concatenation:
string operator +(string x, string y);
string operator +(string x, object y);
string operator +(object x, string y);
- Integer subtraction:
int operator (int x, int y);
uint operator (uint x, uint y);
long operator (long x, long y);
ulong operator (ulong x, ulong y);
- Floating-point subtraction:
float operator (float x, float y);
double operator (double x, double y);
- Decimal subtraction:
decimal operator (decimal x, decimal y);
- Enumeration subtraction.
U operator (E x, E y);
E operator (E x, U y);
6.6 SHI FT OPERATORS
The << and >> operators are used to perform bit shifting operations.
shift-expression:
additive-expression
shift-expression << additive-expression
shift-expression >> additive-expression
When declaring an overloaded shift operator, the type of the first operand must
always be the class or struct containing the operator declaration, and the type of
the second operand must always be int. The predefined shift operators are listed
below.
Shift left:
int operator <<(int x, int count);
uint operator <<(uint x, int count);
long operator <<(long x, int count);
ulong operator <<(ulong x, int count);
The << operator shifts x left by a number of bits computed as described
below. The high-order bits outside the range of the result type of x are dis-
carded, the remaining bits are shifted left, and the low-order empty bit posi-
tions are set to zero.
Shift right:
int operator >>(int x, int count);
uint operator >>(uint x, int count);
long operator >>(long x, int count);
ulong operator >>(ulong x, int count);
The >> operator shifts x right by a number of bits computed as
described below.
Expressions, Operat ors 172
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
6.7 RELATI ONAL AND TYPE TESTI NG OPERATORS
The ==, !=, <, >, <=, >=, is and as operators are called the relational and type
testing operators.
relational-expression:
shift-expression
relational-expression < shift-expression
relational-expression > shift-expression
relational-expression <= shift-expression
relational-expression >= shift-expression
relational-expression is type
relational-expression as type
equality-expression:
relational-expression
equality-expression == relational-expression
equality-expression != relational-expression
All comparison operators return a result of type bool, as described in the follow-
ing table.
Operation Result
x == y true if x is equal to y; false otherwise
x != y true if x is not equal to y; false otherwise
x < y true if x is less than y; false otherwise
x > y true if x is greater than y; false otherwise
x <= y true if x is less than or equal to y; false otherwise
x >= y true if x is greater than or equal to y; false otherwise
The as operator
This operator is used to explicitly convert a value to a given reference type
using a reference conversion or a boxing conversion.
The as operator never throws an exception. Instead, if the indicated conver-
sion is not possible, the resulting value is null.
6.8 LOGI CAL OPERATORS
The &, ^, and | operators are called the logical operators.
and-expression:
equality-expression
and-expression & equality-expression
exclusive-or-expression:
and-expression
exclusive-or-expression ^ and-expression
inclusive-or-expression:
exclusive-or-expression
inclusive-or-expression | exclusive-or-expression
I nput and Out put 149
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
5
5.3 OUTPUT: THE CONSOLE.WRI TELI NE METHOD
The console.writeline method writes the specified data followed by the current
line terminator, to the standard output stream. The only difference between this
method and the console.write method is the line terminator (the cursor) auto-
matically goes one line down after calling this method. This method has the
same overload list as the console.write method.
5.4 I NPUT: THE CONSOLE.READ METHOD
The console.read method reads the next character from the standard input
stream:
public static int Read();
The return value is the next character from the input stream or negative one (-1)
if no more characters are available. This method does not return until the read
operation is terminated, for example, by the user pressing the return key.
Ex ampl e:
int i;
i = Console.Read ();
Console.WriteLine ("{0}", (char) i);
5.5 I NPUT: THE CONSOLE.READLI NE METHOD
The console.readline method reads the next line of characters from the standard
input stream:
public static string ReadLine();
The return value is the next line from the input stream or a null reference if no
characters are available. The returned string does not contain the terminating
character(s).
5.6 GDI +
GDI+ is an application programming interface (API) for Windows program-
mers. It enables applications to use graphics and formatted text on both the
video display and the printer. Instead of accessing the graphics hardware directly,
GDI+ interacts with device drivers on behalf of applications based on the
Microsoft Win32 API. GDI+ can be used in all Windows-based applications.
5. 7 A GDI + CLASS: THE GRAPHI CS CLASS
The graphics class provides methods for drawing lines, curves, figures, images,
and text. A graphics object stores attributes of the display device and attributes of
the items to be drawn.
Expressions, Operat ors 174
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
true, then, following evaluation of the expression, the operator true implementa-
tion provided by that type is invoked to produce a bool value.
6.9 DI RECT I MPLEMENTATI ONS
6.9.1 Mat h Pr obl em
Write a program using the bit-wise operators, that reads a number and checks
whether or not this number is odd and whether or not it is negative. The output
should be similar to the following:
6.9.2 Mat h Pr obl em
Write a program using the shift operators, that reads a number, checks if this
number is divisible by 4 then displays OK or Failure depending on the result.
The output should be similar to the following:
6.9.3 Game Desi gn Pr obl em
Write a program that takes as input two triplets of real numbers (x1, y1, z1) and
(x2, y2, z2), which represent two points in the space, and gives as output the dis-
tance between these two points. The output should be similar to the following:
6.9.4 Game Desi gn Pr obl em
In space, a ball (sphere) is defined by its radius R and the position of its
center (x
C
, y
C
, z
C
).
Write a program that checks collision between two balls b
1
and b
2
of respective
centers c
1
and c
2
, respectively positioned at (x
C1
, y
C1
, z
C1
) and (x
C2
, y
C2
, z
C2
)
and of respective radii, R
1
and R
2
. The output should be similar to the following:
Expressions, Operat ors 175
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
6.9.5 Chemi st r y Pr obl em
Write a program that takes as input the concentration of a
solution in OH
-
ions and returns the pH of the solution.
The output should be similar to the following:
6.9.6 Phy si cs Pr obl em
When a body undergoes a rectilinear sinusoidal motion, (a
periodic motion) the number of cycles that it performs per unit
of time is known as the frequency of motion.
Write a program that takes as input the angular frequency of
motion and returns the period of time. The output should be
similar to the following:
6.9.7 Phy si cs Pr obl em
When a car moves along a curve (part of a
circle), with a constant speed, it performs a
uniform circular motion where the magni-
tude of the acceleration is a function of its
constant speed and the radius of the circle.
Write a program that takes as input the
radius of the circle and the speed of the car
and returns the magnitude of the accelera-
tion. The output should be similar to the
following:
Expressions, Operat ors 176
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
6.9.8 Phy si cs Pr obl em
A simple pendulum is a mechanical system consisting
of a small ball of mass m, attached to a light spring
and suspended from its upper end. The simple pen-
dulum can perform a simple harmonic motion with a
period t, that depends on the length l of the string.
Write a program that takes as input the length l and
returns the period of the pendulum. The output
should be similar to the following:
6.10 OPERATORS I N THE TEXT- BASED GAME
Operators are used in almost any application, one way or another. In the text-
based game, operators are heavily used, which shows their power. Following is
the most important operator usage in the text based game:
In the game, a sequence of information should be repeatedly entered and
interpreted. The game should continuously check if the
end is reached by checking if the solved Boolean is true or if there is no more
money. If none of these two conditions is true, the loop should repeat. How
this is done? Through the use of the while loop with operators as follows:
while((!solved) && (inventory[(int)nouns.Money].values>0))
Here we are using the following operators:
1. The logical negation operator (!).
2. The conditional-AND operator (&&).
3. The dot operator (.).
4. The greater-than relational operator (>).
After the user enters a command, the parser has to check if this is a one or
two-word command. It does so by first splitting the input
string and then testing the length of the result as follows:
if (ss.Length > 1)
If the length of the ss string is greater than one, this means that we have a
two-word command, otherwise it is a one-word
command. The operator we are using is the greater-than relational operator
(>).
After the command is input, it has to be interpreted. This is done by com-
paring it to the available and allowed commands, as follows:
if (v==verbs.GoTo && n==nouns.Game)
Expressions, Operat ors 177
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
Here v represents the first input word and n represents the second input
word. The operators used are:
1. The equality operator (==).
2. The conditional-AND operator (&&).
After we add collision to a map, action must be taken so that the program
knows in future that we have map collision. This is done
as follows:
i[(int)nouns.MapCollision].values++;
Here the values integer member of the MapCollision increments through
the use of the increment operator (++).
After buying something, the value of your money decrements. This is done
as follows:
i[(int)nouns.Money].values -= 40;
Here the values integer member of Money decrements through the use of the
subtraction assignment operator (-=).
These were some of the operators used in the text-based game. Other opera-
tors may exist, but they are similar to the ones mentioned above.
6.11 OPERATORS I N THE BRI X GAME
Following is the most important operator usage in the Brix game:
In the very beginning, each of the 20 bricks used in the game should be cre-
ated. This is done using the new operator, as follows:
r = new rect[2,10];
The new operator is used to create objects and invoke constructors. It is also
used to invoke the default constructor for value types.
Each of the 20 bricks should be placed. This is done using a nested for loop
as follows:
for (int i = 0;i<2;i++)
for (int j = 0;j<10;j++)
{

}
In this way, two rows (ten bricks in each row) are created.
Here, three operators are used:
The assignment operator (=) stores the value of its right-hand operand in
the storage location denoted by its left-hand oper
and and returns the value as its result. The operands must be of the same
type.
The less-than relational operator (<) returns true if the first operand is
less than the second, otherwise false.
The increment operator (++) increments its operand by 1. The increment
operator can appear before or after its operand.
Expressions, Operat ors 178
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
To make all the painting of the window happen only within the Paint func-
tion, the function SetStyle() is called as follows:
SetStyle(ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint | ControlStyles.Double-
Buffer, true);
Here the binary | operator is used. The binary | operators are predefined for
the integral types and bool. For integral types, |
computes the bitwise OR of its operands. For bool operands, | computes the
logical OR of its operands; that is, the result is false if
and only if both its operands are false.
By using this operator with the three styles mentioned in the first argument
of the SetStyle function, we are ensuring that painting
is only worked out within the Paint function, which results in the following
advantages:
User Paint: The control paints itself rather than the operating system
doing so.
AllPaintingInWmPaint: The control ignores the window message
WM_ERASEBKGND to reduce flicker. This style should only be used if
UserPaint is set to true.
DoubleBuffer: If true, drawing is performed in a buffer, and after it com-
pletes, the result is output to the screen. Double-buffering prevents flicker
caused by the redrawing of the control.
Within Form1_KeyDown function, we check the key pressed if it is the
Spacebar, as follows:
if (e.KeyData == Keys.Space)
{

}
Here we are using the equality operator (==). It returns true if the values of
its operands are equal, false otherwise. For reference types other than string,
== returns true if its two operands refer to the same object.
When updating the pad's location, a check should be made to see if the pad
has to move left by checking if the Left1 variable is set
and the paddle did not reach the left border of the window. This is done as
follows:
if ((left1 == 1) && (padRect.top.x1 >= padSpeed))
{

}
Expressions, Operat ors 179
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
The operators used are:
The equality operator (explained before).
The conditional-AND operator (&&): This operator performs a
logical-AND of its bool operands, but only evaluates its second operand
if necessary.
The dot operator: This operator is used for member access. Here we are
accessing the top member of the padRect structure,
and the x1 member of the top line structure.
The greater-than-or-equal relational operator (>=) that returns true if the
first operand is greater than or equal to the
second, false otherwise.
After checking that the pad should move left, the coordinates of rectangle
representing the pad should be changed, as follows:
padRect.top.x1 -= (int)padSpeed;
Here we are using the subtraction assignment operator to subtract from
the x coordinate of the top line of the rectangle, a value that equals the
padSpeed variable.
When accessing a certain member of the array of the rectangle, a special
operator is used: the square brackets ([ ]). Square brackets are used for
arrays, indexers, and attributes.
6.12 OPERATORS I N CAVES OF DOOM
Almost any program uses the assignment (=) operator. One operator usage
is at the beginning of Level_1. The bonus global boolean variable is assigned
a value of true as follows:
GlobalData.bonus = true;
Another assignment operator is in the CreateBigBoss function, where we
assign a value of 4 to the variable that represents the BigBoss's speed, as fol-
lows:
s.Speed = 4;
where s represents the bigBoss sprite.
In the BigBossSM state machine, the state machine that controls the behav-
ior of the bigBoss sprite, we use the less-than relational
operator (<) to test if the sprite's position along the x-axis is less than 500 as
follows:
if(This.Value >=3500)
{

}
where This represents the tmpScore text object.
Expressions, Operat ors 180
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
In the BigBossSM state machine, we use the less-than relational operator (<)
to test if the sprite's position along the x-axis is less
than 500 as follows:
if(This.MapPositionX()<500)
{

}
where This represents the bigBoss sprite, and MapPositionX() is a method
that returns the sprite's position along the x-axis.
In the SuccessSM state machine, the state machine that controls the behav-
ior of the Success level, we use the conditional-or
operator (||) to test if the Right or Left arrow keys are triggered as follows:
return Keyboard.IsTriggered(KeyboardKey.K_LEFT) ||
Keyboard.IsTriggered(KeyboardKey.K_RIGHT);
In the JFMovementSM state machine, the state machine that controls the
behavior of the jetFighter sprite, we use the conditional-
and operator (&&) to test if both the Up and Right arrow keys are not
pressed anymore as follows:
return Keyboard.IsNotPressed(KeyboardKey.K_UP) &&
Keyboard.IsNotPressed(KeyboardKey.K_RIGHT);
In the BulletFN function, the function the controls the jfBullet sprite, we use
the logical negation operator (!) to test if the bullet is not in the viewport
as follows:
if (!This.InViewport)
where This refers to the jfBullet sprite.
In the BulletFN function also, we use the equality operator (==) to test if one
of the barrier sprite's local variable reached the value to 6; if so then change
the barrier's animation to explosion as follows:
if (s.LocalVariables[3].Value==6)
s.Animation = Animations.BARRIER_EXPLOSION;
In the SwarmerSM state machine, when the swarmer enemy is hit, we use
the increment operator (++) to increment the value of the sw global data,
which means that another swarmer is exterminated as follows:
GlobalData.sw++;
In the JFFireFN function, we use the decrement operator (--) to decrement
the value of the shieldCounter variable every time a shield is used to protect
the jet fighter as follows:
sv.Value --;
Also in the JFFireFN function, we use the addition assignment operator
(+=) to add a value of 120 to the first local variable of the jetFighter sprite
every time a shield is used to protect the jet fighter as follows:
This.LocalVariables[0].Value += 120;
Expressions, Operat ors 181
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
In the BigBossSM state machine, we use the subtraction assignment opera-
tor to subtract a value of 2 from the third and fourth local variables of the
bigBoss sprite every time this sprite is hit as follows:
This.LocalVariables[2].Value-=2;
This.LocalVariables[3].Value-=2;
In the OnStart section of the Success level, we use the multiplication opera-
tor (*) to multiply the value of the ld global data by 200, and store the result
in the landerPoints text object as follows:
ldNb.Value = GlobalData.ld * 200;
In the BigBossSM state machine, we use the square brackets ([ ]) to access
the fifth local variable of the bigBoss sprite as follows:
This.LocalVariables[4].Value ++;
In addition to being used to specify the order of operations in an expression,
parentheses are used to specify casts (type conversions). In the SwarmerUp-
dateFN, we use the cast operator to cast the result of a subtraction into an
integer value as follows:
int k = (int) (This.MapPositionY() - sp.MapPositionY());
6.13 TEXT- BASED GAME EXERCI SE
(The complete solution of the exercise is available in the Appendix.)
In this assignment, we will do the following task:
Move from one location to another, and
Analyze the token and display (not take) appropriate actions.
To be able to manage the location, we need a variable to save the current loca-
tion. Associate the variable number with a location, the variable could be a
string, (were you have to assign the string representing the location), or the vari-
able could be enumerated; in other words, the enumerated variable represents
the location number. For example:
enum locations {GameAssets,Game,LevelTrainStation,
MapsCity,SpritesCity}; locations currentLocation=Game;
The previous declarations allow the programmer to specify the location number
by name, so a switch statement will do the job. For example:
switch (currentLocation)
{
case locations.GameAssets:

break;
case locations.Game:
:
:
}
Expressions, Operat ors 182
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
Declare the locations enumerated list.
Declare a variable currentLocation used to specify the location.
Write a switch statement to handle the current location, and display the
appropriate message.
In this assignment only the location is updated.
Output Example:
6.14 ADDI NG CODE TO CAVES OF DOOM
In this section, we will add code to an unfinished version of Caves Of Doom and
then run it to see the changes take effect.
1. With FunEditor.Net Open the file CavesOfDoomChapter6.fun.
Note: This version is not a complete version of the game.
2. In the Project Resources window, under Game Assets, under Object
Function, right-click on the JFPositionUpdateFN function, and on the
pop-up menu, click Properties
The Function Properties window will open.
3. Type the following code exactly:
// moving the jetfighter up and down
if ((int)This.MapPositionY() + GlobalData.planeY > 41 &&
(int)This.MapPositionY() + GlobalData.planeY < 400)
This.MapPositionY(This.MapPositionY() + GlobalData.planeY);
Expressions, Operat ors 183
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
6
// moving the jetfighter right and left
if ((int)This.MapPositionX()+ GlobalData.planeX > 20 &&
(int)This.MapPositionX() + GlobalData.planeX <500)
This.MapPositionX(This.MapPositionX() + GlobalData.planeX);
4. Click Save, then close the Function Properties window.
5. Click Run and then click Yes.
The game will run and the jet fighter can now move in the four directions.
6.15 ADDI NG CODE TO BRI X
In this section, we will add code to an unfinished version of Brix and then run it
to see the changes take effect.
1. With Visual C#.Net, open the project /Brix/Brix Chapter6/Brix.csproj.
Note: This version is an incomplete version of the game.
2. Open the file called Form1.cs.
3. Under the method
private bool collided(line l, int radius, int xcenter, int
ycenter)

replace the line:
return false;

with the following line:
return (((T1 >= 0) && (T1 <=1)) || ((T2 >= 0) && (T2 <=1)));
Save and run the game. When the ball hits a brick, the brick disappears.
7
FUNCTI ONS
Funct ions 185
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
FUNCTI ONS
Functions break large computing tasks into smaller ones and enable people to
build on what others have done instead of starting over from scratch. Appropri-
ate functions hide details of operation from parts of the program that do not
need to know about them, thus clarifying the whole and easing the pain of mak-
ing changes. C# has been designed to make functions efficient and easy to use;
C# programs generally consist of many small functions rather than a few large
ones. In C# we also use the term method to refer to a function.
7.1 DEFI NI TI ON
The definition of a function includes the return type, the function name, the
parameters list and the function body. The function body is enclosed between
opening and closing curly braces.
Ex ampl e:
int add(int a, int b)
{
return a + b;
}
The parameters a and b receive the values of the arguments when the function is
called.
Ex ampl e:
int n;
n = add(4,5);
7.2 SCOPE
The code found in a function is private to the function and cannot be accessed
by any statement from another function. Function code is accessed only through
function call. A C# program starts from the function Main.
All functions have a file scope. Parameters and variables declared inside the
function have function scope. They are created when the function is entered and
destroyed when the function ends. Static variables declared inside the function
have a function scope, but they retain their values between function calls.
7.3 CALLI NG A FUNCTI ON
A function is called by using its name followed by an opening and closing paren-
thesis including the arguments, if any. If the function has no arguments, then the
argument list is left empty. When a function is called, the function parameters
receive the value of the arguments by respecting their order. For example,
Parameter1 receives the value of argument1, and ParameterN receives the value
of argumentN.
Funct ions 186
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
When a function is called, the sequential execution flow is interrupted, and the
program counter jumps to the first statement of the function called. Once the
last statement is executed, or a return instruction is executed, the sequential exe-
cution flow is interrupted and the program counter is updated so it points to the
next instruction after the function call. The return instruction or statement also
returns a value since the function has a returning type. In other words, the func-
tion could be used as a value specified by its type.
7.4 RETURN STATEMENT EXAMPLE
class test
{
struct box
{
public float left;
public float top;
public float right;
public float bottom;
};
static float Maximum(float v1, float v2)
{
if(v1>v2)
return v1;
else
return v2;
}
static float Minimum(float v1, float v2)
{
if(v1<v2)
return v1;
else
return v2;
}
static bool Intersect(float v1, float v2)
{
if(v1-v2<=0)
return true;
else
return false;
}
static void Main()
{
box b1, b2;
Console.WriteLine("Enter the left, top, right,
and bottom coordinates of b1:");
/* the input from keyboard is stored in the
structure members */
b1.left = Int32.Parse(Console.ReadLine());
b1.top = Int32.Parse(Console.ReadLine());
b1.right = Int32.Parse(Console.ReadLine());
b1.bottom = Int32.Parse(Console.ReadLine());
Funct ions 187
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
Console.WriteLine("Enter the left, top, right,
and bottom coordinates of b2:");
b2.left = Int32.Parse(Console.ReadLine());
b2.top = Int32.Parse(Console.ReadLine());
b2.right = Int32.Parse(Console.ReadLine());
b2.bottom = Int32.Parse(Console.ReadLine());
if(Intersect(Maximum(b1.left,b2.left)-
Minimum(b1.right,b2.right),
Minimum(b1.bottom,b2.bottom)-
Maximum(b1.top,b2.top)))
Console.WriteLine("b1 and b2
intersect\n");
else
Console.WriteLine("b1 and b2 do not
intersect\n");
}
}
7.5 CALL BY VALUE FUNCTI ON ARGUMENTS
Arguments can be passed in two ways: call by value and call by reference. The
call by value method copies the value of the argument into the function parame-
ter. Therefore, changes made to the parameter have no effect on the argument. In
other words, the function code cannot modify the arguments used to call the
function.
Ex ampl e:
class test
{
static void Main()
{
int x;
x=10;
callByValue(x);
Console.WriteLine("The argument x was not
modified by the function:
x={0}",x);
}
static void callByValue(int x)
{
x=20;
}
}
7.6 CALL BY REFERENCE FUNCTI ON ARGUMENTS
To pass a parameter by reference, use the ref (or out) keyword. A variable of a
reference type does not contain its data directly; it contains a reference to its
data. When you pass a reference-type parameter by value, it is possible to change
the data pointed to by the reference, such as the value of a class member. How-
ever, you cannot change the value of the reference itself; that is, you cannot use
Funct ions 188
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
the same reference to allocate memory for a new class and have it persist outside
the block. To do that, pass the parameter using the ref (or out) keyword.
Ex ampl e:
class test
{
static void Main()a
{
int x=10, y=20;
Console.WriteLine("Before calling swap: x={0},
y={1}",x,y);
/* call by reference arguments*/
swap(ref x,ref y);
Console.WriteLine("After calling swap: x={0},
y={1}",x,y);
}
/* call by reference parameters*/
static void swap(ref int p1,ref int p2)
{
int tmp;
tmp = p1; /*Saving p1 in tmp*/
p1 = p2; /*p1 takes the value of p2*/
p2 = tmp; /*p2 takes the value of tmp*/
}
}
7.7 FUNCTI ON RETURNI NG VALUE EXAMPLE
7.7.1 Ret ur ni ng an I nt eger
class test
{
static void Main()
{
int i;
Console.Write("Enter an integer value: ");
i = Int32.Parse(Console.ReadLine());
Console.WriteLine("The absolute value of {0} is
{1}", i, Absolute(i));
}
/* the function receives an integer and returns its
absolute value */
static int Absolute(int i)
{
return i>=0? i:-i;
}
}
Funct ions 189
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
7.8 DI RECT I MPLEMENTATI ONS
7.8.1 Mat h Pr obl em
Given the following table:
Write a program that calculates the volume of any one of the three-dimensional
shapes mentioned above. The program should include four functions, one func-
tion for each shape. It should take as input the kind of the shape, then the param-
eter(s) necessary to calculate the volume (A, r, h).
The output should be similar to the following:
7.8.2 Chemi st r y Pr obl em
Write a program that takes as input the number of elec-
trons in an atom (up to 20) and returns the number of
electrons it has on its peripheral electronic layer. Use the
concept of functions.
The output should be similar to the following:
Funct ions 190
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
7.8.3 Chemi st r y Pr obl em
Write a program that takes as input the mass number and the atomic number of
an atom and returns its number of neutrons. Use the concept of functions. The
output should be similar to the following:
7.8.4 Chemi st r y Pr obl em
In a calorimeter, you mix up m
1
grams of water at a tem-
perature
1
T C
o
and m
2
grams of water at a temperature
2
T C
o
. Write a program that takes as input m
1
, T
1
, m
2
,
and T
2
and returns the final temperature T
f
of the mix-
ture. Use the concept of functions. The output should be
similar to the following:
7.8.5 Phy si cs Pr obl em
Write a program that takes as input the initial
velocity (speed and angle with the horizontal)
of a projectile and returns the maximum height
that it will reach from its initial position.
The output should be similar to the following:
Funct ions 191
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
7.8.6 Phy si cs Pr obl em
A person drags a box on a frictionless horizontal path along a distance d with a
force F and making an angle a with the horizontal. Write a program that takes as
input, d, F, and a and returns the work done by the individual. Use the concept of
functions.
Fl ow Char t
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
Mechanical physics book
Funct ions 192
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
Appr oach
The solution of this problem in itself is so easy, yet a very important concept in
physics lies behind this simplicity. It is the concept of work.
What is work?
Although a basic definition of work is so commonly used in our everyday life,
work in physics is defined differently. Simply, when a force is exerted on a body
such that the force makes the body move for a certain distance, we say that this
force has done a certain amount of work. This work is defined as the dot product
of the force which is a vector with the displacement of the object which is
another vector. Notice that the dot product is a scalar quantity. The unit of work
is Nm or Joule.
For example, a girl holds her sled by a rope. She drags her sled straight to her
parents car on the frictionless horizontal ice by a constant force F having a mag-
nitude of 50 N such that the rope makes an angle of 60 degrees with the ice. The
car is 40 m far from the girl. What would be the work done by the girl during this
trip?
First of all, let us define the vector force F
ur
and the vector displacement
d
r
.

d
r
is a vector parallel to the horizontal of magnitude 40 m.
F
ur
is a vector making an angle of 60 degrees with the horizontal (with
d
r

also) and of a magnitude 50 N.
As defined before, the work is the dot product of the vectors just defined.

50 30 60 750 750 W F d F d cos F,d cos N m Joules u u
G G G JG JG JG
As you may figure out, the only component of the vector force that applies work
is the component parallel to the path where the object moves. This leads us to
conclude that when you apply a force perpendicular to the displacement, it will
not make any work. This is verified mathematically by the formula of work since
cos90
o
= 0.
After this brief introduction of the concept of work, it should be easy for you to
solve any problem where the calculation of work is required.
Sol ut i on
1. Find the distance d in meters along which the person dragged the box.
2. Find the cosine of the angle a that the force makes with the horizontal. Usually,
one drags a box by the mean of a rope. In this case, a is the angle between the
rope and the horizontal.
3. Find the force (in Newtons) which the person exerts when dragging the box.
4. Calculate the product Fdcos.
Funct ions 193
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
5. The product calculated in the previous step is equal to the work done in Joules.
Lessons Lear ned
After solving this problem:
I acknowledged the concept of work.
I learned a simple, step-by step method of finding the work done by a cer-
tain force used to move an object.
I can implement this method in a computer programming algorithm.
I developed the skill of finding the work that a force can do according to its
direction with respect to the path.
I find the task of calculating the work is easier now because it was broken
down into several simple steps.
I will remember this method faster because it was described verbally and
visually.
The output should be similar to the following:
7.8.7 Phy si cs Pr obl em
Write a program that takes as input the mass M of an object and
returns its weight W. Use functions.
The output should be similar to the following:
7.8.8 Phy si cs Pr obl em
A voltmeter measures the difference of potential
between the terminals of a resistor placed in an
electrical circuit through which passes a direct current,
I. Write a program that takes as input the resistance R
and the current I and returns the voltage at the resis-
tance. Use functions. The output should be similar to
the following:
Funct ions 194
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
7.9 FUNCTI ONS I N THE TEXT- BASED GAME
The text-based game uses functions extensively. Using functions not only facili-
tates programming, but it also is a way of organizing the program.
Since we are dealing with a lot of strings, a function is defined with one purpose:
to initialize the string, in other words, to set its value to null, as follows:
static public void InitString(ref string s)
This function has one argument, to initialize the string. It returns nothing.
The argument is a reference argument. Try to guess why!
Another function initializes the inventory as follows:
public static void InitInventory(ref sInventory[] i)
It also has one argument: the sInventory structure array. The argument is a refer-
ence argument.
For each station, there is a different valid list of commands. For that station, we
have a function to deal with the valid commands, as follows:
public static bool GameFn(verbs v,nouns n,ref sInventory[] i,ref nouns cl)
This function has four arguments:
The verb that the user entered.
The noun that the user entered.
The sInventory structure array.
A noun representing the current location.
The function returns a Boolean stating whether or not the game is solved.
7.10 FUNCTI ONS I N THE BRI X GAME
In this game, functions are used as follows:
The Form1_KeyDown function is called by the system whenever a keyboard key
is pressed:
private void Form1_KeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)
{

}
Inside this function, a check is made to know which key is pressed, and action is
taken accordingly.
Funct ions 195
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
The Form1_KeyUp function is also called by the system whenever a key is
released:
private void Form1_KeyUp(object sender,
System.Windows.Forms.KeyEventArgs e)
{

}
Within the function, we check to see which key is released and take appropriate
action.
A very important concept in game programming is timing. Timing means that a
specific action should be taken at specific intervals of time. This concept is imple-
mented in the Visual Studio environment by a timer function. A timer is added
and specifies the time interval. A function is then created and automatically called
by the system at the specified intervals of time. The timer can be enabled or dis-
abled. In this game three timer functions are called:
The first timer function is called once every 20 milliseconds:
private void timer1_Tick(object sender, System.EventArgs e)
{

}
This function updates the background and the location and status of all the
objects in the game. This function is initially enabled.
The second timer is called once every 500 milliseconds:
private void timer2_Tick(object sender, System.EventArgs e)
{

}
This function changes the shape of the 20 bricks used in the game. The bricks
have two frames of animation, and this timer function flips between them once
every half a second. This function is initially enabled.
The third function is called only once, two seconds after enabling it:
private void timer3_Tick(object sender, System.EventArgs e)
{

}
This function is enabled when all the bricks are hit. It waits two seconds, then dis-
plays a message announcing the end of the game. This function is initially
disabled.
Funct ions 196
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
We mentioned earlier that a timer is responsible for updating all the objects in
the game. One of its jobs is to check if a ball collided with a brick, and if it did, to
delete the specified brick. This is done through a special function called collided:
private bool collided(line l, int radius, int xcenter,
int ycenter)
{

}
This function takes four parameters as arguments:
A line structure specifying the line to be checked for collision.
An integer number specifying the radius of the circle to be checked
for collision.
An integer specifying the x-coordinate of the circles center.
An integer specifying the y-coordinate of the circles center.
The function returns a Boolean type.
When it is called, the function is given a line structure, a radius, and an x-coordi-
nate and a y-coordinate. The function checks to see if the
specified line intersects with the circle specified by its radius and center. If it
does, the function returns true; otherwise it return false.
The line corresponds to one of the four sides of the rectangle representing a
brick. The circle represents the ball. In this way we can know if the ball collided
with a brick and from which side.
To update the scene after the first timer is called, a special function responsible
for all the drawing is needed. This function is called paint:
private void Form1_Paint(object sender,
System.Windows.Forms.PaintEventArgs e)
{

}
As mentioned earlier, this function is called by the system after calling a special
function named invalidate. All the drawing is done exclusively in this function.
7.11 FUNCTI ONS I N CAVES OF DOOM
Caves Of Doom has a heavy function usage. In FunEditor, we have two kinds of
functions.
Object Functions: These are directly related to certain kinds of objects. An object
can be one of the following:
Game
Levels
Maps
Alarms
Funct ions 197
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
Sprites
Texts
Variables
Cursor
Object functions can be assigned to more than one object of the same type.
My Functions: Also known as user-defined functions, these are functions that
have global scope throughout the game play. They are independent of any FUN
object. These functions can be called from anywhere within the game.
First, let's talk about the game's object functions:
JFPositionUpdateFN: Used by the jetFighter sprite. Updates the jet-
Fighter sprite position.
BulletFN: Used by the jfBullet sprite. Controls the behavior of the jfBul-
let sprite. When jfBullet collides with other sprites, or when it goes out-
side the viewport, it is deleted.
JFFireFN: Used by the jetFighter sprite. Creates the jet fighter's bullets.
When the Spacebar is pressed, a function is called twice from within this
function to create a pair of bullets. This function is also responsible for creat-
ing the fighter's shield.
PositionUpdateFN: Used by five sprites: mutant, lander, baiter, barrier,
and invisible. Updates the position of the sprite. When the sprite's posi-
tion along the x-axis is less than 50, it is deleted.
SwarmerUpdateFN: Used by the swarmer sprite. Updates the position of the
sprite. When the sprite's position along the x-axis is less than 50, it is deleted.
BombFN: Used by the bomb sprite. Updates the bomb sprite position by mak-
ing it follow the jetFighter sprite. When the bomb sprite collides with
another sprite, it is deleted, and a particle system is created. In addition,
when the bomb sprite is outside the viewport, it is deleted.
LaserFN: Used by the laser sprite. Updates the position of the laser sprite.
When the sprite's animation ends, the sprite is deleted.
TmpScoreFN: Used by the tmpScore text. For every value of 3500, the
shieldCounter variable is incremented by one, which means that a new
shield is added to the list, and it can be used by the jetFighter sprite.
ShieldFN: Used by the shield sprite. The shield sprite indicates the status
of the shield available for use. Basically, we can have 0, 1, 2, 3, or 4 shields,
depending on the shieldCounter variable.
Funct ions 198
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
BonusFN: Used by the bonus sprite. Deletes the sprite when its first local
variable reaches a value of 0.
LevelFN: Used by the Level_1 level. When the Esc key is pressed, the game
goes back to the Intro level.
Now, let us talk about the game's My Functions:
Function Name: CreateFighterBullet
Function declaration: bool CreateFighterBullet(int xPos,int yPos)
Return type: bool.
Purpose: To create a jfBullet sprite, set its position, give the created sprite a
new name, a vector direction, a speed, and set its Unused flag to false. It also
plays a sound effect called playerShot.
Function Name: CreateEnemyBullet
Function declaration: bool CreateEnemyBullet(int xPos,int yPos)
Return type: bool.
Purpose: To create an enemyBullet sprite, set its position, give the created sprite
a new name, a vector direction, a speed, and set its Unused flag to false. It also
plays a sound effect called enemyShot.
Function Name: CreateMutant
Function declaration: bool CreateMutant(int xPos,int yPos,uint
timer,uint patternIndex)
Return type: bool.
Purpose: To create a mutant sprite, set its position and local variables, give the
created sprite a new name, a vector direction, a speed, and set its Unused flag to
false. It also sets and starts the movement pattern(s).
Function Name: CreateLander
Function declaration: bool CreateLander(int xPos,int yPos,uint
timer,int patternIndex)
Return type: bool.
Purpose: To create a lander sprite, set its position and local variables, give the
created sprite a new name, a vector direction, a speed, and set its Unused flag to
false. It also sets and starts the movement pattern(s).
Function Name: CreateBaiter
Function declaration: bool CreateBaiter(int xPos,int yPos,uint
timer,int patternIndex)
Return type: bool.
Purpose: To create a baiter sprite, set its position and local variables, give the
created sprite a new name, a vector direction, a speed, and set its Unused flag to
false. It also sets and starts the movement pattern(s).
Funct ions 199
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
Function Name: CreateBarrier
Function declaration: bool CreateBarrier(int xPos,int yPos,uint
timer,bool visible,uint animation)
Return type: bool.
Purpose: To create a barrier sprite, set its position and local variables, give the
created sprite a new name, set its animation, and set its Unused flag to false.
Function Name: CreateImmuneBarrier
Function declaration: bool CreateImmuneBarrier(int xPos,int
yPos,uint timer)
Return type: bool.
Purpose: To create a barrier sprite, set its position and local variables, give the
created sprite a new name, set its animation to Animations.BARRIER_IMMUNE,
and set its Unused flag to false.
Function Name: CreateHalfBarrier
Function declaration: bool CreateHalfBarrier(int xPos,int yPos,uint
timer,bool flipped)
Return type: bool.
Purpose: To create a barrier sprite, set its position and local variables, give the
created sprite a new name, set its animation to
Animations.BARRIER_BOTTOMUP or Animations.BARRIER_TOPDOWN, and
set its Unused flag to false.
Function Name: CreateSwarmer
Function declaration: bool CreateSwarmer(int xPos,int yPos,uint timer,int
speed)
Return type: bool.
Purpose: To create a swarmer sprite, set its position and local variables, give the
created sprite a new name, and set its Unused flag to false.
Function Name: CreateBigBoss
Function declaration: bool CreateBigBoss(int xPos,int yPos,uint
timer1,uint timer2)
Return type: bool.
Purpose: To change some properties of the bigBoss sprite, like setting its posi-
tion, local variables, speed, and setting its Unused flag to false.
Function Name: CreateBossBomb
Function declaration: bool CreateBossBomb(int xPos,int yPos)
Return type: bool.
Purpose: To create a bomb sprite, set its position and vector direction, give the
created sprite a new name, and set its Unused flag to false. It also plays the ene-
myShot sound effect.
Funct ions 200
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
7.12 TEXT- BASED GAME EXERCI SE
(The complete solution of the exercise is available in the Appendix.)
You should refer to the solution available in the directory TBG Part2 and add
code to it.
Declare a function GetLocation that takes the verb and location strings and
returns the new location.
static int GetLocation(String t1, String t2)
Parameters
String t1[]the string to compare with a verb string
String t2[]the string to compare with a location string
If both t1 and t2 are found, the function returns an integer, which is the new
location to go to. Otherwise, the function returns 1 if t1 is Help of if the
command is wrong.
Call the function GetLocation from main.
The GetLocation function is used to get the new location to go to.
Ex ampl e:
currentLocation = (locations) GetLocation(token1, token2);
Add a while-loop that repeats all steps until a Boolean variable solved is set
to true.
Ex ampl e:
while (!solved){
:
}
Set the integer variable solved to true in every case statement.
Funct ions 201
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
Output Example:
7.13 ADDI NG CODE TO CAVES OF DOOM
In this section, we will add code to an unfinished version of Caves Of Doom and
then run it to see the changes taking effect.
1. With FunEditor.Net, open the file called "CavesOfDoomChapter7.fun."
Note: This version is not a complete version of the game.
2. In the Project Resources window, under Game Assests, right-click on My
Functions and from the pop-up menu, click Add
The My Functions Properties New window will open.
3. In the Name box type CreateFighterBullet.
4. In the code area, type the following code exactly
bool CreateFighterBullet(int xPos,int yPos)
{
Sprite s = Sprite.Search("jfBullet");
Sprite bullet = s.CreateSprite();
if (bullet != null){
Sound shot = Sound.Search("playerShot");
//if the sound is playing then stop it
if (shot.IsPlaying)
shot.Stop();
shot.Play(); //play the sound from its start
Funct ions 202
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
bullet.MapPosition(xPos,yPos);//setting the
position
bullet.Name = "jfBulletCopy"; //changing the name
bullet.VectorDirection(1,0); //setting the vector
direction
bullet.Speed = 7; //setting the bullet
bullet.Unused = false; //setting it to used
return true;
}
else return false ;
}
5. Click Save and close the My Functions Properties window.
6. Click Run and click Yes.
The game will run, and the jet fighter can now fire bullets when the Space-
bar is pressed.
7.14 ADDI NG CODE TO BRI X
In this section, we will add code to an unfinished version of Brix and run it to see
the changes taking effect.
1. With VisualC#.Net, open the project called /Brix/Brix Chapter7/
Brix.csproj.
Note: This version is an incomplete version of the game. Attempting to run
this version as is before adding the appropriate code will generate errors.
2. Open the file called Form1.cs.
3. Before the method
private void timer2_Tick(object sender, System.EventArgs e)

add the following method:

private bool collided(line l, int radius, int xcenter,
int ycenter)
{
double A, B, C, T1, T2, Delta;
A = Math.Pow(l.x2,2) - 2*l.x2*l.x1 + Math.Pow(l.x1,2) +
Math.Pow(l.y2,2) - 2*l.y2*l.y1 + Math.Pow(l.y1,2);
B = 2*l.x2*l.x1 - 2*xcenter*l.x2 - 2*Math.Pow(l.x1,2) +
2*xcenter*l.x1 + 2*l.y1*l.y2 - 2*ycenter*l.y2 -
2*Math.Pow(l.y1,2) + 2*ycenter*l.y1;
C = Math.Pow(l.x1,2) - 2*l.x1*xcenter +
Math.Pow(xcenter,2) + Math.Pow(l.y1,2)
- 2*l.y1*ycenter + Math.Pow(ycenter,2) -
Math.Pow(radius,2);
Delta = Math.Pow(B,2) - 4*A*C;
if (Delta < 0) return false;
T1 = (1/(2*A))*(-B + Math.Sqrt(Delta));
T2 = (1/(2*A))*(-B - Math.Sqrt(Delta));
Funct ions 203
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
7
return (((T1 >= 0) && (T1 <=1)) || ((T2 >= 0) &&
(T2 <=1)));
}
4. Save and run the game.
The added method is responsible for detecting collision between the ball
and the bricks and between the ball and the pad.
8
FLOW CONTROL
Flow Cont rol 205
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
FLOW CONTROL
C# executes the statements in a program one after the other in the same order in
which they appear in the main function. The flow control statements allow the
programmer to change the order in which the statements of a program are exe-
cuted. The flow control statements give a greater control to the programmer. The
flow control statements are divided into the following groups:
Loops
Conditional jumps and selection
8. 1 THE WHI LE STATEMENT
The while statement executes a block of statements repeatedly until a specified
expression evaluates to false. It has the form:
while (expression) statement
where expression is an expression that can be implicitly converted to bool or a
type that contains overloading of the true and false operators. The expression is
used to test the loop-termination criteria. Statement is the statement(s) that will
be executed.
A while loop executes zero or more times because the test of expression takes
place before each execution of the loop. It can terminate when a break, goto,
return, or throw statement transfers control outside the loop. To pass control to
the next iteration without exiting the loop, use the continue statement.
Ex ampl e:
using System;
class Test
{
static void Main()
{
int i = 16;
while (n > 0)
{
Console.WriteLine("Another value of i: {0}", i);
i -= 4;
}
}
}
8.2 THE DO- WHI LE STATEMENT
The do statement executes a block of statements repeatedly until a specified
expression evaluates to false. It is in the following form:
do statement while (expression);
where expression is an expression that can be implicitly converted to bool. State-
ment is the statement(s) to be executed. Regardless of the value of expression, the
body of the do statement is executed at least once.
Flow Cont rol 206
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
Ex ampl e:
using System;
public class Test
{
static void Main ()
{
int i = 16;
do
{
Console.WriteLine("Another value of i: {0}", i);
i -= 4;
}
while(i > 0);
}
}
Ex ampl e:
using System;
public class Test
{
static void Main ()
{
int i = 16;
do
{
Console.WriteLine("Another value of i: {0}", i);
i -= 4;
}
while(i > 18);
}
}
In the preceding example, although the condition evaluates initially to false, the
loop will be executed once.
8.3 THE FOR LOOP
The for loop executes a block of statements repeatedly until a specified expres-
sion evaluates to false. It is in the following form:
for ([initializers]; [expression]; [iterators]) statement
where initializers is a comma-separated list of expressions or assignment state-
ments that will initialize the loop, expression is an expression that can be implic-
itly converted to bool, iterators is an expression statement(s) that increments or
decrements the loop counters, and statement is the embedded statement(s) to be
executed.
The for statement executes the statement repeatedly as follows: first, the initial-
izers are evaluated; then, while the expression evaluates to true, the statement(s)
are executed; when expression evaluates to false, control is transferred outside the
Flow Cont rol 207
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
loop. A for statement executes zero or more times because the test of expression
takes place before the execution of the loop. All of the expressions of the for
statement are optional.
Ex ampl e:
using System;
public class Test
{
static void Main()
{
for (int i = 6; i >0; i--)
Console.Write(i);
}
}
8.4 THE FOREACH, I N STATEMENT
The foreach statement repeats a group of statements for each element in an array.
The foreach statement is used to iterate through the array to get the desired
information, but should not be used to change the contents of the array. The
statement is in the following form:
foreach (type identifier in expression) statement
where type is the type of identifier, identifier is the iteration variable that repre-
sents the array element, expression is the array expression, and statement is the
statement(s) to be executed.
The statements continue to execute for each element in the array. Control is
transferred to the next statement following the foreach block after the iteration
has been completed for all the elements. When used with an array, the foreach
statement repeats the embedded statement(s) for each element in the array.
Ex ampl e:
using System;
class test
{
static void Main()
{
int[] ar = new int [] {0,-1,2,-3,4,-5,6,-7,8,-9};
foreach (int i in ar)
{
if (i < 0)
Console.WriteLine("This is a negative number");
else
Console.WriteLine("This is a positive number");
}
}
}
Flow Cont rol 208
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
8.5 THE JUMP STATEMENT
The jump statement is used for branching, which causes a transfer of the pro-
gram control. The following keywords are used in jump statements: break, con-
tinue, goto, return.
8.5.1 Br eak
The break statement terminates the closest enclosing loop or conditional state-
ment in which it appears. Control is passed to the statement that follows the ter-
minated statement, if any. The break statement takes the form: break;
Ex ampl e:
using System;
class Test
{
static void Main()
{
for (int i = 15; i >= 0; i--)
{
if (i == 10)
break;
Console.Write(i);
}
}
}
8.5.2 Cont i nue
The continue statement passes control to the next iteration of the enclosing iter-
ation statement in which it appears. It takes the form: continue;
Ex ampl e:
using System;
class Test
{
static void Main()
{
for (int i = 13; i > 1; i--)
{
if (i > 2)
continue;
Console.WriteLine("The current value is : {0}", i);
}
}
}
8.5.3 Got o
The goto statement transfers control directly to a labeled statement. It can be one
of the following forms:
goto identifier;
goto case constant-expression;
goto default;
Flow Cont rol 209
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
where identifier is a label and constant-expression is switch-case label. Identifier
indicates a label located in the current body, the same scope, or an enclosing
scope of the goto statement. Goto is commonly used to transfer control to a
switch-case label. It is useful to get out of nested loops. A warning message can
be issued if the label has never been referenced in the program.
Ex ampl e:
using System;
class test
{
static void Main()
{
int i = 0;
do
{
if (i == 8) goto Label1;
else i++;
}
while (true);
Label1: Console.Write(i);
}
}
8.5.4 Ret ur n
The return statement terminates execution of the method in which it appears
and returns control to the calling method. If the method is of the type void, the
return statement can be omitted. The return statement has the form:
return [expression];
where expression is the value returned by a method. Expression is not used with
methods of the type void.
Ex ampl e:
class Test
{
static int AddInt(int i1, int i2)
{
int j = i1 + i2;
return j;
}
public static void Main()
{
int n1 = 120;
int n2 = 125;
int sum = AddInt(n1,n2);
}
}
Flow Cont rol 210
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
8.6 THE SWI TCH STATEMENT
The switch statement selects for execution a statement from a list. The type of a
switch statement is specified by the switch expression. The switch statement can
have at most one default label.
A switch statement is executed as follows: the switch expression is evaluated
and converted to the specified type; if one of the constants specified in a case
label is equal to the value of the switch expression, control is transferred to the
statement list following the matched case label; if none of the constants specified
in case labels is equal to the value of the switch expression, control is transferred
to the statement list following the default label, if a default label exists; if no
default label is present, control is transferred outside the switch statement.
A switch section is not permitted to fall through to the next switch section.
When execution of a switch section is to be followed by execution of another
switch section, a goto case or goto default statement must be used. Multiple
labels are permitted in a switch-section.
The statement list of a switch section typically ends in a break, goto case, or goto
default statement. The governing type of a switch statement may be the type
string. If this is the case, null is permitted as a case label constant. The statement
list is reachable if the switch statement is reachable and at least one of the follow-
ing is true:
The switch expression is a non-constant value.
The switch expression is a constant value that matches a case label in the
switch section.
The switch expression is a constant value that doesnt match any case label,
and the switch section contains the default label.
A switch label of the switch section is referenced by a reachable goto case or
goto default statement.
The end point is reachable if at least one of the following is true:
The switch statement contains a reachable break statement that exits the
switch statement.
The switch statement is reachable, the switch expression is a non-constant
value, and no default label is present.
The switch statement is reachable, the switch expression is a constant value
that doesnt match any case label, and no default label is present.
Flow Cont rol 211
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
8.7 I F- ELSE
The if statement is a control statement. It executes a block of code if an expres-
sion evaluates to true. It has the form:
if (expression)
statement1
[else
statement2]
where expression is an expression that can be converted to bool, statement1 is the
statement(s) to be executed if expression is true, and statement2 is the state-
ment(s) to be executed if expression is false.
If expression is true, statement1 is executed. If the optional else clause exists and
expression evaluates to false, statement2 is executed. After executing the if state-
ment, control is transferred to the next statement.
If either of the two results of the if statement (true or false) results in executing
more than one statement, multiple statements can be conditionally executed by
including them into blocks.
The statement(s) to be executed upon testing the condition can be of any kind,
including another if statement nested into the original if statement. In nested
if statements, the else clause belongs to the last if that does not have a corre-
sponding else.
Ex ampl e:
using System;
public class Test
{
static void Main()
{
Console.Write("Enter something from the keyboard ");
char ch = (char) Console.Read();
if (Char.IsLetter(ch))
if (Char.IsLower(ch))
Console.WriteLine("What you entered is a lowercase
character.");
else
Console.WriteLine("What you entered is an uppercase
character.");
else
Console.WriteLine("What you entered is not a
character.");
}
}
Ex ampl e:
using System;
public class Test
{
static void Main()
{
Flow Cont rol 212
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
Console.Write("Press a key: ");
char ch = (char) Console.Read();
if (Char.IsUpper(ch))
Console.WriteLine("You pressed an uppercase
character.");
else if (Char.IsLower(c))
Console.WriteLine("You pressed a lowercase character.");
else if (Char.IsDigit(c))
Console.WriteLine("You pressed a digit.");
else
Console.WriteLine("What You pressed is not
alphanumeric.");
}
}
8.8 DI RECT I MPLEMENTATI ONS
8.8.1 Mat h Pr obl em
Write a program that reads four numbers and displays the maximum and mini-
mum ones. The program contains two functions: the maximum function that
returns the maximum number and the minimum function that returns the mini-
mum number. The output should be similar to the following:
8.8.2 Mat h Pr obl em
Write a program that takes a quadratic equation as input and returns whether it
has two distinct roots, a double root, or no roots. The output should be similar to
the following:
8.8.3 Mat h Pr obl em
Write a program that takes the coordinates of two vectors and compares them to
determine if they are parallel, equal, opposite, or equal in magnitude. The output
should be similar to the following:
Flow Cont rol 213
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
8.8.4 Chemi st r y Pr obl em
Mixing a volume V
1
of a NaCl solution of concentration C
1

and a volume V
2
of an NaCl solution of concentration C
2

produces a NaCl solution of concentration C.
Write a program that takes as input V
1
, C
1
, V
2
, and C
2
and
returns C.
Fl ow Char t
Flow Cont rol 214
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
General chemistry book
Appr oach
In order to solve this problem and many other chemistry problems like this one,
you need a good understanding of what the keywords: solvent, solute, solution,
and concentration mean in chemical context.
Solvent
A liquid that has the ability to dissolve some substances or chemical com-
pounds.
Solute
The substance dissolved in the solvent.
Solution
Together, the solvent and solute form a solution.
Concentration
Represents the quantity of the solute in one unit of volume of the solvent.
Expressed, for example, in moles per liters or grams per liters. For example,
a 0.1 mole/l NaCl solution, means that each liter of this solution contains 0.1
mole of sodium chloride.
Now that we have agreed on the same vocabulary, we can start solving the prob-
lem. Once you know the concentration of a solution, we are able to find the
quantity of solute in any volume V of this solution. How is that?
In fact, let C be the concentration of the solution S given in moles per liter. If we
extract a volume V of S, it will contain a number n of moles given by:
1 liter C moles
Vn
Therefore,
n = CV
In other words, if one liter of the solution contains C moles, then V liters of the
solution will contain CV moles.
We know the fundamental relation solves the problem. Eventually, having C
1

and V
1
, we can find n
1
, and having C
2
and V
2
, we can find n
2
. When we mix
both volumes, we will get a solution of volume V = V
1
+ V
2
containing n moles
Flow Cont rol 215
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
of NaCl such that n = n
1
+ n
2
. Knowing n and V, we can easily find the concen-
tration of the mixture.
After this brief introduction of concentration of chemical solutions, you will feel
more comfortable dealing with chemical problems involving concentration and
certainly be aware of the beautiful concept that underlies this simple problem.
Sol ut i on
1. Measure the volume of the first solution of NaCl in liters. Let V
1
be this vol-
ume.
2. Find the concentration of the first solution of NaCl in moles per liters. Let
C
1
be this concentration.
3. Multiply C
1
by V
1
in order to find n
1
, the number of moles of NaCl in the
first NaCl solution.
4. Measure the volume of the second solution of NaCl in liters. Let V
2
be this
volume.
5. Find the concentration of the second solution of NaCl in moles per liters.
Let C
2
be this concentration.
6. Multiply C
2
by V
2
in order to find n
2
, the number of moles of NaCl in the
second NaCl solution.
7. Add both volumes V
1
and V
2
to find the total volume V of the mixture in
liters.
8. Add n
1
and n
2
to find n, the total number of moles of NaCl in the mixture.
9. Calculate C, the concentration of the solution in moles per liters after the
mixture by dividing n by V.
Lessons Lear ned
After solving this problem:
I understood the meaning of concentration.
I learned a simple, step-by-step method of finding the concentration of a
mixture of solutions of the same compound but with different concentra-
tions.
I can implement this method in a computer programming algorithm.
I developed the skill of finding the concentration of a mixture of two solu-
tions in a certain chemical compound.
I can accomplish the task of finding the concentration of a mixture of two
solutions in a certain chemical compound more easily now because it was
broken down into several simple steps.
Flow Cont rol 216
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
I will remember this method faster because it was described verbally and
visually.
The C# Appr oach
The above chemistry problem was solved using a purely scientific approach.
Now you need to solve it using C#. The output should be similar to the following:
8.8.5 Chemi st r y Pr obl em
To neutralize V
1
liters of a HCl solution of pH x, we need to mix it with V
2
liters
of a NaOH solution of concentration C. Write a program that takes as input V
1
,
x, and C and returns V
2
.
Fl ow Char t
Flow Cont rol 217
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
Tool s
A pen or a pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
General chemistry book
Appr oach
A pleasant manner of solving a volumetric chemistry problem like this one is to
imagine yourself working in a chemistry lab with all the instruments and trying
to implement the given chemical experiment described in the problem.
In a chemistry lab, the chemist usually receives an HCl solution of unknown vol-
ume and unknown pH. If asked to neutralize this solution using an NaOH solu-
tion, the following steps are usually followed:
1. The volume of the HCl solution is measured using a graduated cylinder.
The pH of the HCl solution is measured using litmus paper or a pH-meter
for more precision.
2. Once the chemist knows the volume and the pH of the solution, n, the
number of ions H
+
in the solution which is also the number of moles of
HCl can be found.
4. Then an NaOH solution of a certain concentration C is prepared.
5. V
2
, the volume of the NaOH solution already prepared so that it will
contain n moles of NaOH (n ions of OH
-
, that is, the same number of H
+

ions contained in the HCl solution) is calculated.
6. A volume V
2
of the NaOH solution is taken out using a graduated cylinder
or a pipette.
7. The extracted volume V
2
is added to the acid solution.
8. Finally the pH of the resulting solution is checked to make sure that it was
neutralized.
Calculation of n
First let us find the concentration of the acid solution once we know that pH = x.
pH
H
10 10
x
C



+
1 1
H H
C V 10 V
x
n n

u u
Flow Cont rol 218
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
Calculation of V2
Once the chemist prepares an NaOH solution of concentration C, the volume V
2

of this solution that contains n ions of OH
-
is given as follows:
g
-
2 2
OH OH
C V C V n n

u u
2
V
C
n

2
10 V
V
C
x
u

In this case of neutralization of HCl by NaOH, the neutralization is done mole by


mole each mole of HCl releases one mole ion of H
+
that is used to neutralize
one mole ion of OH
-
released by one mole of NaOH. This in fact simplifies the
problem but is not always the case. Technically, this is called the neutralization of
a strong acid (HCl here) by a strong base (NaOH here). However, if we used a
weak acid, like acetic acide, instead of HCl, the problem would be solved differ-
ently.
Sol ut i on
1. Find x, the pH of the acid solution HCl.
2. Measure V
1
, the volume of the acid solution that needs to be neutralized by
NaOH.
3. Knowing the pH, find n, the number of moles of H
+
contained in the vol-
ume V
1
of the acid solution.
4. Find C, the concentration of the basic solution NaOH with which you will
neutralize the volume V
1
of acid solution that you have.
5. You need to choose the volume V
2
of the solution of NaOH of concentra-
tion C in a way that it contains exactly n moles of OH
-
, that is, the same
number of moles of H
+
because in this case, each mole of H
+
neutralizes
one mole of OH
-
.
6. V
2
is the volume required of the basic solution to neutralize the acid solu-
tion.
5. What di d I acqui r e f r om t hi s ex per i ment ?
After solving this problem:
I understood the neutralization phenomenon.
I learned a simple, step-by-step method of neutralizing a certain volume of
HCl by another one of NaOH.
This method can be implemented in a computer programming algorithm.
I can accomplish the task of finding the volume of an NaOH solution of
concentration C that a certain volume of a HCl solution of pH x needs in
Flow Cont rol 219
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
order to be neutralized more easily now because it was broken down into
several simple steps.
I will remember this method faster because it was described verbally and
visually.
The C# Appr oach
We solved the above chemistry problem using a purely scientific approach. Now
you need to solve it using C#. The output should be similar to the following:
8.8.6 Chemi st r y Pr obl em
To neutralize V
1
liters of an HCl solution of pH x, we need to
mix it with V
2
liters of an NaOH solution of concentration C.
Write a program that takes as input V
1
, x, and V
2
and returns
C. The output should be similar to the following:
8.9 FLOW CONTROL I N THE TEXT- BASED GAME
Usually, the flow control of a game decides how the game will advance and con-
tinue. In the text-based game, there are some places where a decision should be
taken or a loop should take place. This is done as follows:
1. A sequence of information should be repeatedly entered and interpreted.
The game should continuously check if the end is reached by checking if the
solved boolean is true or if there is no more money. If none of these two con-
ditions is true, the loop should repeat. How this is done? Through the use of
the while loop as follows:
while((!solved) && (inventory[(int)nouns.Money].values>0))
Here the while loop repeats as long as the solved boolean is false and there is
money to play with.
2. After the player enters a command, the parser has to check if this is a one-
word or two-words command. For each case, a different action should be
taken. This is done by using an if then else statement, as follows:
if (ss.Length > 1)
{
// do something
}
Flow Cont rol 220
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
else
{
// do something
}
3. Before interpreting a command, the parser has to know where the player is
in order to act accordingly. The best way to do it is through a switch state-
ment, as follows:

switch(currentLocation)
{
case nouns.Game:
//do something
break;
case nouns.GameAssets:
//do something
break;
.
.
.
}
where currentLocation represents the player's current location.
When a command is entered, how can the parser know which command
this is? Simple: the first and second word (if any) is compared against all the
available commands. This is done using a for loop to iterate through all
commands, as follows:
int i;
for (i=0; i<size; i++){
if (list[i].Equals(s))
// do something
}
Where size is the size of the list that contains the commands, and s is a string
representing the input command.
8.10 FLOW CONTROL I N THE BRI X GAME
This game relies mainly on the if and if else statements to control the game
flow. It also uses the for loop to avoid repetition and make the code simpler.
Each of the 20 bricks used in the game should be placed. This is done using
a nested for loop as follows:
for (int i = 0;i<2;i++)
for (int j = 0;j<10;j++)
{

}
In this way, two rows with ten bricks in each row are created.
Flow Cont rol 221
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
Within Form1_KeyDown function, we check to determine if the Space key is
pressed. To do so, we use the if statement as follows:
if (e.KeyData == Keys.Space)
{

}
The if and if else statements are extensively used in this game, but all
with the same principle.
8.11 FLOW CONTROL I N CAVES OF DOOM
FUN Editor provides a mechanism for controlling the flow of events in a game.
This mechanism is hidden from the programmer, but it has an interface. Mainly,
the flow control in FUN Editor is provided through the use of two concepts:
object functions and state machines. (Object functions were discussed in the
previous chapter). A state machine is one of the logical components that add life
and behavior to different FUN objects.

State machines are easier to create and manipulate simply because they have a
visual representation that allows you to follow the codes logic. This is done with
the help of states connected to one another by logical expressions, represented by
edges. The object having a state machine driving it will start with the initial state
(or starting state) and will move to another state if and only if the condition to
move to that other state is true. Any one state can lead to many others, but the
object will only go to one state that has its condition coming from the current
state which is being satisfied. Every state machine should be given a unique
name.
State machines, like object functions, are used by one type of object created in
the game's levels. You can create a state machine to be used later and shared by
more than one sprite. You can create another one that a map or maps objects will
use later. Therefore, when you create a state machine one of the first decisions
you have to make is which type of objects will use it. The used by field provides a
list of supported objects, which can be one of the following:
Game Sprites
Levels Texts
Maps Variables
Alarms Cursor
Technically, it is wrong to select Sprites from the list and then assign the state
machine to a map object. The various functions that will later be created to rep-
resent the various functionalities of any state machine (conditions and actions)
will create an object reference called this. It refers to the instance of the object
calling the state machine. By using this, you can refer to the object from within
any condition body or action body when you later write your game logic. If you
define a state machine to be used by a sprite and then assign it to a map, this will
Flow Cont rol 222
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
then refer to an incorrect data type, causing your game to possibly crash or at
least not run properly.
Following is a detailed list of the state machines used in the game:
Name: JFMovementSM
Used by: sprites.
Object using the state machine: the jetFighter sprite.
Number of states: 9.
Purpose: Controls the movement of the jetFighter sprite. The nine states
represent the nine actual movement states that the jetFighter sprite can
have, which are:
Not Moving (Idle)
Moving Right
Moving Left
Moving Up
Moving Down
Moving Up Right
Moving Up Left
Moving Down Right
Moving Down Left
Name: GenerateAliensSM
Used by: levels.
Object using the state machine: the Level_1 level.
Number of states: 29.
Purpose: Creates the different enemy aliens that attack the jetfighter. Alien
creation occurs sequentially, according to the jetFighter position.
Name: MutantSM
Used by: sprites.
Object using the state machine: The "mutant" sprite.
Number of states: 6.
Purpose: Controls the behavior of the mutant enemy. Initially, the mutant is
Idle. When it reaches a position less than 630 along the x-axis, it goes In
action. From that state, it can Fire on the jetFighter. It can also be Hit by
the jetfighter. When it is badly hit, it will Explode, and then we Remove it
by deleting it.
Name: LanderSM
Used by: sprites.
Object using the state machine: the lander sprite.
Number of states: 6.
Purpose: Controls the behavior of the lander enemy. Initially, the lander
enemy is Idle. When it reaches a position less than 630 along the x-axis, it
goes In action. From that state, it can Fire on the jetfighter. It can also be
Hit by the jetfighter. When it is badly hit, it will Explode, and then we
Remove it by deleting it.
Flow Cont rol 223
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
Name: BaiterSM
Used by: sprites.
Object using the state machine: the baiter sprite.
Number of states: 6.
Purpose: Controls the behavior of the baiter enemy. Initially, the baiter
enemy is Idle. When it reaches a position less than 630 along the x-axis, it
goes In action. From that state, it can Fire on the jetFighter. It can also be
Hit by the jetFighter. When it is badly hit, it will Explode, and then we
Remove it by deleting it.
Name: BarrierSM
Used by: sprites.
Object using the state machine: the barrier sprite.
Number of states: 3.
Purpose: Controls the behavior of the barrier enemy. Initially, the barrier
enemy is Collapsed, which means that no laser beam is launched yet. After
a while it becomes Expanded by launching the laser beam. When it is badly
hit, we Remove it by deleting it.
Name:SwarmerSM
Used by: sprites.
Object using the state machine: the swarmer sprite.
Number of states: 6.
Purpose: Controls the behavior of the swarmer enemy. Initially, the swarmer
is Idle. When it reaches a position less than 630 along the x-axis, it goes In
action. From that state, it can Fire on the jetfighter. It can also be Hit by
the jetfighter. When it is badly hit, it will Explode, and then we Remove it
by deleting it.
Name: BigBossSM
Used by: sprites.
Object using the state machine: the bigBoss sprite.
Number of states: 8.
Purpose: Controls the behavior of the bigBoss enemy. Initially, the bigBoss is
Idle, waiting to attack. When it reaches a position less than 500 along the x-
axis, it goes In action. From that state, it can FireLaser or FireBomb on
the jetfighter. It can also be Hit by the jetFighter. When it is badly hit, it will
Explode, Wait for a while, and then we Remove it by deleting it. When
this enemy is removed, the game ends by going to the success level.
Name: JFLifeSM
Used by: sprites.
Object using the state machine: the jetFighter sprite.
Number of states: 5.
Purpose: Controls the behavior of our jetfighter. Initially, the jetFighter is
Idle, with no important events going on. When it is being attacked by ene-
mies, it can be Hit. When it collides with the barriers, it goes to a state
called CollidedWithHalf. From the Hit state or the CollidedWithHalf
Flow Cont rol 224
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
state, it can Explode. If the jetFighter explodes and there are no more
remaining lives, the jetFighter goes to an End, and the game terminates by
going to the GameOver level.
Name: IntroSM
Used by: levels.
Object using the state machine: the Intro level.
Number of states: 3.
Purpose: Controls the behavior of the Intro level. At this level, we have two
options: Start and Exit. We can switch between those two options by
pressing the Up and Down arrow keys. After choosing one option, we can
Execute it by pressing the Enter or Return key. The Start option leads us to
the beginning of the game, and the Exit option leads us outside the game.
Name: GameOverSM
Used by: levels.
Object using the state machine: the GameOver level.
Number of states: 3.
Purpose: Controls the behavior of the GameOver level. At this level, we have
two options: Start and Exit. We can switch between those two options by
pressing the Up and Down arrow keys. After choosing one option, we can
Execute it by pressing the Enter or Return key. The Start option leads us
back to the Intro level, and the Exit option leads us outside the game.
Name: SuccessSM
Used by: levels.
Object using the state machine: the Success level.
Number of states: 3.
Purpose: Controls the behavior of the Success level. At this level, we have
two options, Start and Exit. We can switch between these two options by
pressing the Left and Right arrow keys. After choosing one option, we can
Execute it by pressing the Enter or Return key. The Start (or Main Menu)
option leads us back to the Intro level, and the Exit option leads us outside
the game.
8.12 TEXT- BASED GAME EXERCI SE
(The complete solution of the exercise is available in the Appendix.)
You should refer to the solution available in the directory TBG Part3 and add
code to it.
Define an integer LOCSIZE to be equal to 5.
Define an integer VERBSIZE to be equal to 3.
Define an integer NOUNSIZE to be equal to 2.
Declare the verbs enumerated list.
Flow Cont rol 225
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
The verbs are: GoTo, Create and Help
Declare the nouns enumerated list.
The nouns are: Map and Sprite
Declare a variable for each enumerated type.
Variable l used to specify the location returned from GetToken function.
n = GetToken(token2, noun, NOUNSIZE);
Variable v used to specify the verb returned from GetToken function.
v = GetToken(token1, verb, VERBSIZE);
Variable n used to specify the noun returned from GetToken function.
l = GetToken(token2, location, LOCSIZE);
Declare and define an array of strings
String verb[]
Initialize the array with the following strings:
GoTo, Create, and Help
Declare and define an array of strings
String noun[]
Initialize the array with the following strings:
Map and Sprite
Declare and define an array of strings
String location[]
Initialize the array with the following strings:
GameAssets, Game, LevelTrainStation, MapsCity and
SpritesCity
Call the function for each location from the switch statement.
For example: case locations.Game:
solved = class2.GameFn (v, n, l,ref currentLocation);
break;
Write a function:
static public int GetToken(string s, string[] list,
int size)
Parameters:
A string (string s) to search for.
An array of strings (string[] list) to search in.
The size of the second argument (int size).
The function returns the index of the row if the string specified in the first
argument matches one of the strings of the second argument, otherwise the
function return -1.
Flow Cont rol 226
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
Write the appropriate code within the location functions to handle all the
messages in the GameAssets, Game, LevelTrainStation, MapsCity
and SpriteCity.
Function definition:
public static bool SpriteFn(verbs v, nouns n, locations l,
ref locations cl)
Code example (you can have it in the SpriteFn function):
if (v == verbs.GoTo && l == locations.LevelTrainStation)
{
cl = locations.LevelTrainStation;
Console.WriteLine("Your new location is:
LevelTrainStation\n");
Console.WriteLine("You can go to: Game,
SpritesCity or MapsCity for 100$.\n\n");
}
else if (v == verbs.Create && n == nouns.Sprite)
{
string name;
Console.WriteLine("Enter the name of
the sprite: ");
name = Console.ReadLine();
}
else if (v == verbs.Help)
Console.WriteLine(" GoTo\n Create\n Help\n\n");
else
Console.WriteLine("Invalid Parser Command\n\n");
return false;
Output Example:
Flow Cont rol 227
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
8.13 ADDI NG CODE TO CAVES OF DOOM
In this section, we will add code to an unfinished version of Caves Of Doom and
then run it to see the changes taking effect.
1. With FunEditor.Net, open the file called CavesOfDoomChapter8.fun.
Note: This version is not a complete version of the game.
2. In the Project Resources window, under Behavior, under State Machines,
right-click IntroSM and from the menu click Properties
The State Machine Properties IntroSM window will open.
3. Double-click Edge going from state Start to state Execute.
An Edge Properties window will open.
4. Click My Code.
5. In the code area, type the following code exactly;
if (Keyboard.IsTriggered(KeyboardKey.K_RETURN)){
Game.LevelName("Level_1");
return true;
}
else return false;
6. Click OK.
7. Click Save and close the State Machine Properties window.
8. Click Run, and then click Yes.
The game will run. When the Intro level is displayed, the play level should
begin when you choose Start and press Enter.
Flow Cont rol 228
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
8
8.14 ADDI NG CODE TO BRI X
In this section, we will add code to an unfinished version of Brix and then run it
to see the changes taking effect.
1. With Visual C#.Net, open the project /Brix/Brix Chapter8/Brix.csproj.
Note: This version is an incomplete version of the game.
2. Open the file called Form1.cs.
3. Under the method
private void timer2_Tick(object sender, System.EventArgs e)
and before the comment line
// Get the color of a background pixel.
add the following lines
if (one)
{
brickBitmap = new Bitmap("brick02.bmp");
one = false;
}
else
{
brickBitmap = new Bitmap("brick01.bmp");
one = true;
}
4. Save and run the game.
The added code changes the shape of the bricks every 500 milliseconds.
9
CLASSES
Classes 230
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
CLASSES
Classes are the essential building blocks of every object-oriented programming
language. A class may contain data, functions, and nested types. A good under-
standing of this topic is the key to good programming skills in the object-ori-
ented programming world.
9.1 DEFI NI TI ON OF A CLASS
A class is a data structure. It may contain data, functions, and nested types. Data
members include constants and fields. Function members include methods,
operators, events, properties, indexers, instance constructors, destructors and
static constructors. A class supports inheritance, which is a mechanism that
allows a derived class to extend and specialize a base class.
9.2 CLASS DECLARATI ON
A class-declaration is a type-declaration that declares a new class. A class-decla-
ration consists of an optional set of attributes, followed by an optional set of
class-modifiers, followed by the keyword class and an identifier that names the
class, followed by an optional class-base specification, followed by a class-body,
optionally followed by a semicolon.
9.2.1 Cl ass Modi f i er s
A class-declaration may optionally include a sequence of class modifiers. The
class modifiers are: new, public, protected, internal, private, abstract, and
sealed. In a class declaration, it is a compile-time error if the same modifier
appears multiple times.
The new modifier is permitted on nested classes. It specifies that the class hides
an inherited member by the same name. If the new modifier appears on a class
declaration that is not a nested class declaration, it is considered a compile-time
error. The public, protected, internal, and private modifiers control the accessi-
bility of the class.
9.2.2 Abst r act Cl asses
The abstract modifier indicates that a class is incomplete and that it is intended
to be used only as a base class. An abstract class cannot be instantiated directly.
Using the new operator on an abstract class is a compile-time error. An abstract
class can contain abstract members and it cannot be sealed.
9.2.3 Seal ed Cl asses
The sealed modifier prevents derivation from a class. If a sealed class is specified
as the base class of another class, a compile-time error is generated. A sealed
class cannot be an abstract class.
Classes 231
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
9.2.4 Base Cl asses
When a class-type is included in the class-base, it specifies the direct base class
of the class being declared. If a class declaration has no class-base, the direct base
class is assumed to be object. A class inherits members from its direct base class.
Ex ampl e:
class B {}
class D: B {}
Class B is said to be the direct base class of D, and D is said to be derived from B.
Class B implicitly derives from object.
The direct base class of a class type must be at least as accessible as the class type
itself. For example, it is a compile-time error for a public class to derive from a
private or internal class. The base classes of a class are the direct base class and its
base classes. Every class has exactly one direct base class, except for class object.
The object class has no direct base class and is the ultimate base class of all other
classes.
9.3 MEMBERS OF A CLASS
Class members consist of the members introduced by its class-member-declara-
tions and the members inherited from the direct base class. Class members are
divided into the following categories:
Fields: the class variables.
Constants: represent constant values associated with the class.
Methods: implement the computations and actions that can be performed
by the class.
Properties: define characteristics associated with reading and writing those
characteristics.
Indexers: permit instances of the class to be indexed like arrays.
Events: define notifications that can be generated by the class.
Instance constructors: implement class initialization.
Operators: define the expression operators that would be applied to
instances of the class.
Static constructors: implement the actions required to initialize the class
itself.
Destructors: implement the actions to be performed before instances of the
class are deleted.
Types: represent local types of the class.
Members that can contain executable code are known as the function members
of the class. The function members of a class are the events, operators, methods,
properties, indexers, instance constructors, static constructors, and destructors
of that class.
Classes 232
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
A class-declaration creates a new declaration space, and the class-member-decla-
rations immediately contained by the class-declaration introduce new members
into this declaration space. Rules that apply to class-member-declarations:
Instance constructors, destructors and static constructors should have the
same name as the immediately enclosing class.
The name of a constant, property, type, field, or event should differ from the
names of all other members declared in the same class.
The name of a method should differ from the names of all other
non-methods declared in the same class.
The signature of a method should differ from the signatures of all other
methods declared in the same class.
The signature of an instance constructor should differ from the signatures of
all other instance constructors declared in the same class.
The signature of an indexer should differ from the signatures of all other
indexers declared in the same class.
The signature of an operator should differ from the signatures of all other
operators declared in the same class.
The inherited members of a class are not part of the declaration space of a
class. Therefore, a derived class is allowed to declare a member with the
same name or signature as an inherited member.
9.3.1 I nher i t ance
A class inherits the members of its direct base class. It implicitly contains all
members of its direct base class, except for the instance constructors, destruc-
tors, and static constructors of the base class. Inheritance is transitive. If C is
derived from B, and B is derived from A, then C inherits the members declared
in B as well as the members declared in A.
A derived class extends its direct base class. It can add new members to those it
inherits, but it cannot remove the definition of an inherited member. Instance
constructors, destructors, and static constructors are not inherited. A derived
class can hide inherited members by declaring new members with the same
name or signature.
A class can declare virtual methods, properties, and indexers, and derived classes
can override the implementation of these function members. This enables
classes to exhibit polymorphic behavior, wherein the actions performed by a
function member invocation vary depending on the run-time type of the
instance through which the function member is invoked.
Classes 233
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
9.3.2 Access Modi f i er s
It is a compile-time error to specify more than one access modifier, except for the
protected internal combination. When a class-member-declaration does not
include any access modifiers, private is assumed. A class-member-declaration
can have any one of the five possible kinds of declared accessibility: public, pro-
tected internal, protected, internal, or private.
9.3.3 St at i c & I nst ance Member s
Members of a class are either static members or instance members. Static mem-
bers belong to classes, and instance members belong to objects (instances of
classes). When a method, event, field, property, operator, or constructor declara-
tion includes a static modifier, it declares a static member. In addition, a constant
or type declaration implicitly declares a static member. When a method, event,
field, property, indexer, constructor, or destructor declaration does not include a
static modifier, it declares an instance member.
9.3.4 Nest ed Ty pes
A type declared within a class or struct is called a nested type. A type that is
declared within a compilation unit or namespace is called a non-nested type.
Note: this within a nested type cannot be used to refer to instance members of
the containing type.
A nested type has access to all of the members that are accessible to its contain-
ing type, including members of the containing type that have private and pro-
tected declared accessibility.
9.3.5 Reser ved Member Names
For each member declaration that is a property, event, or indexer, the implemen-
tation must reserve two method signatures based on the kind of the member
declaration, its name, and its type. It is a compile-time error for a program to
declare a member whose signature matches one of these reserved signatures. The
reserved names do not introduce declarations, thus they do not participate in
member lookup. Destructor declaration causes a signature to be reserved. For a
property P of type T, the following signatures are reserved:
T get_P();
void set_P(T value);
Both signatures are reserved, even if the property is read-only or write-only.
For an event E of delegate type T, the following signatures are reserved:
void add_E(T handler);
void remove_E(T handler);
For an indexer of type T with parameter-list L, the following signatures are
reserved:
T get_Item(L);
void set_Item(L, T value);
Classes 234
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
Both signatures are reserved, even if the indexer is read-only or write-only.
For a class containing a destructor, the following signature is reserved:
void Finalize();
9.4 CONSTANTS
A constant is a class member that represents a constant value that can be com-
puted at compile-time. A constant declaration that declares multiple constants is
equivalent to multiple declarations of single constants with the same attributes,
modifiers, and type. Constants are permitted to depend on other constants
within the same program as long as the dependencies are not of a circular nature.
9.5 FI ELDS
A field represents a variable associated with an object or class. A field-
declaration introduces one or more fields of a given type. One that declares
multiple fields is the same as multiple declarations of single fields with the same
attributes, modifiers, and type.
9.5.1 St at i c and I nst ance Fi el ds
When a field declaration includes a static modifier, the fields introduced are
static fields. When no static modifier is present, the fields introduced are instance
fields. A static field is not part of a specific instance. There is only one copy of a
static field for the associated application domain. An instance field belongs to an
instance. Every instance of a class contains a separate set of all instance fields of
the class.
9.5.2 Readonl y Fi el ds
When a field-declaration includes a readonly modifier, the fields are readonly
fields. Direct assignments to readonly fields can only occur as part of the declara-
tion or in an instance constructor (for readonly non-static fields) or static con-
structor (for readonly static fields) in the same class. It is a compile-time error if
you attempt to assign to a readonly field or pass it as an out or ref parameter in
any other context.
9.6 METHODS
A method is a member that implements a computation or action that can be per-
formed by an object or class. Methods are declared using method-declarations.
The return-type of a method declaration specifies the type of the value computed
and returned by the method. The return-type is void if the method does not
return a value. The member-name specifies the name of the method.
9.6.1 Met hod Par amet er s
The parameters of a method, if there are any, are declared by the methods
formal-parameter-list.
Classes 235
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
9.6.2 Val ue Par amet er s
A parameter declared with no modifiers is a value parameter, which corre-
sponds to a local variable that gets its initial value from the corresponding argu-
ment supplied in the method invocation. When a formal parameter is a value
parameter, the corresponding argument in a method invocation must be an
expression of a type that is implicitly convertible to the formal parameter type. A
method is permitted to assign new values to a value parameter.
9.6.3 Ref er ence Par amet er s
A parameter declared with a ref modifier is a reference parameter. A reference
parameter does not create a new storage location. It represents the same storage
location as the variable given as the argument in the method invocation. A vari-
able must be definitely assigned before it can be passed as a reference parameter.
Within a method, a reference parameter is always considered definitely assigned.
9.6.4 Out put Par amet er s
A parameter declared with an out modifier is an output parameter. An output
parameter does not create a new storage location. It represents the same storage
location as the variable given as the argument in the method invocation. A vari-
able need not be definitely assigned before it can be passed as an output parame-
ter; however, following an invocation where a variable was passed as an output
parameter, the variable is considered definitely assigned. Within a method an
output parameter is considered initially unassigned and must be definitely
assigned before its value is used. Every output parameter of a method must be
definitely assigned before the method returns.
9.6.5 St at i c and I nst ance Met hods
When a method declaration includes a static modifier, the method is said to be a
static method. When no static modifier is present, the method is said to be an
instance method. A static method does not operate on a specific instance, and it is
a compile-time error to refer to this in a static method. An instance method
operates on a given instance of a class, and this instance can be accessed as this.
9.7 PROPERTI ES
A property is a member that provides access to a characteristic of an object or a
class. Examples include the length of a string, the caption of a window, the name
of a customer, and the size of a font. Properties are a natural extension of fields,
and they do not denote storage locations.
The type of a property declaration specifies the type of the property introduced
by the declaration, and the member-name specifies the name of the property.
The type of a property must be at least as accessible as the property itself.
9.7.1 St at i c and I nst ance Pr oper t i es
When a property declaration includes a static modifier, the property is said to be
a static property. When no static modifier is present, the property is said to be an
Classes 236
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
instance property. A static property is not associated with a specific instance,
whereas an instance property is associated with a given instance of a class, and
this instance can be accessed as this in the accessors of the property.
9.7.2 Vi r t ual , Seal ed, Ov er r i de, and Abst r act Accessor s
A virtual property declaration specifies that the accessors of the property are vir-
tual. The virtual modifier applies to both accessors of a read-write property. It is
not possible for only one accessor of a read-write property to be virtual.
An abstract property declaration specifies that the accessors of the property are
virtual, but does not provide an actual implementation of the accessors. Non-
abstract derived classes are required to provide their own implementation for the
accessors by overriding the property. A property declaration that includes both
the abstract and override modifiers specifies that the property is abstract and
overrides a base property. Abstract property declarations are only permitted in
abstract classes.
The accessors of an inherited virtual property can be overridden in a derived
class by including a property declaration that specifies an override directive. An
overriding property declaration may include the sealed modifier. The accessors
of a sealed property are also sealed.
Except for differences in declaration and invocation syntax, virtual, sealed, over-
ride, and abstract accessors behave exactly like virtual, sealed, override, and
abstract methods.
9.8 EVENTS
An event is a member that enables an object or class to provide notifications. Cli-
ents can attach executable code for events by supplying event handlers. An event
can be used as the left hand operand of the += and -= operators.
When an event declaration includes a static modifier, the event is said to be a
static event. When no static modifier is present, the event is said to be an instance
event. A static event is not associated with a specific instance, whereas an
instance event is associated with a given instance of a class, and this instance can
be accessed as this in the accessors of the event.
9.9 I NDEXERS
An indexer is a member that enables an object to be indexed in the same way as
an array. An indexer element is not classified as a variable. Therefore, it is not
possible to pass an indexer element as a ref or out argument.
The formal parameter list of an indexer defines the signature of the indexer. The
signature of an indexer consists of the number and types of its formal parame-
ters. The element type and names of the formal parameters are not part of an
Classes 237
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
indexers signature. The signature of an indexer must differ from the signatures
of all other indexers declared in the same class.
Indexers and properties are very similar in concept, but differ in significant
ways. When an indexer declaration includes an extern modifier, the indexer is
said to be an external indexer.
9.10 OPERATORS
An operator is a member that defines the meaning of an expression operator that
can be applied to instances of the class. There are three categories of overloadable
operators:
Unary operators.
Binary operators.
Conversion operators.
An operator declaration must include both a public and a static modifier.
When an operator declaration includes an extern modifier, the operator is said to
be an external operator. For all non-external operators, the operator-body consists
of a block, which specifies the statements to execute when the operator is
invoked.
The parameter(s) of an operator must be value parameters. The signature of an
operator must differ from the signatures of all other operators declared in the
same class. All types referenced in an operator declaration must be at least as
accessible as the operator itself. It is a compile-time error for the same modifier
to appear multiple times in an operator declaration.
Each operator category imposes additional restrictions, as described in the fol-
lowing sections. Like other members, operators declared in a base class are
inherited by derived classes.
9.11 I NSTANCE CONSTRUCTORS
An instance constructor is a member that implements the actions required to
initialize an instance of a class. They are declared using constructor-declarations,
which may include a set of attributes, a valid combination of the four access
modifiers, and an extern modifier. A constructor declaration is not permitted to
include the same modifier multiple times.
The identifier of a constructor-declarator must name the class in which the con-
structor is declared. If any other name is specified, a compile-time error occurs.
The formal parameter list defines the signature of an instance constructor and
governs the process whereby overload resolution selects a particular instance
Classes 238
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
constructor in an invocation. Each of the types referenced in the formal-parame-
ter-list of an instance constructor must be at least as accessible as the constructor
itself.
The optional constructor-initializer specifies another instance constructor to
invoke before executing the statements given in the constructor-body of this
instance constructor. When a constructor declaration includes an extern modi-
fier, the constructor is said to be an external constructor. Because an external
constructor declaration provides no actual implementation, its constructor-body
consists of a semicolon. For all other constructors, the constructor-body consists
of a block which specifies the statements to initialize a new instance of the class.
This corresponds exactly to the block of an instance method with a void return
type.
Instance constructors are not inherited. Thus, a class has no instance construc-
tors other than those actually declared in the class. If a class contains no instance
constructor declarations, a default instance constructor is automatically pro-
vided. Instance constructors are invoked by object-creation-expressions and
through constructor-initializers.
Default constructors
If a class contains no instance constructor declarations, a default instance con-
structor is automatically provided. The default constructor simply invokes the
parameterless constructor of the direct base class. If the direct base class does not
have an accessible parameterless instance constructor, a compile-time error
occurs. If the class is abstract, then the declared accessibility for the default con-
structor is protected; otherwise, the declared accessibility for the default con-
structor is public. A default constructor is provided because the class contains no
instance constructor declarations.
9.12 STATI C CONSTRUCTORS
A static constructor is a member that implements the actions required to initial-
ize a class. Static constructors are not inherited and cannot be called directly. The
exact timing of static constructor execution is implementation-dependent.
9.13 DESTRUCTORS
A destructor is a member that implements the actions required to destruct an
instance of a class. They are not inherited; thus, a class has no destructors other
than the one which may be declared in it. Since a destructor is required to have
no parameters, it cannot be overloaded. Thus, a class can have, at most, one
destructor.
Destructors are invoked automatically, and cannot be invoked explicitly. An
instance becomes eligible for destruction when it is no longer possible for any
Classes 239
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
code to use the instance. Execution of the destructor for the instance may occur
at any time after the instance becomes eligible for destruction. When an instance
is destructed, the destructors in its inheritance chain are called sequentially from
most-derived to least-derived. Since destructors in an inheritance chain are
called in order, from most derived to least derived.
Destructors are implemented by overriding the virtual method Finalize on
System.Object. Programs are not permitted to override this method or call it
(or overrides of it) directly.
9.14 DI RECT I MPLEMENTATI ONS
9.14.1 Chemi st r y Pr obl em
The combustion of propane is given by the following balanced combustion reac-
tion:
3 8 2 2 2
5 3 4 C H O CO H O + +
. Write a program that takes as input m
1
, the
mass of propane involved in combustion with enough oxygen, and returns the
mass of water produced and the mass of carbon dioxide produced. The output
should be similar to the following:
Classes 240
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
9.14.2 Chemi st r y Pr obl em
A radioactive element is characterized by its half-life, the time that an amount A
0

of this element needs in order to lessen to half its amount (A
0
/2). In other words,
we say that half the initial amount has been disintegrated or transmuted.
Write a program that takes as input the half-life of a certain element and the per-
centage of mass disintegrated and returns the time elapsed since the disintegra-
tion started.
Fl ow Char t
Tool s
A pen or pencil
A sharpener
An eraser
Scratch paper
Calculator
Ruler
General chemistry book
Classes 241
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
Appr oach
Being familiar with the idea of radioactive elements and the exceptional phe-
nomenon of transformation that governs their existence (so called disintegration
or transmutation) is crucial if you want to solve this problem. In what follows, we
introduce you to the concept of radioactivity.
Some of the chemical elements that exist in nature have the special characteristic
of being radioactive. The name itself already means something about this special
property. In fact, radioactive elements spontaneously emit radiation of different
types without any external agent forcing them to do so. This is due to the insta-
bility of their atomic structure, specifically their nucleus.
Three different types of radiation may be emitted by a radioactive element:
Alpha (Helium nucleus
4
2
He
)
Beta (electron)
Gamma (neutron)
A radioactive element is transformed into another element according to the type
of radiation that it emits. Since the nucleus of the radioactive element is losing
electrons, neutrons, and protons under the form of radiation. The resulting ele-
ment may be radioactive or not. If it is radioactive, it will transmute itself into
another element by radiating its neutrons, protons, and electrons. This process
continues until a non-radioactive stable element that does not radiate, and there-
fore does not transmute, is reached,
Think if this as a series of radioactive elements that originate subsequently one
from another and finally reach a stable element. This series is called a decay
series. An example is the uranium decay series that starts with uranium passing
through many isotopes of thorium, radon, radium, and bismuth and ends with
lead.
An important property of a radioactive element is its half-life, and unlike what
the word may tell you at first glance, it is not one-half the life of the element, but
it is really the lifetime of half of the initial amount. In other words it is the time
that half the initial amount needs to be transformed into another element.
The decay of a radioactive element is described mathematically as being expo-
nential. Let A
0
be the initial amount of the radioactive element at the beginning
of the transmutation process. Also, let A(t) be the amount of element present at
time t and k be the constant of decay of the element. A(t) is represented in func-
tion of time by the equation of disintegration as follows:
( )
0
A A
kt
t e =
Let T be the half-life of the element involved. After T units of times, A(t) is
reduced to A
0
/2. Replacing this in the equation of disintegration allows us to
Classes 242
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
determine k, the decay constant. In fact,
( )
( )
T T 0
0
1
ln
A 1 1 ln2
2
A T A T ln
2 2 2 T T
k k
e e k k = = = = = =
Therefore, the equation of disintegration may be written as follows:
( )
ln2
T
0
A A
t
t e

=
Knowing p
d
, the percentage of disintegrated amount of A
0
at a certain time t, we
can write that the percentage of remaining amount is ( ) ( ) ( ) 100
r d
p t p t = .
The equation of disintegration could be finally written as follows:
( ) ( )
ln2
T
0 0
A A A
t
r
t p t e

= =
Finally, solving the equation of disintegration for t, permits us to figure out when
the transmutation process started:
( )
ln2 ln2 ln2
T T T
0 0
ln2 T
A A ln ln ln ln
100 100 100 T ln2 100
t t t
r r r r
r
p p p p
p t e e e t t
| |
| | | | | |
= = = = =
| | | |
\ . \ . \ .
\ .
As you may notice, t is given in function of p
r
, the percentage of the remaining
mass and T, the half-life of the chemical element involved. Given p
r
and T, deter-
mining the t, the time that passed since the disintegration started, becomes very
easy.
Sol ut i on
1. Find the half-life of the radioactive element, that is, the time that an amount of
this radioactive element takes in order to be reduced to the half.
2. Find p
d
, the percentage of mass disintegrated, that is, the amount that has been
transmuted.
3. Find p
r
, the percentage of the initial amount that has not been disintegrated
yet.
4. Having the half-life of the radioactive element, find the equation of disintegra-
tion that represents how the amount of this element changes with respect to
time. This equation will involve the half-life, the initial amount of the radioac-
tive element, and the percentage of mass that remains untransformed (the
percentage of mass disintegrated).

( )
1
ln
2
T
0
1 1
ln ln
2 2
T T
0 0
1 1
ln ln
2 2
T T
0 0
A A
1 A A 1
100 100
A A
100 100
t
t t
d d
t t
r r
t e
p p
e e
p p
e e
=
| | | |
= =
| |
\ . \ .
= =
Classes 243
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
5. Solve for t, the disintegration equation to find the time t required.
( )
T
ln
1
100 ln
2
r
p
t
| |
=
|
\ .
Lessons Lear ned
After solving this problem:
I am aware of radioactive elements.
I recognize the natural phenomenon of disintegration.
I learned a simple, step-by-step method of finding the time when the disin-
tegration phenomenon of a certain element started given its half-life and the
amount of mass disintegrated.
I can implement this method in a computer programming algorithm.
I developed the skill of finding the time when the disintegration phenome-
non of a certain element started given its half-life and the amount of mass
disintegrated.
I can accomplish the task of finding the time when the disintegration phe-
nomenon of a certain element started given its half-life and the amount of
mass disintegrated more easily now because it was broken down into several
simple steps.
I will remember this method faster because it was described verbally and
visually.
The output should be similar to the following:
9.15 CLASSES I N THE TEXT- BASED GAME
For the sake of clarity and organization, the text-based game is divided into two
parts. Each part contains a namespace, which contains a class declaration, as fol-
lows:
The first part is embedded within a namespace called TBG_charp, as fol-
lows:
namespace TBG_charp
{
.
.
.
}
Within this namespace, a class declaration is provided, as follows:
class Class1
{
.
.
.
}
Classes 244
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
Within this class, lies the Main method, as follows:
static void Main(string[] args)
{
.
.
.
}
The second part contains most of the defined methods. For simplicity, it has
the same namespace of the first part, namely TBG_charp. In addition to a
structure definition and two enumerations, we have a class definition within
this namespace:
class class2
{
.
.
.
}
Within this class, we have defined most of the methods we will use.
9.16 TEXT- BASED GAME EXERCI SE
(The complete solution of the exercise is available in the Appendix.)
You should refer to the solution available in the directory TBG Part4 and add
code to it.
1. Add to the verbs enumerated list the verb Inventory.
2. Add to the nouns enumerated list the noun Money.
3. Add to the array verb the string Inventory.
4. Add to the two dimensional array noun the string Money.
5. Change the integer VERBSIZE to 4.
6. Change the integer NOUNSIZE to 3.
7. Create a structure called sInventory having three members:
int value
bool available
String name
8. Create an array of the sInventory structure:
The name of the array is inventory.
The size of the array is the number of nouns:
sInventory[] inventory = new sInventory[NOUNSIZE];
Classes 245
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
9. Write a function InitInventory to initialize the array of structure inventory.
Note: You can use the noun enumerated data type to access a specific
structure in the array of structures.
For example:
i[(int)nouns.Map].values = 0;
i[(int)nouns.Map].available = false;
i[(int)nouns.Map].name = "Map";
i[(int)nouns.Sprite].values = 0;
i[(int)nouns.Sprite].available = false;
i[(int)nouns.Sprite].name = "Sprite";
i[(int)nouns.Money].values = 1500;
i[(int)nouns.Money].available = true;
i[(int)nouns.Money].name = "Money";
10. Write a function ListInventory to display the available inventory.
This function displays all the available inventory. It checks if the available
boolean is true and displays the name and value of the corresponding
inventory.
11. Write a function DisplayMoney to display the current balance.
This function displays the value of the money inventory at each location.
12. Update all the location functions to display the inventory and the money
balance.
Code example of the SpriteFN function:
if (v == verbs.GoTo && l == locations.LevelTrainStation)
{
cl = locations.LevelTrainStation;
Console.WriteLine("Your new location is:
LevelTrainStation\n");
Console.WriteLine("You can go to: Game,
SpritesCity or MapsCity for 100$.\n\n");
i[(int)nouns.Money].values -= 100;
DisplayMoney(i);
}
else if (v == verbs.Create && n == nouns.Sprite)
{
string name;
Console.WriteLine("Enter the name of the
sprite: ");
name = Console.ReadLine();
i[(int)nouns.Sprite].available = true;
i[(int)nouns.Sprite].values++;
i[(int)nouns.Money].values -= 40;
DisplayMoney(i);
}
else if (v == verbs.Inventory)
ListInventory(i);
else if (v == verbs.Help)
Console.WriteLine(" GoTo\n Create\n Help\n\n");
else
Classes 246
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
9
Console.WriteLine("Invalid Parser Command\n\n");
return false;
13. Check the end of the game for the money inventory; if it is <=0, then dis-
play a failing text.
14. Check the end of the game as follows; if solved is true, then display a con-
gratulations text.
9.17 ADDI NG CODE TO CAVES OF DOOM
In this section, we will take an unfinished version of Caves Of Doom, add some
code to it, then run it and see the changes taking effect.
1. With FunEditor.Net, Open the file called CavesOfDoomChapter9.fun.
Note: This version is not a complete version of the game.
2. In the Project Resources window, under Game, under the Success level,
right-click on Sprites and from the menu, click Add
The Sprite Properties New window will open.
3. In the Name field, type: exit
4. Select Main for the Map field.
5. On the Animation tab, select MENUITEMS for Actor.
6. Select Exit for Initial Animation.
7. On the Position tab, type 504 for PositionX and 1 for PositionY.
8. Click OK.
A new sprite called exit is added under Level_1.
9. Click Run then click Yes.
The game will run. When the Success level is displayed, the exit sprite
should be visible.
10
ARRAYS
Ar rays 248
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
10
ARRAYS
An array is a collection of objects of a single data type except void. The individ-
ual objects are not named; rather, each one is accessed by its position in the array.
This form of access is referred to as indexing or subscripting.
10.1 I NTRODUCTI ON
An array is a data structure. It contains a number of variables that are accessed
through computed indices. Also called the elements of the array, the variables
contained in an array are all of the same type, and this type is called the element
type of the array.
An array has a rank, which determines the number of indices associated with
each array element. The rank of an array is also referred to as the dimensions of
the array. An array with a rank of one is called a single-dimensional array, and an
array with a rank greater than one is called a multi-dimensional array. Multi-
dimensional arrays of specific sizes are often referred to by size, as two-dimen-
sional arrays, three-dimensional arrays, and so on.
Each dimension of an array has an associated length, which is an integer greater
than or equal to zero. The dimension lengths are not part of the type of the array,
but rather are established when an instance of the array type is created at run-
time. The length of a dimension determines the valid range of indices for that
dimension. For a dimension of length N, indices can range from 0 to N 1 inclu-
sive. The total number of elements in an array is the product of the lengths of
each dimension in the array. If one or more of the dimensions of an array have a
length of zero, the array is said to be empty. The element type of an array can be
any type, including an array type.
10.2 ARRAY TYPES
The System.Array type is the abstract base type of all array types. An implicit
reference conversion exists from any array type to System.Array, and an explicit
reference conversion exists from System.Array to any array type. System.Array
itself is not an array-type. Rather, it is a class-type from which all array-types are
derived. At run-time, a value of type System.Array can be null or a reference to
an instance of any array type.
10.3 ARRAY CREATI ON
Array instances are created by array-creation-expressions or by field or local
variable declarations that include an array-initializer. When an array instance is
created, the rank and length of each dimension are established and then remain
constant for the entire lifetime of the instance. It is not possible to change the
rank of an existing array instance, nor is it possible to resize its dimensions. An
array instance is always of an array type. The System.Array type is an abstract
Ar rays 249
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
10
type that cannot be instantiated. Elements of arrays created by array-creation-
expressions are always initialized to their default value.
10.4 ARRAY ELEMENT ACCESS
Array elements are accessed using element-access expressions of the form A[I
1
,
I
2
, ..., I
n
], where A is an expression of an array type, and each I
X
is an expression
of type int, uint, long, ulong, or of a type that can be implicitly converted to one
or more of these types. The result of an array element access is a variable, namely
the array element selected by the indices. The elements of an array can be enu-
merated using a foreach statement.
10.5 ARRAY MEMBERS
Every array type inherits the members declared by the System.Array type.
10.6 ARRAY I NI TI ALI ZERS
Array initializers may be specified in field declarations, local variable declara-
tions, and array creation expressions. The context in which an array initializer is
used determines the type of the array being initialized. In an array creation
expression, the array type immediately precedes the initializer. In a field or vari-
able declaration, the array type is the type of the field or variable being declared.
When an array initializer is used in a field or variable declaration, such as:
int[] ar = {1, 3, 5, 7, 9};
it is simply shorthand for an equivalent array creation expression:
int[] arr = new int[] {1, 3, 5, 7, 9}
For a single-dimensional array, the array initializer must consist of a sequence of
expressions that are assignment compatible with the element type of the array.
The expressions initialize array elements in increasing order, starting with the
element at index zero. The number of expressions in the array initializer deter-
mines the length of the array instance being created. For example, the array ini-
tializer above creates an int[] instance of length 5 and then initializes the instance
with the following values:
a[0] = 1; a[1] = 3; a[2] = 5; a[3] = 7; a[4] = 9;
For a multi-dimensional array, the array initializer must have as many levels of
nesting as there are dimensions in the array. The outer-most nesting level corre-
sponds to the left-most dimension, and the inner-most nesting level corresponds
to the right-most dimension.
The number of elements at the corresponding nesting level in the array initial-
izer determine the length of each dimension of the array. For each nested array
initializer, the number of elements must be the same as the other array initializ-
ers at the same level. For example:
Ar rays 250
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
10
int[,] ar = {{10, 11}, {12, 13}, {14, 15}, {16, 17}};
creates a two-dimensional array with a length of four for the left-most dimen-
sion, and a length of two for the right-most dimension:
int[,] ar = new int[4, 2];
and then initializes the array instance with the following values:
ar[0, 0] = 0; b[0, 1] = 11;
ar[1, 0] = 2; b[1, 1] = 13;
ar[2, 0] = 4; b[2, 1] = 15;
ar[3, 0] = 6; b[3, 1] = 17;
ar[4, 0] = 8; b[4, 1] = 19;
When an array creation expression includes both explicit dimension lengths and
an array initializer, the lengths must be constant expressions and the number of
elements at each nesting level must match the corresponding dimension length.
10.7 DI RECT I MPLEMENTATI ONS
10.7.1 Mat h Pr obl em
Write a program that adds two matrices. The output should be similar to the fol-
lowing:
10.7.2 Mat h Pr obl em
Write a program that subtracts two matrices. The output should be similar to the
following:
Ar rays 251
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
10
10.7.3 Mat h Pr obl em
Write a program that multiplies a matrix by a scalar. The output should be simi-
lar to the following:
10.7.4 Mat h Pr obl em
Write a program that multiplies two matrices. The output should be similar to
the following:
10.7.5 Mat h Pr obl em
Write a program that gives the opposite of a matrix. The output should be similar
to the following:
10.7.6 Mat h Pr obl em
Write a program that calculates the determinant of a 22 matrix. The output
should be similar to the following:
Ar rays 252
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
10
10.7.7 Phy si cs Pr obl em
A certain number of resistors R
1
, R
2
, , R
n
connected in parallel
can be replaced by an equivalent resistor of resistance R.
Write a program that takes as input R
1
, R
2
, , R
n
and returns the
equivalent resistance R. The output should be similar to the following:
10.7.8 Phy si cs Pr obl em
A certain number of resistors R
1
, R
2
, , R
n
connected in
series can be replaced by an equivalent resistor of resis-
tance R. Write a program that takes as input R
1
, R
2
, ,
R
n
and returns the equivalent resistance R. The output
should be similar to the following:
10.8 ARRAYS I N THE TEXT- BASED GAME
In the text-based game, we have some useful arrays, as follows:
An array of 36 sInventory structures is created to store all available nouns
that we can use, as follows:
sInventory[] inventory = new sInventory[NOUNSIZE];
An array of 8 strings is created to store all available verbs, as follows:
String[] verb = {"GoTo","Buy","Create","Add", "Look", "Run",
"Inventory","Help"};
An array of 36 strings is created to store all available nouns, as follows:
String[] noun =
{
"Invalid","GameAssets","FramesStore","BackgroundsStore",
"ActorRoom","AnimationRoom","FrameRoom","CollisionRoom",
"Game","RunCenter","LevelTrainStation","MapsCity",
"CollisionBld","SpritesCity","EffectsBld",
"DisplacementBld","BackgroundImage","FrameImage","Money",
"Actor","Animation","Frame","Collision","FrameCollision",
"Backgrounds","Frames","Map","MapCollision","Sprite",
"sAnimation","sCollision","sEffect","sDisplacement",
"AnimationBld","Effect","Displacement"
};
In addition to the previously mentioned arrays, we can find some local
arrays that are less important and less complicated.
Ar rays 253
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
10
10.9 ARRAYS I N THE BRI X GAME
In this game we use one array:
public rect[,] r;
This is a two-dimensional array of 210 rectangle structures representing the 20
bricks available in the game. A two-dimensional array is used because the bricks
are put in two rows with ten bricks each.
10.10 ADDI NG CODE TO BRI X
In this section, we will add code to an unfinished version of Brix, and then run it
to see the changes taking effect.
1. With VisualC#.Net, open the project /Brix/Brix Chapter10.Brix.csproj.
Note: This version is an incomplete version of the game.
2. Open the file called Form1.cs.
3. Under the method
private void Form1_Paint(object sender,
System.Windows.Forms.PaintEventArgs e)
and after the line
e.Graphics.DrawImage(padBitmap, padRect.top.x1,
padRect.top.y1, padBitmap.Width, padBitmap.Height);
add the following lines:
for (int i = 0;i<2;i++)
for (int j = 0;j<10;j++)
{
if (r[i,j].active)
e.Graphics.DrawImage(brickBitmap,
r[i,j].top.x1, r[i,j].top.y1,
brickBitmap.Width, brickBitmap.Height);
}
4. Save and run the game.
The added code repaints the remaining bricks in the game every game
loop. The array r of rect structures is accessed by testing its Boolean mem-
ber active to see whether it is true or false. For every brick in the game,
this Boolean is tested. If it is true, it means that the brick is still active, and
therefore should be repainted. Otherwise, the brick no longer exists and
should not be repainted.
11
STRUCTURES
St ruct ures 255
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
11
STRUCTURES
A structure is a set of values that can be referenced collectively. It differs from an
array in that elements of the structure (referenced to as the structure's members)
do not necessarily have to be of the same type, and that the structure's elements
are also referenced differently.
11.1 DEFI NI TI ON OF A STRUCT
Structs are similar to classes in that they represent data structures, that can con-
tain data members and function members. Unlike classes, structs are value types
and do not require heap allocation. A variable of a struct type directly contains
the data of the struct, whereas a variable of a class type contains a reference to the
data, the latter known as an object.
Structs are particularly useful for small data structures that have value semantics.
Complex numbers, points in a coordinate system, or key-value pairs in a dictio-
nary are all good examples of structs. The simple types provided by C#, such as
int, double, and bool, are in fact all struct types. It is possible to use structs and
operator overloading to implement new primitive types in the C# language.
11.2 STRUCT DECLARATI ON
A struct-declaration is a type-declaration that declares a new struct.
A struct-declaration may optionally include a sequence of struct modifiers. It is
a compile-time error for the same modifier to appear multiple times in a struct
declaration. The modifiers of a struct declaration have the same meaning as
those of a class declaration.
A struct declaration may include a struct-interfaces specification, in which case
the struct is said to implement the given interface types.
The struct-body of a struct defines the members of the struct.
11. 3 MEMBERS OF A STRUCT
The struct members are the members introduced by its
struct-member-declarations, and the members inherited
from System.ValueType, which inherits from object.
11.4 CLASS AND STRUCT DI FFERENCES
Structs are value types. All struct types implicitly inherit from class objects.
Instance field declarations for a struct are not permitted to include variable ini-
tializers. Assignment to a variable of a struct type creates a copy of the value
being assigned. However, the meaning of this is different for structs. A struct is
St ruct ures 256
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
11
not permitted to declare a destructor. The default value of a struct is the value
produced by setting all value type fields to their default value and all reference
type fields to null. A struct is not permitted to declare a parameterless instance
constructor. Boxing and unboxing operations are used to convert between a
struct type and object. Structs are value types and are said to have value seman-
tics. On the other hand, classes are reference types and are said to have reference
semantics.
A variable of a struct type directly contains the data of the struct, whereas a vari-
able of a class type contains a reference to the data, the latter known as an object.
With classes, it is possible for two variables to reference the same object, and thus
possible for operations on one variable to affect the object referenced by the
other variable. With structs, the variables each have their own copy of the data,
and it is not possible for operations on one to affect the other. Since structs are
not reference types, it is not possible for values of a struct type to be null.
All struct types implicitly inherit from class objects. A struct declaration may
specify a list of implemented interfaces, but it is not possible for a struct declara-
tion to specify a base class. Struct types are never abstract and are always implic-
itly sealed. Therefore, the abstract and sealed modifiers are not permitted in a
struct declaration. Since inheritance is not supported for structs, the declared
accessibility of a struct member cannot be protected or protected internally.
Function members in a struct cannot be abstract or virtual, and the override
modifier is allowed only to override methods inherited from the object type.
Assignment to a variable of a struct type creates a copy of the value being
assigned. This differs from assignment to a variable of a class type, which copies
the reference but not the object identified by the reference. Similar to an assign-
ment, when a struct is passed as a value parameter or returned as the result of a
function member, a copy of the struct is created. A struct may be passed by refer-
ence to a function member using a ref or out parameter.
When a property or indexer of a struct is the target of an assignment, the
instance expression associated with the property or indexer access must be clas-
sified as a variable. If the instance expression is classified as a value, a compile-
time error occurs. A value of a class type can be converted to type object or to an
interface type that is implemented by the class simply by treating the reference as
another type at compile-time. Likewise, a value of type object or a value of an
interface type can be converted back to a class type without changing the refer-
ence (but of course a run-time type check is required in this case).
Since structs are not reference types, these operations are implemented differ-
ently for struct types. When a value of a struct type is converted to type object or
to an interface type that is implemented by the struct, a boxing operation takes
place. When a value of type object or a value of an interface type is converted
back to a struct type, an unboxing operation takes place. A key difference from
the same operations on class types is that boxing and unboxing copies the struct
value either into or out of the boxed instance.
St ruct ures 257
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
11
Following a boxing or unboxing operation, changes made to the unboxed struct
are not reflected in the boxed struct. Within an instance constructor or instance
function member of a class, this is classified as a value. Thus, while this can be
used to refer to the instance for which the function member was invoked, it is
not possible to assign to this in a function member of a class. Within an instance
constructor of a struct, this corresponds to an out parameter of the struct type,
and within an instance function member of a struct, this corresponds to a ref
parameter of the struct type.
The this is classified as a variable, and it is possible to modify the entire struct for
which the function member was invoked by assigning to this or by passing this as
a ref or out parameter. The default value of a struct consists of the value that
results from setting all value type fields to their default value and all reference
type fields to null. For this reason, a struct does not permit instance field declara-
tions to include variable initializers.
Unlike a class, a struct is not permitted to declare a parameterless instance con-
structor. Instead, every struct implicitly has a parameterless instance constructor
which always returns the value that results from setting all value type fields to
their default value and all reference type fields to null. A struct instance con-
structor is not permitted to include a constructor initializer of the form base(...).
The this variable of a struct instance constructor corresponds to an out parame-
ter of the struct type, and similar to an out parameter, this must be definitely
assigned at every location where the instance constructor returns. A struct can
declare instance constructors having parameters, but it is not permitted to
declare a destructor.
11.5 DI RECT I MPLEMENTATI ONS
11.5.1 Mat h Pr obl em
Write a program to check if an input point is inside a rectangle (left=10, top=10,
right=50 and bottom=50) or not. The program contains the following:
A structure to hold the point coordinates.
A structure to hold the rectangle borders.
The output should be similar to the following:
11. 5. 2 Comput er Sci ence Pr obl em
Create a data type that will hold the information for a pixel. The information is
divided into three parts:
Position: x and y.
Color mode: the color mode can be 8, 16, 24 and 32.
St ruct ures 258
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
11
Color:
1 Byte (8 bit)
2 Bytes (16 bit)
3 Bytes (24 bit)
4 Bytes (32 bit)
The data type should be created using:
One structure for the position.
One union for the colors.
One variable for the color mode.
11.5.3 Soci al Sci ences Pr obl em
Write a program that fills a structure that holds a string Name variable, an inte-
ger Age variable, a character Sex variable, and then displays the content of the
structure each on a line. For example:
Name: John Smith
Age: 30
Sex: m
11.6 STRUCTURES I N THE TEXT- BASED GAME
In the text-based game, we have one structure:
public struct sInventory
{
public int values;
public bool available;
public String name;
};
The first member of the structure is an integer called values. This member
defines the actual value of the specified structure. For example, it defines the
value of the money structure; in other words, it defines how much money we
actually have. The second member is a Boolean called available. This member
indicates whether this specific structure is available or not. The third member is
a String called name. It defines the name of the structure. From this structure, we
are defining 36 instances:
sInventory[] inventory = new sInventory[NOUNSIZE];
11.7 STRUCTURES I N THE BRI X GAME
Two structures are defined in this game, as follows:
public struct line
{
public int x1, x2, y1,y2;
}
St ruct ures 259
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
11
The line structure is used to define a line in 2D space. As we know, a line is
defined by two points: p1(x1,y1) and p2(x2,y2).
public struct rect
{
public line top, right, bottom, left;
public bool active;
}
The rect structure is used to define a rectangle in 2D space. It uses the line struc-
ture to define four lines that form a rectangle. The rect structure defines the rect-
angle that represents a brick. This structure is used to know when the ball hits a
brick. After a ball hits a brick, the brick disappears. That is why we need the
active Boolean to mark the brick as inactive after it is hit.
11.8 ADDI NG CODE TO BRI X
In this section, we will add code to an unfinished version of Brix, and then run it
and see the changes taking effect.
1. With Visual C#.Net, open the project located under /Brix/Brix
Chapter11/Brix.csproj.
Note: This version is an incomplete version of the game. Attempting to run
this version as is before adding the appropriate code will generate errors.
2. Open the file called Form1.cs.
3. Under the class
public class Form1 : System.Windows.Forms.Form
and after the line
public Bitmap ballBitmap, padBitmap, brickBitmap;
add the following lines:
public struct line
{
public int x1, x2, y1,y2;
}
4. Save and run the game.
The added code creates a line structure with four integer members: x1 and
y1 defining the starting point of the line; x2 and y2 defining the ending
point of the line. This line structure is used later in a structure called rect to
define a rectangle by defining the four lines of the rectangle, with a Boolean
variable that gives the status of the rectangle.
A
APPENDI X
Appendix 261
I nt roduct ion t o Comput er Programming wit h C# 1996- 2005 DigiPen I nst it ut e of Technology. All right s reserved.
A
This is a student version of the course document.
Please see the instructor for solution set.

Vous aimerez peut-être aussi