programming fundamentals

353
Sajid Iqbal BAHAUDDIN ZAKARIYA UNIVERSITY, MULTAN Programming Fundamentals USING C#

Upload: sajid-iqbal

Post on 15-Apr-2017

158 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Programming Fundamentals

Sajid Iqbal BAHAUDDIN ZAKARIYA UNIVERSITY, MULTAN

Programming Fundamentals USING C#

Page 2: Programming Fundamentals

Programming Fundamentals Using C# 1

ABOUT AUTHOR

……………………….

Page 3: Programming Fundamentals

Programming Fundamentals Using C# 2

CONTENTS ........................................................................................................... ERROR! BOOKMARK NOT DEFINED.

INTRODUCTION TO PROGRAMMING ...................................................................................................................... 8

DATA AND ITS REPRESENTATION ........................................................................................................................... 32

THE PROGRAM ....................................................................................................................................................... 55

INTRODUCTION TO DOT NET FRAMEWORK ........................................................................................................... 66

INTEGRATED DEVELOPMENT ENVIRONMENT (IDE) ................................................................................................ 80

C# BASICS ............................................................................................................................................................. 100

OPERATORS AND EXPRESSIONS ........................................................................................................................... 120

DECISION MAKING ............................................................................................................................................... 153

CODE REPETITION ................................................................................................................................................ 176

DATA SEQUENCES ................................................................................................................................................ 196

NAMED CODE BLOCKS.......................................................................................................................................... 218

INDIRECT VARIABLES ............................................................................................................................................ 262

USER DEFINED DATA TYPES .................................................................................................................................. 297

ERRORS AND EXCEPTIONS ................................................................................................................................... 321

Page 4: Programming Fundamentals

Programming Fundamentals Using C# 3

TABLE OF CONTENTS INTRODUCTION TO PROGRAMMING ...................................................................................................................... 8

1.1. COMPUTER AND COMPUTER TYPES ........................................................................................................................ 8 1.2. COMPUTER SYSTEM AND ITS COMPONENTS ............................................................................................................. 9 1.3. TYPES OF SOFTWARE ......................................................................................................................................... 10

1.3.1. Application SOFTWARE ....................................................................................................................... 10 1.3.2. System SOFTWARE.............................................................................................................................. 10 1.3.3. Computer Programming Tools ............................................................................................................ 11

1.4. THE COMPUTER PROGRAMMING ......................................................................................................................... 11 1.4.1. Computer Programming Languages ................................................................................................... 11 1.4.2. The different generations of languages .............................................................................................. 16

1.5. PROGRAMMING PARADIGMS .............................................................................................................................. 21 1.5.1. Imperative/Procedural Programming:................................................................................................ 21 1.5.2. Declarative / Functional Programming .............................................................................................. 22 1.5.3. Object oriented programming ............................................................................................................ 22 1.5.4. Logic Programming ............................................................................................................................. 22 1.5.5. Event Driven Programming ................................................................................................................. 22

1.6. PROGRAMMING TOOLS AND ENVIRONMENTS ......................................................................................................... 23 1.7. PRACTICE QUESTIONS AND EXERCISES .................................................................................................................. 29

1.7.1. Objectives ........................................................................................................................................... 29 1.7.2. Subjective – Descriptive Questions ..................................................................................................... 30 1.7.3. Activities ............................................................................................................................................. 30

1.8. USEFUL WEB RESOURCES .................................................................................................................................. 31

DATA AND ITS REPRESENTATION ........................................................................................................................... 32

2.1. DATA AND INFORMATION .................................................................................................................................. 32 2.1.1. Data .................................................................................................................................................... 32 2.1.2. Information ......................................................................................................................................... 33

2.2. NUMBER SYSTEM ............................................................................................................................................. 33 2.2.1. Decimal Number System ..................................................................................................................... 33 2.2.2. Binary Number System ....................................................................................................................... 36 2.2.3. Octal Number System ......................................................................................................................... 38 2.2.4. Hexa-Decimal Number System ........................................................................................................... 40

2.3. BINARY NUMBER SYSTEM AND HARDWARE ........................................................................................................... 43 2.4. DATA AND DATA TYPES ..................................................................................................................................... 44

2.4.1. Numeric Data ...................................................................................................................................... 45 2.4.2. Text Data ............................................................................................................................................ 49 2.4.3. Image Data ......................................................................................................................................... 52 2.4.4. Sound Data ......................................................................................................................................... 54 2.4.5. Video Data .......................................................................................................................................... 54

2.5. DATA AND DATA TYPES – REVISITED .................................................................................................................... 54

THE PROGRAM ....................................................................................................................................................... 55

3.1. ABSTRACTION .................................................................................................................................................. 55 3.2. WAYS OF WRITING INSTRUCTIONS ....................................................................................................................... 56 3.3. THE ALGORITHM .............................................................................................................................................. 57

Page 5: Programming Fundamentals

Programming Fundamentals Using C# 4

3.4. TURING MACHINE ............................................................................................................................................ 61 3.5. DATA, INSTRUCTIONS AND INSTRUCTION EXECUTION .............................................................................................. 62 3.6. STAGES IN SOFTWARE DEVELOPMENT .................................................................................................................. 63 3.7. SYSTEM FLAWS ................................................................................................................................................ 65

INTRODUCTION TO DOT NET FRAMEWORK ........................................................................................................... 66

4.1. WHAT IS DOT NET FRAMEWORK ........................................................................................................................ 66 4.2. WHERE IS THE DOT NET FRAMEWORK ................................................................................................................. 67 4.3. WHAT CAN WE DO WITH DOT NET FRAMEWORK ................................................................................................... 67

4.3.1. What type of applications can we develop? ....................................................................................... 69 4.3.2. Platforms Supported by Dot NET ........................................................................................................ 69

4.4. THE DOT NET FRAMEWORK ARCHITECTURE .......................................................................................................... 70 4.4.1. Dot NET Framework Objectives .......................................................................................................... 70 4.4.2. Dot NET Framework Salient Features ................................................................................................. 70

4.5. THE DOT NET FRAMEWORK – A LAYERED APPROACH ............................................................................................. 72 4.5.1. Common Language Infrastructure (CLI) .............................................................................................. 73 4.5.2. The Dot NET Class Framework ............................................................................................................ 75

4.6. WRITING MANAGED CODE ................................................................................................................................ 77 4.7. DEVELOPMENT TOOLS: ...................................................................................................................................... 78

INTEGRATED DEVELOPMENT ENVIRONMENT (IDE) ................................................................................................ 80

5.1. WHAT IS VISUAL STUDIO 2010 ABOUT? .............................................................................................................. 80 5.2. INSTALLING VISUAL STUDIO 2010 ....................................................................................................................... 81 5.3. RUNNING VISUAL STUDIO 2010 ......................................................................................................................... 89 5.4. NAVIGATING VISUAL STUDIO 2010 ENVIRONMENT ................................................................................................ 91 5.5. HELLO C# ....................................................................................................................................................... 94

5.5.1. Creating Your First Project .................................................................................................................. 94 5.5.2. Program Description ........................................................................................................................... 98

C# BASICS ............................................................................................................................................................. 100

6.1. WHY TO LEARN C# ......................................................................................................................................... 100 6.2. DATA TYPES IN C# .......................................................................................................................................... 102

6.2.1. Variables and Constants ................................................................................................................... 103 6.2.2. Language Defined Data Types .......................................................................................................... 103

6.3. C# PROJECT TYPES ......................................................................................................................................... 106 6.4. I/O STATEMENTS ........................................................................................................................................... 106

6.4.1. Output Statements ........................................................................................................................... 106 6.4.2. Constants and Variables in C# .......................................................................................................... 108 6.4.3. Input Statements .............................................................................................................................. 114 6.4.4. Comments ......................................................................................................................................... 115 6.4.5. Code Formatting ............................................................................................................................... 117 6.4.6. C# Compilation Process ..................................................................................................................... 118

OPERATORS AND EXPRESSIONS ........................................................................................................................... 120

7.1. OPERATORS .................................................................................................................................................. 120 7.1.1. Operators Associativity ..................................................................................................................... 121 7.1.2. Operators Precedence ...................................................................................................................... 121 7.1.3. Operators in Detail ........................................................................................................................... 122

7.2. TYPE CONVERSION AND CASTING ...................................................................................................................... 136

Page 6: Programming Fundamentals

Programming Fundamentals Using C# 5

7.2.1. Implicit Conversion ........................................................................................................................... 136 7.2.2. Explicit Conversion (Casting) ............................................................................................................. 137 7.2.3. String Conversion .............................................................................................................................. 138

7.3. EXPRESSIONS ................................................................................................................................................. 139 7.4. INPUT/OUTPUT STATEMENTS REVISITED ............................................................................................................. 140

7.4.1. Formatted Output ............................................................................................................................. 141 7.4.2. Console Input .................................................................................................................................... 146

7.5. A REAL PROBLEM ........................................................................................................................................... 151

DECISION MAKING ............................................................................................................................................... 153

8.1. OPERATORS RESULTING IN BOOLEAN VALUES ...................................................................................................... 153 8.1.1. Conditional Operators ...................................................................................................................... 153 8.1.2. Logical Operators .............................................................................................................................. 155

8.2. CONDITIONAL STATEMENTS .............................................................................................................................. 157 8.2.1. “if” Statement ................................................................................................................................... 157 8.2.2. Flow Chart Diagram .......................................................................................................................... 160 8.2.3. More on “if” Statement .................................................................................................................... 161 8.2.4. “if-else” Statement ........................................................................................................................... 163 8.2.5. ?: Ternary Operator .......................................................................................................................... 165 8.2.6. Nested “if” and “if-else” Statements ................................................................................................ 166 8.2.7. “switch-case” Statement .................................................................................................................. 171

CODE REPETITION ................................................................................................................................................ 176

9.1. REPETITION CONSTRUCTS ................................................................................................................................ 176 9.1.1. While Loop ........................................................................................................................................ 176 9.1.2. Break Statement ............................................................................................................................... 181 9.1.3. “continue” Statement ....................................................................................................................... 183 9.1.4. “do – while” Loop.............................................................................................................................. 185 9.1.5. “break” and “continue” .................................................................................................................... 187 9.1.6. “for” Loop ......................................................................................................................................... 188 9.1.7. Nested Loops .................................................................................................................................... 192

DATA SEQUENCES ................................................................................................................................................ 196

10.1. DATA AND MEMORY ....................................................................................................................................... 196 10.2. WHAT IS AN ARRAY ........................................................................................................................................ 197

10.2.1. Array Default Values and Initialization ............................................................................................. 199 10.2.2. Accessing Array Elements ................................................................................................................. 201 10.2.3. Reading Arrays from User ................................................................................................................. 204 10.2.4. “foreach” Loop .................................................................................................................................. 204

10.3. MULTIDIMENSIONAL ARRAYS ............................................................................................................................ 205 10.3.1. Rectangular Arrays ........................................................................................................................... 206 10.3.2. Initializing 2D Rectangular Arrays .................................................................................................... 208 10.3.3. Higher Dimensional Rectangular Arrays ........................................................................................... 211 10.3.4. Arrays of Arrays – Jagged Arrays ...................................................................................................... 212

NAMED CODE BLOCKS.......................................................................................................................................... 218

11.1. THE METHODS............................................................................................................................................... 218 11.1.1. What is a Method ............................................................................................................................. 218 11.1.2. Why to use Methods ......................................................................................................................... 219

Page 7: Programming Fundamentals

Programming Fundamentals Using C# 6

11.2. IMPLEMENTING METHODS ............................................................................................................................... 220 11.2.1. Method Declaration .......................................................................................................................... 220 11.2.2. Method Definition (Implementation)................................................................................................ 221 11.2.3. Where to Write Method ................................................................................................................... 222 11.2.4. Use of Methods ................................................................................................................................. 223

11.3. METHODS AND PARAMETERS ........................................................................................................................... 225 11.3.1. Passing Single Parameter ................................................................................................................. 226 11.3.2. Passing Multiple Parameters ............................................................................................................ 227

11.4. USING DIFFERENT ARGUMENT AND PARAMETERS TYPES ........................................................................................ 229 11.4.1. Methods and Variables ..................................................................................................................... 230

11.5. USING MULTIPLE METHODS ............................................................................................................................. 237 11.5.1. Nested Method Calls ......................................................................................................................... 238 11.5.2. Overloaded Methods ........................................................................................................................ 239

11.6. RETURNING VALUES FROM METHOD ................................................................................................................. 240 11.6.1. “return” Statement ........................................................................................................................... 240 11.6.2. Multiple “return” Statements ........................................................................................................... 243

11.7. PASS BY VALUE AND PASS BY REFERENCE ............................................................................................................ 244 11.7.1. Pass by Value .................................................................................................................................... 244 11.7.2. Pass by Reference using “ref” ........................................................................................................... 244 11.7.3. PASS BY REFERENCE using “out”....................................................................................................... 246 11.7.4. Pass by Pointer.................................................................................................................................. 248

11.8. PASSING AND RETURNING ARRAYS..................................................................................................................... 248 11.8.1. Passing and Returning One Dimensional Arrays ............................................................................... 248 11.8.2. Passing and Returning Multi-Dimensional Arrays ............................................................................ 251 11.8.3. “params” Array ................................................................................................................................. 253 11.8.4. Passing and Returning Jagged Array ................................................................................................ 254 11.8.5. Optional Parameters and Named Arguments .................................................................................. 255

11.9. RECURSION ................................................................................................................................................... 257 11.9.1. Direct and Indirect Recursion ............................................................................................................ 259 11.9.2. Recursion vs Iteration ....................................................................................................................... 259

11.10. BEST PRACTICES WHEN USING METHODS ...................................................................................................... 260

INDIRECT VARIABLES ............................................................................................................................................ 262

12.1. WHAT ARE INDIRECT VARIABLES ........................................................................................................................ 262 12.2. POINTERS ..................................................................................................................................................... 262

12.2.1. Unsafe Context ................................................................................................................................. 263 12.2.2. Declaring Pointer Variable ................................................................................................................ 265 12.2.3. Pointer Arithmetic ............................................................................................................................. 272 12.2.4. Pointer Conversions .......................................................................................................................... 273 12.2.5. Pointer To Pointer ............................................................................................................................. 278 12.2.6. Memory Management: new and delete ........................................................................................... 280 12.2.7. Garbage Collection and Pointers ...................................................................................................... 281 12.2.8. Fixed and movable variables ............................................................................................................ 283 12.2.9. Pointers and Arrays .......................................................................................................................... 284 12.2.10. Pointers and Functions ..................................................................................................................... 288

12.3. REFERENCE TYPES........................................................................................................................................... 291 12.3.1. Declaring Reference Type Variables ................................................................................................. 291 12.3.2. Reference Types and Methods .......................................................................................................... 293

Page 8: Programming Fundamentals

Programming Fundamentals Using C# 7

USER DEFINED DATA TYPES .................................................................................................................................. 297

13.1. WHAT IS USER DEFINED DATA TYPE .................................................................................................................. 297 13.2. ENUMERATIONS ............................................................................................................................................. 298

13.2.1. Defining Enumerations ..................................................................................................................... 298 13.2.2. Initializing enumerations .................................................................................................................. 300 13.2.3. Underlying data types of enumeration ............................................................................................. 301 13.2.4. Enumerations and Pointers ............................................................................................................... 302 13.2.5. Enumerations Arrays ........................................................................................................................ 303 13.2.6. Enumerations and Methods ............................................................................................................. 303

13.3. STRUCTURES.................................................................................................................................................. 305 13.3.1. What is Structure? ............................................................................................................................ 305 13.3.2. Accessing Structure Members........................................................................................................... 307 13.3.3. Initializing structure variables .......................................................................................................... 308 13.3.4. Structure and Structure Variables ..................................................................................................... 310 13.3.5. Multiple Structures and Structure Arrays ......................................................................................... 312 13.3.6. Nested Structures ............................................................................................................................. 314 13.3.7. Structures and Pointers..................................................................................................................... 317 13.3.8. Structures and Functions .................................................................................................................. 319

ERRORS AND EXCEPTIONS ................................................................................................................................... 321

14.1. THE ERRORS .................................................................................................................................................. 321 14.1.1. Error Types ........................................................................................................................................ 321 14.1.2. Program Compilation Methods ........................................................................................................ 324

14.2. EXCEPTIONS .................................................................................................................................................. 335 14.3. EXCEPTIONS HANDLING IN C# ........................................................................................................................... 337 14.4. FINALLY-BLOCK .............................................................................................................................................. 344

Page 9: Programming Fundamentals

Programming Fundamentals Using C# 8

Chapter 1

Introduction to Programming Computer programming is one of the wonderful fields of this era. It is science but

requires highly artistic vision and expertise. Today, around every electronic device is

programmed or going to be programmed in near future. Programming is an attitude

and a passion. To be a good programmer, you need to be passionate and build desired

attitude that will enable you to take programming as fun that you can enjoy when

doing. Virtually, it is accepted reality that through programming, you can build

anything that you need and want in “cyber world”.

In this chapter we will build the bases required for computer programming by

discussing initial concepts and terms, computer and its components, software and its

categories and all required basic ideas to start learning computer programming. After

studying this chapter, you should be able to know and describe basic tools, skills and

software required to learn programming.

1.1. COMPUTER AND COMPUTER TYPES A computer is a general device that accepts some information as input and manipulates it

to produce some specific results. The processing in computers is done according to pre-

specified instructions. In general, anything that can perform calculations could be

referred as computer. According to this definition human being is also computer.

Encyclopedia Britannica defines computer as “A computer is a device for processing,

storing, and displaying information[1]” However a popular definition now a days is “A

computer is an electronic device that accepts information, processes it and presents them”.

Figure 1- 1: Abstract View of Computer, describes this definition visually:

Computers could be manual or automatic. Computers developed in early ages were

mechanical and manual. The list may include abacus, slide rules, Babbage difference

engine, W. Thomson’s predicting machine and Torpedo Data Computer. In manual

Data Computer Information

Instructions

Figure 1- 1: Abstract View of Computer

Page 10: Programming Fundamentals

Programming Fundamentals Using C# 9

computers, human need to operate calculating machines by providing instructions. Now

a days the computers can perform calculations automatically by using stored instructions.

Based on the type of input and output, computers are grouped as follows:

Analog Computers

Digital Computers

Hybrid Computers

ANAL O G CO MPUT ER S

Computers that deal with analog type of data are called the analog computers.

Analog data like temperature, voltages, current, speed, are provided as input to

the analog computers that produce results after processing them [1]. For example,

speedo meter that measures speed is an analog computer. Input and output of

these computers is in analog form. You may have used variety of analog computers

in your life. Other examples include thermometer, vehicle petrol gauge and analog

petrol measuring meter.

D IG ITA L CO MPU TER S

Digital computers deal with discrete or digital type of data. Such computer receive

data in digital form like numbers, letters and symbols which are expressed in

binary form. “A computer that works with numbers that are represented by the

digits 0 and 1 is called the digital computer [2]”. Today when we refer to computer,

we usually mean digital computer. However reader must be aware that there are

other computer types that exist.

HYBR ID CO MP UTER S

A computer system consisting of a combination of analog and digital computer

systems [2]. These computers combine the best features of analog and digital

computers. Usually they are designed for special purposes where digital and

analog data is required to be processed. For example a petrol pump contains a

processor that converts fuel flow measurements into quantity and price values. In

hospital Intensive Care Unit (ICU), an analog device is used which measures

patient's blood pressure and temperature etc, which are then converted and

displayed in the form of digits.

1.2. COMPUTER SYSTEM AND ITS COMPONENTS A computer is a device that performs calculations. A computer system is a set of devices

including computer and other related devices like input/output devices, which make

computer to function. There is no well-defined list of devices to be included in computer

system. However “computer” must be in computer system. Every computer system may

have different number of devices.

There are two major types of computer components: Hardware and Software.

Page 11: Programming Fundamentals

Programming Fundamentals Using C# 10

COM PUT ER HARD WARE

Any physical device used in or with your machine for example, the computer

monitor that is used to view results and the mouse to point and click in screen. All

computer hardware can be further categorized as input devices, output devices

and processing devices.

COM PUT ER SO FT WARE

It is a set of instructions, stored digitally within the computer memory which tell

the computer what to do. Software components of computer have no physical

presence, they are stored in digital form within computer memory.

CONS O LE

A computer console is default (minimal) set of input and output devices attached

to computer. Usually they are keyboard and display screens. These devices allow

the user to interact with the system.

In your computer system, there may be multiple input and output devices. C#

provides you ways to program them however in this book, we will be dealing with

console programming. This is because, we are going to learn how to program not

what to program.

1.3. TYPES OF SOFTWARE A software is designed/developed to fulfil some task electronically. There are different

categories of software including:

Application Software

System Software and

Computer Programming Tools

1.3.1. APPLICATION SOFTWARE The software which perform the general user tasks is known as application

software. Such software is considered as general purpose software within specific

domain. For example MS Word for document editing, MS PowerPoint for

presentations etc.

1.3.2. SYSTEM SOFTWARE It is the software used to manage computer hardware components and allows the

interaction between hardware and other type of software. There is variety of

system software like operating systems, BIOS, Device drivers, boot loaders, linkers

and compilers.

An operating system is most important system software that run on a computer.

Every general purpose computer has an operating system to run other software.

Page 12: Programming Fundamentals

Programming Fundamentals Using C# 11

An operating system could be considered as computer manager that manages all

resources (hardware and software) of the computer. Usually no program or user

can interact with other software or hardware without the help of operating

system. Hence an operating system could be considered as a bridge between user

or software and machine.

There are lot many operating systems present in market and installed on

computers. In this book, we will be dealing with Microsoft Windows (any version).

This is default operating system for C#.

1.3.3. COMPUTER PROGRAMMING TOOLS These are special type of software used to build other software. A process to

develop software is called the programming and there is big list of programming

languages and software development tools. For example compilers, interpreters

and other translators.

In this book we are concerned with one software that lie in the domain of

computer programming tools.

1.4. THE COMPUTER PROGRAMMING A computer program is a set of instructions for computer to perform a specific task.

Computer programming, a process of software development, is done by professionals

called computer programmers or software engineers. The set of instructions written by

the programmer is called the S O U R C E C O D E .

1.4.1. COMPUTER PROGRAMMING LANGUAGES We can communicate with each other using some language. These languages are

categorized as I N F O R M A L or FO R M A L L A N G U A G E S . We do not consider the rules

and regulations when using I N F O R M A L L A N G U A G E S . Mostly, when we speak, we

violate the grammar rules easily but still we can communicate our views and actual

meaning of what we want to say. In short we can say that informal languages lack

the language construction rules and are ambiguous in this context. Informal

language is more commonly used in situations that are more relaxed and involve

people we know well. We follow language construction rules (grammar) strictly

when using formal language. No rule violation is tolerated. So we define as a

“F O R M A L L A N G U A G E” is a set of strings of symbols that may be constrained by

rules that are specific to it”.

A computer is a machine that can only understand what it has been already told.

Therefore, if we have written the language construction rules in computer,

computer can understand the language which is according to those rules. As a

result we can conclude that computer only understands the formal language.

Page 13: Programming Fundamentals

Programming Fundamentals Using C# 12

Every computer language is a formal language and all software are written using

these formal languages.

P R O G R A M M I N G L A N G U A G E

A programming language is a formal constructed language designed to

communicate instructions and data to a computer. There are so many languages

(formal ways) to build software. Using programming languages either we can

develop specific type of software or any type of software. First type of languages

are called the special purpose computer languages whereas the last type is known

as general purpose languages.

L A N G U A G E TY P E S

All general purpose and special purpose languages are divided into two broad

classes as shown in Figure 1- 2: Language Categories:

High level programming languages

Low level programming languages

L O W L E V E L L A N G U A G E S

Computer can understand only binary number system that consists of two digits 0

and 1. Therefore it is essential to provide data and instructions to computer in

binary form. As an example 5 could be represented as 0101 in binary and an

instruction for adding two numbers could be represented by a code 100. An

instruction to add 4 with 4 will be interpreted in binary as 100 0100 0100 add

4 4 (there is one to one correspondence between binary numbers and human

understandable English symbols and words). A formal way of writing instructions

in binary form is called the low level computer programming language. Low level

language is more arcane and difficult to understand and use. These languages are

designed to operate and handle the entire hardware and instructions set

architecture of a computer directly.

Low level languages are closer to computer hardware (CPU). Their prime function

is to operate, manage and manipulate the computing hardware and components.

Programs and applications written in low-level language are directly executable on

the computing hardware without any interpretation or translation. There are

many vendors developing processors and different type of processors may be built

in different ways (known as processor architecture). Hence binary codes of one

processor may be different from others. In other words, low level language of one

Hardware – Machine Circuit

Low Level Languages

High Level Languages

Figure 1- 2: Language Categories

Page 14: Programming Fundamentals

Programming Fundamentals Using C# 13

processor is different from other and as a result low level instructions written for

one type of processor may not run on other type of processor. This problem is

called the “portability” issue. Programs written in low level languages (machine

languages) are not portable.

It is very difficult to remember each instruction in binary form. The computer

scientists have coined the English like words or codes known as mnemonics to use

for different combinations of binary digits. A programmer writes instructions for

computer hardware in the form of mnemonics which are then translated into

binary form with the help of some other software called translator. For example

100 0100 0100 could be written as ADD 4 , 4 and this will be translated back into

binary to run on computer. A software that translates this symbolic representation

into binary is called the assembler and the set of mnemonics is known as assembly

language. This coding and translation process has made the programmer’s life lot

easier.

A D V A N T A G E S O F L O W L E V E L L A N G U A G E S

Assembly language can express very low-level things. We can: access machine hardware, CPU parts, IO devices and communication

channels

exactly define and control code behavior

control and change the way of code translation of compilers

Every CPU can offer multiple modes of programming. Compilers may not

use all the modes. Using low level language, we can access to unusual

programming modes of your processor i.e special mode for accessing the

firmware

optimize the code to an extent to produce fast code

write some code for compiler optimization

In short, we can completely control our code

D I S A D V A N T A G E S O F L O W L E V E L L A N G U A G E S

Assembly is a very low-level language (the lowest above hand-coding the binary instruction patterns). Programming in assembly is not always easy and enjoyable.

it is long and tedious to write initially

it is quite bug-prone and one can easily introduce bugs in program

Bugs introduced in program can be very difficult to chase

Code can be fairly difficult to understand and modify, i.e. to maintain

Code produced is non-portable to other architectures (machines), existing

or upcoming

It is very time consuming to code in Assembly. The programmer spends

more time on a few details and can't focus on small and large algorithmic

design

Page 15: Programming Fundamentals

Programming Fundamentals Using C# 14

A small change in algorithmic design might completely invalidate all

existing assembly code.

Normally code produced by compilers is much better and manageable

than code written by hand.

H I G H L E V E L P R O G R A M M I N G L A N G U A G E S :

To make programming job easier computer researchers have developed the way

to write instructions in more English like way and another software is developed

to translate this English like instructions into binary form. This software is known

as C O M P I L E R or I N T E R P R E T E R . Such languages are independent of machine and

easy to work with and are called high level programming languages. It lets the

programmer concentrate on the logic of the problem to be solved rather than the

machine architecture.

As an example we can write 4 + 4 in a high level language that is translated into

binary by the translation software as 100 0100 0100. Examples of high level

languages include C, C++, Java, C# etc.

A D V A N T A G E S O F H I G H L E V E L L A N G U A G E S :

High-level languages such as C# and Java are preferred for programming because they provide a convenient abstraction of the underlying system suitable for problem solving. The advantages of programming in a high-level language include the following: PR O G R A M D E V E L O P M E N T I S E A S I E R

High level languages are very similar to natural languages such as English so they are very easy to learn and use. For higher level languages programmers needs not to learn about internal structure of the computer. PR O G R A M D E V E L O P M E N T I S F A S T E R

Many high-level languages provide structures (sequential, selection, iterative) that facilitate program development. Programs written in a high-level language are relatively small and easier to code and debug. PR O G R A M M A I N T E N A N C E I S E A S I E R

Programming for a new application can take several weeks to several months, and the lifecycle of such an application software can be several years. Therefore, it is critical that software development be done with a view toward software maintainability, which involves activities ranging from fixing bugs to generating the next version of the software to incorporating new features. Programs written in a high-level language are easier to understand and, when good programming practices are followed, easier to maintain. Assembly language programs tend to be lengthy and take more time to code and debug. As a result, they are also difficult to maintain.

Page 16: Programming Fundamentals

Programming Fundamentals Using C# 15

PR O G R A M S W R I T T E N I N A H I G H-L E V E L L A N G U A G E A R E P O R T A B L E

High-level language programs contain very few machine-specific details, and they can be used with little or no modification on different computer systems. In contrast, assembly language programs are written for a particular system and cannot be used on a different system. O V E R V I E W O F F E W H I G H L E V E L L A N G U A G E S

Here we present an overview of few high level languages which are common in

software development. Figure 1- 3: Tiered View of Languages, shows language

hierarchy.

HTML:

Hyper Text Markup Language (HTML) is core language of the World Wide Web that

is used to define the structure and layout of web pages by using various tags and

attributes. Although a fundamental language of the web, HTML is static - content

created with it does not change. It specifies the web page contents and their

formatting. The language does not have the feature to define functionality of web

page.

J A V A S C R I P T :

A language developed by Netscape is used to provide dynamic and interactive

content on webpages. With JavaScript it is possible to communicate with HTML,

create animations, create interactive web content, validate forms, and more.

JavaScript is often confused with Java, but they are two different languages.

JAVA:

A powerful and flexible language created by Sun Microsystems that can be used

to create applets (a program that is executed from within another program) that

run inside webpages as well as software applications. Things you can do with Java

include interacting with the user, creating graphical programs, reading from files,

and more.

High Level

Languages

Low

Level

Hardware – Machine Circuit

Machine Language

Assembly Language

High Level

Languages

C C++ C#

VB Jav

a

HTML

Figure 1- 3: Tiered View of Languages

. . .

Page 17: Programming Fundamentals

Programming Fundamentals Using C# 16

PHP:

Hypertext Preprocessor (it's a recursive acronym). A powerful language used for

web development. PHP was originally created in 1994 By Rasmus Lerdorf.

JavaScript provides web page interactivity for client side whereas PHP provides

server side interaction and database access and manipulation related features.

C:

An advanced programming language of 70’s used for software application

development. Originally developed by Dennis Ritchie at Bell Labs in the 1970's and

designed to be a systems programming language but since then has proven itself

to be able to be used for various software applications such as business programs,

engineering programs, and even games. The UNIX operating system is written in

C.

C++:

This language is descendant of the C language. The difference between the two

languages is that C++ more advanced and is object-oriented. C++ was developed

by Bjarne Stroustrup at Bell Labs and is a very popular language.

V I S U A L B A S I C :

A language developed by Microsoft based on the BASIC language. Visual Basic is

used for creating Windows applications. This language has been widely used for

learning and business software development. The VBScript language (also

developed by Microsoft) is based on Visual Basic.

1.4.2. THE DIFFERENT GENERATIONS OF LANGUAGES From start of computer programming, till now, hundreds of computer languages

have been developed and used. Usually, every new language developed is more

powerful and feature rich than old languages. Based on increasing power, better

feature set, programming style, easiness and efficiency, programming languages

have been classified into five groups known as programming language

generations. With every generation new features are introduced in the languages.

Figure 1- 4: Language Generations, provides a view of different language

generations with example languages.

Figure 1- 4: Language Generations

Page 18: Programming Fundamentals

Programming Fundamentals Using C# 17

F IRST G EN ERAT IO N LA N G UA G ES (AB BREV IAT ED AS 1GL)

First generation (programming) language (1GL) is a group of machine level

programming languages used to program first-generation computers. These

computers are equipped with front panel switches which are used to give

instruction directly to the CPU as shown in Figure 1- 5: IBM Front Panel. There was

originally no compiler or assembler to process the instructions in 1GL. The

instructions in 1GL are made of binary numbers, represented by 1s and 0s. This

makes the language suitable for the understanding of the machine but very much

more difficult to interpret and learn by the human programmer.

The main advantage of programming in 1GL is that the code can run very fast and very efficiently, precisely because the instructions are executed directly by the CPU. One of the main disadvantages of programming in a low level language is that when an error occurs, the code is not as easy to fix. First generation languages are very much adapted to a specific computer and CPU, and code portability is therefore significantly reduced in comparison to higher level languages. Modern day programmers still occasionally use machine level code, especially when programming lower level functions of the system, such as drivers, interfaces with firmware and hardware devices. Modern tools, such as native-code compilers are used to produce machine level from a higher-level language.

Figure 1- 5: IBM Front Panel

SEC OND G EN ERAT ION L AN GU AG E S (2GL)

Languages in this generation represent a step up from the first generation languages. As discussed above, in these languages symbolic codes are used to represent data and instructions in the program. Programs written in these type of languages need the translator called assembler to translate English like codes into binary form. These languages are known as assembly languages. Figure 1- 6:

Page 19: Programming Fundamentals

Programming Fundamentals Using C# 18

Assembly to Machine Translation, shows the translation process of code in assembly into machine language.

Computer processors are the electronic components forming complex circuits made by different manufacturers. Each manufacturer builds its processor differently. One processor may have different components than other or the circuit design may differ. Different type of processors are programmed differently hence for different type of processors, there are different type of assembly languages. Example include assembly for x86, assembly for MIPS etc. Figure 1- 7: Assembly Language Code, shows a code snap shot written in Assembly language for x86 architecture.

Figure 1- 7: Assembly Language Code

Assembly Language Program

INPUT Assembler

Machine Language Program

OUTPUT

Source

Program

Object

Program

One to One

Correspondence

Figure 1- 6: Assembly to Machine Translation

Page 20: Programming Fundamentals

Programming Fundamentals Using C# 19

THIRD GE NER ATI ON LA NG UA G E S (3GL)

With the languages introduced by the third generation of computer programming, words and commands (instead of just symbols and numbers) were being used. These languages therefore, had syntax that was much easier to understand. Third generation languages are known as "high level languages" and include C, C++, Java, and JavaScript, among others. Figure 1- 8: 3G Language C Code, shows a code snippet of C language. 3GLs are much more machine independent and more programmer-friendly. This includes features like improved support for aggregate data types, and expressing concepts in a way that favors the programmer, not the computer. A third generation language improves over a second generation language by having the computer take care of non-essential details. The main advantage of high-level languages over low-level languages is that they are easier to read, write, and maintain. Ultimately, programs written in a high-level language must be translated into machine language by a compiler or interpreter.

Figure 1- 8: 3G Language C Code

FOURTH GE NER ATI ON L AN GU AG E S (4GL)

The syntax used in 4GL is very close to human language, an improvement from the

previous generation of languages. Each of the programming language generations

aims to provide a higher level of abstraction (conceptual view) of the internal

computer hardware details, making the language more programmer-friendly,

powerful and versatile. Normally 4GL are domain specific languages. 4GL

languages are typically used to access databases and include SQL. Other examples

may include Power Builder, Forth, Clipper, MatLab. Figure 1- 9: 4G Language SQL

Code, shows an SQL command and its result.

Page 21: Programming Fundamentals

Programming Fundamentals Using C# 20

Figure 1- 9: 4G Language SQL Code

F IFT H GEN ERA TI ON L AN G UA G ES (5GL)

5GLs are based on solving problems using constraints given to the program, rather

than using an algorithm written by a programmer. 5th-generation languages are

designed to make the computer solve a given problem without the programmer.

This way, the programmer only needs to worry about what problems need to be

solved and what conditions need to be met, without worrying about how to

implement a routine or algorithm to solve them. Fifth-generation languages are

used mainly in artificial intelligence research. Examples in this generation include

Prolog, Lisp and Mercury. You can see a program written in Prolog in Figure 1- 10:

5G Language Prolog Code.

Page 22: Programming Fundamentals

Programming Fundamentals Using C# 21

Figure 1- 10: 5G Language Prolog Code

1.5. PROGRAMMING PARADIGMS A programming paradigm is a fundamental style of computer programming, a way of

building the structure and elements of computer programs. Some programming languages

follow one paradigm whereas other can support multiple paradigms. Here is the list of

different programming paradigms (certainly, there are more):

Imperative Programming or procedural programming

Declarative Programming / Functional Programming

Object Oriented Programming

Logic Programming

Event Driven Programming

1.5.1. IMPERATIVE/PROCEDURAL PROGRAMMING: This programming paradigm (way of programming) focuses on how a program

should operate. It is based on algorithmic details. In our daily life, to solve any

problem, we perform small steps and get our task done. Similarly in this way of

programming, we concentrate on how to write instructions such that the required

task is achieved.

A procedure is set of statements that has been given a unique name. In procedural

way of programming, we name different set of instructions that perform sub-tasks

and collectively all subroutines performs one main task.

Page 23: Programming Fundamentals

Programming Fundamentals Using C# 22

1.5.2. DECLARATIVE / FUNCTIONAL PROGRAMMING In this style of programming logic of how to do the task is specified with describing

the control flow. Many languages applying this style attempt to minimize or

eliminate side effects by describing what the program should accomplish in terms

of the problem domain, rather than describing how to go about accomplishing it

as a sequence of the programming language instructions. Structured Query

Language is one of the example of languages that lie in this domain. In this style,

the computation is considered as set of mathematical functions.

1.5.3. OBJECT ORIENTED PROGRAMMING Object Oriented Programming (OOP) is based on the concept of object. In our daily

life, everything is an object of some type. For example, a glass is an object of type

glass, you are an object of type human, rose is of type flower, and your motor car

is an example of type car. Each object is identified from others based on its

features and actions i.e. you are different from others based on your name, your

facial image, your way of talking, way of walking. You can do some tasks which

others may or may not do. In short collection of features and tasks defines “you”

- the object.

In this programming style, a programmer models the real world in object oriented

way that is more natural representation of things in software. Some object-

oriented languages include C++, Java, C# and PHP.

1.5.4. LOGIC PROGRAMMING This programming paradigm is based on logical rules. To program any task, some

facts about that task and rules used in doing that task are formulated. The

computer is then instructed to deduce the results based on these rules. You can

refer to prolog code in Figure 1- 10: 5G Language Prolog CodeError! Reference

source not found., for better understanding.

1.5.5. EVENT DRIVEN PROGRAMMING This method of programming is based on the philosophy that do something when

some event occurs. For example, something should be done by the computer

when user clicks the mouse button or when a key is pressed, predefined action

should be executed. Event-driven programming is the dominant paradigm used in

programming graphical user interfaces based and other applications (e.g.

JavaScript web applications) that are centered on performing certain actions in

response to user input.

Page 24: Programming Fundamentals

Programming Fundamentals Using C# 23

A group of statements (block of code) is bound with a particular event. Whenever

that event occurs, that block of code is executed. The language used in this book,

C#, too provides event driven way of programming.

1.6. PROGRAMMING TOOLS AND ENVIRONMENTS

SYN TAX

Each language defines a set of rules according to which instructions are written.

This set of rules makes the syntax of the language.

Every programming language has its own syntax. Program translation software

(compiler/interpreter) translates the instructions from high level language to

machine code according the language rules.

The process of learning programming could be divided into two tasks. First one is

to learn the syntax of the language and second one is to learn the logical way of

problem solving. This second phase is less related to language syntax and most of

the students find this phase difficult. Logical thinking and problem solving is based

on practice. Once you have developed your skills for problem solving, learning

syntax remains as small job.

SEM AN TI CS

Semantics refer to M EA N I N G of programming language constructs and its usage

rules. It focuses on the relation between signifiers, like words, phrases, signs, and

symbols, and what they stand for. We can define semantics as “semantics provides

the rules for interpreting the syntax which do not provide the meaning directly but

constrains the possible interpretations of what is declared”. For example in some

languages “=” sign is used for assignment and comparison where as in other

languages “=” sign may only be used for assignment and “==” is used for

comparison. So semantics of “=” this either define two meanings or single one.

SO URCE CODE

Instructions written in a programming language is called the program or source

code. Such set of instructions may be as simple as few lines of code or as complex

as millions of lines of code.

The software developers sometime make source code available to other users.

Such software is called the O P E N S O U R C E S O F T W A R E whereas other developers

or companies developing code sell only machine translated software. They hide

the source code for commercial purpose. A software whose source code is not

available is called the C L O S E D S O U R C E S O F T W A R E .

Page 25: Programming Fundamentals

Programming Fundamentals Using C# 24

SO URCE CODE EDI TOR

A basic job of programmer is to write the instructions for computer to perform

specific task. To write and edit the source code a special type of software is used

called the source code editor. This editor could be a separated software or part of

other software. Some source code editors have features specifically designed to

simplify and speed up input of source code, such as syntax highlighting,

indentation, autocomplete and bracket matching functionality. These editors also

provide a convenient way to run a compiler, interpreter, debugger, or other

program relevant tools required during software development process. So, while

many text editors can be used to edit source code, if they don't enhance, automate

or ease the editing of code, they are not source code editors, but simply text

editors that can also be used to edit source code. Microsoft provides a feature rich

source code editor intended to make programming fast, easy and enjoyable task.

COM PILE R

A compiler is a computer program (or set of programs) that transforms source

code written in a programming language into another computer language The

most common reason for converting a source code is to create an executable

program. Usually a compiler performs multiple tasks that include syntax analysis,

semantic analysis, code generation and code optimization.

FIGURE 10: COMPILATION PROCESS

Figure 1- 11: Compilation Process, shows the overview of code compilation

process. Source code is provided as input to the compiler program. This translates

the program into machine language that is understandable for machine and

machine can run it. A translated machine language program that machine can run

is known as Executable program. If there are some inconsistencies or ambiguities

in input program, the compiler can point out and report them to the programmer.

These inconsistencies are known as errors that may be of type syntax or semantics.

Compiler either translates all program into machine language or produces error

report, either succeeds or fails however no partial code translation occurs.

Figure 1- 11: Compilation Process

Source Code Compiler

Object Program

Error Report

INPUT OUTPUT

Page 26: Programming Fundamentals

Programming Fundamentals Using C# 25

INTE RPRE TE R

An interpreter is a software that reads one instruction from source code written

in high level language, at a time, translates it in machine language, executes it and

then proceeds to next instruction.

An interpreter is a good tool to look at the results produced by each instruction in

your program. You will be using this software to dig out errors and ambiguities in

code you write.

DE BUG GER

Every software is designed and developed to fulfill a particular task. A programmer

may write an instruction in software that either violates the language semantic

rule or intended task real world rule. Syntactically program is correct and compiler

does not complain during compilation. But due to this violation, the software does

not produce the intended results or may entirely fail. A software can also show

such behavior due to invalid data. These type of violations are known as bugs. A

"trap" occurs when the program cannot normally continue because of a

programming bug or invalid data. When a trap is reached program execution is

stopped and an appropriate action is taken by the debugger if installed and

configured. The code being translated by compiler may invoke debugger or

translated code being run by operating system may initiate debugging software.

A debugger is a software that allow the programmer to find bugs in her program

and remove them. Some debuggers operate on a single specific language while

others can handle multiple languages transparently. C# comes with powerful

debugging software that can either debug at high level or even low level.

PROJE CT O R SOLUTI O N

A student or beginner writes few lines of code to fulfil small tasks. A professional

can write hundreds or even thousands of lines of code. When a huge amount of

code is written, it is required to manage the code in such way that it could be easily

understood and organized. Normally a programmer distributes the code among

different files. All such files relate to single software. A collection of files that

contain code for single software is called the project or solution. Besides code files,

there may be other text, picture, audio or video files that are part of software.

Figure 1- 12: Visual Studio .NET Solution Explorer and Solution Files, shows a

solution and files listed in it (in visual studio IDE);

Page 27: Programming Fundamentals

Programming Fundamentals Using C# 26

Figure 1- 12: Visual Studio .NET Solution Explorer and Solution Files

BUIL T- IN LIBRARIES

Every language consists of multiple features that could be divided into two

categories: Language core features and extended features. Core features are built

into the language translator (compiler). The extended features are provided with

language in the form of libraries, the software used to enhance the language

functionality. These may include configuration data, documentation, help data,

message templates, and pre-written code. These libraries either come with

language compiler in compiled form or could be added by the user (built-in

libraries could be extended too). Every program written in any language uses some

of functionality from built-in libraries or user libraries. As a result the library

functionality used in program also becomes the part of program.

OBJE CT CODE

The compiler of a language translates the user program into machine language. As

discussed above, the user program also uses some functionality from library.

During compilation process, the compiler translates the user program and places

references of library functionality in translated code. Already translated code from

library is not made part of user translated program. Computer can execute the

translated instructions but cannot run the library references as actual machine

code is not linked with user program. It mean a high level code translated into

Page 28: Programming Fundamentals

Programming Fundamentals Using C# 27

machine code with library references cannot be used to achieve the task for what

it is developed. Such a code is called object code.

LINKE R

A linker is a software that takes object code as input and attaches the library code

with machine code from library that is referred by the programmer. Hence it

transforms object code to executable code. Error! Reference source not found.

escribes the linking process:

Figure 1- 13: Compilation and Linking Process

Look at ovals in Figure 1- 13: Compilation and Linking Process, which describe how

compiler translates user code into machine code (object code) but library

references (Lib ref) are not changed. The linker software links library files with

object code by replacing library references with actual code from library,

transforming it into executable code. Now machine will be happy to obey this

code.

EXECUTABLE CODE

An executable code causes the computer to perform indicated tasks according to

encoded instructions. Source code is translated using some translation software

into machine code which is runnable on the machine (after linking). This runnable

code is also called the executable code.

You may write your code in any language (each language has different syntax) but

for same machine, translated machine code is same. However machine code

produced for one type of processor may not run on other type of processor due to

Page 29: Programming Fundamentals

Programming Fundamentals Using C# 28

different processor architecture. Operating system also plays important role

regarding executable code. A program translated into machine code using one

operating system may not run on other operating system even the hardware

remains same.

INTE G RATED DE VELO PMENT EN VI RON MEN T

As we have seen above, multiple software (tools) are required to build new

software. These tools either come separately or combined in the form of single

software. Every tool becomes the part of that bigger software. Such a big single

software is called the Integrated Development Environment (IDE). There may be

multiple IDEs for single language and there may be single IDE for multiple

languages. Every IDE may include different set of tools and software for the ease

of software development. Following is the image of Visual Studio 2010 IDE.

Figure 1- 14: Visual Studio 2010 IDE

Detailed introduction of VS IDE is provided in next chapters.

Page 30: Programming Fundamentals

Programming Fundamentals Using C# 29

1.7. PRACTICE QUESTIONS AND EXERCISES

1.7.1. OBJECTIVES Q.1. F I LL IN T HE B LA N KS

1. A programming language is a formal…………………designed to communicate…………….and

data to a computer.

2. Low level languages are designed to operate and handle the entire…………….and

instructions set…………of a computer directly.

3. A software that translates symbolic representation into binary is called the………………..and

the language is known as………………………

4. Your………….can be very difficult to chase.

5. ………………… languages programmers needs not to learn about internal structure of the

computer.

6. HTML stand for……………………………………………

7. Java is a powerful and flexible language created by…………………………..

8. Third generation languages are known as…………………and include…………….

9. In object-oriented programming, data types defined by the……………….. are called…………..

10. A………….. is a computer program that transforms source code written in a programming

language into another……………..language.

11. An……………… is a software that reads………… instruction from source code written in high

level language, at a time, translates it in…………….and executes it.

12. A………….. is a software that allow the programmer to find……….. in her program and

remove them.

13. A collection of files that contain code for single software is called the…………….or…………….

14. An ………..code causes the computer to perform indicated tasks according

to…………instructions.

15. Fifth-generation languages are used mainly in…………………………research.

Q.2. TRU E / FA LS E

1. Programs written in low level languages are portable.

2. Software components of computer have physical presence, they are stored in digital form

within computer memory.

3. The software used to manage the hardware components is called application software.

4. The set of instructions written by the programmer is called source code.

5. A programming language is an informal constructed language designed to communicate

instructions and data to a computer.

6. Computer can only understand digital number system.

7. A formal way of writing instructions in binary form is called the low level computer

programming language.

Page 31: Programming Fundamentals

Programming Fundamentals Using C# 30

8. High level languages programmers needs to learn about internal structure of the

computer.

9. The main disadvantages of programming in a low level language is that when an error

occurs, the code is not as easy to fix.

10. First generation languages are known as high level languages.

11. Fifth generation languages are designed to make the computer solve a given problem

without the programmer.

12. A software whose source code is not available is called the closed source software.

13. A compiler is a computer program that transforms source code written in a programming

language into another computer language.

14. A debugger is a software that cannot allow the programmer to find bugs in her program.

15. Source code is translated using some translation software into machine code which is

runnable on the machine. This runnable code is also called the executable code.

1.7.2. SUBJECTIVE – DESCRIPTIVE QUESTIONS Q.3. DE SCR IB E TH E FO LL OW IN G S

1. What are the major components of a computer? Describe briefly.

2. What is software? Describe its different types.

3. Define computer programming?

4. Define programming language and describe its different types?

5. Briefly describe low level language?

6. What are the advantages and disadvantages of low level languages?

7. Describe high level language with its advantages and disadvantages?

8. Describe some high level languages?

9. Briefly describe working of first and second generation languages?

10. Describe third generation languages with examples?

11. What is programming paradigms? Discuss different programming paradigms mentioned in

this chapter.

12. Define compiler, interpreter and debugger?

13. What is the difference between compiler and interpreter?

14. Describe source code, object code, linker and executable code?

15. What is Integrated Development Environment? List few of tools present in an IDE.

1.7.3. ACTIVITIES 1. Prepare a list of ten system software

2. Make a list of 5 languages along with code samples of each language generation

3. There are different programming paradigms. Few are listed in this chapter. Prepare a

report on various paradigms and list languages in them.

Page 32: Programming Fundamentals

Programming Fundamentals Using C# 31

4. Download and install different IDEs from Internet and make a list of various tools that you

can find in IDE of C, C++ and C#. Could there be a list of fixed number of tools in an IDE?

Discuss. Do include IDE snapshots in your report.

1.8. USEFUL WEB RESOURCES 1. General computing information. http://www.wikipedia.org/wiki/computer

2. Collection of analog computers. http://www.analogmuseum.org/english/

3. General computing information. http://whatis.techtarget.com/

4.

Page 33: Programming Fundamentals

Programming Fundamentals Using C# 32

Chapter 2

Data and its Representation In our daily life we play with data, extract knowledge from data by transforming it into

information using different methods and techniques. We get data through our input

organs like ears, eyes, nose, and skin, and using our mind we transform that data into

information. Our decisions and actions are based on gained knowledge. Computer is

an electronic machine that carries this data transformation task rapidly. This rapid

processing assist us in our decision making.

But what is data and information? In this chapter, we will learn about data. Its

different types, their representation in computers, transformation of one type of data

into another.

2.1. DATA AND INFORMATION

2.1.1. DATA It is defined as “collection of raw facts and figures” such as numbers, words,

measurements, observations or even just descriptions of things. Raw data does

not provide us useful knowledge about things. The data is divided into two

categories: qualitative and quantitative.

QU ALI TA T IV E DATA is descriptive data that describe something. Like

“computer”, “milk”, “road”, “work” etc.

QU ANT I TA TI VE DA TA is numeric data that measures something. Like 5, 6 and 7.

The quantitative data is further categorized as discrete data and continuous data.

The D ISCRET E DATA can only take certain values like 4 and after that 5. No value

between 4 and 5 are included in discrete data. We use discrete data to measure

complete things. For example in sentence “5 members attended the meeting”

represent five persons. There could not be 4.5 or 5.5 persons. Similarly there may

be 2 or 3 schools but not 2.5 schools. CONTINU OUS DATA can take any possible

value between two complete numbers. For example, between 4 & 5 there would

be infinite numbers. Continuous data is used to measure quantities that are

fractional. For example, you may have 4 rupees, 4.5 rupees or 4.55 rupees.

Page 34: Programming Fundamentals

Programming Fundamentals Using C# 33

2.1.2. INFORMATION Processed data is considered as information. Information is defined in different

ways. “Knowledge obtained after applying some processing on the observed data

is known as information”.

In rest of the book we will use data and information interchangeably. Particular

meaning would be clear from context. Before we discuss more about data and

information, we look at some mathematical background necessary to understand

the concept.

2.2. NUMBER SYSTEM A number system is system that we used to express quantities. It is a mathematical

notation for to measure quantities. In a number system, a finite set of symbols is defined.

Each symbol is used to represent a value. When all symbols in the set are used, a

combination of multiple symbols of same set are used to represent larger quantities. There

may be number systems having similar symbols but each number system assigns different

values to them. For example, “11” is used represent eleven in one number system but

three in other number system. All number systems works on some basic rules. If we know

those basic rules, we can easily under the number system and follow its implementation

in computers as well. There are multiple number systems in practice in world. But here we

will study only those which are related to computers and computation.

2.2.1. DECIMAL NUMBER SYSTEM The word decimal stands for “ten”. A number system which has ten symbols to

represent the quantities is called the decimal number system. These ten symbols

are 0, 1, 2,3,4,5,6,7,8 and 9. Following set shows the symbols used in this number

system.

S={0,1,2,3,4,5,6,7,8,9}

The relationship of these symbols is as follows:

0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9

The amount of symbols in a number system is called its “base”. We explain below

two basic operations in this number system: counting and addition.

DE C I M A L C O U N T I N G

Let we explain the concept of counting with the help of an example. Suppose that

you are enrolled in a class to study C#. At 7.00 am there is no one of your class

Page 35: Programming Fundamentals

Programming Fundamentals Using C# 34

present in class room so we use the “smallest value symbol” to represent this

information that is “0” (zero). Next only one student arrives, you use symbol “1”

and so on. When there are nine students in the class room, you use “9” symbol.

How will you use this set of symbols if one other student arrives i.e. total students

are ten. You do as follows:

Suppose previous symbols as (consisting of two digits) 09

Place next greater symbol in place of left digit and smallest value symbol in place of right digit

10

Now there are two symbols in “10”. Here “1” represents that all the set of symbols

is repeated once. The quantity “12” means that all set is used once and after that

counting has reached to “2”. Here are few such representations:

All set is used two times 20

All set is used two times and counting reached to 5 25

All set is used 9 times and counting has reached to 9 99

To proceed to next quantity

Suppose 0 on left side of 99 099

1 = Repetition of sets at middle digit position has reached to maximum one time 0 = All digits have been used to represent the repetition and repetition counting started again 0 = counting it started again.

100

In this way the counting process continues. Whenever a maximum value symbol

i.e. “9” is placed on some location, for next counting, this symbol is replaced by

smallest value symbol and its neighboring left side symbol is replaced with next

higher value symbol.

P O S I T I O N A L NO T A T I O N

In positional notation, positions of digits are defined. Value of digit is known with

its position (for example, the "ones place", "tens place", and “hundreds place"). A

digit placed on different positions represents different values. This positional

notation greatly simplified arithmetic that lead its rapid spread across the world.

The right most digit of a number represents minimum value i.e. unit value. The

next left digit is multiplied with base (i.e. “ten” position digit represents that how

many times complete set of symbols has been used on “unit” position) to find its

positional value. Following example clears the concepts.

Number 5789

Page 36: Programming Fundamentals

Programming Fundamentals Using C# 35

Positional Value of 9 9 * 100 9

Positional Value of 8 8 * 101 80

Positional Value of 7 7 * 102 700

Positional Value of 5 5 * 103 5000

5 * 103 7 * 102 8 * 101 9 * 100

5000 700 80 9

5000 + 700 + 80 + 9

= 5789

A number an an−1...a2 a1 a0 where a0, a1 ... an are all digits in a base b (note that

here, the subscript does not refer to the base number; it refers to different

objects), the number can be represented in any other base, including decimal,

by:

This general rule is applicable on all number systems we discuss in this chapter.

DE C I M A L A D D I T I O N

We explain the decimal addition with the help of an example. Let we want to add

two number 4978 and 8486.

4 9 7 8

8 4 8 6

The addition process starts from the right most position. 8 and 6 are added using

the counting process. I.e. IIII IIII + IIII II = IIII IIII IIII II = 14. At the result position

of right most digits, 4 is placed and ten is taken as carry toward 10s position where

it becomes 1.

Same process is repeated for digits at 10s position. The carry is taken toward

100s position and remainder is left on result position. 7+8+1=16 using above

mentioned process.

1

4 9 7 8

8 4 8 6

4

Page 37: Programming Fundamentals

Programming Fundamentals Using C# 36

Continuing the addition process, all digits are added resulting:

In general, for numbers in base b, we can write as follows:

Here “C” stands for carry and “R” stands for remainder.

Carries Remainders

C1=(d+h)/b R1=(D+H)%b

C2=(C1+C+G)/b R2=(C1+C+G)%b

C3=(C2+B+F)/b R3=(C2+B+F)%b

C4=(C3+A+E)/b R4=(C3+A+E)%b

“/” operator finds the quotient of division and “%” operator gives the remainder

of division. It is emphasized that the reader should understand these calculations

as same rules applies with following number systems.

2.2.2. BINARY NUMBER SYSTEM Binary number system consists of two symbols 0 and 1 to represent the quantities.

S = {0.1} 0 < 1

1 1

4 9 7 8

8 4 8 6

6 4

1 1 1 1

4 9 7 8

8 4 8 6

1 3 4 6 4

C4 C3 C2 C1

A B C D

E F G H

R4 R3 R2 R1

C4 C3 C2 C1

(C3+A+E)/b (C2+B+F)/b (C1+C+G)/b (d+h)/b

A B C D

E F G h

C4 (C3+A+E)%b (C2+B+F)%b (C1+C+G)%b (d+h)%b

R4 R3 R2 R1

Page 38: Programming Fundamentals

Programming Fundamentals Using C# 37

If you have clearly understood the decimal counting and addition, it would be very easy for you to understand this discussion. Binary number system is a positional system too. B I N A R Y C O U N T I N G

The counting process proceeds as that is in decimal. Counting starts with small

value digit which is zero. For next quantity, higher value digit is used that is 1. For

next number, we observe that the set is used, we place 1 on left and 0 on right as

shown below:

You suppose previous symbols as (consisting of two digits)

01

Place next greater symbol in place of left digit and smallest value symbol in place of right digit 1 = the set is used one time at ones position 0 = counting at ones position is not started yet

10

Left 1 = the set is used one time at ones position Right 1 = the counting has reached to 1 at right position

11

Now for next counting, we proceed as before:

You suppose smallest value symbol on left most position 011

Place next greater symbol in place of left digit and smallest value symbol in place of right digit 1 = the set repetition counting has done one time 0 = set repetition count is not yet started 0 = counting at ones position is not started yet

100

Being positional number system, the value of each digit in a number is determined by its position.

Number 1101

Positional Value of 1 1 * 20 1

Positional Value of 0 0 * 21 0

Positional Value of 1 1 * 22 4

Positional Value of 1 1 * 23 8

1 * 23 1 * 22 0 * 21 1 * 20

1000 100 00 1

1000 + 100 + 10 + 1

= 1101

A number an an−1...a2 a1 a0 where a0, a1 ... an are all digits in a base b (note that

here, the subscript does not refer to the base number; it refers to different

objects), the number can be represented in any other base, including decimal, by:

Page 39: Programming Fundamentals

Programming Fundamentals Using C# 38

FORMULA - 1

B I N A R Y A D D I T I O N

This works in same way as that of decimal addition. We will not explain it here but

interested reader can understand the working of binary addition using tables given

in “Decimal Addition” section.

B I N A R Y T O DE C I M A L C O N V E R S I O N

The formula - 1 given in above section provides the way to convert binary number

into decimal. We see its working using following example:

Binary Number 1101

1 * 23 1 * 22 0 * 21 1 * 20

8 4 0 1

8 + 4 + 0 + 1

= 13

DE C I M A L T O B I N A R Y C O N V E R S I O N

There are different ways to convert the number in decimal into binary. Here we

present only one method. Let we have a decimal number 547 and we want to

convert it into binary, we proceed as follows:

Divisor Quotient Remainder

2 547

2 273 1

2 136 1

2 68 0

2 34 0

2 17 0

2 8 1

2 4 0

2 2 0

1 0

The resultant number in binary is (1000 1000 11)2.

2.2.3. OCTAL NUMBER SYSTEM Octal number system has eight symbols in its set as listed below:

Page 40: Programming Fundamentals

Programming Fundamentals Using C# 39

S = {0, 1, 2, 3, 4, 5, 6, 7} 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7

O C T A L C O U N T I N G

As in decimal number system, counting starts with smallest value digit which is

zero. For next quantity, higher value digit is used that is 1. The process simply

continues till highest value digit “7”. For next number, we observe that the set is

used, we place 1 on left and 0 on right as shown below:

You suppose previous symbols as (consisting of two digits)

07

Place next greater symbol in place of left digit and smallest value symbol in place of right digit 1 = the set is used one time at ones position 0 = counting at ones position is not started yet

10

Left 1 = the set is used one time at ones position Right 4 = the counting has reached to 4 at right position

14

Now for next counting, we proceed as before

You suppose smallest value symbol on left most position 077

Place next greater symbol in place of left digit and smallest value symbol in place of right digits 1 = the set repetition counting has done one time 0 = set repetition count is not yet started 0 = counting at ones position is not started yet

100

Being positional number system, the value of each digit in a number is determined by its position:

Number 5674

Positional Value of 4 4*80 4

Positional Value of 7 7*81 70

Positional Value of 6 6*82 600

Positional Value of 5 5*83 5000

5 * 83 6 * 82 7 * 81 4 * 80

5000 800 70 4

5000 + 800 + 70 + 4

= 5674

A number an an−1...a2 a1 a0 where a0, a1 ... an are all digits in a base b (note that

here, the subscript does not refer to the base number; it refers to different

objects), the number can be represented in any other base, including decimal, by:

Page 41: Programming Fundamentals

Programming Fundamentals Using C# 40

FORMULA - 2

O C T A L A D D I T I O N

This works in same way as that of decimal addition. We will not explain it here but

interested reader can understand the working of binary addition using tables given

in “Decimal Addition” section.

O C T A L T O DE C I M A L C O N V E R S I O N

The formula - 1 given in above section provides the way to convert binary number

into decimal. We see its working using following example:

Octal 5674

5 * 83 6 * 82 7 * 81 4 * 80

2560 384 56 4

2560 + 384 + 56 + 4

= 3004

2.2.4. HEXA-DECIMAL NUMBER SYSTEM Hexa-Decimal number system has sixteen symbols in its set as listed below:

S = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F}

0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < A < B < C < D < E < F

H E X A -DE C I M A L C O U N T I N G

Like decimal number system, counting starts with smallest value digit which is

zero. As counting continues, next higher value symbols are used till it reaches

“F”, the highest value symbol. For next number, we observe that the set is

completely used, we place 1 on left and 0 on right as shown below:

You suppose previous symbols as (consisting of two digits)

0F

Place next greater symbol in place of left digit and smallest value symbol in place of right digit 1 = the set is used one time at ones position

10

Page 42: Programming Fundamentals

Programming Fundamentals Using C# 41

0 = counting at ones position is not started yet

Left 1 = the set is used one time at ones position Right 9 = the counting has reached to 9 at right position

19

Now for next counting, we proceed as before

You suppose smallest value symbol on left most position 0FF

Place next greater symbol in place of left digit and smallest value symbol in place of right digits 1 = the set repetition counting has done one time 0 = set repetition count is not yet started 0 = counting at ones position is not started yet

100

Being positional number system, the value of each digit in a number is determined by its position.

Number 5AEF

Positional Value of F F * 160 F

Positional Value of E E * 161 E0

Positional Value of A A * 162 A00

Positional Value of 5 5 * 163 5000

5 * 163 A * 162 E * 161 F * 160

5000 A00 E0 F

5000 + A00 + E0 + F

= 5AEF

A number an an−1...a2 a1 a0 where a0, a1 ... an are all digits in a base b (note that

here, the subscript does not refer to the base number; it refers to different

objects), the number can be represented in any other base, including decimal, by:

FORMULA - 3

H E X A -DE C I M A L A D D I T I O N

This works in same way as that of decimal addition. We will not explain it here but

interested reader can understand the working of binary addition using tables given

in “Decimal Addition” section.

H E X A -DE C I M A L T O DE C I M A L C O N V E R S I O N

The conversion process is described below:

Hexa-Decimal Number 5AEF

5 * 163 A * 162 E * 161 F * 160

20480 2560 224 15

Page 43: Programming Fundamentals

Programming Fundamentals Using C# 42

20480 + 2560 + 224 + 15

= 23280

DE C I M A L T O HE X A -DE C I M A L C O N V E R S I O N

Following division process shows the conversion of 5AEF into decimal number

system:

Divisor Quotient Remainder

16 23279

16 1454 F

16 90 E

5 A

The resultant number in binary is (5AEF)16.

H E X A -DE C I M A L T O B I N A R Y C O N V E R S I O N

This conversion is very handy and fast. First look at following table:

Hexa-Decimal

0 1 2 3 4 5 6 7 8

Binary 0000 0001 0010 0011 0100 0101 0110 0111 1000

Hexa-Decimal 9 A B C D E F

Binary 1001 1010 1011 1100 1101

1110 1111

Here we see that four binary digits are sufficient to represent one octal digit. In

other words an octal digit can be represented by three binary digits. Using this

procedure we convert the number 5AEF.

So the resultant binary number is (0101 1010 1110 1111)2.

B I N A R Y T O HE X A -DE C I M A L C O N V E R S I O N

It is also very easy to convert a binary number into hexa-decimal using the above

mentioned procedure. The conversion for (0101 1010 1110 1111)2 is shown

below:

Hexa-Decimal 5 A E F

Binary 0101 1010 1110 1111

Page 44: Programming Fundamentals

Programming Fundamentals Using C# 43

Hence the number is octal is (5AEF)16.

H E X A -DE C I M A L T O O C T A L C O N V E R S I O N

As it is stated that in octal three binary digits can represent one octal digit and four

binary digits can represent one hexa-decimal digit. So using this observation we

try to convert a hexa-decimal number into octal. Let the number is (5AEF)16.

So converted number is (055357)8.

O C T A L T O HE X A -DE C I M A L C O N V E R S I O N

For this conversion, we just reverse the above conversion process.

2.3. BINARY NUMBER SYSTEM AND HARDWARE There are many electrical components (devices) that have only two states. For example a

light bulb is either on or off, a capacitor is either charged or discharged, a circuit is either

closed or open. These two states of any component are sufficient to represent two binary

digits 0 and 1. A computer consists of mainly CPU, RAM, ROM and IO Devices. All these

devices are based on tiny electronic devices like capacitor or transistor that have two

states to map 0 and 1 of binary system.

Let we consider the case of capacitor. If there is charge on capacitor, we say 1 is stored

and if there is no charge, we say 0 is stored. Every small component can store one binary

digit which is shortly called bit. A group of 8 bits is known as byte. A collection of 1024

bytes is called a kilo byte and so on.

Binary 0101 1010 1110 1111

Hexa-Decimal 5 A E F

Hexa-Decimal 5 A E F

Binary (4 digit group) 0101 1010 1110 1111

Binary (3 digit group) 0 101 101 011 101 111

Octal 0 5 5 3 5 7

Octal 0 5 5 3 5 7

Binary (3 digit group) 0 101 101 011 101 111

Binary (4 digit group) 0101 1010 1110 1111

Hexa-Decimal 5 A E F

Page 45: Programming Fundamentals

Programming Fundamentals Using C# 44

Figure 2- 1: Bits and Bytes

CPU consists of internal memory that is used for computation and storing intermediate

results. A part of these memory locations is known as Registers. Different CPUs have

different sizes of registers i.e. 8 bit, 16 bit, 32 bit, 64 bit or higher. The size of such register

is also called the word size. Hence we say that word size is register size. The term word or

word size would be used in next chapters.

To store data permanently, a storage – Hard Disk – is used. The surface of hard disk is

coated with magnetic material. There are lot of tiny dots on hard disk surface that could

either be magnetized or demagnetized. Any such tiny dot if magnetized represents 1 and

absence of magnetization represents 0. Data on hard disk is also written in binary form.

2.4. DATA AND DATA TYPES Now that we have learnt how the different number systems works and how numbers are

represented in them, we proceed our discussion to know how different type of data is

stored in computer. We are already familiar with different types of data like numeric data

and text data. Here is the list of different data types:

Numeric Data

Textual Data

Image Data

Voice Data

Video Data

Page 46: Programming Fundamentals

Programming Fundamentals Using C# 45

2.4.1. NUMERIC DATA We represent raw facts in the form of numbers like 4 and 5.9. The numeric data

could further be divided into two categories. Discrete numeric data and

Continuous numeric data.

D I S C R E T E NU M E R I C DA T A

This type of data is used to count or represent such quantities which exist in whole.

For example in a sentence “There are four persons in the room”, there are exactly

four persons neither 4.1 nor 3.9. Because fractional numbers does not make sense.

Similarly “I bought two dozen oranges” represent exact 24 elements.

PO S I T I V E D I S C R E T E DA T A

Discrete numbers could be either positive or negative. Here we discuss how these

numbers could be represented in computer. A one bit could represent two

quantities, two bits represent four quantities, 3-bits represent 8 quantities and so

on. Following tables describe the binary representations:

Quantity Representation

0 0

1 1

Using 3-bits, smallest value to be represented is 0 and highest value is 7. Similarly

using 8-bits, smallest value is 0 (0000 0000) and highest value is 255 (1111

1111). A group of eight tiny electrical components storing eight bits could be

named for referencing purpose. We can imagine such named group of bits as a

“variable”. The bit value combination stored is called the value of variable. At a

time, one value could be stored in a variable. The value stored in variable of n-bits

( an−1...a2 a1 a0 ) is calculated as

∑2𝑖𝑎𝑖

𝑛−1

0

The reader is encouraged to find out decimal equivalents of 16-bit variables and

32-bit variables.

Quantity Representation

0 00

1 01

2 10

3 11

Quantity Representation

0 000

1 001

2 010

3 011

4 100

5 101

6 110

7

111

Page 47: Programming Fundamentals

Programming Fundamentals Using C# 46

N E G A T I V E D I S C R E T E DA T A

The representation of negative numbers is called the sign-magnitude

representation. Before continuing the discussion, we present two more concepts:

1’s complement and 2’s complement.

1’S CO MP LEMENT : By converting any bit from 0 to 1 and 1 to 0, 1’s complement

is achieved. Example is given as follows:

Number 0 1 1 1 0 0 1 0

1’s Complement 1 0 0 0 1 1 0 1

2’S CO MP LEMENT : It is achieved by adding one into 1’s complement.

Number 0 1 1 1 0 0 1 0

1’s Complement 1 0 0 0 1 1 0 1

1’s Complement 1 0 0 0 1 1 0 1

+ 1

2’s Complement 1 0 0 0 1 1 1 0

In sign magnitude representation, left most bit is used to represent the sign of the

number and rest of the bits are used to represent the magnitude. The sign-

magnitude representation is shown as follows with three bits number:

Decimal Value

Binary Representation

Positive Number

0 000

1 001

2 010

3 011

4 100

5 101

7 110

8 111

Page 48: Programming Fundamentals

Programming Fundamentals Using C# 47

In this table of sign magnitude representation, we notice that for “0” value, there

are two representations “-0” and “+0”. If we take any number and find its 1’s

complement, a negative quantity in the list is achieved and vice versa. For example

011 is +3, its 1’s complement is 100 which is negative zero. This ambiguity is

removed using 2’s complement.

Using 2’s complement, the “-0” and “+0” ambiguity is removed. We want to come

up with mechanism that by taking 2’s complement, its negative should be

achieved. To do this, we rearrange the bit patterns as follows:

Decimal Value

Binary Representation

Decimal Value

Binary Representation

Positive Number Sign-Magnitude (left most bit 0 mean + ) (left most bit 1 mean - )

0 000 +0 0 00

1 001 +1 0 01

2 010 +2 0 10

3 011 +3 0 11

4 100 -0 1 00

5 101 -1 1 01

7 110 -2 1 10

8 111 -3 1 11

Decimal Value

Binary Representation

Decimal Value

Binary Representation

Decimal Value

Binary Representation

Positive Number Sign-Magnitude 1’s Complement

(left most bit 0 mean + ) (left most bit 1 mean - )

Sign-Magnitude 2’s Complement

(left most bit 0 mean + ) (left most bit 1 mean - )

0 000 +0 0 00 0 0 00

1 001 +1 0 01 1 0 01

2 010 +2 0 10 2 0 10

3 011 +3 0 11 3 0 11

4 100 -0 1 00 -1 1 00

5 101 -1 1 01 -2 1 01

7 110 -2 1 10 -3 1 10

8 111 -3 1 11 -4 1 11

Sign

bit

Sign

bit

Page 49: Programming Fundamentals

Programming Fundamentals Using C# 48

Now for any number, if we take its 2’s complement, its negative representation is

achieved and vice versa. For example, if we take 010 and take its 1’s complement

we get 101 and by adding 1, 2’s complement is achieved which is 110. 010 is +2

and 110 is -2.

For 3-bit positive number representation, smallest value is 0 and largest value is 7.

This range of numbers could be represented as 0 – 2n-1 (0 --- 8-1). Different

representations are shown below:

Positive numbers

Decimal Range Formula Range

3-bit representation 0 to 7 0 to 23-1

n-bit representation - 0 to 2n-1

Sign Magnitude numbers

Decimal Range Formula Range

3-bit representation -4 to 3 -23-1 to +23-1-1

n-bit representation - -2n-1 to +2n-1-1

Using these formulas for 16-bit word

Sign Magnitude numbers

Decimal Range Formula Range

Magnitude only 0 to 65535 0 to +216-1

Sign-Magnitude -32768 to +32767 -216-1 to +216-1-1

Decimal Value

Binary Repr. Decimal Value

Binary Repr. Decimal Value

Binary Repr.

Sign-Magnitude 1’s Complement

(left most bit 0 mean + ) (left most bit 1 mean - )

Sign-Magnitude 2’s Complement

(left most bit 0 mean + ) (left most bit 1 mean - )

Sign-Magnitude 2’s Complement

(left most bit 0 mean + ) (left most bit 1 mean - )

New Arrangement

+0 000 0 000 +0 000

+1 001 1 001 +1 001

+2 010 2 010 +2 010

+3 011 3 011 +3 011

-0 100 -1 100 -4 100

-1 101 -2 101 -3 101

-2 110 -3 110 -2 110

-3 111 -4 111 -1 111

Page 50: Programming Fundamentals

Programming Fundamentals Using C# 49

As an exercise the user should try to find the ranges for 32 bit word and 64 bit

word.

C O N T I N U O U S NU M E R I C D A T A

There are various quantities that does not exist in exact form like distance, amount

of water, temperature and speed. To represent these quantities, we need

continuous numbers like 3.4567. The representation of this type of data in

computers is complex and out of this book scope.

2.4.2. TEXT DATA As we have seen above, computer can only handle the numeric data. How the text

data is represented in computer? Computer monitor screen or LCD display could

be considered as matrix of dots called picture elements and pixels in short. The

number of horizontal pixels and vertical pixels makeup the screen size called

resolution. 800 X 600 is very basic resolution in which on monitor screen there are

horizontally 800 pixels are and 600 pixels vertically. Computer can separately

access each pixel and color is as required by the screen management software. By

coloring different pixels on the screen, a picture or image could be formed.

ASCII C O D E S

Considering the English language, each letter of English is considered an image.

The computer engineers have compiled a list of letter or characters that is around

256. These images are numbered from 0 to 255. Following the above discussion

about numeric data, we know that 8-bits could be sufficient to number each such

letter or shape. This list of images contains:

In this list every character is given a number that is called the code. The list is titled as American Standard Code for Information Interchange (ASCII). Below is a short list from ASCII table.

Character Types Characters

Numeric letters 0, 1,2,3,4,5,6,7,8,9

Alphabets A,B,C,….,Z a,b,c,….,z

Special Symbols ~, !, @,#,$,%,

Arithmetic Signs +, -, *, /

Punctuation symbols , . ? ( ) [ ]

Control characters

Page 51: Programming Fundamentals

Programming Fundamentals Using C# 50

Complete ASCII table is given in Appendix-A. A user normally uses keyboard to

enter text data into the computer. As the user presses a key, its corresponding

code is sent to the processor according to ASCII chart. The computer displays the

corresponding shape on the screen. If text data is to be written on the hard drive,

ASCII code for each character is written separately. To display the data on screen

from saved file, ASCII codes are read and their corresponding shapes are displayed.

In this way computer manages the text.

C O D E PA G E S

Although the computers were started in English speaking countries but with the

passage of time, it become the requirement to incorporate alphabets of other

languages like Urdu, Punjabi and Seraiki. To use characters of other languages, it

was attempted to replace ASCII with other language characters by redefining the

shapes for same codes. For example, “b” has code 98 in ASCII table, by redefining

shape “ب” could be placed on code 98. This change of mappings are called the

code pages. A code page could be visualized as:

Code (in Decimal)

English Characters

Urdu Characters

… … …

67 A ا 88 B ب 89 C پ … … …

There are hundreds of such code pages in use. A popular code is ASCII. A "code

page" usually means a byte oriented encoding, but with regard to some suite of

encodings (covering different scripts), where many characters share the same

codes in most or all those code pages.

UN I V E R S A L C O D E

What to do when a user need to write in two or more languages simultaneously.

For this ASCII table was insufficient and effort was made by two companies Xerox

and Apple to formulate a universal character set that contains characters of

different languages in 1988. Since then the Unicode set has been reviewed many

Shape/Character Code

0 0011 0000

1 0011 0001

… …

A 0100 0001

B 0100 0010

…. …

Mapping Two

Mapping

One

Page 52: Programming Fundamentals

Programming Fundamentals Using C# 51

a times. Each revision is referred as Unicode standard revision. In start instead of

8-bit ASCII encoding, 16-bit encoding was proposed. Using this 16-bit encoding,

the list can contain 65536 characters which found to be sufficient to represent all

world languages. In 1991, Unicode consortium published its first Unicode

standard.

First version of Unicode was developed to incorporate characters of existing live

languages but later on it become the requirement to incorporate letter of old dead

languages, other special characters of composite shapes like “هللا”. To handle

these extra characters, wider range of codes are used. The new list can contain 0-

1,114,111 characters. Using hexa-decimal notation this count is 10ffff. We use

0x10ffff (21-bits) to make sure that it is hexadecimal notation. A code of

character in hexa-decimal is called the Code Point. A small list showing some code

points is given below:

The code points and characters are not tightly bound with each other. In Unicode

specified code point may have different character at different times. The graphical

shape of a character is called it glyph. For example glyph for first character of

English alphabet is “A”, for second alphabet of Urdu is “۔”ب A character may have

different glyphs i.e. “A” could be written like A, A, A or A. To find out which

character or glyph is represented at a time by a code point, we use some rules

known as “Encoding”. UTF-8 ISO-8859-1, and UTF-16 are few of such encodings.

Encodings don’t have to handle every possible Unicode character, and most

encodings don’t. For example, if there are only 258 characters in a particular

language, UTF-8 encoding is sufficient (UTF-8 uses 8-bits for character code point)

whereas if the language has more than 256 characters then UTF-8 encoding is

insufficient, hence UTF-16 becomes feasible. To clear the discussion, we describe

UTF-8 encoding as example:

UTF-8 is one of the most commonly used encoding. UTF stands for “Unicode

Transformation Format”, and the ‘8’ means that 8-bit numbers are used in the

encoding. UTF-8 uses the following rules:

1. If the code point is < 128, it’s represented by the corresponding byte value.

2. If the code point is between 128 and 0x7ff, it’s turned into two byte values between 128 and 255.

Shape Decimal Code Point

A 65 0041

a 97 0061

… … …

Page 53: Programming Fundamentals

Programming Fundamentals Using C# 52

3. Code points > 0x7ff are turned into three- or four-byte sequences, where each byte of the sequence is between 128 and 255.

UTF-8 has several convenient properties: 1. It can handle any Unicode code point. 2. A string of ASCII text is also valid UTF-8 text. 3. UTF-8 is fairly compact; the majority of code points are turned into two

bytes, and values less than 128 occupy only a single byte. There are three Unicode encodings:

UTF-8

UTF-16

UTF-32

2.4.3. IMAGE DATA There are different ways to represent an image as binary data. Here we discuss its

simplest form called the bitmap image. As stated above, the computer monitor of

any display device screen is composed of matrix of pixels. A pixel is smallest point

on the screen used to display picture or image. These are arranged horizontally

and vertically. Figure 2- 2: Screen Pixels shows the pixel arrangement on screen.

Figure 2- 2: Screen Pixels

Every pixel could be addressed separately. In monochrome display, each pixel

could be given either black or white color. By using a proper combination of black

and white pixels, a picture could be constructed.

Page 54: Programming Fundamentals

Programming Fundamentals Using C# 53

Figure 2- 3: Monochrome Display

If we use, 1 bit to represent color of each pixels and there are say 800 horizontal

pixels and 600 vertical pixels (Resolution = 800 X 600) then we need 4, 80,000 bits

or 60,000 bytes to store this image. The summary is that numbers or binary data

is used to store image.

Now we discuss the representation of color image. Using a common coloring

scheme, three colors could be used to form any color. These are red, green and

blue. And there could be 256 different levels of each color. Each color could be

represented one byte hence 3 bytes for three colors. The color of each pixel on the

screen is made by the combination of each color. Red, Green and Blue make up

the color of one pixel. As a result R+G+B=8-bit+8-bit+8-bit=24-bit are used to

represent the color of one pixel. Using above mentioned resolution (800 X 600) we

need 24*800*600 bits for a full screen image. Again numbers are used to store

image.

Page 55: Programming Fundamentals

Programming Fundamentals Using C# 54

Figure 2- 4: Color Display

2.4.4. SOUND DATA Sound data is also represented in binary form in computer. The description of this

representation is complex and beyond the scope of this book.

2.4.5. VIDEO DATA A video is collection of image and sound data. Both image and sounds could be

represented in binary form hence video could also be represented in binary form.

The discussion is beyond the scope of book.

2.5. DATA AND DATA TYPES – REVISITED As we have seen that there are different types of data referred as data types. A data is a

constant like 4, 5, “Multan” etc. or it could be referred by a variable like City. City could

take the name of any city i.e. Lahore, Karachi. Constant data could not be changed whereas

variable could be changed. We may have numeric constants, text constants, image

constants and numeric variables, text variables and image variables. It is to note that a

variable is a name that points to some constant. In other words, a variable is like a

container that can contain a constant. At one time, one constant is placed in it whereas at

other time, some other constant is placed in it. A variable can contain one data item at a

time.

Data Variable Variable Containing Data

Figure 2- 5: Data and Variable

Page 56: Programming Fundamentals

Programming Fundamentals Using C# 55

Chapter 3

The Program Main task of computer is to transform data from one form to another. This

transformation is performed according to some user defined rules known as

directions or instructions. A set of instructions written to perform some specific task

is called the “Program”.

A program is like a recipe. It contains a list of ingredients (constants and variables) and

a list of directions (instructions) that tell the computer what to do with the

ingredients. These ingredients may be of type numeric, text or graphical images. The

statements/instructions could be written in different ways. In this chapter, we will

discuss visualization and representation of real world ideas and will attempt to

understand the program writing process.

3.1. ABSTRACTION An abstraction could be considered as conceptual view of some real idea, person or thing.

It is a conceptual process in which we extract the rules, ideas and concepts from specific

instance of those ideas at work. For example, if someone has not seen computer, you

attempt to describe it with the help of its features and functions. This hypothetical, verbal

or written description is known as AB S T R A C T I O N . It is to note that you do not and cannot

tell each and every detail of computer in order to make listener understand the thing. Only

major features or features which are understandable to the listener are described. Further,

you describe computer differently to different listeners. Hence abstraction captures only

those details about an object that are relevant to the current perspective.

A programmer has to write code about real world things. They use abstraction to represent

entities and things in code. For example, if a software engineer is writing software for some

sale purchase system, she will model the “customers” and “products” etc. How these

things are represented in software is based on abstraction. One software engineer may

keep X number of features about “product” whereas other will handle Y number of

features. In short abstraction in programming refers to representation of real or

conceptual things in software. In software engineering, word “Abstraction” is used in dual

context. First context is to represent concepts, ideas and things in code. Second context of

“abstraction” is use of abstract language constructs to define and implement abstract type

of code. This section refers to first context only.

Page 57: Programming Fundamentals

Programming Fundamentals Using C# 56

3.2. WAYS OF WRITING INSTRUCTIONS A language is described by set of rules collectively known as grammar. During our

communication with each other, either we follow these rules or we ignore. The level to

which we obey the grammar in communication varies from person to person. With friends

we may totally ignore grammatical rules but in official communication rule following

becomes essential. We show similar behavior in our writings. Let we call every sentence

written by us as instruction then there are three ways of writing instructions:

Informal Way

Semi-Formal Way

Formal Way

IN F O R M A L WA Y

An informal way is expressing something (in writing or speaking) without following

grammar rules. For example, in sentence, “Hay wats up dude” the speaker has not

followed any grammatical or spelling rule. But important is that the speaker is successful

to convey the meaning of his words. In this type of communication, speaker and intended

listener already know about the exact meaning and context of what is being

communicated. In our daily life, we mostly use informal way of communication when

interacting with friends, speaking or chatting online. As another example look at following

sentence:

Correct Way Informal Way

Have you finished your work? work finished

“work finished” is question asked by a friend from another. This sentence does not

describe, who finished the work, whether it is question, information or announcement and

whose work is finished? Instructions written in informal way are ambiguous, incomplete

and misleading. Therefore in computer science, such instructions are useless.

S E M I-F O R M A L WA Y

In this way of communication, the speaker follows some grammar rules but the

communication is not exactly based on rules. We use semi-formal way for day-to-day

interaction with colleagues, teachers, and people we respect. Semi-formal way of

communication is used when we want to convey ideas and instructions to someone who

already has somewhat knowledge about the matter of communication.

F O R M A L W A Y

In formal way of communication, the speaker or writer follows all the rules defined in

grammar. Spellings, punctuation, proper grammar, and correct sentence structure are very

important. We use this way when communicating officially or with persons who are not

known to us.

Page 58: Programming Fundamentals

Programming Fundamentals Using C# 57

A computer is a machine that works with well-defined instructions, hence we need

F O R M A L W A Y to communicate or provide instructions to the computer. Like spoken and

written languages, grammars are also defined for computer languages. Instructions

written in computer languages follow grammar rules completely. The way of writing

instructions following language grammar is called the S Y N T A X . The meaning of each

grammar rule is called the S E M A N T I C S .

3.3. THE ALGORITHM Mathematics is a formal way of teaching and learning. It is interdisciplinary language and

tool. It is considered one of the "basics" in our formal educational system. Computer

science could be considered as systematic study of feasibility, structure, representation

and automation of mathematical procedures (algorithms). Famous computer scientist

Donald E. Knuth defines C O M P U T E R S C I E N C E as “study of algorithms”. This definition

describes computer science as branch of mathematics. What is an algorithm? DE Knuth

defines it as:

An algorithm is precisely defined sequence of rules telling how to produce

specified output information from given input information in finite

number of steps.

A particular representation of an algorithm is called the “P R O G R A M ”. Algorithm does not

have a generally accepted formal definition. Here are few more definitions:

1. "A set of rules that precisely defines a sequence of operations to solve

particular problem”.

2. “An unambiguous (and precise) set of steps for solving a problem in a finite

amount of time using finite amount of data”.

EX A M P L E O F AL G O R I T H M

PR O B L E M : How to find largest number among a group of n numbers.

AL G O R I T H M :

Let we have a list of 10 items {5, 4, 8, 7, 6, 3, 9, 11, 2, 1}. Let L1=5

Step 1: Let Largest = L1

Step 2: For each item in the list:

Step 3: If the item > Largest:

Step 4: Then Largest = the item

Step 5: Return Largest

PR O P E R T I E S O F AL G O R I T H M

An algorithm must possess the following properties:

Page 59: Programming Fundamentals

Programming Fundamentals Using C# 58

S I M P L I C I T Y : There should be no un-necessary step and no un-necessary

complexity. Algorithm should contain to the point steps which are easily

understandable and solvable. Each step must perform one logical step.

C O M P L E T E N E S S : The algorithm must complete the task for which it is

designed.

F I N I T E N E S S : Algorithm must always terminate after finite number of

steps.

C O R R E C T NE S S : Algorithm must be correct and every time it is used, it

produces correct results.

PR E C I S E : Each step (or instruction) must lead to one meaning only. The

words like “may be”, “could be” should not be used.

SY M B O L I C : An algorithm should be written in semi-formal way where

different symbols are used to represent different components of

algorithm.

IN P U T : An algorithm must take some data as input.

OU T P U T : An algorithm must produce some output.

S T E P S T O DE S I G N T H E A L G O R I T H M

Designing an algorithm for given problem is heart of problem solution. There may be

multiple solutions for a problem. Each one is called the feasible algorithm. However there

would be one algorithm among all that takes minimum resources i.e. time, computational

effort and memory. Such an algorithm is known as optimal algorithm. Computer science

defines a systemized way to measure the efficiency of algorithm. Measuring algorithm

efficiency is beyond the scope of this book so we leave it.

Designing an efficient and better algorithm needs lot of practice, deep problem analysis

and sufficient knowledge of computer language features. However by following below

listed steps you can come up with sound algorithm:

UN D E R S T A N D T H E P R O B L E M : Before you start writing the algorithm, spend

enough time to under the problem. Every small detail must be clear to you. It

is equally important to understand the intended audience.

DE V I S E A PL A N : Think possible solutions of the problem. Ask few questions

from yourself like

o Have I already solved a similar problem?

o What ingredients do I need to solve this problem?

o Who needs this solution?

o What are the required steps?

C A R R Y O U T T H E PL A N : Implement your devised plan. This implementation

could be theoretically, physically or mathematically. See that does it work? Is

each step correct?

Page 60: Programming Fundamentals

Programming Fundamentals Using C# 59

S O L U T I O N A C C U R A C Y : And finally see that devised and implemented

algorithm produces the intended results? Will it always produce the required

r e s u l t s ?

AL G O R I T H M RE P R E S E N T A T I O N

An algorithm could be expressed in following different ways:

IN F O R M A L WA Y : Using natural language you can write the algorithm. For

example, you can describe our example algorithm using language of your

choice. If you are four friends and everyone is asked to describe the solution

of above mentioned problem, everyone will come up with his own solution.

This solution will be verbose and ambiguous.

F L O W C H A R T S : You can express your algorithm using graphical notations and

flow of control. It removes most of the problems presented when using

informal way. This expression of algorithm is difficult to modify and consumes

lot of space.

PS E U D O -C O D E : It is better representation than above mentioned both ways.

Pseudo code means statements written in the form that looks like actual

program code where we only care about eliminating ambiguity. It uses

mathematical notations to represent the steps but still it allows designers to

incorporate their own terms and symbols. Hence this method is considered as

semi-formal way.

PR O G R A M M I N G L A N G U A G E : This is fully formal way of representing the

algorithm where no ambiguity lies. It is bit complex and contains somewhat

unwanted details (i.e. variable declarations) however is very useful from

computer perspective.

From this discussion, it should be clear that the programmer (you) need to understand the

problem and know the steps required to solve the problem. If you have grip on these two

issues, programming becomes a problem of translation only (semi-formal to formal). We

repeat that most of the students find programming difficult but in fact difficulty lies

in algorithm design. One could be good algorithm designer only with practice. There is

no shortcut for it.

Considering our example algorithm, we present its different representations here:

Informal Rep resentation :

Find largest among group of these ten numbers: {5, 4, 8, 7, 6, 3, 9, 11, 2,

1}. Pick a number and consider it maximum. Take every other number of

list and if that is greater than your chosen number, make it your number.

AT the end, your chosen number is the largest

Page 61: Programming Fundamentals

Programming Fundamentals Using C# 60

Flow Ch art :

PS E U D O C O D E

Input numbers: sequence of numbers and count: is count of numbers in sequence

Output large (the largest number in sequence)

1. Max(numbers,count)

2. Large=numbers[1]

3. For i=2 to count

4. If(large < numbers[i])

5. Large=numbers[i]

6. Return large

No

Yes

Start

Let count=1 Numbers={5, 4, 8, 7, 6, 3, 9, 11, 2, 1}

Let Largest=numbers[count]

count<10 ?

Largest <

numbers[coun

t]

Largest=numbers[count]

Count=count+1

Yes

No

Result is “Largest”

End

Figure 3- 1: Flow Chart Representation

Page 62: Programming Fundamentals

Programming Fundamentals Using C# 61

Use of Algorithm: numbers = {5, 4, 8, 7, 6, 3, 9, 11, 2, 1} count=10

C O M P U T E R PR O G R A M

Program: FindMaximum using System; namespace FindMaximum { class Program { static void Main(string[] args) { int[] numbers = new int[] { 5, 4, 8, 7, 6, 3, 9, 11, 2, 1 }; int count = 10; int large = Max(numbers, count); Console.Out.WriteLine(large); Console.Read(); } static int Max(int[] numbers, int count) { int large=numbers[0]; for (int i = 1; i < count; i++) if (large < numbers[i]) large = numbers[i]; return large; } } }

PR O G R A M M I N G RE V I S I T E D

After above discussion, we can understand that computer programming is the process of

translating problem solution from informal to semi-formal and then to formal

representation. If you omit the second step, translation to semi-formal, you will be

spending lot of time on writing and correcting the formal representation. To be a good

programmer, one should spend enough amount of time to find second step

representation.

3.4. TURING MACHINE A Turing machine (TM) is a hypothetical device that represent the working model of

computer. It gets data as input and changes it according to the rules (instructions) written

into it. The rules are also referred as TM states. Turing machine can be adapted to simulate

the logic of any computer algorithm, and is particularly useful in explaining the functions

of a CPU inside a computer. The data provided to TM is called the input symbols. This data

is provided through a tape on which it is written. The machine reads a symbol at a time

and changes it according to rules built into it. After changing, it writes the results (output)

Page 63: Programming Fundamentals

Programming Fundamentals Using C# 62

on another tape which is called the output tape. Input tape could also be used as output

tape. In this case TM reads a symbol from it, changes it according to built-in rules and rights

it back on same tape. Figure 3- 2: Turing Machine, shows single tape view:

Turing machines helps computer scientists to understand the working and limits of

electrical computation.

3.5. DATA, INSTRUCTIONS AND INSTRUCTION EXECUTION We have completed our discussion about data and instruction. Now we see how are these

inter-related and how do they work. Instructions are used to manipulate data. Every

instruction written in any form (formal, semi-formal or informal) are intended to work with

data of specific type. For example 3+5 is an instruction to add two constants. Considering

the programming languages, there are different types of instructions. Few of them are

listed below:

Instructions serve as the way to transform data into required information. For example, a

teacher asks a student to enlist the names of all students enrolled in the class by

alphabetical order. A student will do this job by consuming considerable amount of time

whereas the computer will do this task rapidly.

Instruction Type Description

Input instructions Used to input data from user

Output instructions Use to show data to user

Arithmetic instructions Used to perform arithmetic operations

Repetition instructions Used to repeat other instructions

Decision instructions Used to make decision based on some specified criteria

Meta instructions Used to describe other instructions

Code management instructions

Used to manage code for better readability etc.

… ….

1 0 1 1 0 0 1 0 . . . one of

. . . one of

Program

Input / Output Tape

Figure 3- 2: Turing Machine

Page 64: Programming Fundamentals

Programming Fundamentals Using C# 63

3.6. STAGES IN SOFTWARE DEVELOPMENT A program normally refers to small scale software whereas software system refers to a

large and complex software. Writing a software is complex and time consuming job. It may

require many people as an integrated software development team to perform the difficult

task in well managed and organized way. Every team member of software development

team possess different type of skills to aid rest of the members to build final solution.

Every stage of software engineering produces some documents to help next stage team.

Documentation refers to collection of documents related to software produced during all

software engineering stages. The team members and stages of software creation may

differ to some extent from project to project but following stages are almost present in

every software development process.

S Y S T E M AN A L Y S I S

System Analysis involves the understanding of the system which is required to be

built. In this understanding process, information and requirements about the

manual or already existing process is gathered. Such information may include data

about people interacting with existing system, rules which are followed,

constraints which need to be considered during task execution and system

feasibility etc. For example if you want to build a software for accounting

department of a company, the person doing system analysis, called the system

analyst, need to understand all type of accounts, ledger entries, rules under which

cache flow occurs, who are allowed to make transactions etc. This analysis task is

normally done by meeting with people working in that system, studying their

paper based records, transaction documents and reports produced for higher

administration etc. The documents produced as result of this phase are normally

written in English language (informal or semi-formal way).

S Y S T E M DE S I G N

Once all required information are collected by interacting with existing system, the

requirements are finalized. Redundant data and requirements are removed.

Feasible and valid requirements are kept and vague or infeasible requirements are

filtered out.

The finalized requirement document known as software requirement

specifications are then again studies and a software design is obtained. Software

team members creating software design are called the system designers or system

architects. During software design process, the requirements are presented in

computer implementable form. There are different tools and techniques which are

used to represent different perspectives of software. Such tools may include Entity

Relationship diagram, Use-case diagrams, class diagrams etc.

Page 65: Programming Fundamentals

Programming Fundamentals Using C# 64

Various algorithms and flow diagrams to solve the complex processes are also

designed in this phase. This is very critical step and success of software is based on

the solidity of design.

Although there are many rules facilitating the correct analysis and planning, a fair

amount of intuition and insight is required at this stage. This step predetermines

the further advancement of the development process. There is no programming

done at this stage, but only preparation. The documents produced in this phase

are written in semi-formal language.

S Y S T E M IM P L E M E N T A T I ON

The design made by system architects are then translated into computer

understandable form using language of choice. This task is done by a person called

the programmer. It is repeated again that if design is flawless, translation process

is very simple and does not require too much expertise from programmer. We can

define this step as “translation of semi-formal solution into formal solution”. The

documents produced at the end of this phase are called the source code.

S Y S T E M TE S T I N G

The developed system is never flawless because it is developed by humans. The

software testing team starts testing software with the philosophy that there are

flaws in software. Software test team is called the Quality Assurance team. It tries

to find out whether the design provided by system architects is properly

implemented (translated) into machine language. There are two major ways to

perform this task. Ultimate objective of software is to transform data into

information. In first way of testing the data is passed through the software and it

is observed that whether it is properly transformed into information or not. In

second way of testing, each software part is read and understood whether the

algorithms are properly written into instructions or are any shortcut. Many defects

and errors are usually found during the testing stage and the program is sent back

to the implementation stage. These two stages are very closely tied and it is

common for a software product to switch between them many times before it

covers all the requirements and is ready for the deployment.

DE P L O Y M E N T

The developed and tested software is finally delivered to the customer for which

it is developed. The process of installing the software on customer site, configuring

it there and bringing it into operational form as per requirements is called the

system deployment. If the system supports multiple users then tasks like user

management, user rights management, user communication and interaction

management, required network establishment and system operational schedule

management are considered the deployment process.

Page 66: Programming Fundamentals

Programming Fundamentals Using C# 65

S Y S T E M S U P P O R T

A developed system never fulfills complete requirements of the customer. After

using the software for some time, the customer may require new features to be

built into the system or may require the modification of existing features. There

may be flaws in finally deployed system. Removal and fixing of such flaws is the

part of system supports.

3.7. SYSTEM FLAWS All tasks carried by humans are prone to error. All phases of software development

(software engineering) may contain flaws, missing or ambiguities. Flaws at each stage is

given a different name.

M I S S I N G RE Q U I R E M E N T

If system analysis team fails to document or understand some feature or process

of system under consideration, the software design team will eventually miss the

related features resulting in missing feature design.

S Y S T E M BU G S

If the software design team, creates some error in software design or writes the

algorithm which does not meet all above mentioned requirements, it may produce

correct output for some input whereas may produce wrong results for other input.

These type of errors are called the system bugs.

S Y S T E M ER R O R S

These type of errors and mistakes are introduced by programmers. Such type of

errors are categorized as syntax errors and semantics errors. SYNTA X ERROR S

refer to mistakes caused by programmer due to not following proper language

rules. For example to declare a variable in a language, the way is “ int

myvariable”, the programmer writes “intmyvariable” (inner space is missed).

SE MAN TI CS ERROR S refer to inappropriate use of statement in required context.

For example a variable of one data type assigned to different data type variable.

Semantics errors are also referred as bugs.

E R R O R RE M O V A L

An error could be either vital or non-vital. This severity level is more if introduced

in early stages and less sever if introduced in later stages. All syntax errors and

most of the semantic errors are indicated by the compiler and removed during

program compilation phase. The bugs are hard to identify so humans are deployed

to find out them. There are two automated ways to control and find out bugs.

Languages themselves provide a way to find bug and properly treat it. There are

specialized type of software provided in IDE to find and remove the bugs called

the debugger.

Page 67: Programming Fundamentals

Programming Fundamentals Using C# 66

Chapter 4

Introduction to Dot NET

FRAMEWORK At Microsoft Windows platform, Dot NET is popular development framework. What is

this and how it is related to programming? Before answering this questions, let us

understand few concepts:

As we have seen in previous chapter, every programming language comes with some

built-in libraries and other relevant programming resources, and there are lots of

languages for developing software. Sometimes the vendors and compiler writers write

their library codes or application codes in such a way that one code component

interacts with other code component and second one interacts with hardware etc.

This way of coding is known as layering. A framework is a big collection of inter-

related library files managed in the form of layers to facilitate the programming task.

The user can write code to use or enhance the library code functionality which fulfills

the user requirements. This leads to the creation of application specific software. A

platform is either hardware, software or combination of both for which software is

developed. Dot NET is framework that operates on Microsoft Windows operating

system. Hence MS Windows could be considered as Dot NET platform.

4.1. WHAT IS DOT NET FRAMEWORK Microsoft Dot NET Framework is a complex technology that provides the infrastructure for

building, running, and managing applications. The Dot NET Framework is a layer positioned

between the Microsoft Windows operating system and your applications developed using

any Dot NET language. Dot NET is a platform but also is defined as a technology because it

is composed of several parts such as libraries, executable tools, and relationships that

integrate with the operating system. Microsoft Dot NET framework support various

languages i.e. C#, VB Dot NET and F#. At present the framework only operates on MS

Windows however Microsoft intends to open source Dot NET core and Microsoft with Dot

NET 2015 is extending it to run on Mac OS platforms and Linux.

There are many versions of Dot NET framework. Every new version brings some

improvements in previous version. At the time of writing Dot NET Framework 4.5 is

available. Microsoft Visual Studio 2010 relies on the new version of the Dot NET

Page 68: Programming Fundamentals

Programming Fundamentals Using C# 67

Framework 4.0. Visual Basic 2010, C# 4.0, and F# 2010 are Dot NET languages that rely on

and can build applications for the Dot NET Framework 4.0.

4.2. WHERE IS THE DOT NET FRAMEWORK When you install Microsoft Visual Studio 2010, the setup process installs the Dot NET

Framework 4.0. Dot NET is installed to a folder named

%windir%\Microsoft .NET\Framework\4.0.

If you open this folder with Windows Explorer, you see a lot of subfolders, libraries, and

executable tools. Most of the DLL libraries constitute the Base Class Library, whereas most

of the executable tools are invoked by Visual Studio 2010 to perform different kinds of

tasks, even if they can also be invoked from the command line. The language compilers

and interpreters reside in this language. Figure 4- 1: Location of .NET Framework, is the

snapshot of my system windows explorer showing the installed Dot NET Frameworks.

Figure 4- 1: Location of .NET Framework

4.3. WHAT CAN WE DO WITH DOT NET FRAMEWORK Dot NET is collection of different programming technologies that can work together to

solve your business problems and other different application specific tasks. A large list of

languages are supported by Dot NET. All languages are based on Common Language

Infrastructure (CLI). Below is the list of languages and technologies present in Dot NET

Framework. The list is provided for reader to appreciate Dot NET framework:

1. A# : CLI implementation of Ada.

2. BO O : A statically typed CLI language, inspired by Python.

3. C# : Most widely used CLI language, bearing similarities to Java, Object Pascal (Delphi) and C++.

4. C++/CL I : A version of C++ including extensions for using Common Language Runtime (CLR) objects. Implementation provided only by Dot NET Framework. Can produce either CLI-based managed code or mixed-mode code that mixes managed and native code. The compiler is provided by Microsoft.

Page 69: Programming Fundamentals

Programming Fundamentals Using C# 68

5. C O B R A : A CLI language supporting different features like static and dynamic typing (related to data types), design by contract and built-in unit testing.

6. C O M P O N E N T PA S C A L : A CLI-compliant Oberon dialect. It is a strongly typed language in the heritage of Pascal and Modula-2 but with powerful object-oriented extensions.

7. E I F F E L : Purely object-oriented language, focused on software quality, includes integrated design by contract and multiple inheritance and is CLI compliant.

8. F# : A multi-paradigm CLI language supporting functional programming and imperative object-oriented programming disciplines.

9. IR O N PY T H O N : An open-source CLI implementation of Python, built on the Dynamic Language Runtime (DLR).

10. IR O N RU B Y : An open-source CLI implementation of Ruby, built on the Dynamic Language Runtime (DLR).

11. IR O N L I S P : A CLI implementation of Lisp. Deprecated in favor of Iron Scheme.

12. J# : A CLI-compliant implementation of Java. The compiler is provided by Microsoft. J# has been discontinued. The last version shipped with Visual Studio 2005, and will be supported until 2015.

13. JS C R I P T DO T NET : A CLI implementation of ECMAScript version 3, compatible with JScript. Contains extensions for static typing. Deprecated in favor of Managed JScript.

14. L# : A CLI implementation of Lisp.

15. MA N A G E D E X T E N S I O N S F O R C ++ : A version of C++ targeting the Common Language Runtime (CLR). Deprecated in favor of C++/CLI.

16. MA N A G E D JS C R I P T : A CLI implementation of JScript built on the Dynamic Language Runtime (DLR). Conforms to ECMAScript version 3.

17. NE M E R L E : A multi-paradigm language similar to C#, OCaml and Lisp.

18. O X Y G E N E : An Object Pascal-based CLI language.

19. P# : A CLI implementation of Prolog. 20. PH A L A N G E R : An implementation of PHP with extensions for ASPDot NET. 21. PH R O G R A M : A custom CLI language for beginners and intermediate users

produced by The Phrogram Company 22. PO W E R BU I L D E R : Can target CLI since version 11.1. 23. S Y N E R G Y DBL DO T NET : An object oriented CLI compliant implementation

of DBL and DIBOL produced by Synergex 24. TE A M DE V E L O P E R : SQLWindows Application Language (SAL) since Team

Developer 6.0.

25. VIS UAL BA S I C DO T NET (VBDO T NET) : A redesigned dialect of Visual Basic. Implementations provided by Dot NET Framework

26. W I N D O W S PO W E ` RS H E L L : An object-oriented command-line shell. PowerShell can dynamically load Dot NET assemblies written in any CLI language. PowerShell itself uses a unique scripting syntax and uses curly-braces, similar to other C-based languages.

27. And various others.

Page 70: Programming Fundamentals

Programming Fundamentals Using C# 69

4.3.1. WHAT TYPE OF APPLICATIONS CAN WE DEVELOP? When you hear the name Dot NET, it gives a feeling that it is something to do only

with the Internet or networked applications. Even though it is true that Dot NET

provides solid foundation for developing such applications, it is also possible to

create many other types of applications. Following list will give you an idea about

various types of application that we can develop on Dot NET.

ASP DO T NE T WE B A P P L I C A T I O N S: These include dynamic and data

driven browser based applications.

W I N D O W S F O R M B A S E D A P P L I C A T I O N S : These refer to traditional rich

client applications.

C O N S O L E A P P L I C A T I O N S : Traditional command line based application

could also be developed with Dot NET.

C O M P O N E N T L I B R A R IE S : This refers to components that typically

encapsulate some business logic.

W I N D O W S C U S T O M C O N T R O L S : As with traditional ActiveX controls, you

can develop your own windows controls.

WE B C U S T O M C O N T R O L S : The concept of custom controls can be

extended to web applications allowing code reuse and modularization.

WE B S E R V I C E S : They are “web callables”. The functionality is available via

industry standards like HTTP, XML and SOAP.

W I N D O W S SE R V I C E S : They refer to applications that run as services in the

background. They can be configured to start automatically when the

system boots up. Dot NET is not just for creating web application but for

almost all kinds of applications that you find under Windows.

Microsoft also provides a cut down version of Dot NET framework called Dot NET

Compact Framework for MO B I L E A N D E M BE D D E D A P P L I C A T I O N S D E V E L O P M E N T .

Dot NET Compact Framework is hardware independent. Microsoft also provides

feature rich Integrated Development Environment (IDE) for mobile apps and

embedded applications development.

4.3.2. PLATFORMS SUPPORTED BY DOT NET Dot NET is set of technologies that supports multiple platforms. At present, only

windows and its variants are supported. However in future, Microsoft intends to

make framework available for non-Microsoft platforms. These platforms include:

W I N D O W S DE S K T O P : Windows Presentation Foundation (WPF) is new set

of libraries for developing visually amazing windows client applications.

Using WPF, browser based and standalone applications can be developed.

Page 71: Programming Fundamentals

Programming Fundamentals Using C# 70

W I N D O W S RT DE V I C E S A N D W I N D O W S ST O R E A P P S : Windows runtime is

library that provides graphical user interface elements to build windows

store apps and provide access to operating system features.

W I N D O W S P H O N E : A library provided for windows phone apps

development with special focus on windows game development.

W I N D O W S SE R V E R A N D W I N D O W S A Z U R E : Dot NET provides best

development tools for its server operating system and cloud based

operating system (Windows Azure).

M I C R O F R A M E WO R K : Smallest version of Dot NET framework designed for

resource deficient devices i.e. mobile and embedded. It is an open source

platform.

Compac t F ra mework : This framework enables developers to make

managed applications and run web services. This framework contains

more tools than micro framework. It is hardware independent.

4.4. THE DOT NET FRAMEWORK ARCHITECTURE

4.4.1. DOT NET FRAMEWORK OBJECTIVES The Dot NET platform is developed to fulfil a comprehensive list of following

objectives:

1. To provide a consistent object-oriented programming environment.

2. To provide a code-execution environment that minimizes software

deployment and versioning conflicts.

3. To provide a code-execution environment that promotes safe execution

of code, including code created by an unknown or semi-trusted third

party.

4. To provide a code-execution environment that eliminates the

performance problems of scripted or interpreted environments.

5. To make the developer experience consistent across widely varying types

of applications, such as Windows-based applications and Web-based

applications.

6. To build all communication on industry standards to ensure that code

based on the Dot NET Framework can integrate with any other code.

4.4.2. DOT NET FRAMEWORK SALIENT FEATURES The Dot NET framework is feature rich software. Let see what makes Dot NET a

wonderful platform for developing modern applications.

Page 72: Programming Fundamentals

Programming Fundamentals Using C# 71

RICH FUN CTION ALI TY

Dot NET framework provides a rich set of functionality out of the box. It contains

hundreds of classes that provide variety of functionality ready to use in your

applications. This means that as a developer you need not go into low level details

of many operations such as file IO, network communication and so on.

EASY DE VELO PME NT O F W E B APPLICATI ONS

Using framework on Dot NET platform, development of web applications has

become easier and enjoyable. ASP Dot NET is a technology available on Dot NET

platform for developing dynamic web applications. ASP Dot NET provides an event

driven programming model with complex user interface. ASP Dot NET server

controls provide advanced user interface element that save lot of coding and time

from programmer‘s side.

OBJE CT ORIEN TED PROG RAMMIN G SUPPO RT

The advantages of Object Oriented programming are well known. Dot NET

provides fully object oriented environment. The philosophy of Dot NET is “Object

is mother of all”. Languages like Visual Basic Dot NET now support many of the

Object Oriented features that were lacking traditionally. Even primitive types like

integer and characters can be treated as Objects.

MUL TI LANG UAGE SUPPO RT

As listed above, Dot NET framework provides Multilanguage support which is

beneficial for heterogeneous development (from language perspective). For

example a company might have people with skills in Visual Basic, C++, and Java

etc. It is an experience that whenever a new language or environment is invented

existing skills are outdated. This naturally increases cost of training and learning

but Dot NET solve this problem. Dot NET provides something attractive in this area.

It supports multiple languages. This means that if you have skill in C++, you need

not throw them but just mold them to suit Dot NET environment. The beauty of

multi-language support lies in the fact that even though the syntax of each

language is changed, the basic capabilities of each language remain at par with

one another.

MUL TI DE VI CE S UPPO RT

Modern life style is increasingly embracing mobile and wireless devices such as

PDAs, mobiles and handheld PCs. Dot NET provides promising platform for

programming such devises. Dot NET compact framework and Mobile Internet

Toolkit are step ahead in this direction.

Page 73: Programming Fundamentals

Programming Fundamentals Using C# 72

SECURI TY

Windows platform was always criticized for poor security mechanisms. Microsoft

has taken great efforts to make Dot NET platform safe and secure for enterprise

applications. Features such as type safety, code access security and role based

authentication make overall more and secure.

4.5. THE DOT NET FRAMEWORK – A LAYERED APPROACH The Dot NET Framework is layered architecture. Figure 4- 2: Dot NET Framework Layered

Architecture, shows its abstract view:

Operating system is a lower layer for Dot NET framework. The framework sits between

user application and operating system. The framework layer is further divided into

different layers. Common Language Runtime (CLR) is layer of framework that interacts with

the operating system. This part does most of the work. At next layer, Base Class Library

(BCL) is present. BCL provides all Dot NET objects that can be used in user code and by the

language itself. Using BCL, you can write code for different specialized type of applications.

At the top layer is user application that utilizes the BCL which in turn utilizes the CLR and

Visual

Studio

.NET

C#, VB.Net, F#,…

Common Language Runtime

Windows Operating System

Core WPF

ASP.NET LINQ ADO.NET

Parallel FX Workflow

foundation WCF

Framework Class Library

Windows

Forms

Common Language Specification

Common Type

System

Memory

Management

Figure 1- 15: .NET Framework Layered Architecture Figure 4- 2: Dot NET Framework Layered Architecture

Page 74: Programming Fundamentals

Programming Fundamentals Using C# 73

that finally uses operating system functionality. Microsoft provides overview of Dot NET

with following figure:

4.5.1. COMMON LANGUAGE INFRASTRUCTURE (CLI) CLI provides language neutral platform for application development and

execution. It is open specification developed by Microsoft and standardized by ISO.

These specifications describe the executable code and its runtime environment.

The specifications describe an environment in which programs written in different

high level languages could run on different platforms without rewriting or

recompiling. Code written in any high level language is translated into Common

Intermediate Language (CIL). CIL is a high level object oriented language. CIL code

is an intermediate representation which is similar for all languages. For example

same program written in two different languages i.e. C# and .NET will be translated

into one language i.e. CIL. Any computer that wish to run this CIL code must have

Common Language Runtime (CLR) installed. This CLR translates CIL code according

to underlying computer hardware and runs it on that machine. CLR could be

considered as .NET virtual machine. Figure 4- 3: Common Language Infrastructure,

shows this concept:

CLI mainly define the following four components:

C O M M O N TY P E S Y S T E M S (CTS ): A set of data types and their operations which

are common to all languages of .Net Framework. It mean each language supports

similar data types.

C O M M O N L A N G U A G E S P E C I F I C A T I O N S (CLS ) : Each language supported by .NET

platform contains nearly similar language constructs and their semantics. It is due

to the fact that these languages are defined using common language

specifications. Apparently syntax of each language differs but internally all

languages are similar.

ME T A DA T A (MD) : It is the data about your program structure, libraries,

references and about other program aspects. This meta data is used by different

.NET framework and platform tools during program compilation and execution.

V I R T U A L EX E C U T I O N S Y S T E M (VES) : This system loads and executes the CIL-

compatible programs. It uses meta data to combine separately compiled program

components to integrate them into single software. VES gets CIL code as input and

translates it into machine code. There may be different VES for different hardware.

Page 75: Programming Fundamentals

Programming Fundamentals Using C# 74

Figure 4- 3: Common Language Infrastructure

TH E C O M M O N L A N G U A G E RU N T I M E (CL R)

Virtual Execution System (VES) is known as CLR. It is considered as the heart of the

Dot NET framework. It provides “infrastructure” which is common to all Dot NET

languages. This infrastructure contains software components to perform memory

management, system resource access management, security services, compilation

and other relevant tasks. Before CLR every programming language on MS

Windows platform has to do all programming tasks itself separately like code

editing, compilation, hardware access, system resource management and memory

management. Every language does these tasks in its own way. This causes a wide

variety in compiled software. The CLI provides a common base for all languages

having different syntax and semantics. This uniform approach provides an efficient

way to write code in language of your choice. The user written code in any

Page 76: Programming Fundamentals

Programming Fundamentals Using C# 75

language is translated into an “IN TE R ME D I A T E L A N G U A G E (IL)”. From IL, this code

is translated into machine code using Just In Time compilation (JIT), at this point

the program is executed. It is clear that IL code for a program written in any

language is similar.

Figure 4- 4: CIL to Machine Code Translation

4.5.2. THE DOT NET CLASS FRAMEWORK The next layer up in the framework is called the Dot NET Class Framework also

referred as Dot NET base class library. The Dot NET class framework consist of

several thousand type definitions (classes – for now only), where each type

exposes some functionality. To grasp the concept, a programmer defines multiple

functions in his code and each function is named. Set of functions and data items

(variables) are grouped together to form higher level abstraction called the “class”.

Each class is modelled to perform some particular task. A set of related classes are

grouped and named as “NameSpace”. There are hundreds of namespaces present

in Dot NET. Every namespace help the user to build application of different type

or incorporate different type of functionality in one application. These

namespaces are present in Dot NET framework folder in the form of dll files or

assemblies. Here is the list of few namespaces:

System.Collection

System.IO

System. NET

……

All in all the CLR and Dot NET class framework allow developers to build the

following kinds of applications:

Page 77: Programming Fundamentals

Programming Fundamentals Using C# 76

WE B SE R V I C E S – Components that can be accessed over the internet

very easily.

Web Forms – HTML based applications

Windows Forms – Rich window GUI applications. Windows form

applications can take advantages of controls, mouse and keyboard events

and can talk directly to the underlying OS.

Window C onsol e A pplications – Compilers, utilities and tools are

typically implemented as console applications.

Windows Servic es – It is possible to build service applications

controllable via the windows Service Control Manger (SCM) using the Dot

NET framework.

Component Libra ry - Dot NET framework allows you to build standalone

components that may be easily incorporated into any of the above

mentioned applications types.

Mobil e Development – Applications for mobile platform could be

developed. Mobile and embedded devices running Windows CE are the

target OS for these applications.

AP P L I C A T I O N PR O G R A M M I N G IN T E R F A C E (API)

Each Dot NET library is made of classes and methods. The programmer uses these

library classes by calling public methods and variables defined in them. These

public methods and variables are collectively called the Application Programming

Interface (API). The use of library APIs in your programs is a common practice.

ADO .NET: DA T A A N D XML

A set of namespaces provided for database programming is named as ADO Dot

NET. Microsoft has been providing this functionality with its languages with same

name. ADODot NET is the next generation of Microsoft ActiveX Data Object (ADO)

technology. It is heavily dependent on XML for representation of data. It provides

support to program connected or disconnected database development

architecture. These features are discussed in detail in chapters dedicated for

database programming.

G R A P H I C A L US E R IN T E R F A C E

This layer allows programmer to easily build GUI based applications using built-in

GUI software components. Followings are the types of interaction interfaces that

are supported by the Dot NET framework.

Web Forms

Windows Forms

Web Services

DO T NET RE D I S T R I B U T A B L E

Page 78: Programming Fundamentals

Programming Fundamentals Using C# 77

In order to run applications developed using Dot NET framework the machine must

have certain ‘runtime’ files installed. They are collectively called Dot NET

redistributable. This is analogous to traditional Visual Basic application that

required Visual Basic runtime installed on the target computer. Dot NET

redistributable provides one redistributable installer that contain the common

language runtime and Microsoft Dot NET framework components that are

necessary to run the Dot NET applications. The redistributable is available as a

stand-alone executable and can be installed manually or as a part of your

application setup. If you have installed Dot NET framework SDK then no need to

install redistributable separately. The difference between Dot NET SDK and Dot

NET redistributable is that Dot NET SDK is intended to ‘develop’ application and

Dot NET redistributable is intended to ‘run’ Dot NET applications.

4.6. WRITING MANAGED CODE Normally there are two styles of writing code: Managed and Unmanaged. In

unmanaged coding, the user has to manage all the system resources that his

program accesses i.e. file handles, memory pointers (memory management). In

other words the programmer has to manage his code that most of the time lead

to bugs in software as programmer forget or ignore many management issues

leaving loopholes in the system. In managed programming, most of such

responsibilities are shifted from programmer to underlying programming

environment. Tasks like memory management and resource management is

automatically taken care of by the development environment and user is freer to

focus on the solution of problem. Common Language Environment (CLR) is such

an environment provided by Dot NET framework. The CLR is also referred as a

managed environment, in which common services, such as garbage collection and

security, are automatically provided. Code translated with a language compiler

that targets the CLR is called managed code. With Dot NET framework, user

application does not interact with operating system directly, it communicates with

OS through framework which handles all management issues. Every application

developed through Dot NET framework runs inside some software components

collectively called Common Language Runtime (CLR). This CLR monitors every

activity of user program and handles any inconsistency if one occurs.

DO T NET A S S E M B L I E S

In other languages like C++ and VB 6, the machine code produced for user

programs are binary executable files. Each such exe file has its own runtime

environment. In other words, every exe file consists of machine code and runtime

environment.

Page 79: Programming Fundamentals

Programming Fundamentals Using C# 78

With Dot NET this situation is different. Every program written in a high level

language is compiled into Microsoft Intermediate Language (MSIL) that also

contains some metadata to describe the code to Dot NET framework. Metadata is

collection of information about types implemented in the code. This may include

signatures, functions and procedures, members in types, and members in

externally referenced types. Collection of metadata and compiled intermediate

language code is called the assembly. Although an assembly may have “exe”

extension but it is not directly executable. Every assembly is presented to Just in

Time compiler (JIT) to be executed on the target machine.

4.7. DEVELOPMENT TOOLS: If you are developing a feature rich application such as a software that uses

pictures, icons, text files etc. you will require a sophisticated tool to write the code.

Such a tool is called the C OD E E D I T O R . Simple notepad like software can serve the

purpose but more enhanced and specialized tools for this purpose will help you a

lot in development process.

Integrated Development Environment (IDE) allows for Rapid Application

Development (RAD) by providing all the required tools at one place. The new Visual

Studio.NET is such an IDE. VS.NET is a powerful and flexible IDE that makes

developing Dot NET applications a breeze. Here is a look of IDE (Error! Reference

ource not found.):

Page 80: Programming Fundamentals

Programming Fundamentals Using C# 79

Figure 4- 5: Visual Studio 2010 - Integrated Development Environment

The detailed introduction to visual studio 2010 is provided in next chapter. Some

of the features of VS. NET that make you more productive are:

Drag and Drop design

IntelliSense features

Syntax highlighting and auto-syntax checking

Excellent debugging tools

Integration with version control software such as Visual Source Safe (VSS)

Easy project management

When you install Visual Studio .NET, .NET Framework is automatically installed on

the machine. However you can also install the Dot NET framework separately.

There are many other tools, to make the programmer’s job easier, present in IDE,

that are explored in next chapters.

Page 81: Programming Fundamentals

Programming Fundamentals Using C# 80

Chapter 5

Integrated Development

Environment (IDE) Visual studio has been primary Integrated Development Environment (IDE) for

software development on Microsoft platform for several years. An Integrated

Development Environment (IDE), also known as integrated design environment and

Integrated Debugging Environment, is a type of computer software designed to assist

computer programmers in software development process. Visual Studio .NET is an IDE

specially designed to develop software using .NET framework.

This chapter will show you how to leverage Visual Studio 2010 to your advantages,

increasing your skills set, and helping you become more productive in building

software. The language you will learn to write code is C#.

5.1. WHAT IS VISUAL STUDIO 2010 ABOUT? Visual Studio 2010 (VS) is an integrated development environment (IDE); a set of tools in

a single application that helps you write programs. Without VS, you would need to open a

text editor, write all of the code, and then run a command-line compiler to create and

execute application. Visual studio .NET provides you many features to ease the software

development process. These features may include code writing, code management,

project metadata management, project resources management, code debugging and

software documentation creation. Although VS does not provide you complete assistance

in these tasks however various tools present in IDE can do a lot automatically on your

behalf. For example, automatic skeletal code creation, resource management, code files

management and creation of documentation can be done by VS to large extent.

Before discussion the features provided in Visual Studio, we learn the process of its

installation. Following section presents a pictorial tour of installation process.

Page 82: Programming Fundamentals

Programming Fundamentals Using C# 81

Figure 5- 1: Visual Studio 2010 - Welcome Page

5.2. INSTALLING VISUAL STUDIO 2010 Visual studio software can be obtained from market or its free cut down versions, called

express editions, could be downloaded from Microsoft website. Here is the link to

download the software:

http://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx

After getting the software, next step is its installation. If you haven’t already installed VS,

this section walks you through the setup process. The guidance along the way will explain

how to install software:

1. When you first place the VS DVD into the drive, you’ll see the Microsoft Visual

Studio 2010 installation window, shown in Figure 5- 2: Visual Studio 2010

Setup Window. Available options are to Install Microsoft Visual Studio 2010

and Check for Service Releases. Click Install Microsoft Visual Studio 2010.

Page 83: Programming Fundamentals

Programming Fundamentals Using C# 82

If the software is present on some other media or software installation process

does not start automatically, you can start it by clicking on “Setup” file present

in Visual Studio folder as shown in Figure 5- 3: Visual Studio 2010 Setup File.

Figure 5- 3: Visual Studio 2010 Setup File

2. We will select “Install Microsoft Visual Studio 2010” as shown in Figure 5- 2:

Visual Studio 2010 Setup Window.

3. In next step VS installation dialogue box will appear as show in Figure 5- 4:

Visual Studio 2010 Setup Wizard:

Figure 5- 2: Visual Studio 2010 Setup Window

Page 84: Programming Fundamentals

Programming Fundamentals Using C# 83

Figure 5- 4: Visual Studio 2010 Setup Wizard

This figure shows that I’m installing the Ultimate version. Installation for other

versions is similar, but the number of features available to install varies. If you

check the box on this page in the Help Improve Setup section, the installer will

gather logs (installation information) produced during the setup process and

send them across the Internet to Microsoft after the setup is complete. To help

you make an informed choice as to whether to check this box, there is a Privacy

Statement link under the check box to click and read if you would like more

information about what Microsoft does with setup information.

4. After loading setup components, set up wizard will show you next command

page as shown in Figure 5- 5: Setup Wizard - Next Command:

Page 85: Programming Fundamentals

Programming Fundamentals Using C# 84

Figure 5- 5: Setup Wizard - Next Command

When you’re ready, click Next. Licensing screen is displayed.

Page 86: Programming Fundamentals

Programming Fundamentals Using C# 85

Figure 5- 6: Setup Licensing Page

5. In Figure 5- 6: Setup Licensing Page you’ll see what components will be

installed. You’ll need to read the VS license to ensure that you understand

what the terms are. The licensing terms can differ, depending on what type of

package you acquired and your particular country or region. Once you’ve read

the license, you’ll need to check “I have read and accept the license terms” to

proceed. Next, enter the license key that comes with your software and enter

your name. The installer will automatically fill in the product key if you

downloaded VS via Microsoft Developer Network (MSDN). Click Next and

you’ll see options for customizing product installation.

6. Figure 5- 7: Setup Customization, lets you choose between full and custom

installation. If you click the Custom option, you’ll be able to choose precisely

which components should be installed. This is a good opportunity to uncheck

the items you won’t ever use. If this is your first installation of VS .NET and you

have sufficient space, you can check everything by selecting “full”. You can

always return to installation process later, and can customize according to

your need.

Page 87: Programming Fundamentals

Programming Fundamentals Using C# 86

Figure 5- 7: Setup Customization

The configuration screen in Figure 5- 7: Setup Customization shows that you

can also change the location of where to install VS. Take note of the

installation location because this is where you will go to find sample code,

common assemblies, and more items affecting the development environment.

Evaluate the disk space requirements to ensure you have enough available

storage. You’ve now completed the configuration options for installation. Click

Install to start the installation.

If you select “Custom” in Figure 5- 7: Setup Customization, you will see

following screen that will allow you to select the components that you want

to install. For now we are choosing “full” install, so this screen will not be

displayed during our installation process.

Page 88: Programming Fundamentals

Programming Fundamentals Using C# 87

Figure 5- 8: Visual Studio Custom Installation

You’ll see a screen similar to Figure 5- 8: Visual Studio Custom Installation.

7. During the installation process where the small check marks indicate which VS

components have successfully installed.

Figure 5- 9: Visual Studio Installation Progress Window

Page 89: Programming Fundamentals

Programming Fundamentals Using C# 88

8. During the installation, the VS installer may need to reboot your computer,

showing the restart message in Figure 5- 10: Visual Studio Restart Dialogue

Box. Make sure you close any applications you currently have open so that you

don’t lose your work, and then click “Restart Now”.

Figure 5- 10: Visual Studio Restart Dialogue Box

9. When installation completes without error, you’ll see the Success window,

shown in Figure 5- 11: Visual Studio Setup Completion Window. If you have

errors during installation, this window will give you guidance on what to do to

solve the problem.

Figure 5- 11: Visual Studio Setup Completion Window

10. Click “Finish” to end the setup process.

Page 90: Programming Fundamentals

Programming Fundamentals Using C# 89

You have successfully completed the installation of Visual Studio. As an optional

step, you are asked by the VS installer to install documentation. Documentation is

the collection of documents explaining different features and language libraries. If

you get stuck during code writing, you can read these documents to resolve your

problem. “Install Documentation” button in Figure 5- 11: Visual Studio Setup

Completion Window will start the process. The initial installation screen that

appeared when beginning the installation will reappear, as shown in Figure 5- 12:

Checking for Service Releases. Documentation will only be installed if it is present

on the media containing VS software. You should also check for service releases;

not only for the updated functionality to VS, but also because service releases

often include important security updates.

Figure 5- 12: Checking for Service Releases

5.3. RUNNING VISUAL STUDIO 2010 Congratulations, you are now ready to run VS for the first time. Goto Windows

startup menu and select “Microsoft Visual Studio 2010” as shown in Figure 5- 13:

Visual Studio Start Menu.

Page 91: Programming Fundamentals

Programming Fundamentals Using C# 90

Figure 5- 13: Visual Studio Start Menu

At that point, you’ll need to perform one more easy configuration step, where you

will choose your default environment settings, as shown in Figure 5- 14: Choose

Default Environment Settings Window

The choice you make for default environment settings depends a lot on what

language or environment you’ll use to write software in. The environment settings

choice isn’t locked in stone and can be reset if you decide you don’t like the

settings. For this book, you will choose “Visual C# Development Settings”.

Figure 1- 16: Choose Default Environment Settings window Figure 5- 14: Choose Default Environment Settings Window

Page 92: Programming Fundamentals

Programming Fundamentals Using C# 91

This section is a high-level view of VS, describing what is available when you first

start Visual Studio 2010, also known as the Visual Studio integrated development

environment, commonly known as the IDE. Seeing what is available will help you

find features more quickly. Additionally, knowing what is available by default will

help you differentiate between default functionality and the context-sensitive

features of the software items you’re working on. Figure 15 shows how VS appears

when first started. It refers to portions of the screen, helping you see how the IDE

is organized. The following sections describe of the Start screen shown in the

Figure 5- 15: Visual Studio 2010 IDE.

5.4. NAVIGATING VISUAL STUDIO 2010 ENVIRONMENT

Figure 5- 15: Visual Studio 2010 IDE

The IDE consists of various components that are described below. The description

is according to part numbers marked by rectangles as show in figure 15:

1. TH E ME N U BA R

At the very top left of Figure 15, is menu bar. Menu bar consists of different top

level menus i.e. “File,” “Edit,” “View,” “Tools,” and so on. Following figure shows

the menu bar. Menu items in menu bar could be changed dynamically to some

extent.

1

2

4 3

5

6 7

Page 93: Programming Fundamentals

Programming Fundamentals Using C# 92

You can do different tasks using menu bar like project management, building and

executing solution, debugging and project analysis. Although every menu and its

options are important to know but for a learner like you, it would be difficult to

understand every option at this time. As we progress through learning process,

more and more options will be explored.

2. TO O L B A R

Menu bar options are a comprehensive set of functionality offered by VS 2010.

Most frequently used features are presented in toolbar. Toolbar items are

dynamic and context sensitive. Toolbar items are changed with different tasks

carried by programmer in VS. VS IDE also provides the feature to customize toolbar

according to your choice. Different toolbars can be hide and shown explicitly.

3. WO R K AR E A

Area of VS IDE shown in above figure is called the work area. VS IDE displays a

special window in this area called S T A R T P A G E . This is the same area that you’ll use

to write code. The Start page is divided into two sections: project management

and information. The project management side of the page, on the left, offers a

quick way to start new projects or work with a list of recently open projects. The

information side of the page, on the right, contains resources to help you get

started with VS, such as links to the Microsoft Web site, walkthroughs to help you

learn new features, and a tab that updates with the latest developer news from

Microsoft.

Page 94: Programming Fundamentals

Programming Fundamentals Using C# 93

4. TO O L B O X

On the far left side of Error! Reference

ource not found. is a vertical tab, titled

Toolbox, which contains a context

sensitive list of controls that can be

dragged and dropped onto the current

designer surface. The term “context-

sensitive” means that certain items are

visible or hidden, depending on where

you’ve clicked last or what context you

are working in, such as creating or

editing a new Web page. If you’re following along, you don’t have a designer

surface open right now, so the Toolbox is empty. In this book we are mostly

working on projects that do not require use of toolbox.

5. S O L U T I O N EX P L O R E R

The Solution Explorer window, to the right of the Start

page in Figure 15, is where your solutions, projects, and

project items will appear. This is where you can find and

organize all of the files and settings that belong to a

project.

6. PR O P E R T I E S

If we are working with Graphical User Interface (GUI)

applications, every GUI component possess some

properties. Properties window is context sensitive.

Properties and their values listed in this window are

changed when a GUI component is selected. Selecting

different GUI component, populates this window with

different set of properties. Properties window may be

displayed or hidden when you start VS.

Page 95: Programming Fundamentals

Programming Fundamentals Using C# 94

7. ER R O R L I S T

When you write

code for your

project, it is

normal to get

errors

introduced that

stop your program from compilation. However compiler reads all your code and if

it finds any error, these are listed in error list. These errors are listed with proper

description to help you in removing errors.

There may be other parts of VS 2010 IDE when run on your system however its

main parts are discussed in this section. If you see partially different view, do not

get confused. It is ok and you can go ahead with learning programming.

5.5. HELLO C#

5.5.1. CREATING YOUR FIRST PROJECT Now that we have enough introduction with VS IDE, we can proceed to develop our first project. We do “Bismillah” by following these listed steps:

1. Start VS2010 by clicking its icon present on desktop or from windows startup menu. 2. VS 2010 IDE window will get opened.

3. Select “File New Project”.

4. A dialogue box will appear with option to select a type of project. Select the

“Console Application”. In Name text box, specify the name of project. The example

application has been given the name “HelloCSharp”. The location text box shows

the location on hard disk where all files related to this project will be stored. You

can change the location using “Browse…” button.

Page 96: Programming Fundamentals

Programming Fundamentals Using C# 95

5. VS IDE will prepare your project and will open it for editing purpose as shown

below. You should notice that IDE has created skeleton project for you. This

automatic code generation has saved you from writing this code:

Before moving to next step, we find it important to explain automatic generated

code and other relevant windows’ contents.

A U T O M A T I C G E N E R AT E D C O D E E X P L A I N E D

Let you go to market and order candy on a shop. Shopkeeper gives you candy

covered in wrapper. This wrapping makes it easy to keep candy safe and handle it

conveniently. You should notice that shop keeper has received this candy in a big

Page 97: Programming Fundamentals

Programming Fundamentals Using C# 96

wrapper in which dozens of candies are packed. This big wrapper was taken from

a cartoon of big wrappers. All these packaging are made to design better and

efficient handling of candies.

Figure 5- 16: Multilevel Candy Packing

A computer program is composed of lot of statements. If we exemplify each

program statement with candy, it is required to make its packaging to better

manage and handle. This packaging of statements is done by enclosing code with

curly brackets in C#. Opening curly “{“ bracket is used to start package and

closing curly brackets “}” to end package. A package is normally named in C#.

One or more small packages are collected and made part of large package that

also starts with opening curly bracket “{“ and ended with closing curly bracket

“}”.

In C#, normally there are there levels of packaging in C#. By looking at IDE

generated code, you can identify these packaging levels. Let we mark it in Figure

5- 17: Multilevel Code Packing.

You are only allowed to write your code in smallest level of packing just like candies

that are found only in smallest packaging. (although some type of code could be

written out of smallest level of packaging or middle level of packaging but at this

stage of learning, we can only suppose that code could only be written within

smallest level of code packing).

You do not need to understand the statements packaging mechanism completely

at this point of book. For now, you can just take it as it is. We will be only interested

to write code within smallest level of packing.

Page 98: Programming Fundamentals

Programming Fundamentals Using C# 97

Figure 5- 17: Multilevel Code Packing

“U S I N G ” ST A T E M E N T

Every program of C# includes some code from built-in libraries. “using” statement

is used to link libraries with your program.

SO L U T I O N E X P L O R E R W I N D O W

As shown in the “solution explorer”, the project

consists of three types of files listed below:

6. Edit VS produced code as shown below

using System;

File Type Description

Properties This is the folder that contains configuration files. Most of the

properties are automatically set by the VS.

References Almost all programs in VS include some libraries. Every library

which is referenced by the program is listed here.

Program.cs This is main file which contains user written code. As a

programmer you will be doing most of the code writing task in

this file.

Largest

Level of

Packing Second

Level of

Packing

Smallest

Level of

Packing

Page 99: Programming Fundamentals

Programming Fundamentals Using C# 98

using System.Collections.Generic; using System.Linq; using System.Text; namespace HelloCSharp { class Program { static void Main(string[] args) { Console.Out.WriteLine("Hello to C Sharp"); Console.Read(); } } }

7. Now run the program. You can run the program using different ways:

a. By pressing F5 key.

b. By selecting run button from toolbar .

c. By selecting “Debug Start Debugging”

8. The program will run and will show following output.

CONGRATULATIONS, YOU HAVE WROTE, COMPILED AND RUN YOUR FIRST PROGRAM IN C#.

5.5.2. PROGRAM DESCRIPTION Here is the re-write of above program:

1 2

using System; using System.Collections.Generic;

Page 100: Programming Fundamentals

Programming Fundamentals Using C# 99

3 4 5 6 7 8 9 10 11 12 13 14 15 16

using System.Linq; using System.Text; namespace HelloCSharp { class Program { static void Main(string[] args) { Console.Out.WriteLine("Hello to C Sharp"); Console.Read(); } } }

Line number 1-4 contains .Net Framework library references. Only “System”

reference to library is required for our program but we have left VS generated

code as it is. Most probably you will also find the same program structure when

you start.

To better manage the code, the programmer names the set of instructions called

code blocks. In our example program there are three such blocks. Every block

starts with “{“ symbol and ends with matching “}” symbol. First block in our code

is named as “HelloCSharp”, second block is named as “Program” and third block is

“Main”. You can see few other words written before these names like

“namespace”, “class” and “static void”. We will explain them later in next

chapters. After word “Main” you can see additional text “(string args[])”. Again this

will be explained later on. It must be clear that every block must be properly

started with “{“ and ended with “}”. So for three blocks you see three opening

braces and three closing braces. This part of syntax of language which must be

followed. Line 7,9,11 are opening braces. Line# 12 contains an output instruction

that displays the results on console (LCD or any other display). Line# 13 is an input

instruction that reads the key from console (keyboard). Line 14, 15 and 16 are the

matching closing braces.

We have concluded this chapter with one example program and its description.

The reader is encouraged to write same program and practice with it by changing

its statements and looking at their results.

Page 101: Programming Fundamentals

Programming Fundamentals Using C# 100

Chapter 6

C# Basics C# (pronounced as C Sharp) is one of the major programming languages of .Net

platform. It could be considered as enhanced form of C, C++ and Visual C++. The

language is versatile in the context that it has ease of learning like Visual Basic and

strength of programming like C++.

In this chapter, we will look at strength features of C# that make it superior to other

languages. We will take you to the ride of C# by introducing basic computer

programming like constants, variables, data and its types supported in C# and how to

write simple programs. We will also describe code formatting and project compilation

process. After completing this chapter, you should be able to write small programs

using IO statements and should different data types and their variables.

6.1. WHY TO LEARN C# It could be your natural question that why I should learn C# whereas hundreds of other

programming languages are present? We attempt to answer your question in this section.

This book chapter discussion .NET framework provides in-depth picture about the

strengths of framework supported languages. However in this section we argue about C#

by discussion its major merits. C# is a feature rich language that make it attractive for

programmers. It has an interactive development environment consisting of designer for

different type of applications, compiler, debugger and other development tools. .NET

framework provides Common Language Specification (CLS) that provides the access of .Net

framework libraries to all languages supported by .Net framework.

Following is the list of C# core features:

Easy to Learn

Typed and Case Sensitive

Object Orientation

Type Safety

Rapid Application Development Support

Event Driven

There are other technical features of the language which will be discussed as the learning

of language progresses.

E A S Y T O L E A R N

Page 102: Programming Fundamentals

Programming Fundamentals Using C# 101

The language is easy to learn as compared to its predecessors like C, C++ and Visual

C++. Application programming can be done with the ease of Visual Basic, which

has been very popular among development community, and power of C++ for

system level programming. This is why the language is being used by millions of

programmers around the world.

TY P E D A N D C A S E S E N S I T I V E

C# is strongly typed language. “Typing” means that programs written in C# must

declare every data element with its data type that is used in a program. If there is

any data element which is either not defined or its type is not declared, the

compiler will complain. No data item without its type is allowed in this language.

Like C and C++, C# is also case sensitive. It means that instruction written in C#

makes difference between small and capital letters. The word “BZU” is different

from “Bzu” or “bZu”. So you must be careful when coding in C#.

O B J E C T O R I E N T A T I O N

Today the object oriented programming paradigm is state of the art practice. This

paradigm is developed to overcome the deficiencies found in procedural

programming. Major problem with procedural paradigm is the complexity and lose

control on variables defined in the program. Other major issue is that procedural

programming does not provide the way of real world modeling (real world

abstraction). In real world, we deal with objects of some type which have some

properties and can perform some operations or operations can be performed

upon them. As an example, consider a chair object (a specific chair, may be one in

which you are sitting). Using the process of abstraction, one can define following

set of properties and operations for your chair (Table 1: Abstraction of Chair

Object):

Properties Price Legs Seat Arms Wait Moveable Weight Color

Operations Purchase Sale Repair Place remove

TABLE 1: ABSTRACTION OF CHAIR OBJECT

Page 103: Programming Fundamentals

Programming Fundamentals Using C# 102

Object orientation provides the right abstraction to write code in the same way as

things occur in real world. We will describe this concept in detail in later chapters.

TY P E S A F E T Y

There are different types of errors that could occur in a program written. One of

such error type is “Type Error”. Every variable we define in the program has

specific data type. Type error occurs when one type of variable is assigned or used

to other type of variable or different type of variable is used where another type

of variable is expected in the program. This is because every type of variable is

represented differently in hardware. For example if discrete type of variable is

used in place of real type of variable, it will generate type error. Typed languages

are those which require that data type of every variable is specified before that is

used in any instruction. Proper use of variable data types is either checked at

compile time or at runtime. If data types of variables are checked at compile time

is known static type checking. On the other hand if type checking is done on run

time, it is called the dynamic type checking.

R A P I D AP P L I C A T I O N DE V E L O P M E N T S U P P O R T

.Net framework provides a large number of class libraries. These libraries provides

functionality required in software development and graphical user interface

components like buttons, check boxes etc. A programmer can use these library

functionalities to rapidly develop his application.

E V E N T DR I V E N

To provide instructions to computer, user interacts through the interface provided

by hardware or software. Every such interaction is called the event. For example

mouse click, key press, mouse move. Event driven programming allows the

programmer to write code for specific hardware or software events. Whenever

that event occurs, specified code runs. This programming model provide the

abstraction for real life model in which we perform events to do something.

6.2. DATA TYPES IN C# As discussed in “Data and Information” chapter, multiple types of data could be

represented in the language. For example discrete numbers and real numbers. Every type

of data can further be categorized into sub-classes which are also called the data types.

Here we present another view of data type. “A data type is a set of values for which a

variable could be defined”. This concept is explained with the help of number sets. Below

is the list of few sets of numbers:

Set Name Set Description Mathematical Notation

N Set of natural numbers

{1,2,3,4,…}

Page 104: Programming Fundamentals

Programming Fundamentals Using C# 103

W Set of whole numbers

{0,1,2,3,4,….}

Z Set of complete numbers

{ ….,-3,-2,-1,0,1,2,3,…}

Every set could be considered as data type. A variable defined on set N has different data

type than a variable defined over set W.

6.2.1. VARIABLES AND CONSTANTS A variable “v” could be defined over any above mentioned set like v=3 where v ϵ

N or v could take value from W set like v=0 where v ϵ W. If v belongs to W then it

can take any value of that set but one value at a time. A variable is just a name

which may refer to any member of specified set. All the members of the set are

constants. In other words we can say that a variable always point to a constant of

particular set. Such a set is called the data type. You have been working with

variables and constants in elementary classes when dealing with algebra.

There are various types of sets defined in C# referred as data types. The language

allows to define variables over these data types. These data types are further

divided into two major categories:

Language defined data types (Built-in Data Types)

User defined data types

6.2.2. LANGUAGE DEFINED DATA TYPES All programming languages define some sets of values for which variables could

be defined. These are called the built-in data types or language defined data types.

Such data types could be further divided into two categories: Basic data types and

advanced data types.

BAS IC DATA T YP E S

The data sets which contain simple values are considered as basic data types. Here

is the list:

BO O L E A N V A L U E TY P E S

Type Description Set of values Default Value

bool Boolean value {true, false} False

D I S C R E T E V A L U E TY P E S ( IN T E G E R V A L U E S )

Type Description Set of values Default Value

byte 8-bit unsigned integer {0,1,2,..,255} 0

Page 105: Programming Fundamentals

Programming Fundamentals Using C# 104

int 32-bit signed integer {-2147483848,…, 2147483647} 0

long 64-bit signed integer {-923372038854775808, … , 9223372036854775807}

0

sbyte 8-bit signed integer {-128,-127,…,0, …,128, 127} 0

short 16-bit signed integer {-32,788,…,0, …, 32,787} 0

uint 32-bit unsigned integer

{0,1,2, … , 4294967295} 0

ulong 64-bit unsigned integer

{0,1,2,…, 18446744073709551615}

0

ushort 16-bit unsigned integer

{0,1, 2, … , 85535} 0

R E A L V A L U E TY P E S

The values in the set are too large. So here these are written as range where first

value and last value are mentioned only.

There are some special values in real data types. These are negative infinity,

positive infinity and uncertainty. These values are represented by text constant as

shown below:

Single.NegativeInfinity, Double.NegativeInfinity

Single.PositiveInfinity, Double.PositiveInfinity

Single.NaN, Double.NaN

Type Description Range Default Value

decimal 128-bit precise decimal values with 28-29 significant digits

(-7.9 x 1028 to 7.9 x 1028) 0.0

float 32-bit single-precision floating point type

-3.4 x 1038 to + 3.4 x 1038 0.0

double 64-bit double-precision floating point type

(+/-)5.0 x 10-324 to (+/-)1.7 x 10308

0.0

Page 106: Programming Fundamentals

Programming Fundamentals Using C# 105

TE X T V A L U E TY P E S

Text value types are special sets that could be considered as values and characters

table as shown below:

Type Description Range Default Value

char 16-bit Unicode character U +0000 to U +ffff '\0' ASCII TA B L E

Code 0 .. 48 … 65 ..

Character (null) .. 0 … A … S T R I N G V A L U E TY P E S

A string data type represents a list of multiple characters.

Type Description Range Default Value

String 16-bit Unicode character list U +0000 to U +ffff '\0'

O B J E C T V A L U E TY P E S

Object is a special type of data that will be discussed later in this book.

Type Description Range Default Value

Object Object null

ADV ANC ED DATA T YP E S

There are number of advanced data types available in C#. The use of advanced

data types requires deeper understanding of data structures and other related

concepts. Although a programmer can write software using basic data types

however the knowledge of advanced built-in data types makes programming

easier and faster. Few of advanced data types are listed below without description.

We will explain any such data type whenever used in next chapters.

Hashtables

Dictionary

Enum

Flags

String

Stringbuilder

US ER DE FI NE D DATA T YP E S

Almost all programming languages allow the programmer to build new data types

based on programming requirement. For example, a programmer, writing

software that involve the measurement of room dimensions, may need to build

Page 107: Programming Fundamentals

Programming Fundamentals Using C# 106

new data type called distance consisting of feet and inches. The process of making

new data types is discussed in next part of this book.

6.3. C# PROJECT TYPES As stated in previous chapters, VS 2010 can support multiple type of projects. A list of

such projects is shown below, Figure 6- 1: Visual C# Project Types:

The description of these projects will be provided when

we will explore them.

6.4. I/O STATEMENTS The instruction written in a program are also called the statements. Mostly we are

dealing with “Console” devices (screen and keyboard). There is a variety of I/O

statements in C# but at present we only introduce the following statements:

6.4.1. OUTPUT STATEMENTS Output Statements

Statement Description

Console.Out.Write() This statement writes the output to the console screen

Console.Out.WriteLine() The statement writes the output on screen and transfers control to next line so that next output could be displayed on new line.

Input Statements

Figure 6- 1: Visual C# Project Types

Page 108: Programming Fundamentals

Programming Fundamentals Using C# 107

Statement Description

Console.Read() This instruction reads a character from user

Console.ReadLine() This statement reads a complete line from user. When user presses the “Enter” key the line ends.

CONS O LE .OU T .WR IT E(…)

You already know that instructions are used to manipulate/process the data. The

data is either provided as “constant” or “variable”. We write (provide) data in

parenthesis which is written on the screen. Consider the following instruction

Console.Out.Write(“Hello to C Sharp”);

In parenthesis everything written in double quotes is called the constant. This

constant data is also known as “Parameter” or “argument”. Here are some other

examples of this statement.

Console.Out.Write(3);

Console.Out.Write(6.9);

CONS O LE .OU T .WR IT EL INE(…)

This command works in same way as above but after writing its argument on

screen, it transfers control to new line and next output is written on next screen

as shown in Figure 6- 2: Using Output Statements:

Figure 6- 2: Using Output Statements

Page 109: Programming Fundamentals

Programming Fundamentals Using C# 108

6.4.2. CONSTANTS AND VARIABLES IN C# Data in computers is represented in two forms: Constants and Variables. Constants

are data items that could not be changed whereas variables are containers that

can contain different constant data items at different times. A constant data items

is also known as literal.

L I T E R A L S (C O N S T A N T S)

These are the members of sets defining the data type. In other words the every

member of data type set is known as constant or literal. A literal 5 may belong to

different sets i.e. discrete, real. To explicitly specify its type literals contain some

character as suffix. Here is the list of such literals.

IN T E G E R L I T E R A L S : These are sequence of digits, a sign (+,-), suffixes and prefixes.

Using prefixes, you can present integers in the program in decimal or hexadecimal

format.

Prefix Suffix Example Literal

Description

“0x” or “0X”

0x87AF It indicates values in hexadecimal format. 87AF is in hexa-decimal.

“l” or “L”

6897L Indicates the literal is from “long” set (data type)

“u” or “U”

4357U Indicates uint or ulong data type

If no suffix or prefix is used, the literal is considered decimal and integer.

Figure 6- 3: Program with Output

R E A L L I T E R A L S : These are sequence of digits, a sign (+,-), suffixes and decimal

point character. These literals can be either in normal notational form or in

exponential format.

Page 110: Programming Fundamentals

Programming Fundamentals Using C# 109

Data Type Suffix Example Literal Description

float “f” or “F” 34.89f 34.89F

double “d” or “D” 34.89d 34.89D

decimal “m” or “M” 78.87m 78.87M

exponential “E” 1.25e+5f 1.25*10+5f

If no suffix is used the literal is considered as double.

Program: CSharpLiterals Output

using System; namespace CSharpLiterals { class Program { static void Main(string[] args) { Console.Out.WriteLine(34.89f); Console.Out.WriteLine(34.89d); Console.Out.WriteLine(34.89M); Console.Out.WriteLine(1.25e+5f); Console.Read(); } } }

34.89 34.89 34.89 125000

C H A R A C T E R L I T E R A L S : These are single characters enclosed in single

apostrophes used to set the value of character type variables. It could be defined

as:

Representation Example

By character ‘A’ By code ‘\u0065’ By Escape Sequence

\n

E S C A P E S E Q U E N C E S : It is a single character represented by a sequence of

characters. It is due to that single character cannot represent this character. “\”

character (escape character) is used to make sequence with other characters.

Most frequently used escape sequences are:

Escape Sequence Description

\’ For single quote \” For double quotes

Page 111: Programming Fundamentals

Programming Fundamentals Using C# 110

\\ For back slash \n For new line \t For inserting tab \uxxxx For specifying Unicode of a

character i.e. \u87B7

Line# Program: EscapeSequences

Output Statement

Output

1

2

3

4

5

6 7

8

9

10

11

12

13

14

15

16

17

using System; namespace HelloCSharp { class Program { static void Main(string[] args) { Console.Out.WriteLine("\'test string\'"); Console.Out.WriteLine("\"test string\""); Console.Out.WriteLine("\\test string\\"); Console.Out.WriteLine("\ntest string\n"); Console.Out.WriteLine("\ttest string\t"); Console.Out.WriteLine("\u0061"); Console.Read(); } } }

- - - - - - - 8 9 10 11 11 11 12 13 - -

'test string' "test string" \test string\ test string test string a

S T R I N G L I T E R A L S : These are multiple characters enclosed in double quotes also

referred as string constants. A single character enclosed in double quotes is also

called the string literal. If @ symbol is used before string literal, it stops translation

of escape sequence characters.

Program: StringLiterals Output using System; namespace HelloCSharp { class Program { static void Main(string[] args) { Console.Out.WriteLine("this is string literal"); Console.Out.WriteLine("\\special\\ people");

this is string literal

String Literal Example output

“ This is string literal” This is string literal “\\Special\\ people” \Special\ people @”\\Special\ people” \\Special\\ people

Page 112: Programming Fundamentals

Programming Fundamentals Using C# 111

Console.Out.WriteLine(@"\\special\\ people"); Console.Read(); } } }

\special\ people \\special\\ people

VARIA BL E S

As discussed above, there are different data types (data sets) available in C#. You

can define a variable of any of these data types. For a set of integers, you can

define the variable as:

Syntax is a way to write the instruction. Angle brackets containing word represent

a place holder, it will be replace by actual thing as shown in example. Square

brackets show the optional component of syntax. Writing semicolon after each

statement is compulsory part of C# syntax.

V A R I A B L E DE C L A R A T I O N : It is the statement which introduces a variable in the

program. For example “double testMarks”.

V A R I A B L E DE F I N I T I O N : This concept is related to memory. The statement which

causes the compiler to allocate memory for it is called variable definition. In C#,

for primitive data types, definition and declaration is done with single statement.

Hence “double testMarks” also serves the purpose of definition.

V A R I A B L E IN I T I A L I Z A T I O N : The statement that gives value to the variable at the

point of its declaration is called the variable initialization. For example “double

testMarks=88.99” performs three tasks: declaration, definition and

initialization.

V A R I A B L E A S S I G N M E N T : Giving some value to the variable after its declaration is

called the variable assignment. This value could be direct constant or some other

variable. Here are examples:

double testMarks; double totalMarks=77.98; testMarks=56.67; testMarks=totalMarks

Variable declaration and definition Variable declaration, definition and initialization Value assignment Variable assignment

Here is the program showing the use of variables, Figure 6- 4: Using Variable in

User Program:

Syntax Example

<data type> <variable name> [=<initialization>]; int count; float quantity; double measurement=5.4;

Page 113: Programming Fundamentals

Programming Fundamentals Using C# 112

Figure 6- 4: Using Variable in User Program

Here you can see that we have declared a variable “score” of type “int” on line#

9. On On line# 10, variable is assigned the value “5”. A constant is now referred

by the variable “score”. On line# 11, output statement is used where a constant

is provided as parameter which is printed as it is on output screen. On line# 12,

there is another output statement but this time variable is provided as an

argument instead of constant:

Program: UsingVariables Output using System; namespace HelloCSharp { class Program { static void Main(string[] args) { //variable declaration and defination int testVariable; // declaration, defination and initialization int Variable2 = 5; //value assignment testVariable = 10; //variable assignment Variable2 = testVariable; Console.Out.WriteLine(Variable2); Console.Out.WriteLine(testVariable); Console.Read(); } } }

10 10

Page 114: Programming Fundamentals

Programming Fundamentals Using C# 113

CHARACT ER IS TI CS OF VARIAB LE S

A variable is described with the help of three features:

Name: Each variable is identified by its name

Data type: each variable must have some data type, the set name to which

it belongs

Value: The constant of its set to which it points.

An example of variable is “double price=5.6”. A variable is a named area of

memory (RAM).

VARIA BL E NAM IN G RU L ES

In writing source code, you need to name variables, code blocks and files. Every programming language defines few rules for this purpose. The name of the variable can be any of our choice but must follow certain rules defined in the C# language specification:

A variable name can contain the alphabets either in small (a-z) or capital (A-Z) case. It can also contain digits (0-9) and special character “_” (under score).

Variable name cannot start with digit.

Variable name should be descriptive (recommendation).

No C# keyword can be used as variable name.

Valid Variable Names

Invalid Variable Names

Price 2ndPrice (Digit as first character) Price2 boolean (Keyword) _test %test (Not allowed symbol used)

All languages uses a set of words for their own particular use. These words are

called the reserve words or keywords. Below is the list of C# keywords:

abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interfa

ce internal

is lock long namespace new null object operator out override prams private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while

Page 115: Programming Fundamentals

Programming Fundamentals Using C# 114

6.4.3. INPUT STATEMENTS Input statements are used to read data from user. User can enter data into

computer through various input devices such as keyboard, mouse, microphone

etc. Here we will explore the data entered through keyboard only. When we press

a key a code is sent to the computer. This code is according to the ASCII table or

Universal Code Table (we will restrict ourselves to ASCII only). The system gives

this key code to our program that could be placed in a variable of that type.

CONS O LE .READ()

To better understand look at the following example program:

Line# Program: UsingInputStatement Input Output

1 2 3 4 5 6 7 8 9 10 11 12 13

using System; namespace HelloCSharp { class Program { static void Main(string[] args) { int userInput; userInput = Console.Read(); Console.Out.WriteLine(userInput); } } }

A 65

Here is the program description:

Line# Description

1 Required part of library is attached with our program

2 Name of code block specified 3 Code block started 4 Name of inner code block provided 5 Inner block started 6 Most inner code block name specified 7 Most inner block started 8 Variable declared 9 Input taken from user and assigned to variable 10 Data present in variable is given to output

statement that will display it on screen 11 Most inner code block ended 12 Inner code block ended 13 Outer code block ended

Page 116: Programming Fundamentals

Programming Fundamentals Using C# 115

CONS O LE .READL I NE()

This input statement reads a complete line of text. When you press “Enter key”

the input line ends and data entered from keyboard is given to your program. Look

at the following example program:

Line# Program: ConsoleReadLine Input Output

1 2 3 4 5 6 7 8 9 10 11 12 13

using System; namespace HelloCSharp { class Program { static void Main(string[] args) { string userInput; userInput = Console.ReadLine(); Console.Out.WriteLine(userInput); Console.Read(); } } }

Test Test

And here is the program description. Only those lines are described which are

different from previous program:

Line# Description

7 A variable named “userInput” is declared with data type string. String data type is used to read multiple characters from user.

8 This instruction reads the line of text from user and assigns to “userInput” variable.

9 This output instruction displays the read data 10 The output screen displays the result and then

vanishes. This line stops the program to read another character from user. As soon as user enters input for this statement, the output screen vanishes. Hence we can see the output of instruction before this line.

6.4.4. COMMENTS Sometimes, programmer may need to write hints for himself in his program. The

compiler is supposed to ignore these hints. Such lines of text are called the

comments. C# uses special characters to mark the comments. The comments are

either single line or multiline. Single line comments are marked with “//”

characters where multiline comments are marked with “/*” (for start of

Page 117: Programming Fundamentals

Programming Fundamentals Using C# 116

comments) and “*/” (for end of comments”). Following program describes the

concept.

Figure 6- 5: Using Comments in User Program

Line# Program: Comments

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

using System; namespace HelloCSharp { class Program { static void Main(string[] args) { //We use string constant to output through output statement. Console.Out.WriteLine("Multan is very old city"); /* in following code we use a string variable to read data from user and display it*/ string userInput; userInput=Console.ReadLine(); Console.Out.WriteLine(userInput); Console.Read(); } } }

Input This is user entered text Output Multan is very old city

This is user entered text This is user entered text

In this program line# 8 contains the single line comments whereas line#10 and 11

contains the multi-line comments. You may use comments freely whenever you

Page 118: Programming Fundamentals

Programming Fundamentals Using C# 117

need to put hints in your program. These hints are for your understanding,

computer ignores them.

6.4.5. CODE FORMATTING As a programmer, you may write the code in any way of your choice following the

syntax and semantics rules. The compiler will translate it into machine code

without any complain. However the code you write, will be read many times as

you will often forget the syntax rules or will introduce other type of mistakes. If

your code is not written in ready to read and fast to understand way, you will

become irritated soon.

Formatting is adding characters such as spaces, tabs and new lines, which are

insignificant to the compiler and they give the code a logical structure and make it

easier to read.

As a good programming practice it is recommended that code must be written by

following some rules formulated by experienced programmers.

IN D E N T A T I O N : A code block may be written inside other code block as in our

example programs. Indentation requires that inner block should be written in such

a way that an eye view should represent its position as inner block that is covered

by outer block. You can see this above programs.

NA M I N G C O N V E N T I O N S : Languages allow you to name program variables, code

blocks, files and other resources. You must define some consistent way to name

them such that just by looking at name you can tell whether it is variable, code

block or file. Two widely used conventions by programmers are camel casing and

Pascal casing. In camel casing, if a name consist of two words, first word, first

character is written in small letter whereas first letter of second word is written as

capital. For example “myVariable” is written in camel casing. Pascal casing

suggests that first letter of both words must be written in capital like

“MyVariable”.

MAIN FOR MAT TI NG RU LE S

Following is the list of few formatting rules to be followed to better code writing:

Each inner code block must be indented inside the outer code block.

Statements inside the code block must be indented inside code block

The opening brace for a code block must be place on separate line and just

under the name of code block

The closing brace must be placed on separate line and on same level of

opening brace.

Page 119: Programming Fundamentals

Programming Fundamentals Using C# 118

All code block names (classes, namespaces, and methods) must be in

Pascal case.

All variable names must be in camel case.

.

6.4.6. C# COMPILATION PROCESS Now that we have seen some programs of C# and we also know little bit about

programming in C#, we look at the compilation process of C#. How the high level

program gets translated into machine code.

Common Language Runtime (CLR) is the heart of the compilation and execution

process of programs written in any Dot NET framework supported language like

C#. A wide variety of data types and language features are supported by CLR that

are visible to every framework language. Any code run by CLR is called the

managed code. C# compiler translates user written program into Microsoft

Intermediate Language (MSIL). Intermediate Language (IL) is set of CPU

independent instruction that could be translated into native machine code rapidly.

Code generated by MSIL includes instructions for loading, storing, initializing and

calling methods. It also includes the instructions for arithmetic and logical

instructions, control flow, direct memory access, error handling and other

operations. Just in Time compiler is used to convert MSIL code into native code.

For every CPU type, framework provides a separate JIT compiler. Besides user code

translation into MSIL, C# compiler also produces program metadata. Both,

translated program and metadata, make up a file that is portable and executable

(by CLR). This file is known as portable executable (PE). Runtime uses metadata

during program execution to better manage and safely execute it.

To produce executable code on particular CPU, MSIL code needs to be translated

into into native form. The framework provides two ways to translate MSIL code:

Translation using JIT

Install Time Code Generation using NGen.exe

JU S T I N T I M E C O M P I L E R ( JIT C O M P I L E R) : It translates MSIL code on demand on

runtime. Instead of translating all the IL code into native code, it only translates

that code which is referred at run time. The translated code is kept in memory

area called translation repository. This saves time and memory as all of the code

may not be needed to be translated. The loader program accesses the code to

execute. If it is already translated by JIT, it is fetched from translation repository

and used. If it is not already translated, a request is launched to JIT for translation.

After translation the code is run and translation is saved in translation repository.

Subsequent calls to this code finds a translated version.

Page 120: Programming Fundamentals

Programming Fundamentals Using C# 119

NG EN C O M P I L A T I O N : JIT compiler consumes some time for runtime compilation.

This affects the execution and slows it down to some extent. For more efficient

execution, framework provides a way to ahead of time translation. In this method,

all code is translated into native code before program execution and saved as file

on disk. When program is run, already translated file is used, it saves time and runs

the program fastly.

C O D E V E R I F I C A T I O N : As part of compilation process, JIT or NGEN check the code

for type safety and correct translation of source code into IL code.

R U N N I N G T H E P R O G R A M : During program execution, various other software

interact with native code. These software include garbage collector, security

checker and some other tools.

Following figure shows the compilation process in detail.

Figure 6- 6: Program Compilation Details

Page 121: Programming Fundamentals

Programming Fundamentals Using C# 120

Chapter 7

Operators and Expressions Like every programming language, C# uses special symbols called operators to

perform various type of operations. These symbols are used in combination with data

items (literals and variables) to produce new data items. Most of the operators are

same as we use in our daily life mathematics. Few are specialized symbols having new

meanings in C#.

You will learn different operators, their categories and uses in C#. Operands and

operators when used in combination make expressions. This chapter also discusses

expressions, their types, uses as simple statement or as embedded statement in

composite statements. After completing this chapter, you must be confident in use of

operators and expressions.

7.1. OPERATORS Every programming language uses operators to transform data from one form to another.

This data transformation is called the processing. Each operator either transform one data

item, two data items or more. The data items processed by the operator are called the

operands. All operators are catego rized based on the number of operands.

Unary Operators: The operators that take only one argument for processing

Binary Operators: The operators that take two operands to operate

Ternary Operators: The operators that take three arguments/operands to

operate

Special symbols like “+”,”-“ are used to denote the operators. Familiar operators have

familiar meanings i.e. “+” is used for addition. Operators in C# could be divided into

different categories as listed below:

S# Category Operators Description

1 Arithmetic - , +, *, / ,% ,++ ,-- Used to perform simple mathematical operations

2 Logical &&, ||, !, ^ Used with Boolean data types and expressions

3 Comparison ==, !=, >, >=, <, <= Used for data comparisons

4 Bitwise &, |, ~, ^, >>, << Used to perform bitwise operations

5 String concatenation

+ Used to join two strings into a single

Page 122: Programming Fundamentals

Programming Fundamentals Using C# 121

6 Type Conversion

(type), as, is, typeof, sizeof

Used to convert data type from one to another

7 Other ., new, (),[], ?:, ??, <<, >>

Used for different purposes, will be described later.

8 Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

Used for variable assignment

7.1.1. OPERATORS ASSOCIATIVITY This property of operators defines the direction of operators processing. There are

two processing directions: left associativity, right associativity.

L E F T A S S O C I A T I V I T Y : The operands are evaluated from left to right. For example,

the addition operator is left associative. In expression 7+8+9, first 7 and 8 are

added resulting into 15 which is added with 9 producing final result 24.

R I G H T AS S O C I A T I V I T Y : The operands are evaluated from right to left. For

example in expression a=7+8, first 7 and 8 are added resulting in 15 that is assigned

to variable a.

NO N -A S S O C I A T I V I T Y : The unary operators are not associative as there is only one

operand which solved in either way results in same value.

7.1.2. OPERATORS PRECEDENCE Some operators have priority over other operators. If in a mathematical

expression, multiple operators are used, one with higher priority is solved first. For

example in expression 3+4*5+8, two operators are used + and *. Multiplication

operator has higher precedence so it will be solved first resulting 3+20+8. Now

same operator exists in the expression which will be solved using associativity.

3+20+8 23+8 31.Following table lists the operators according to their

precedence. By using parenthesis (), priority of operators can also be changed.

Here is the precedence wise list of operators:

Priority Operators

14 (highest priority)

( )

13 ++ (as post fix), -- (as postfix), new, type, typeof, sizeof

12 ++ (as prefix), -- (as prefix), + (unary), - (unary), !, ~

11 *, /, %

10 + (string concatenation)

9 +, -

Page 123: Programming Fundamentals

Programming Fundamentals Using C# 122

8 <<, >>

7 <, >, <=, >=, is, as

6 ==, !=

5 &, ^, |

4 &&

3 ||

2 ?:, ??

1 (lowest priority)

=,*=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=

Parenthesis serve two purposes in expressions. These redefine the precedence of

different operators and secondly makes the sense of expression clear if not

defining the new precedence.

An operator is defined on the set of values (data types). There may be the situation

where one operator is defined for one data type but not defined for other. For

example concatenation operator “+” is only defined for string data type.

7.1.3. OPERATORS IN DETAIL As listed above, operators are divided into different categories. In this section we

look at these operators in detail.

AR I T H M E T I C O P E R A T O R S

These operators are:

Operator Description

+ Used for addition. Defined for integer and real numbers

- Used for subtraction. Defined for integer and real numbers

* Used for multiplication. Defined for integer and real numbers

/ Used for division. Defined for integer and real numbers.

% Used to find remainder of division operation.

Syntax : <numeric value> <operator> <numeric value>

Page 124: Programming Fundamentals

Programming Fundamentals Using C# 123

S E M A N T I C S : On left of operator, some integer or real value is provided and

similarly on right side integer or real value is provided. If both values are integer,

the result is also integer however in case of any real value operand, the result

produced is real.

Following program shows the use of arithmetic operators with integer numbers.

Line# Program – ArithmeticOperators Output

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

using System; namespace HelloCSharp { class Program { static void Main(string[] args) { int a = 5,b=7; Console.Out.WriteLine(a+b); Console.Out.WriteLine(a - b); Console.Out.WriteLine(a * b); Console.Out.WriteLine(a / b); Console.Out.WriteLine(a % b); Console.Read(); } } }

12 -2 35 0 5

The division operator has different working for integer and real numbers. If an

integer is divided by other integer the result is also integer and no fractional part

is obtained. This is called integer division.

Statements Result Description

int a=5; int b=2; Console.Out.WriteLine(a/b);

2 Integer is divided by other integer. Result is also integer

int a=5; int b=2; float c; c=a/b; Console.Out.WriteLine(c)

2 Integer divided by other integer. Result produced is integer and is assigned to float.

If any of the operands is real number the result produced is also real.

Statements Result Description

int a=5; float b=2; Console.Out.WriteLine(a/b);

2.5 Integer is divided by other integer. Result is also integer

Page 125: Programming Fundamentals

Programming Fundamentals Using C# 124

int a=5; float b=2; int c; c=a/b; Console.Out.WriteLine(c)

Error Compiler cannot convert real value into integer value.

IN T E G E R D I V I S I O N : When two integer operands are divided, they result into

integer results. Integer division by zero is not allowed as it is not defined and

causes exception.

R E A L D I V I S I O N : If two operands are divided and result is real number. In real

division, both or one operand could be real. In real division, division by zero is

allowed and it may result into positive infinity, negative infinity and NaN.

Una ry A rithmetic operators :

There are four operators in this list that include + (positive), - (negation), ++

(increment) and – (decrement).

Syntax : <operator> <numeric value>

S E M A N T I C S : These operators operate on single operand. For “+” and “-“ the

operand is provided on right whereas for increment and decrement the operand

can be provided on either side.

IN C R E M E N T O P E R A T O R : “++” operator is used to increase the operand value by

one. It could be used before or after the operand. If it is used before operand, it is

called the prefix increment. If it is used after operand, it is called the postfix

increment.

Increment Statements Output Description

Prefix ++<variable>

int a=5; Console.Out.WriteLine(++a) Console.Out.WriteLine(a)

6 6

Prefix operator first increases the value of operand and then uses it.

Postfix <variable>++

int a=5; Console.Out.WriteLine(a++) Console.WriteLine(a)

5 6

Postfix operator first uses the current value of variable and then increments it.

Page 126: Programming Fundamentals

Programming Fundamentals Using C# 125

DE C R E M E N T O P E R A T O R : “--“ operator is used to decrease the operand value by

one. It could also be used before or after the operand. If it is used before operand,

it is called the prefix decrement. If it is used after operand, it is called the postfix

decrement.

Decrement Statements Output

Description

Prefix - - <variable>

int a=5; Console.Out.WriteLine(--a); Console.Out.WriteLine(a);

4 4

Prefix operator first decreases the value of operand and then uses it.

Postfix <variable> - -

int a=5; Console.Out.WriteLine(a--); Console.WriteLine(a);

5 6

Postfix operator first uses the current value of variable and then decreases it.

Here is the complete program showing the use of increment and decrement

operators.

Program - IncDecOperators

using System; namespace HelloCSharp { class Program { static void Main(string[] args) { int a = 5, b = 10; int c = 5, d = 10; Console.Out.WriteLine(a); // result is 5 Console.Out.WriteLine(++a); // result is 6 Console.Out.WriteLine(a); // result is 6 Console.Out.WriteLine(b); // result is 10 Console.Out.WriteLine(b++); // result is 10 Console.Out.WriteLine(b); // result is 11 Console.Out.WriteLine(c); // result is 5 Console.Out.WriteLine(--c); // result is 4 Console.Out.WriteLine(c); // result is 4 Console.Out.WriteLine(d); // result is 10

Page 127: Programming Fundamentals

Programming Fundamentals Using C# 126

Console.Out.WriteLine(d--); // result is 10 Console.Out.WriteLine(d); // result is 09 Console.Read(); } } }

Increment and decrement operators are defined for integer and real numbers

only. They do not work with other data types.

L O G I C A L O P E R A T O R S

Logical operators operate on Boolean values (constants or variables) and produce

the result as Boolean value (true or false). In general any expression producing

Boolean result is known as logical expression and any such operator is called the

Boolean operator or logical operator. There are various boolean or logical

operators. Few of them are listed below:

Logical AND – it is binary operator i.e. takes two arguments

Logical OR – it is binary operator i.e. takes two arguments

Logical NoT – it is unary operator i.e. takes one operand

Logical Exclusive OR – it is binary operator i.e. takes two operands

Following logical tables show the working of these operators:

Logical OR

A OR B = R , (A || B)=R

Operand one (A) Operand Two (B) Result

False False False

False True True

True False True

True True true

The result is “true” if any of the operands is true

Logical AND

A AND B = R, (A && B)=R

Operand one (A) Operand Two (B) Result

False False False

False True False

True False False

True True True

The result is true if both operands are true

Page 128: Programming Fundamentals

Programming Fundamentals Using C# 127

Syntax : <integer value> <operator> <integer value>

S E M A N T I C S : These operators only work with integer values. The operator requires

to have integer values on its both sides. The result produced is also integer.

Following program shows the use of logical operators:

Program - LogicalOperators

using System; namespace LogicalOperators { class Program { static void Main(string[] args) { //Variables' declaration, defination and Initialization bool a = true,b=true,c=false,d=false; // INSTRUCTION RESULT // OR OPERATOR Console.Out.WriteLine(a || b); // true Console.Out.WriteLine(a || c); // true Console.Out.WriteLine(c || a); // true Console.Out.WriteLine(c || d); // false //AND Operator Console.Out.WriteLine(a && b); // true Console.Out.WriteLine(a && c); // false

Logical Not

Not A, (!A=R)

Operand one (A) Result

False True

True False

The result is opposite of operand value

Exclusive OR

A EXOR B = R, (A ^ B=R)

Operand one (A) Operand Two (B) Result

False False False

False True True

True False True

True True False

The result is true if only one of the operands it true.

Page 129: Programming Fundamentals

Programming Fundamentals Using C# 128

Console.Out.WriteLine(c && a); // false Console.Out.WriteLine(c && d); // false // NOT Operator Console.Out.WriteLine(!a); // false // Exclusive OR Console.Out.WriteLine(a ^ b); // false Console.Out.WriteLine(a ^ c); // true Console.Out.WriteLine(c ^ a); // true Console.Out.WriteLine(c ^ d); // false Console.Read(); } } }

C O M P A R I S O N O P E R A T O R S

Comparison operators are used to compare two operands. As listed above these

are six operators > (greater than), < (less than), >= (greater than equal to), <= (less

than equal to), == (equal to) and != (not equal to). The result of these operators is

boolean value. Normally these operators are used with integer and real operands.

Syntax : <numeric value> <operator> <numeric value>

S E M A N T I C S : The operator requires to have integer values on its both sides. The

result produced is boolean. Following program lists the use of these operators.

Program - ComparisonOperators

using System; namespace ComparisonOperators { class Program { static void Main(string[] args) { int a = 22, b = 24,c=22; double d = 22.5, e = 24.5, f = 22.5; // INSTRUCTION RESULT Console.Out.WriteLine(a > b); // false Console.Out.WriteLine(a < b); // true Console.Out.WriteLine(a <= b); // true Console.Out.WriteLine(b <= a); // false Console.Out.WriteLine(d < e); // true

Page 130: Programming Fundamentals

Programming Fundamentals Using C# 129

Console.Out.WriteLine(d > e); // false Console.Out.WriteLine(d <= f); // true Console.Out.WriteLine(f >=d ); // true Console.Out.WriteLine(a == c); // true Console.Out.WriteLine(a != c); // false Console.Read(); } } }

B I T W I S E O P E R A T O R S

Every data either constant or variable is represented in binary form in computer.

For example a variable ‘A’ with value 100 like int A=100, will be represented

internally as “1100100”. If we consider every bit of such data as separate boolean

date item and then apply logical operators, the result will be same as that of

bitwise operators. Here is the list of bitwise operators. Let A=100 and B=99:

& - binary bitwise AND. It performs logical AND operation on each

corresponding bit of each operand. Below given table explains the

concept.

Bitwise AND ( A & B )

A 1 (true) 1 0 0 1 0 0 =100

B 1 (true) 1 0 0 0 1 1 =99

Result 1 (true) 1 0 0 0 0 0 =96

1 could be considered as ‘true’ and 0 as ‘false’.

| - bitwise binary OR. It performs logical OR operation on each

corresponding bit of each operand. Here is the table showing working of

this operator.

Bitwise OR ( A | B ) Decimal

A 1 (true) 1 0 0 1 0 0 100

B 1 (true) 1 0 0 0 1 1 99

Result 1 (true) 1 0 0 1 1 1 103

1 could be considered as ‘true’ and 0 as ‘false’.

~ - Bitwise unary NOT. It performs logical NOT operation on each bit of

operand. Following is the working of this operator.

Page 131: Programming Fundamentals

Programming Fundamentals Using C# 130

Bitwise NOT ( ~A ) Decimal

A 1 (true) 1 0 0 1 0 0 100

Result 0 (false) 0 1 1 0 1 1 27

1 could be considered as ‘true’ and 0 as ‘false’.

^ - Bitwise binary exclusive OR. The operator performs logical EX-OR on

each corresponding bits of each operand.

Bitwise Ex-OR ( A ^ B )

A 1 (true) 1 0 0 1 0 0 100

B 1 (true) 1 0 0 0 1 1 99

Result 0 (false) 0 0 0 1 1 1 7

1 could be considered as ‘true’ and 0 as ‘false’.

>> - Bitwise unary right shift. This operator shifts each bit of the operand

to right. The number of shifts is specified by the user. Spaces produced on

left due to shift are filled with zero. Right shift one time produce the same

effect as that of integer division by two.

Bitwise Right Shift ( A >> 1 ) one time right shift

A 1 (true) 1 0 0 1 0 0 100

A>>1 0 (false) 1 1 0 0 1 0 50

1 could be considered as ‘true’ and 0 as ‘false’.

<< - Bitwise unary left shift. This operator shifts each bit of the operand

to right. The number of shifts is specified as the second operand (hence it

could also be considered as binary operator). Spaces produced on right

due left shift are filled with zero. Left shift one time has equivalent effect

as that of integer multiplication.

Bitwise Left Shift ( A << 1 ) one time left shift

A 0 (false) 1 0 0 1 0 0 36

A<<1 1 (true) 0 0 1 0 0 0 72

1 could be considered as ‘true’ and 0 as ‘false’.

Syntax : <integer> <operator> <integer>

Page 132: Programming Fundamentals

Programming Fundamentals Using C# 131

S E M A N T I C S : The operators work with integer values only. Although we have

categorized it into unary operators but some authors consider it as binary operator

too. Left side operand is the value that is to be shifted whereas the right side

operand tells the number of shifts. The result produced is an integer value.

Following programs show the use of these operators:

Program – BitwiseOperators

using System; namespace BitwiseOperators { class Program { static void Main(string[] args) { uint A = 100, B = 99; // Instructions RESULT Console.Out.WriteLine(A & B); // 96 Console.Out.WriteLine(A | B); // 103 Console.Out.WriteLine(~A); // 4294967195??? Console.Out.WriteLine(A ^ B); // 7 Console.Out.WriteLine(A >> 1); // 50 Console.Out.WriteLine(A << 1); // 200 Console.Read(); } }}

S T R I N G C O N C A T E N A T I O N O P E R A T O R

“+” operator is an overloaded operator in C#. Overloaded means that it can

operate differently with different type of operands. It is binary operator. When

both operators are integers or reals it adds them. If one of them or both are string

type data then it joins them. In case one argument is and other is not, this operator

converts non-string operand into string operand and produces single string as

output.

Syntax : <operand1> <operator> <operand2>

S E M A N T I C S : To work, this binary operator requires at least one operand as a

string. The result of this operator is string too.

Following program shows the use:

Program – ConcatenationOperator

using System;

Page 133: Programming Fundamentals

Programming Fundamentals Using C# 132

namespace ConcatenationOperator { class Program { static void Main(string[] args) { int b = 191; float c = 89.98f; double d = 67.78; bool e = true; string s = "test string"; Console.Out.WriteLine(b + c); // 280.98 Console.Out.WriteLine(s + b); // test string191 Console.Out.WriteLine(s + c); // test string89.98 Console.Out.WriteLine(s + d); // test string67.78 Console.Out.WriteLine(s + e); // test stringTrue Console.Out.WriteLine(s + s); // test stringtest string Console.Out.WriteLine(s + " new string"); // test string new string Console.Read(); } } }

AS S I G N M E N T O P E R A T O R S

These operators are used to assign constant or variable value to other variable.

Assignment operator does not moves the value from one data item to other but it

copies it. For example int A=20, B=30; then A=B, means that value of B is copied

into A. Now A and B both have the value 30. The list of operators is given as under:

= - This is called the simple assignment operator. It is binary operator that

takes two arguments (operands). The value of right side operand is copied

into left side operand. Example: A=B, B’s value is copied into A. B’s own

value remains unaffected. This operator can also be used for cascaded

assignment. As a general rule, the variables in cascaded assignment must

be of same data type. For example int a,b,c; a=b=c=60; are valid

statements.

*= - Arithmetic Multiplication Assignment Operator. This operator also

require two operands. First it performs the arithmetic operation with both

operands and then assigns the result to the left operand. For example int

a=10,b=20; b*=a; The resulting value in b is 200.

/= - Arithmetic Division Assignment operator. It divides left operand

with right operand and assigns the result to the left operand. Example: int

a=40,b=10; a/=b; The result will be 4.

Page 134: Programming Fundamentals

Programming Fundamentals Using C# 133

%= - Arithmetic Remainder Assignment Operator. This operator divides

left operand with right operand and the resulting remainder value is

assigned to the left operand.

+= - Arithmetic Addition Assignment Operator. This operator adds left

and right operands and the resulting value is assigned to left operand.

-= - Arithmetic Subtraction Assignment Operator. This operator subtracts

right operand from left operand and assigns the result to left operand.

<<= - Arithmetic Left Shift Assignment Operator. This operand left shifts

the bits of left operand times right operand and new value is assigned to

left operand.

>>= - Arithmetic Right shift Assignment Operator This operator works the

same way as that of left shift.

&= - Arithmetic Bitwise AND Assignment Operator. The operator takes the

bitwise AND of both operands and assigns the result to left operand.

^= - Arithmetic Bitwise EX-OR Assignment Operator. This operator takes

the ex-OR of both operands and assigns the result to left operand.

|= - It takes the bitwise OR of both operands and assigns the result to left

operand.

Syntax : <numeric value> <operator> <numeric value>

S E M A N T I C S : The operator performs two operations simultaneously. First one is

arithmetic operation and second is the assignment. The result produce is integer

if both values are integer. If any operand is real the result would be real.

Here is the program showing the use of these operators:

Program – Arithmetic Assignment Operators

using System; namespace CompoundOperators { class Program { static void Main(string[] args) { uint a = 35, b = 5; double c = 23.6, d = 34.5; Console.WriteLine(a += b); // 40 // value changed by above statement is restored a = 35; Console.WriteLine(a -= b); // 30

Page 135: Programming Fundamentals

Programming Fundamentals Using C# 134

a = 35; Console.WriteLine(a /= b); // 7 a = 35; Console.WriteLine(a *= b); // 175 a = 35; Console.WriteLine(a %= b); // 0 a = 35; Console.WriteLine(a <<= 1); // 70 a = 35; Console.WriteLine(a >>= 2); // 8 a = 35; Console.WriteLine(a &= b); // 1 a = 35; Console.WriteLine(a |= b); // 39 a = 35; Console.WriteLine(a ^= b); // 38 Console.Read(); } } }

M I S C E L L A N E O U S O P E R A T O R S

Besides above discussed operators, C# uses some more operators that may be

called advanced operators. Few of them are discussed below whereas rest of the

operators are studied in rest of the book where their usage concepts are

explained.

C O N D I T I O N A L O P E R A T O R (?:) : This operator takes three arguments and

produces the results based on specified condition.

Syntax : <operand1> ? <operand2> : <operand3>

S E M A N T I C S : For operand1, a real, integer or boolean value or expression is

specified. If the result of operand1 is true then operand2 is returned otherwise

operand3 is returned. All three operands could be expressions as well. Here we

discuss only constant and variable operands.

The operator works on three operands and that is why it is called ternary operator.

The first operand (or expression) must be Boolean, and the next two operands

must be of the same type, such as numbers or strings. Here is the program:

Program – Ternary Operator

using System; namespace TernaryOperator

Page 136: Programming Fundamentals

Programming Fundamentals Using C# 135

{ class Program { static void Main(string[] args) { int a = 5, b = 6; bool bol = true; Console.Out.WriteLine(bol ? b : 8); // 6 bol = false; Console.Out.WriteLine(bol ? b : 8); // 8 Console.Out.WriteLine((a > b) ? "a is greater" : "b is greater"); // b is greater Console.Read(); } } }

NU L L -C O A L E S C I N G O P E R A T O R (??) : This operator takes two arguments and

produces the results based on first operand. To our understanding, we call it “This

or Alternate Operator”.

Syntax : <operand1> ?? <operand2>

S E M A N T I C S : First operand is tested if it is not null, its value is returned otherwise

second operand is returned.

Program – Alternate Operator

using System; namespace AlternateOperator { class Program { static void Main(string[] args) { string a = null; Console.Out.WriteLine(a ?? "test"); // test a = "Pakistan"; Console.Out.WriteLine(a ?? "test"); // Pakistan Console.Read(); } } }

Page 137: Programming Fundamentals

Programming Fundamentals Using C# 136

I S O P E R A T O R : This operator tells the type of the operand to which it is applied.

Syntax : <operand> is <data type>

S E M A N T I C S : The operator determines the data type of operand. It returns the

boolean value showing whether the operand belongs to given type or not.

Program – is Operator

using System; namespace isOperator { class Program { static void Main(string[] args) { string s = "i am student"; int a = 90; Console.Out.WriteLine(s is string); // True Console.Out.WriteLine(a is int); // True Console.Out.WriteLine(a is double); // False Console.Read(); } } }

7.2. TYPE CONVERSION AND CASTING Generally you as programmer work with variables of same data types. However there are

the situations where, you may need to assign data item of one data type to other as shown

in the following code segment.

int a = 400; float b=56.78f; a=b; // Error: You cannot assign float variable to integer variable.

To handle such situations, it is required to convert one type of data to other. This is done

using conversion and casting process. The changing of type is done either automatically by

the compiler or you need to write command for explicit conversion.

7.2.1. IMPLICIT CONVERSION Conversion from smaller data type to larger data is done automatically by the

compiler. Smaller data type contains small number of bits as compared to larger

data type. So there is no loss of information by this conversion. Following code

shows this idea.

Page 138: Programming Fundamentals

Programming Fundamentals Using C# 137

int a = 400; // smaller data type long b=56; // larger data type b=a; // Implicit Conversion: You cannot assign float variable to // integer variable.

Considering above rule, here is the list of possible implicit conversions.

Data Type Can be converted to

sbyte short, int, long, float, double, decimal

byte short, ushort, int, uint, long, ulong, float, double, decimal

short int, long, float, double, decimal;

ushort int, uint, long, ulong, float, double, decimal

Char ushort, int, uint, long, ulong, float, double, decimal

uint long, ulong, float, double, decimal

int long, float, double, decimal

long float, double, decimal

ulong float, double, decimal

float double

In above table, you can see that left side column contains small data type whereas all other data types in corresponding row is larger.

7.2.2. EXPLICIT CONVERSION (CASTING) When large data type is required to be converted into small data type, there is

chance of data loss. For example a variable of 64-bit cannot be converted into 32-

bit variable because 32 extra bits will not be copied into smaller data type variable.

The compiler needs to confirm from programmer when doing so. Therefore

compiler needs explicit commands for this purpose. This explicit task is called the

casting. Following code snippet shows the use of casting.

long longvar=78; int smallvar=900; smallvar=longvar; // invalid statement, will produce error smallvar=(int) longvar; // valid statement. Will compile successfully

Page 139: Programming Fundamentals

Programming Fundamentals Using C# 138

It is to clear that due to casting, data loss occurs and it is responsibility of

programmer to understand the effect. As one can see we have used new data type

name in parenthesis i.e. (int). This is called the type casting and following program

shows its use.

Program – Type Casting

using System; namespace ConversionAndCasting { class Program { static void Main(string[] args) { int a = 45; long b = 4500450045; a = (int)b; Console.Out.Write(a);//205482749 Console.Read(); } }}

7.2.3. STRING CONVERSION Converting any data type to string is a different process. There are two ways to

convert ToString() function and concatenation operator. Following program

shows the use of ToString() method.

Program – String Conversion

using System; namespace StringConversion { class Program { static void Main(string[] args) { int a = 900; string s = a.ToString(); int b = s; // Error Console.Out.WriteLine(a.ToString()); Console.Read(); } } }

Page 140: Programming Fundamentals

Programming Fundamentals Using C# 139

In this program a variable of type integer is declared. At next line using

a.Tostring() method it is converted into string. The next line will produce the

error and s is a string which can not be assigned to integer variable.

If any string is concatenated with some other data type variable, the result

produced is also a string. Following program shows this use.

Program – String Conversion Concatenation

using System; namespace StringConversionConcatenation { class Program { static void Main(string[] args) { int a = 40; string b = "it is programming"; string c = b + a; Console.Out.WriteLine(c); // it is programming40 Console.Read(); } } }

7.3. EXPRESSIONS Computer programs are written to perform calculations and computations. An expression

is sequence of literals, variables and operators like 3+5*x. The result of the expression is

value of some data type. You can mix any type of literals, variables and operators but

according to syntax.

In expressions, the operators are solved according to their precedence. But by using

parenthesis (), the precedence of operators can be changed. Following table shows the

expressions and their results:

Expression Results

7+8*3 (7+8)*3

31 45

An expression having one type of operators is named according to type of operators. For

example, 8+9/3 is arithmetic expression. “A > B” is comparative expression and “A && B”

is logical expression. Normally the programmers use mixed type of expressions like “A &&

(B/7)”. We cannot categorize such type of expressions.

Program – Expressions

Page 141: Programming Fundamentals

Programming Fundamentals Using C# 140

using System; namespace Expressions { class Program { static void Main(string[] args) { int a = 5; string s; s=(a % 2 == 0) ? "Number is Even" : "Number is Odd"; Console.Out.WriteLine(s); // Number is Odd Console.Read(); } } }

This program has number of expressions. “int a=5;” is an assignment expression , “a%2”

is arithmetic expression, “a%2==0” is mixed expression, “s=(a%2==0)” is again a mixed

expression.

7.4. INPUT/OUTPUT STATEMENTS REVISITED IO statements, already discussed, are examined here in more detail.

C O N S O L E .O U T .WR I T E L I N E(…)

This statement is used to write literals and variables to the console screen.

Anything given in parenthesis to Console.Out.WriteLine() statement is

called the parameters or arguments. If parameter is literal (constant of any type)

it is printed as it is.

// Statement Result Console.Out.WriteLine(6); // 6 Console.Out.WriteLine(56.89); // 56.89 Console.Out.WriteLine(‘A’); // A Console.Out.WriteLine(“a string”); // a string

There are two basic output statements, Console.Out.Write() and

Console.Out.WriteLine(). Both work in the same way except that

WriteLine() prints its arguments on the screen and then brings the output

cursor on next line where next output is printed as shown below:

Page 142: Programming Fundamentals

Programming Fundamentals Using C# 141

Figure 7 - 1: Using Console.Out.WriteLine

Console.Out.Write() prints the argument on the same line. No new line is

introduced as shown below:

Figure 7 - 2: Using Console.Out.Write

7.4.1. FORMATTED OUTPUT The output statement can include variables and literals of different types. If one

of the argument is string, in concatenation statement, all other literals and

variables are converted into string.

int a=20; Console.Out.WriteLine(“ The Roll No. of Mr. Ahmed is ::” + a); Console.Out.WriteLine(“ The Roll No. of Mr. Ahmed is ::” + a + “ and class is BSCS”);

In both above statements, string literals are concatenated with integer variable.

When we have to output the values of variables as part of strings, we can embed

Page 143: Programming Fundamentals

Programming Fundamentals Using C# 142

the variables in between string literals as shown above. Another way of

incorporating values of variables in the strings is to use formatted way as shown

below:

int b=40; Console.Out.WriteLine(“ The value of b ” + b + “ is below 100”); Console.Out.WriteLine(“ The value of b {0} is below 100”,b);

Output of both statements is same “The value of b is below 100”. Second

Console.Out.WriteLine() statement will substitute the {0} parameter with

value of b. Using this way, we can provide as many arguments as we like. Following

code segment shows this use.

int b=40,c=700,d=670; Console.Out.WriteLine(“ The value of b is {0} and c is {1}”,b,c); Console.Out.WriteLine(“ The value of b is {0} and c is {1} and d is {2}”,b,c,d);

First output statement will substitute b in place of {0} and c in place of {1}. Similarly

second statement will substitute b,c and d in place of {0},{1} and {2} respectively.

The expression {0}{1} and {2} are called placeholders.

You can provide literals instead of variables.

int b=2; string s=”Pakistan”; Console.Out.WriteLine(“{0} is {1}nd capital of {3}”, ”Islamabad”,b,s);

OutPut: Islamabad is 2nd capital of Pakistan

NU M B E R S A N D F O R M A T S

A format is a way to write numbers. For example a number could be represented

in usual notational format or in exponential form. In usual notational form a

number 546786500 could be written as 5.467865X108. There are different ways to

express a number. These ways or formats are specified by letters like ‘C’ that have

particular meanings. These letters are known as format specifiers. Precision is an

integer value that has different meaning for different format specifiers. Following

list explains different format specifiers:

Page 144: Programming Fundamentals

Programming Fundamentals Using C# 143

C U R R E N C Y F O R M A T (“C” O R “C”) : The result displayed will be in the form

of currency notation including currency symbol. The precision is also

provided with format specifier. For example:

Console.Out.WriteLine(“ The Amount {0:C2} is

enough”,67.9876);

will output $67.99. in {0:C2}, 0 specifies the argument number, C specifies

the currency format and 2 specifies the precision, the number of digits to

which currency should be written.

IN T E G E R F O R M A T (“D” O R “D”) : This format specifier is used to printout

integer numbers. For example:

Console.Out.WriteLine(" The amount {0:d3}", 8787800);

Console.Out.WriteLine(" The amount {0:d8}", 8787800);

In first output statement, the integer value 8787800 will be displayed as it

is. Precision number i.e. 3, that is smaller than actual number of digits does

not reduce the number of digits and prints all digits. But if precision digit

is larger than actual number of digits then 0s are appended on left side of

actual digits to make precision equivalent to specified number. In second

output statement, the output is “08787800”.

EX P O N E N T I A L F O R M A T(“E” O R “E”) : In this format the precision

indicates the number of digits after decimal point. The output is

67.98E+004.

Console.Out.WriteLine(" The amount {0:E3}", 67.9876);

IN T E G E R O R DE C I M A L NU M B E R (“F” O R “F”) : It specifies the number of

digits after decimal point. This format is similar to Currency format except,

currency symbol is not used. The output is 67.99.

Console.Out.WriteLine(“ The Amount {0:f2} is

enough”,67.9876);

NU M B E R N U M B E R F O R M A T (“N” O R “N”) : this format represents the number in “number” format where thousands and millions separator is included. The output is “58,789.988”. Console.Out.WriteLine(" The amount {0:N3}", 56789.9876);

PE R C E N T A G E F O R M A T (“P” O R “P”): It multiplies the number with 100 and places “%” sign after the number. Precision digit specifies the number of digits after decimal point. The output is “58700.000 %”. Console.Out.WriteLine(" The amount {0:P3}", 567);

Page 145: Programming Fundamentals

Programming Fundamentals Using C# 144

Hexa- Decimal Forma t ( “X” or “x”) : This format displays the number

in hexadecimal number format. The precision specifies the minimum

number of digits to be used to represent the number. If the minimum

number is smaller than actual digits, it does not affect the output (first

output statement). If it is greater than the actual number of digits, extra

zeros are appended on left of the output (second output statement).

Console.Out.WriteLine(" The amount {0:x2}", 567); Console.Out.WriteLine(" The amount {0:x5}", 567); The output is “237” and “00237”.

Following program shows the use of these format specifiers and their output.

Program – Format Specifiers

using System; namespace FormatSpecifiers { class Program { static void Main(string[] args) { double a = 56789.9876; int b = 8787800; int c = 567; Console.Out.WriteLine(" Currency Format {0:C3}", a); Console.Out.WriteLine(" Currency Format {0:C8}", a); Console.Out.WriteLine(" Decimal Format {0:d2}", b); Console.Out.WriteLine(" Decimal Format {0:d8}", b); Console.Out.WriteLine(" Exponential Format {0:E2}", a); Console.Out.WriteLine(" Exponential Format {0:E8}", a); Console.Out.WriteLine(" Integer Format {0:F4}", a); Console.Out.WriteLine(" Integer Format {0:F4}", 8); Console.Out.WriteLine(" Number Format {0:N3}", a); Console.Out.WriteLine(" Number Format {0:N8}", a); Console.Out.WriteLine(" Percentage Format {0:P2}", c); Console.Out.WriteLine(" Percentage Format {0:P8}", c); Console.Out.WriteLine(" Hexa Decimal Format {0:x2}", c); Console.Out.WriteLine(" Hexa Decimal Format {0:x5}", c); Console.Read(); } } }

Output: Currency Format $56,789.988 Currency Format $56,789.98760000 Decimal Format 8787800 Decimal Format 08787800 Exponential Format 5.68E+004 Exponential Format 5.67899876E+004 Integer Format 56789.9876 Integer Format 8.0000 Number Format 56,789.988

Page 146: Programming Fundamentals

Programming Fundamentals Using C# 145

Number Format 56,789.98760000 Percentage Format 56,700.00 % Percentage Format 56,700.00000000 % Hexa Decimal Format 237 Hexa Decimal Format 00237

C U S T O M F O R M A T S F O R N U M B E R S

The programmer can also define his own formats for numbers. Any user defined

format is known as custom format. Following table shows the way to define your

own format specifier.

Specifier Description

0 Indicates a digit. If at this position of the result a digit is missing, a zero is written instead. Console.Out.WriteLine("0 Format Specifier {0:0.00}",456.987); Console.Out.WriteLine("0 Format Specifier {0:0000.000000}", 456.987); Output: “0 Format Specifier 456.99”. First statement specifies that first argument must have integers before point sign and two integers after that. Precision before and after the point are less than the actual digits in actual value so all digits are displayed. Output: “0 Format Specifier 0456.987000”. In second output statement, the digits of format specifier are more than digits in actual value before and after the point. So actual value digits are appended with zeros to make them equal to access specifier.

# Indicates a digit. Does not print anything if at this position in the result a digit is missing. Console.Out.WriteLine("0 Format Specifier {0:#.##}",456.987); Console.Out.WriteLine("0 Format Specifier {0:####.######}", 456.987); First output statement result: “# Format Specifier 456.99”. Format specifier digits are smaller than original value digits so no. of access specifier digits are ignored. Second statement result: ”# Format Specifier 456.987”. No. of format specifier digits are greater than actual value digits so nothing is printed on place of extra digits.

Space specifier. It is used to insert spaces in between the number. Console.Out.WriteLine(" <space> Format Specifier {0:## ## .## ## ##}", 456.987); Output: “<space> Format Specifier 4 56 .98 7”

. Determines the position of point in the value.

, Thousands separator for the respective “culture”. Console.Out.WriteLine(" , Format Specifier {0:#,###}", 4569876); Output: “4,569,876”

% Multiplies the result by 100 and prints the character for Percent Console.Out.WriteLine("% Format Specifier {0:%###.###}", 456.987);

Page 147: Programming Fundamentals

Programming Fundamentals Using C# 146

Output: “% Format Specifier %45698.7”.

E0 or

E+0 or E-0

Indicates an exponential notation. The number of zeroes indicates the number of signs of the exponent. The sign "+" means that we always want to represent also the number’s sign while minus means to display the sign only if the value is negative Console.Out.WriteLine(" E Format Specifier {0:E4}", 4569876); Output: 4.5699E+006 Digit after “E” specifies that how many digits should be there in fractional part.

Following program shows the use of custom formats:

Program – Custom Formats

using System; namespace CustomFormats { class Program { static void Main(string[] args) { Console.Out.WriteLine("0 Format Specifier :: {0:0.00}",456.987); Console.Out.WriteLine("0 Format Specifier :: {0:0000.000000}", 456.987); Console.Out.WriteLine("# Format Specifier :: {0:#.##}", 456.987); Console.Out.WriteLine("# Format Specifier :: {0:####.######}", 456.987); Console.Out.WriteLine(" <space> Format Specifier :: {0:## ## .## ## ##}", 456.987); Console.Out.WriteLine(" . Format Specifier :: {0:## ## .#### ##}", 456.987); Console.Out.WriteLine(" , Format Specifier :: {0:#,###}", 4569876); Console.Out.WriteLine("% Format Specifier :: {0:%###.###}", 456.987); Console.Out.WriteLine(" E Format Specifier ::{0:E4}", 4569876); Console.Read(); } } } Output: 0 Format Specifier :: 456.99 0 Format Specifier :: 0456.987000 # Format Specifier :: 456.99 # Format Specifier :: 456.987 <space> Format Specifier :: 4 56 .98 7 . Format Specifier :: 4 56 .987 , Format Specifier :: 4,569,876 % Format Specifier :: %45698.7 E Format Specifier ::4.5699E+006

7.4.2. CONSOLE INPUT The Standard Input Device is part of the Operating System. This OS software the

default input device communication. Part of OS that controls the input and output

devices is called the driver. By default, computer reads from keyboard driver.

Operating system can change the driver for default device and default device will

Page 148: Programming Fundamentals

Programming Fundamentals Using C# 147

also be changed. As discussed previously, Console.Read() and

Console.ReadLine() methods are used for console input. When any of this

method is used (User enters some data and presses [Enter] key) to read data from

default input device (DID), the computer stops processor from its normal work

(interrupt occurs) and data from DID is transferred to processor for processing.

The transferred data is always in the form of string data type. We can receive this

entered data in some variable.

C O N S O L E .RE A DL I N E ()

The use of Console.ReadLine() method is shown in following program:

Program – Console.ReadLine()

using System; namespace ConsoleReadLine { class Program { static void Main(string[] args) { string yourName; yourName = Console.ReadLine(); Console.Out.WriteLine("You have entered :: {0}", yourName); Console.Read(); } } } Sajid Iqbal You have entered :: Sajid Iqbal

C O N S O L E .RE A D()

This method works differently from Console.ReadLine(). It reads only one

character and returns its code. Following program shows it use:

Program – Console.Read()

using System; namespace ConsoleRead { class Program { static void Main(string[] args) { int a; a=Console.Read(); Console.Write("You entered :: {0}", a); Console.Read(); } }

Page 149: Programming Fundamentals

Programming Fundamentals Using C# 148

} a You entered :: 97

It is to note that when user enters a character, it is not read presses the [Enter]

key. In this case two characters are input by the user for example character “a”

and “Enter”. The first one is read by first Console.Read() and second is read by

second Console.Read() in above program. Your program may not stop to show

the output. To stop the program and see the output, you may write two

Console.ReadLine() statements as shown below:

Program – Console.Read()

using System; namespace ConsoleRead { class Program { static void Main(string[] args) { int a; a=Console.Read(); Console.Write("You entered :: {0}", a); Console.ReadLine(); Console.ReadLine(); } } } a You entered :: 97

C O N S O L E .RE A DK E Y ()

The Console.Read() method does not read a character until user presses the

[Enter] key. Console.ReadKey() method reads the key as soon as user presses

it. The read information is not a character but it is of special type

“ConsoleKeyInfo”. The use of this method is shown below:

Program – Console ReadKey Method

using System; namespace ConsoleReadKey { class Program { static void Main(string[] args) { ConsoleKeyInfo a;

Page 150: Programming Fundamentals

Programming Fundamentals Using C# 149

a = Console.ReadKey(); Console.Out.WriteLine(a.KeyChar); Console.Read(); } } }

More about this method will be discussed in later chapters.

R E A D I N G NU M B E R S

Numbers in C# are not read directly. As stated above, everything read from

keyboard is considered as string. If you intend to read numbers, read them as

string and then convert them into numbers. The process of converting string into

numbers is known as Parsing. Following program shows the use:

Program – Reading a Number User Interaction

using System; namespace ReadingNumbers { class Program { static void Main(string[] args) { int aNumber; string input; input=Console.ReadLine(); aNumber = Convert.ToInt16(input); Console.Out.WriteLine(aNumber); Console.Out.WriteLine(input + input); Console.Out.WriteLine(aNumber + aNumber); Console.Read(); } } }

25 25 2525 50

First output statement prints the read number converted into integer. Second

output statement prints the read data which is string. Here we have used “+”

operators that when used with strings acts as concatenation operators. Our read

data is “25” so “2525” is printed. In third output statement, the read data is

converted into integer form and “+” operator adds them resulting in “50”.

Another way to do this is to use parse method. This method is available for all data

types. Here is the same program with same interaction.

Page 151: Programming Fundamentals

Programming Fundamentals Using C# 150

Program – Reading a Number User Interaction

using System; namespace ReadingNumbers { class Program { static void Main(string[] args) { int aNumber; string input; input=Console.ReadLine(); aNumber = int.Parse(input); Console.Out.WriteLine(aNumber); Console.Out.WriteLine(input + input); Console.Out.WriteLine(aNumber + aNumber); Console.Read(); } } }

25 25 2525 50

You can write the Console.ReadLine() command inside Parse() method as

shown below:

Program – Reading a Number User Interaction

using System; namespace ReadingNumbers { class Program { static void Main(string[] args) { int aNumber; string input; aNumber=int.Parse(Console.ReadLine()); Console.Out.WriteLine(aNumber); Console.Out.WriteLine(input + input); Console.Out.WriteLine(aNumber + aNumber);

Console.Read(); } } }

25 25 2525 50

If you enter different type of data, you may use relevant parse method as shown

below:

Page 152: Programming Fundamentals

Programming Fundamentals Using C# 151

Program – Parse Method

using System; namespace ParseMethod { class Program { static void Main(string[] args) { int a; double b; char c; a = int.Parse(Console.ReadLine()); b = double.Parse(Console.ReadLine()); c = char.Parse(Console.ReadLine());

Console.Out.WriteLine(" You entered {0}, {1}, {2}", a, b, c); Console.Read(); } } }

User Interaction:

678 23.25

b

You entered 678, 23.25, b

Warning: You must be careful about data entry. If first line is to read integer, you

must enter integer and so on. If you enter integer where double is expected, there

would be error in your program.

7.5. A REAL PROBLEM In this section we introduce a real life problem. You are required to find out the area of

rectangle. The formula of finding rectangle area is ( Area=Height*Width). You need two

parameters “height” and “width” to find out area. The things you will require could be

considered as input and the result you will calculate could be considered as output. Hence

“height” and “width” are input and “area” is output. Here is the program solving this

problem:

Program – Area of Rectangle

using System; namespace AreaOfRectangle { class Program { static void Main(string[] args) { double height, width, area; Console.Out.WriteLine("Please enter rectangle height:"); height = double.Parse(Console.ReadLine()); Console.Out.WriteLine("Please enter rectangle width:");

Page 153: Programming Fundamentals

Programming Fundamentals Using C# 152

width = double.Parse(Console.ReadLine()); area = height * width; Console.Out.WriteLine(" The area of rectangle: {0}", area); Console.Read(); } } }

Please enter rectangle height: 45.25 Please enter rectangle width: 20.15 The area of rectangle: 911.7875

Page 154: Programming Fundamentals

Programming Fundamentals Using C# 153

Chapter 8

Decision Making During programming, a programmer needs to make decisions based on different

condition. These decisions either execute one set of statements or the other. Decision

making in an important part of programming and programing languages provide

special type of instructions for this purpose. All these type of instructions are called

the decision statements. The decision statements base their operation (decision) on

the result of expression provided as argument. The expression result must be

computed to Boolean value. In this chapter, we will discuss various decision

statements found in C# and the way of using them.

There are two type of operators that produce their results as Boolean values:

Conditional Operators and Logical Operators.

8.1. OPERATORS RESULTING IN BOOLEAN VALUES There are multiple operators in C# that return result as Boolean (true, false) value. Based

on these returned results, specific code is executed.

8.1.1. CONDITIONAL OPERATORS Decision statements use conditional operators to make decisions about executing

a set of instructions. These are following six operators

These are binary operators that produce Boolean result (true, false). All binary operators take two operands. These operands could be either direct values, variables or expressions that result in single values. The syntax of conditional operators is as follows:

Operator Meaning

> Greater Than

>= Greater Than or Equal to

< Less Than

<= Less Than or Equal to

== Equal to

!= Not Equal to

Page 155: Programming Fundamentals

Programming Fundamentals Using C# 154

Syntax : <Value or variable> <conditional operator> <value of

variable>

And

Syntax : <Expression > <conditional operator> <Expression>

The expression should result in a single value. Following C# statements shows the

use of comparison operators

C# Comparison Operators.

int a=500,b=698; Console.Out.WriteLine( 5 > 7); // false Console.Out.WriteLine((9+8) < (8*6)); //true Console.Out.WriteLine( a >= b); // false

Comparison operators can compare values or expressions of different types. For

example, you can compare integer value with floating point value or you can

compare a character with integer value as shown below:

Mixed Data Type Comparison

int a = 500; double d = 500; Console.Out.WriteLine(d==a); // true

A character data type could also be used for comparison as its codes are used in

calculations. However string data type is not comparable with numbers or

characters. A string could be compared with string only. Following program shows

the use of conditional operators with different data types.

Program: Conditional Operators

using System; namespace ConditionalOperators { class Program { static void Main(string[] args) { int a = 500; double d = 500; int aa = 500, b = 698; char c='A'; string s = "Pakistan";

Page 156: Programming Fundamentals

Programming Fundamentals Using C# 155

string p = "Islam"; Console.Out.WriteLine(5 > 7); // false Console.Out.WriteLine((9 + 8) < (8 * 6)); //true Console.Out.WriteLine(aa >= b); // false Console.Out.WriteLine(d==a); // true Console.Out.WriteLine((a + d) != (c + a)); // true Console.Out.WriteLine(s == p); // false Console.Read(); } } }

8.1.2. LOGICAL OPERATORS The logical operators && (logical AND), || (logical OR), ! Logical Not and ^ Logical

Exclusive OR are only used on Boolean expressions (values of type bool). The

logical AND operator results in “true” when both operands contain “true” value.

The logical OR results in “false” when both operands contain “false” value. As the

syntax of these operators, you can either use direct Boolean values, variables or

expressions that result into Boolean value. Following program shows the use of

these operators:

Program: Logical Operators

using System; namespace LogicalOperators { class Program { static void Main(string[] args) { int a = 5, b = 6; char ch1 = 'B', ch2 = 'c'; bool b1 = true, b2 = false; double d1 = 7.8, d2 = 9.7; // Operator '&&' cannot be applied to operands // of type 'int' and 'int' //Console.Out.WriteLine((5 + 6) && (7 + 8)); Console.Out.WriteLine((5 < 6) && (8 > 9)); // false Console.Out.WriteLine(true && true); // true Console.Out.WriteLine(b1||b2); // true //Operator '&&' cannot be applied to //operands of type 'char' and 'char' //Console.Out.WriteLine(ch1 && ch2); //Operator '&&' cannot be applied to

Page 157: Programming Fundamentals

Programming Fundamentals Using C# 156

//operands of type 'double' and 'double' //Console.Out.WriteLine(d1 && d2); Console.Out.WriteLine((d1 < ch1) && (d2 >= b)); // true Console.Out.WriteLine(!true); // false Console.Out.WriteLine(!(8 < 9)); // false Console.Out.WriteLine((8<9) ^ (8>4)); // false Console.Read(); } } }

In above example, we can see that && and || operators require Boolean values or

expressions resulting in Boolean values on both sides.

S H O R T C I R C U I T I N G : && and || operations can perform short circuiting in

evaluation. As said above, the && operator produces “true” result if both operands

are “true”. In any other case the result is “false”. If first operand is found to be

“false”, there is no need to evaluate the second operand as the result will be

ultimately “false”. In following statement, you can understand the short circuiting.

Console.Out.WriteLine(( 8>9) && (9 >5));

There are two expressions (8 > 9) and (9 > 5). We can see that first expression

evaluates to “false”. Now whatever the result of second expression is, final result

will be “false”. Hence there is no need to evaluate the second expression.

However, if first expression resulted in “true” then to find out overall result,

second expression was required to be evaluated.

Similarly “||” operator also use short circuiting. The result of logical OR is “true” if

any one operand or expression is true. In any other case its result is “false”. Now

if during evaluation it is found that first expression results in “true” value,

whatever the value of second operand or expression is, overall value would be

“true”. Hence there is no need to evaluate the second operand or expression.

Console.Out.WriteLine(( 8 < 9) || (9 >5));

However, if first operand results in false value, now it is required to calculate the

second operand.

Logical Not is unary operator hence it is full-circuit operator. Logical Exclusive OR

is binary and full circuit operator.

Page 158: Programming Fundamentals

Programming Fundamentals Using C# 157

8.2. CONDITIONAL STATEMENTS After reviewing the operators resulting in Boolean values, we discuss the conditional

statements that make decision based on these operators.

8.2.1. “IF” STATEMENT “If” statement is one of the decision statements available in C#. Its syntax is shown

below:

SYN TA X if ( <Boolean value> ) { // Body of if statement; }

EXA MP L E if( 8< 9) { Console.Out.WriteLine(“ 8 is smaller than 9”); }

The reserved word “if” is called the if clause. “If” statement includes the “if-

clause”, opening parenthesis and closing parentheses. Between these two

parentheses, there is some Boolean value of an expression which results in

Boolean value. Then there is the body of if statement enclosed in two braces, “{“

opening brace and “}” closing brace. The Boolean expression or Boolean value in

parenthesis can be “true” or “false”. If it is “true”, the body of “if” statement is

executed. If the result of Boolean expression is “flase” the body of if statement will

not be executed. The body of if statement could contain one or more statements.

If there is only one statement, then curly brackets are optional but if there are

more than one statements, curly brackets are essential. Following figure shows

the flow diagram of if-statement.

Figure 8 - 1: Control Flow of if-Statement

Page 159: Programming Fundamentals

Programming Fundamentals Using C# 158

It is to note that in C# Boolean expression must result the value of type Boolean.

In other languages, non-zero integer value is considered as “true” and zero as

“false” but in C#, integer values are not considered as Boolean.

Following program shows the use of if-statement:

Program: If-Statement

using System; namespace IfStatement { class Program { static void Main(string[] args) { int number; number = int.Parse(Console.ReadLine()); if (number % 2 == 0) { Console.WriteLine("The number is Even"); } } } }

In this program, Console.ReadLine() statement reads a number from user.

This read number (which is in string data type) is then parsed and converted into

integer and assigned to variable “number”. Next the if-statement is present where

“number%2==0” is complex expression that results into Boolean value. First the

value in number is divided by 2 and then the remainder is compared with zero. If

the remainder is zero then body of if-statement is executed. In this if-body, there

is one output statement that prints the string literal “The number is Even”. If the

result of expression is “false” the body of if-statement excluded and program ends.

As you can see, every example program contains few common lines which are

listed below:

Program: if-Statement2 (Skeletal Program)

using System; namespace IfStatement2 { class Program { static void Main(string[] args) { // Body of Main

Page 160: Programming Fundamentals

Programming Fundamentals Using C# 159

} } }

To keep code size small in our book, we will next exclude these common lines of

code and will provide only the code for “Body of Main”. As a reader, you must

understand that given body of main in included in above given code. To explain

the idea following program lists both views:

Program: If-Statement2

Complete Program

using System; namespace IfStatement2 { class Program { static void Main(string[] args) { int num1,num2; num1 = int.Parse(Console.ReadLine()); num2 = int.Parse(Console.ReadLine()); if (num1 > num2) { Console.Out.WriteLine("Num1 is greater and is {0}", num1); } Console.WriteLine("Larger number is printed"); Console.Read(); } } }

Short Program

static void main(string[] args) { int num1,num2; num1 = int.Parse(Console.ReadLine()); num2 = int.Parse(Console.ReadLine()); if (num1 > num2) { Console.Out.WriteLine("Num1 is greater and is {0}", num1); } Console.WriteLine("Larger number is printed"); Console.Read(); }

From now onward, we will present only short program and you can understand

how it would be fixed inside complete program. The last instruction

Page 161: Programming Fundamentals

Programming Fundamentals Using C# 160

“Console.Read();” is only to stop the output screen to view the output. It will

also be omitted in next example programs.

8.2.2. FLOW CHART DIAGRAM It is a pictorial view of the program that is used to better understand the code and

language constructs you have written. We have already seen a picture showing

the control flow of if-statement. In this section we discuss different symbols and

their use to represent the program.

FLOW C HART BA S IC EL EM EN T S

A large set of figures and shapes is defined for visual view of program. We will

discuss only important and required symbols here. Following table describes the

basic symbols:

Symbol Name Description

Flow Line Flow line connectors show the direction that the process flows or control flows

Terminator Terminators show the start and stop points in a process. When used as a Start symbol, terminators depict a trigger action that sets the process flow into motion.

Decision Indicates a question or branch in the process flow. Typically, a Decision flowchart shape is used when there are 2 options (Yes/No, etc.)

Connector (Inspection)

This symbol is used as a Connector to show a jump from one point in the process flow to another. Connectors are usually labeled with capital letters (A, B, AA) to show matching jump points. They are handy for avoiding flow lines that cross other shapes and flow lines. They are also handy for jumping to and from a sub-processes defined in a separate area than the main flowchart.

Data (I/O)

The Data flowchart shape indicates inputs to and outputs from a process. As such, the shape is more often referred to as an I/O shape than a Data shape

Process Show a Process or action step. This is the most common symbol in both process flowcharts and process maps.

Page 162: Programming Fundamentals

Programming Fundamentals Using C# 161

FLOW C HART PRO GRA M EXA MP L E

The above program is now shown pictorially below:

We will not provide the complete program flow diagrams from now onward. As a

student, you must practice by drawing flowcharts of different programs given in

this book or you write yourself.

8.2.3. MORE ON “IF” STATEMENT Curly brackets in if statement are optional if there is only one statement in the

body of if. Following example shows the use:

Program: Simple and Compound Statements

static void main(string[] args) { int num1,num2; num1 = int.Parse(Console.ReadLine()); num2 = int.Parse(Console.ReadLine()); if (num1 > num2) {

Yes

Start of Program

int num1,num2;

num1 = int.Parse(Console.ReadLine()); num2 = int.Parse(Console.ReadLine());

if (num1 > num2)

Console.Out.WriteLine("Num

1 is greater and is {0}", num1);

Console.WriteLine("Larger number is printed");

End of Program

No

Figure 8 - 2: Program Flow Chart

Page 163: Programming Fundamentals

Programming Fundamentals Using C# 162

Console.Out.WriteLine("Num1 is greater and is {0}", num1); } Console.WriteLine("Larger number is printed"); } static void main(string[] args) { int num1,num2; num1 = int.Parse(Console.ReadLine()); num2 = int.Parse(Console.ReadLine()); if (num1 > num2) Console.Out.WriteLine("Num1 is greater and is {0}", num1); Console.WriteLine("Larger number is printed"); }

Both programs are equivalent and will produce same output. However if more

than one statements needs to be included in the body of if, curly brackets are

compulsory. Look at the following program.

Program: If-Statement3

// Program to find the area of triangle double height, width,area=0; height = int.Parse(Console.ReadLine()); width = int.Parse(Console.ReadLine()); if (height > 0 && width > 0) { area = (height * width) / 2; Console.Out.WriteLine(“Area::{0}”,area); } Console.Out.WriteLine("Area calculation done"); Output: if-statement results in “true” (let width=5, height=10) Area::25

Area calculation done

Output: if-statement results in “false” Area calculation done

P R O G R A M DE S C R I P T I O N : If-statement3 program reads two double type values

from user. Using if-statement, it checks whether both entered values are greater

than zero. Both left and right expressions of && operator produce Boolean result

and finally && operator too produces Boolean result. After if statement

evaluation, if the result is “true”, the body of if-statement executes. Suppose if the

result is “true”, if body starts and “area” is calculated and then it is displayed on

console using output statement. After output statement, the body of if-statement

ends and last output statement executes. NOW what happens if the result of if-

Page 164: Programming Fundamentals

Programming Fundamentals Using C# 163

statement is “false”, the body of “if” is not executed and control moves to end of

body of “if” and “Console.Out.WriteLine("Area calculation

done");” output statement executed only.

Now we consider the effect of curly brackets. Consider the following code which

is same as that of above but only curly brackets are removed.

Program: If-Statement4

// Program to find the area of triangle double height, width,area=0; height = int.Parse(Console.ReadLine()); width = int.Parse(Console.ReadLine()); if (height > 0 && width > 0) area = (height * width) / 2; Console.Out.WriteLine(area); Console.Out.WriteLine("Area calculation done");

Output: if-statement results in “true” (let width=5, height=10) Area::25

Area calculation done

Output: if-statement results in “false” Area:: 0

Area calculation done

P R O G R A M DE S C R I P T I O N : In if-statement4 program when curly brackets are

removed then body of if-statement is restricted to one immediate statement that

is “area = (height * width) / 2;”. The output statement

“Console.Out.WriteLine(area);” is now out of the body of if-

statement. During program execution, if the result of if-statement is “true”, the

“area” is calculated, area is printed and “Area calculation done” is printed. If the

result of if-statement is “false”, its body is excluded which is single statement only.

“area” is printed but it has garbage value and then “Area calculation done” is

printed.

You can understand from above example that if curly brackets are not used the

results may differ from the expected results. It is recommended to use curly

brackets even a single statement is used in the body of “if”.

8.2.4. “IF-ELSE” STATEMENT With if-statement, a group of statements is either executed or not based on the

result of if-statement expression. “if-else” statement provides two groups of

statements. If result of if expression is true, first group of statements is executed

but if the result if “false”, second group of statements is executed. First group is

Page 165: Programming Fundamentals

Programming Fundamentals Using C# 164

known as body of “if” whereas second group is called the body of “else”. Here is

the syntax of “if-else”.

if-else syntax

if (<Boolean expression>)

{

Body of the conditional statement;

}

else

{

Body of the else statement;

}

Following flow chart shows the flow of “if-else”.

Figure 8 - 3: Control Flow of if-else Statement

Following program shows the use of “if-else” statement.

Program: if-else

static void Main(string[] args) { int a; a = int.Parse(Console.ReadLine()); if (a % 2 == 0) { Console.Out.WriteLine("You entered Even number"); } else { Console.Out.WriteLine("You entered Odd number"); } }

Page 166: Programming Fundamentals

Programming Fundamentals Using C# 165

P R O G R A M DE S C R I P T I O N : In this program the user enters a number that is parsed

and assigned to a variable “a”. Next “a” is tested in if-statement, whether is

completely divisible by 2 or not. If we divide the number with 2 and there is zero

remainder, then it is completely divisible by 2 and expression results in “true”. In

case the result is true, the body of “if” is executed and the output is “You entered

Even number” and body of else is not executed. If the result is “false”, the body of

“if” is not executed but body of else is executed. The output is “You entered Odd

number”.

8.2.5. ?: TERNARY OPERATOR ?: operator is a shorter alternate of if-else statement. If there is single instruction

in both if and else block then ternary operator is handy way to write the code. Its

syntax is as under:

SYNTAX: (expression)?<statements>:<statements>;

If the expression results in “true” value then statements just after the “?” are

executed. If expression results in “false” value then statements after “:” are

executed. You can consider the code after “?” as if part and code after “:” as else

part. Following program shows the use of ternary operator in multiple ways:

Ternary Operator Example

static void Main(string[] args) { int a = 6; int height = 5, width = 10; // choice:: 1 for rectangle area, 2 for triangle area int choice = 1; int b=(a > 5) ? 6 : 7; Console.Out.WriteLine(b); double area = (choice == 1) ? (height * width) : (height * width) / 2; Console.Out.WriteLine(area); double area2 = (choice == 2) ? (height * width) : (height * width) / 2; Console.Out.WriteLine(area2); double inputVal = (choice == 2) ? int.Parse(Console.ReadLine()) : double.Parse(Console.ReadLine()); Console.Out.WriteLine(inputVal); Console.Read();

Page 167: Programming Fundamentals

Programming Fundamentals Using C# 166

}

A ternary operator can be used inside other ternary operator. This type of use is

called the nesting of ternary operator and the operator used inside other is called

the nested ternary operator. Following program shows its use:

Program: Nested Ternary Operator

static void Main(string[] args) { int a = 6; int height = 5, width = 10; // choice:: 1 for rectangle area, 2 for triangle area int choice = 1; double area2 = (choice == 2) ? (height >0 && width> 0)?(height*width):0 : (height >0 && width >0 )?(height * width) / 2:0; Console.Out.WriteLine(area2); Console.Read(); }

8.2.6. NESTED “IF” AND “IF-ELSE” STATEMENTS During programming, we may need to write “if-statement” within the body of “if-

statement”. This is called the nesting of statements. This nesting could be done to

any level. For example, an if could be nested in other if which is further nested in

other if. Following type of nesting is possible:

Nesting Type

Name Description

Type1

If-if nested If statement is nested in other if statement

Type2

If-If-else nesting If-else is nested in if-statement

Type3 If-else-if nesting If is nested in else part of other if-else statement

Type4 If-else-if-else nesting

If-else is nested in else part of other if-else.

Below are given program showing the use of nesting structures.

Type1 Nesting: if-if nesting

static void Main(string[] args)

Page 168: Programming Fundamentals

Programming Fundamentals Using C# 167

{ double height=0, width=0, area=0; height = double.Parse(Console.ReadLine()); width = double.Parse(Console.ReadLine()); if (height > 0) { if (width > 0) { area = (height * width) / 2; Console.Out.WriteLine(area); } } }

P R O G R A M DE S C R I P T I O N :

Program declares and initializes three variables, height, width and

area.

Input statement reads a string and after converting it into double type,

assigns to height variable.

Next input statement reads a string and after converting it into double

type, assigns to width variable.

If-statement tests the “height” variable and if it is “true”, the control

enters in the body of if-statement.

o Nested If-statement tests the “width” variable and if it is true,

control enters its body.

o Area is calculated and result is printed out.

If outer if-statement result is “false”, the control moves to end of if-

statement body.

There are no more instructions so program ends.

Type2 Nesting: if-if-else nesting

static void Main(string[] args) { double height = 0, width = 0, area = 0; height = double.Parse(Console.ReadLine()); width = double.Parse(Console.ReadLine()); if (height > 0) { // start of if body if (width > 0) { // start of nested if body area = (height * width) / 2; Console.Out.WriteLine(area); } // end of nested if body else { // start of else body

Page 169: Programming Fundamentals

Programming Fundamentals Using C# 168

Console.Out.WriteLine("Area could not be calculated"); } // end of nested else body } // end of outer if body }

P R O G R A M DE S C R I P T I O N :

As before the program reads two values in height and width variables.

Outer if-statement checks the height variable. If result is true, it enters the

body of if-statement otherwise the control moves to end of if-body.

Inner if-statement tests the “width” variable and if result is “true” program

control moves in the nested “if” body.

If nested-if result is “true”, “area” is calculated and printed

If nested-if result is “false”, body of “if” is skipped and body of “else” is

executed. “Area could not be calculated” is printed.

No further statements so program ends.

Type3 Nesting: If-else-if nesting

static void Main(string[] args) { double height = 0, width = 0, area = 0; height = double.Parse(Console.ReadLine()); width = double.Parse(Console.ReadLine()); if (height > 0 && width>0) { area = (height * width) / 2; Console.Out.WriteLine(area); } else { if (width > 0) { Console.Out.WriteLine("Height is invalid value, width is ok"); } } }

P R O G R A M DE S C R I P T I O N :

As before, after reading and converting values in variables, if-statement is

executed.

If result is “true”, the body of “if-statement” is executed. In if-statement

body, “area” is calculated and printed.

If result is “false”, body of “else” is executed.

Page 170: Programming Fundamentals

Programming Fundamentals Using C# 169

In “else” body, there is another “if” statement. If this statement executes

to “true”, “Height is invalid value, width is ok” is printed.

If nested else results in “false”, nothing is printed and program ends.

Type4 Nesting: If-else-if-else nesting

static void Main(string[] args) { double height = 0, width = 0, area = 0; height = double.Parse(Console.ReadLine()); width = double.Parse(Console.ReadLine()); if (height > 0 && width > 0) { area = (height * width) / 2; Console.Out.WriteLine(area); } else { if (width > 0) { Console.Out.WriteLine("Height is invalid value"); } else { Console.Out.WriteLine("Both values are invalid"); } } }

P R O G R A M DE S C R I P T I O N :

The program reads two values, converts them into double and assigns to

the variables.

Outer if-statement tests the values of “height” and “width”. If both values

are ok, it moves into the body of if-statement and after calculating “area”,

prints it.

If outer if-statement results into “false”, the program control moves to

else part and body of else is executed.

In else-body, the nested-if tests the value of the “width”. If it is “true”, the

program prints “Height is invalid value” and skips the else part.

If nested-if results in “false”, the body of if is not executed and control

moves to nested else part where “Both values are invalid” are printed.

No further statements so program ends.

Page 171: Programming Fundamentals

Programming Fundamentals Using C# 170

Here are few more programs given without description involving nested if-else

use.

Status of Numbers

static void Main(string[] args) { int a, b; a = int.Parse(Console.ReadLine()); b = int.Parse(Console.ReadLine()); if (a == b) { Console.WriteLine("\'a\' and \'b\' are equal"); } else { if(a<b) { Console.Out.WriteLine("\'a\' is smaller than \'b\'"); } else { Console.Out.WriteLine("\'a\' is greater than \'b\'"); } } }

Vowels and Pronunciation

static void Main(string[] args) {

char ch = 'X' ; if (ch == 'A' || ch == 'a' ) { Console.WriteLine( "Vowel [ei]"); } else if (ch == 'E' || ch == 'e' ) { Console.WriteLine( "Vowel [i:]"); } else if (ch == 'I' || ch == 'i' ) { Console.WriteLine( "Vowel [ai]"); } else if (ch == 'O' || ch == 'o' ) { Console.WriteLine( "Vowel [ou]"); }

Page 172: Programming Fundamentals

Programming Fundamentals Using C# 171

else if (ch == 'U' || ch == 'u' ) { Console.WriteLine( "Vowel [ju:]" ); } else { Console.WriteLine( "Consonant"); }

}

8.2.7. “SWITCH-CASE” STATEMENT As we can see in “vowels and pronunciation” example, if there is a big list of

choices and program has to decide among them, use of if-else makes the program

more complicated and difficult to understand. Programming languages provides a

better way to program such situations. “switch-case” construct is used for such

type of handy programming. Here is the syntax of switch-case statement.

Switch-case syntax

switch (Selector) { case value_1:

statements; break;

case value_2: statements; break;

// … default:

statements; break;

}

“switch” is a keyword that takes some variable called selector as parameter. A

selector is a variable or some expression resulting in some value. The data type of

selector could be one of the followings:

bool, char, string or integer

switch is a compound statement i.e. like if-statement, it has its body. The body

starts with “{“ bracket and ends with “}” bracket. “case” is a keyword that will be

used as it is. “value_1” given ahead of “case” is the actual value to be compared

with the value of selector. If selector value matches with any value given in

different “case”s, that case is said to have hit. Each “case” can have multiple

statements under it (as its body). The body of case does not start and end with

braces. The body of “case” starts from its next statement and ends when next

Page 173: Programming Fundamentals

Programming Fundamentals Using C# 172

“case” arrives. Usually the value of selector matches with value of some “case”. If

selector value does not match with any case, optional “default” case is provided

that handles all mismatches. If selector value matches with any case value, its body

is executed and in case of no match, “default” is executed. It is not necessary to

write the “default” case at the end of other cases, but it is better to write at the

end.

“break” is special keyword. It is used to move program control out of structure in

which it is written. In this case, “break” is used to move control out of switch

statement. C# requires you to write “break” at the end of the body of each “case”.

Before exploring switch further let’s look at an example.

Program: Switch-Case

static void Main(string[] args) { int a = 8; switch (a) { case 7: Console.Out.WriteLine("case 7"); break; case 8: Console.Out.WriteLine("case 8"); break; default: Console.Out.WriteLine("default case"); break; } }

P R O G R A M DE S C R I P T I O N :

The program defines an integer variable “a” that is assigned a value 8.

“switch” statement matches value of “a” with value of each case. We see

that it matches with “case 8”.

Body of “case 8” is executed that prints “case 8”. The next statement in

this case is “break” that brings program control out of switch statement.

If “break” is not used at the end of “case” body, theoretically the next case

value will not be tested and its body will be executed. If you want to have

one body against multiple values of selector, you can leave the body

empty. As shown in following program:

Case with multiple values

static void Main(string[] args) { int number = 6; switch (number)

Page 174: Programming Fundamentals

Programming Fundamentals Using C# 173

{ case 1: case 4: case 6: case 8: case 10: Console.WriteLine("The number is not prime!"); break; case 2: case 3: case 5: case 7: Console.WriteLine("The number is prime!"); break; default: Console.WriteLine("Unknown number!"); break; } }

P R O G R A M DE S C R I P T I O N : in this program, case 1, case 4, case 6, case 8 have no

bodies and there is no “break” statement. The value of “number” is matched with

1,4,8,8. No match occurs but due to absence of “break” statement, the control

continues to match next statement. Finally it checks case 10. If value of number

matches any of these “case 10” body is executed and “The number is not prime!”

is printed. At the end of “case 10” body, there is “break” statement. On reaching

this statement, the program control moves out of switch statement. Similar is the

case with “case 2, case 3, case 5, case 7”. If value in number is not from 1 to 10

then “default” case is executed and its “break” statement is executed and control

moves out of switch statement.

GO OD PRA CT IC ES WH E N US IN G "SW ITC H-C AS E"

A good practice when using the switch statement is to put the default

statement at the end, in order to have easier to read code.

It’s good to place first the cases, which handle the most common situations.

Case statements, which handle situations occurring rarely, can be placed at

the end of the structure.

If the values in the case labels are integer, it’s recommended that they be

arranged in ascending order.

If the values in the case labels are of character type, it’s recommended that

the case labels are sorted alphabetically.

Page 175: Programming Fundamentals

Programming Fundamentals Using C# 174

It’s advisable to always use a default block to handle situations that cannot be

processed in the normal operation of the program. If in the normal operation

of the program the default block should not be reachable, you could put in it

a code reporting an error.

SWI TCH -CA S E AND OTH ER DATA TY PE S

Here we list few more examples without description that use different data type

values:

Switch statement with Boolean value

static void Main(string[] args) { int a = 40, b = 30; switch (a > b) { case true: Console.Out.WriteLine("it is true case"); break; case false: Console.Out.WriteLine("it is false case"); break; } }

Switch statement with string value

static void Main(string[] args) { string s = "Pakistan"; switch (s) { case "Pakistan": Console.Out.WriteLine("Pakistan"); break; case "India": Console.Out.WriteLine("India"); break; case "Afghanistan": Console.Out.WriteLine("Afghanistan"); break; default: Console.Out.WriteLine("Any other Country"); break; } }

Switch statement with character value

static void Main(string[] args) {

Page 176: Programming Fundamentals

Programming Fundamentals Using C# 175

char ch = 'C'; switch (ch) { case 'A': Console.Out.WriteLine("ch has value \'A\'"); break; case 'B': Console.Out.WriteLine("ch has value \'B\'"); break; case 'C': Console.Out.WriteLine("ch has value \'C\'"); break; default: Console.Out.WriteLine("some other character"); break; } }

Page 177: Programming Fundamentals

Programming Fundamentals Using C# 176

Chapter 9

Code Repetition C# contains multiple code repetition statements. Such statements are called loop

constructs in programming languages. A loop construct allow the programmer to

repeat a single or group of statements according to programmer’s requirements. In

this chapter, we will discuss different types of loops, their implementation, usage and

nested loops (placing a loop within other loop) will be discussed. “break” and

“continue” statements that change the normal flow of loop body are also discussed in

detail.

9.1. REPETITION CONSTRUCTS A loop is basic programming construct/instruction that repeats other instructions.

Repetition constructs are known as loops. There are multiple loop constructs present in

C#. Depending upon the type of loop, the code in it is repeated fixed number of times or

repeats until a given condition becomes true. There are two major categories of loops:

finite loops and infinite loops. Loops that repeat the group of instructions again and again

and this repetition never ends, are called the infinite loops. Finite loops are those that

either end after fixed number of repetition or based on some condition. In your program,

it is normally recommended to avoid the infinite loops. Following is the list of loop

constructs present in C#:

While Loop

Do - While Loop

For Loop

Foreach Loop

Almost every loop could be used for other loop. It means that no loop is specific to

particular type of programming. Any loop could be used to repeat a set of instructions.

9.1.1. WHILE LOOP It is one of the simplest and easy to understand repetition construct. Its syntax is

similar to “If” statement.

While Loop Syntax

While (<condition>) { // loop body }

Page 178: Programming Fundamentals

Programming Fundamentals Using C# 177

In this syntax, “while” is keyword, condition (loop condition) is either Boolean

value or some expression that results in Boolean value. If the condition is “true”,

the body of the “while” is executed. Like “If” statement, the body of while loop is

enclosed in “{“ opening and “}” closing braces. The loop body can consist of either

single statement or multiple statements. If there is only one statement in loop

body, it is called the “simple statement” and if there are multiple statements

enclosed in curly braces, these are collectively called “Compound Statement”.

After executing the body of loop, loop condition is checked again, if it is still true,

the loop body executes again. This repetition process continues until the condition

becomes “false”. Every time the loop body is executed, it is referred as loop

iteration. For example if loop body is executed 4 times, we call it 4 loop iterations.

As the loop condition is checked before loop body, while loop is called the “pre-

test loop”. The working of for loop is shown pictorially below:

Figure 9 - 1: Control Flow of While Loop

The working of above control flow is described below:

1. First of all, loop condition is checked. If it is false, the loop body is skipped

2. If loop condition is true, loop body is executed

3. After loop body execution the, program control moves to step 1.

If the loop condition is false in first condition test, the body of loop will not execute

at all and if loop condition never becomes “false”, loop never ends and becomes

an infinite loop. If there is only one statement in loop body, the use of curly braces

is optional but if there are multiple statements in loop body then you need specify

the braces to mark the statements as compound statement that will be repeated

by the loop. Following program shows the use of “while” loop:

S# Infinite While Loop

1 2 3 4 5 6

static void Main(string[] args) { int a = 5; while (a < 6) { Console.Out.WriteLine("I am Muslim");

Page 179: Programming Fundamentals

Programming Fundamentals Using C# 178

7 8 9 10

} Console.Out.WriteLine("Loop has been ended"); Console.Read(); }

P R O G R A M DE S C R I P T I O N : The program declares and initializes an integer variable

“a” with value 5 at line# 3. At line number 4, while loop is started and in loop

condition “a < 8” is given. At this point the “a” is smaller than 8, the loop condition

results in “true” and program control enters the loop body. Loop body contains

only one output statement that prints “I am Muslim”. At line 7, loop ends and

control transfers back to line number 4 where the condition is checked again. It is

to note that value of variable “a” is not changed during loop body execution and

is still “5”. Loop condition results in “true” again, the loop body is executed again

and control transfers to loop condition again. In this way this process continues.

You can observe that value of “a” never changes and hence the loop condition is

always “true”. As a result loop will never end and will become infinite loop. “Loop

has been ended” will never get printed.

Here is modified version of above program:

S# Finite While Loop

1 2 3 4 5 6 7 8 9 10 11

static void Main(string[] args) { int a = 1; while (a < 6) { Console.Out.WriteLine("I am Muslim"); a++; } Console.Out.WriteLine("Loop has been ended"); Console.Read(); }

P R O G R A M DE S C R I P T I O N : In this program, at line 3, variable “a” is initialized with

value 1. At line 4, while loop starts and in loop condition, value of “a” is compared

with 8. Result of this comparison is “true” as value of “a” (1) is smaller than 8. The

program control enters the body of loop and “I am Muslim” is printed. Line 7

increments the value of “a” to 2. At line 8, loop body ends and control transfers

back to line 4. Now new value of “a” (2) is compared with 8, the result is “true”.

Program control enters the loop body again, “I am Muslim” is printed and “a” is

incremented again. This repetitive process continues until the value of “a”

becomes 8. In next loop condition comparison, value of “a” (8) is compared with 8

that results in “false”. Now the program controls moves to line 9 that prints “Loop

Page 180: Programming Fundamentals

Programming Fundamentals Using C# 179

has been ended”. As usual, Console.Read(), stops the output screen for your

view and when you press any key, the output windows disappears and program

ends.

Following program shows the effect of curly brackets:

S# Finite While Loop

1 2 3 4 5 6 7 8 9 10 11

static void Main(string[] args) { int a = 1; while (a < 6) //{ Console.Out.WriteLine("I am Muslim"); a++; //} Console.Out.WriteLine("Loop has been ended"); Console.Read(); }

P R O G R A M DE S C R I P T I O N : In this program, we have commented the curly braces.

Now only one statement “Console.Out.WriteLine(“I am Muslim”);” lies in the

body of loop. Do not get confused with indentation which is used only to enhance

readability. “a++” is out of loop body. Every time the loop condition is checked, is

found “true” and loop body consisting of single statement is executed. Value of

“a” never changes, hence it has become an infinite loop.

Considering the above example, it is clear that you must include loop body opening

and closing braces otherwise, the result may not be as expected. Loop condition

could be on any data type. Following example places loop condition on character

data type:

S# While Loop with Char Data Type

1 2 3 4 5 6 7 8 9 10

static void Main(string[] args) { char ch='a'; while (ch != 'z') { Console.Out.WriteLine(ch); ch = char.Parse(Console.ReadLine()); } Console.Out.WriteLine("Loop ended"); }

P R O G R A M DE S C R I P T I O N :

1. At line 1, main program starts

Page 181: Programming Fundamentals

Programming Fundamentals Using C# 180

2. 2nd line starts the body of main program

3. 3rd line declares, defines and initializes the character variable with ‘a’.

4. 4th line starts the while loop and as loop condition, “ch” is compared with

character ‘z’. if “ch” is not equal to ‘z’, loop body is executed

5. 5th line starts the body of while loop

6. On 6th line, character is printed

7. 7th line reads one character from user as string, converts it into character

and assigns to “ch” variable.

8. Line 8 ends the loop body and control moves back to line 4. If new read

character is not ‘z’, the loop body is executed again otherwise loop ends

and control moves to line 9

9. “Loop ended” is printed

10. Main program body ends here.

Some programmer may provide complex expression as loop condition.

Remember loop condition requires expression or variable or constant that is

of type Boolean. If any simple or complex expression provided as loop

condition results into Boolean value, it is perfectly right. Following program

shows this concept.

S# Finite While Loop with Complex Loop Condition

1 2 3 4 5 6 7 8 9

static void Main(string[] args) { char ch = 'a'; while ((ch=char.Parse(Console.ReadLine())) != 'z') { Console.Out.WriteLine(ch); } Console.Out.WriteLine("Loop ended"); }

PR O G R A M DE S C R I P T I O N :

1. Main program starts

2. Main program body starts

3. Variable “a” is declared and initialized

4. While loop started. In loop condition, first Console.ReadLine()

reads a string from user, converts it into character ans assigns to “ch”.

This “ch” variable is them compared with ‘z’. if the result is “true”, the

control transfers to line 5. If result is false, control transfers to line 8.

5. Start of body of loop.

6. This output statement prints the read character.

Page 182: Programming Fundamentals

Programming Fundamentals Using C# 181

7. End of loop body. After executing line 7, the control transfers back to

line 4.

8. Output statement that prints “Loop ended”.

9. End of main program.

Here is another program without description that prints the table of user given

number:

Printing the Table Program

static void Main(string[] args) { uint num = 0; Console.Out.Write("Please enter the number:"); num = uint.Parse(Console.ReadLine()); int count = 0; Console.Out.WriteLine("Printing the table of " + num); while (count <= 10) { Console.Out.WriteLine(num + "*" + count + "=" + (num * count)); count++; } Console.Out.WriteLine("Table has been printed"); Console.Read(); } Output: Please enter the number:9 Printing the table of 9 9*0=0 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 9*10=90 Table has been printed

9.1.2. BREAK STATEMENT We have already seen a use of “break” statement in “switch” construct. Here we

see its another use. In loop construct, this statement is used to terminate the loop

or exit from loop body. As soon as the “break” statement is found in the program

by the computer, the program control moves out of loop body. You can place the

“break” statement anywhere in loop body where you find it required.

Page 183: Programming Fundamentals

Programming Fundamentals Using C# 182

Figure 9 - 2: Control Flow for break Statement

Following program shows the use of break statement:

S# While Loop with break

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

static void Main(string[] args) { uint num = 0; Console.Out.Write("Please enter the number:"); num = uint.Parse(Console.ReadLine()); int count = 0; Console.Out.WriteLine("Printing the table of " + num); while (true) { Console.Out.WriteLine(num + "*" + count + "=" + (num * count)); count++; if (count > 10) break; } Console.Out.WriteLine("Table has been printed"); Console.Read(); }

The program has same output as that of “Printing the Table” program.

PR O G R A M DE S C R I P T I O N :

1. Main program starts

2. Start of main program body

3. “num” variable declaration and initialization

4. Printing a message to user “Please enter the number:”.

5. Program reads a number from user, converts it into unsigned integer

and assigns to the variable “num”.

6. Declaration of second variable “count” and its initialization.

Page 184: Programming Fundamentals

Programming Fundamentals Using C# 183

7. Printing a message to user “Printing the table of <num>”. <num> is

place holder for user entered number on line 5

8. Start of loop. Note that as loop condition “true” value is provided.

Now the loop condition will always be true resulting in an infinite loop.

Such loop must be terminated in some other way.

9. Start of loop body

10. This statement prints the message by concatenating different

variables and literals.

11. “count” variable is incremented

12. This “if” statement tests the value of “count” variable. If it is above

than 10, body of “if” that consists of “break” statement only is

executed. Otherwise it is skipped.

13. “break” statement. It brings program control out of loop body to line

15.

14. End of loop body. Program control moves back to line 9.

15. Output “Table has been printed” is displayed on console.

16. Program stops to read a character from console so that user can see

the output.

17. Body of main program ends

9.1.3. “CONTINUE” STATEMENT “continue” statement causes the control to jump back to loop condition. If

“continue” statement is used in middle of loop body i.e. half loop body is executed

and half is remaining, the program control moves back to loop condition and if

loop condition is true, a new loop iteration is started. You can use “continue”

statement anywhere in the loop body. Following diagram shows the control flow:

Figure 9 - 3: Control Flow of continue Statement

Page 185: Programming Fundamentals

Programming Fundamentals Using C# 184

The use of “continue” statement is shown in following program:

S# While with continue Program

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

static void Main(string[] args) { uint num = 0; Console.Out.Write("Please enter the number:"); num = uint.Parse(Console.ReadLine()); int count = 0; Console.Out.WriteLine("Printing the table of " + num); while (count<10) { count++; if (count %2==0) continue; Console.Out.WriteLine(num + "*" + count + "=" + (num * count)); } Console.Out.WriteLine("Table has been printed"); Console.Read(); }

Output: Please enter the number:7 Printing the table of 7 7*1=7 7*3=21 7*5=35 7*7=49 7*9=63 Table has been printed

P R O G R A M DE S C R I P T I O N : Lines 1-7 and 13-17 are same like previous programs

and are not described here.

8. While loop starts here. Value of “count” is compared with 10. In start

the condition is true so program control will enter in the loop body

9. Loop body starts

10. “count” variable is incremented.

11. In “if-statement”, remainder of count when divided with 2 is tested. if

it is zero then body of “if” consisting of single statement “continue” is

executed.

12. “continue” statement that causes program control to move to line 8.

Line 9 is skipped and new iteration is started. Whenever “count”

Page 186: Programming Fundamentals

Programming Fundamentals Using C# 185

contains even value, the if-condition becomes true and “continue”

statement is executed that causes the program to jump.

9.1.4. “DO – WHILE” LOOP This is second loop construct present in C#. It is similar to the while loop. The

difference is that loop condition is checked after the loop body. So even if the loop

condition is false, loop body is executed at least once. As the condition of loop is

checked after the loop body, do-while loop is called the “post-test loop”. Following

flowchart shows the control flow of do-while loop:

Figure 9 - 4: Control Flow of do-while Loop

The syntax of do-while loop is shown below:

do

{

executable code;

} while (condition);

“initially the loop body is executed, then its condition is checked, if the condition is

true, the loop body is executed again, otherwise the loop is exited”.

We use the do-while loop in conditions where we need to be guaranteed that at

least once the loop body will be executed. Here is the program that shows the use

of do-while loop.

S# Do-while loop program

1 2 3

static void Main(string[] args) { Console.Out.Write("Enter a number:");

Page 187: Programming Fundamentals

Programming Fundamentals Using C# 186

4 5 6 7 8 9 10 11 12 13 14

uint num = uint.Parse(Console.ReadLine()); decimal fact = 1; do { fact *= num; // fact=fact*num num--; } while (num > 0); Console.Out.WriteLine("It\'s factorial is :{0}", fact); Console.Read(); }

Output: Enter a number: 5 It’s factorial is 120

P R O G R A M DE S C R I P T I O N :

1. Start of main program

2. Main program body starts

3. A message “Enter a number:” is printed.

4. A string of characters is read from user, it is converted into unsigned

integer and assigned to a variable “num”.

5. A variable of type decimal is declared and a value of 1 is assigned to it.

6. “do” keyword for do-while loop is written.

7. Start of body of do-while loop

8. An expression in which “fact” is multiplied with “num” and result is

assigned to “fact”.

9. “num” is decremented.

10. Loop body ends. “while” keyword is written and loop condition is

specified. It is to note that “while” is terminated with semi colon.

11. No instruction is present on this line

12. Output statement that prints “It’s factorial is 120”

13. Program waits to read a character from user. The screen remains visible

to user until user presses some key. The program moves to next

instruction.

14. Main program body ends. Program ends.

“fact” is initialized with 1. Let the user has entered number 5. In first iteration, the

fact is multiplied with 5 (1*5) and result is assigned back to “fact” (5). “num” is

decremented to 4. Loop condition is checked that is true and loop body starts

again. Now “fact” is multiplied with 4 (5*4) and result is assigned back to “fact”

(20). “num” is decremented to 3 and loop condition is checked which is “true” so

loop body starts again. “fact” (20

Page 188: Programming Fundamentals

Programming Fundamentals Using C# 187

) is multiplied with “num” (3) (20*3) and result is assigned back to “fact” (80).

“num” is decremented to 2, loop condition is still true so loop body starts again.

“num” (2) is multiplied with “fact” (80) (80*2) and result is assigned back to “fact”

(120). “num” is decremented to 1 and loop condition is checked that is still true so

loop body is started again. “num” (1) is multiplied with “fact” (120) and result

(120*1) is assigned to “fact” (120). “num” is decremented to 0 and loop condition

is checked. Now the loop condition is “false” so loop body does not start again.

Program control moves to line 12 and factorial is printed.

9.1.5. “BREAK” AND “CONTINUE” “break” and “continue” statements work in the same way as in while loop. These

statements are not bound to any loop but they perform their particular task

wherever used. It is repeated that “break” statements takes program control out

of loop body and “continue” statement, skips the remaining iteration and starts

next iteration if loop condition is “true”. Following programs show the use of these

statements with do-while loop.

Do-while with break

static void Main(string[] args) { //Program to test a number whether //it is prime or composit int num = int.Parse(Console.ReadLine()); int divisor = 1; bool prime = true; do { if (num % divisor == 0) { prime = false; break; } divisor++; } while (divisor < num); if(prime==true) Console.Out.WriteLine("The number is prime"); else Console.Out.WriteLine("The number is composite"); }

Do-While with continue

static void Main(string[] args) { //Program to sum only even digits // from 1-10

Page 189: Programming Fundamentals

Programming Fundamentals Using C# 188

int sum = 0; int count = 0; do { count++; if (count % 2 == 1) continue; sum = sum + count; } while (count <= 10); Console.Out.WriteLine("The sum of even numbers:{0}", sum); Console.Read(); }

9.1.6. “FOR” LOOP for loop is one of the complex loops present in C#. Its syntax is complicated as

compared to while and do-while loops but it can offer more functionality hence it

is more versatile. “for” loop is normally used for counter based repetition. The

syntax of “for” loop is given below:

“for” loop syntax

for (<expression A>; <expression B>; <expression C>) { // body of for loop }

“for” loop consists of “for” clause and three expressions in parenthesis. First

expression A is called the “initialization” expression. A counter variable is

initialized at this place. After “;” another expression is provided that is called the

“loop condition”. It is same as that of while and do-while loop. Expression C is

called the “step expression” and it either reduces or increases the counter as

required. After for clause and three expressions, loop body enclosed in braces is

required. Following flow diagram shows the working of for loop.

Page 190: Programming Fundamentals

Programming Fundamentals Using C# 189

Figure 9 - 5: Control Flow for for-Loop

As shown in flow chart, for-loop first executes the initialization expression. This is

done only one time. After that loop condition is checked and if loop condition is

“true” the loop statements or body of loop is executed. And in last, the step

expression is evaluated. The control moves back to loop condition. Note that

control does not move to initialization expression. The loop continues repeating

the body of loop until the loop condition becomes false. This sequence of

execution can be written as:

<Initialization expression> <loop condition> <loop body> <step expression>

Following program shows the use of for-loop.

S# For-loop Program

1 2 3 4 5 6 7 8 9 10 11

static void Main(string[] args) { //Program to print counting //from 1-10 int count; for (count = 0; count <= 10; count++) { Console.Out.WriteLine(count); } Console.Read(); }

Output: 1 2 3 4 5 6

Page 191: Programming Fundamentals

Programming Fundamentals Using C# 190

7 8 9 10

P R O G R A M DE S C R I P T I O N :

1. Start of main program

2. Main program body starts

3. Comments

4. Comments

5. int variable “count” declaration

6. for-loop started. First expression initializes the “count” variable. Second

expression provides the loop condition and third expression increments

the value of “count”. If the loop condition is true, the body of loop is

executed and then step expression is evaluated. After step expression

loop condition is again checked. If loop condition becomes “false”, the

control moves to line 9, end of loop body.

7. Start of for-loop body

8. Output statement printing the value of “count”

9. End of loop body

10. Statement to stop output window

11. End of main program

“for” loop could equally perform the functionality offered by while and do-while

loop. All three expressions inside (A, B, C) or any expression in for-loop could be

omitted and placed on any suitable location in code. Following set of programs

show the omitting of expressions using same program:

For-loop variations

static void Main(string[] args) { //Program to print counting //from 1-10 int count=0; // initialization is done here for (; count <= 10; count++) { Console.Out.WriteLine(count); } Console.Read(); }

static void Main(string[] args) { //Program to print counting

Page 192: Programming Fundamentals

Programming Fundamentals Using C# 191

//from 1-10 int count = 0; // initialization is done here for (; ; count++) { if (count <= 10) // loop condition is here { Console.Out.WriteLine(count); } else break; } Console.Read(); }

static void Main(string[] args) { //Program to print counting //from 1-10 int count = 0; // initialization is done here for (; ; ) { if (count <= 10) // loop condition is here { Console.Out.WriteLine(count); count++; // step is here } else break; } Console.Read(); }

All programs have the same output. If we omit all expressions of for-loop and does

not provide loop condition inside loop body, this may become “infinite” loop. Any

variable defined inside the loop body or its expression, will not be useable (visible)

outside the loop body. Following program shows its usage.

For-Loop Variable

static void Main(string[] args) { for (int count = 0; count <= 10; count++) { Console.Out.Write(count + " "); } // following statement produces the error // "The name 'count' does not exist in the current context" // as variable 'count' is not usable outside loop body

Page 193: Programming Fundamentals

Programming Fundamentals Using C# 192

Console.Out.Write(count); }

for-loop construct allows you to declare and use multiple variables at the location

of “expression A” and “expression C”. Here is the use:

for-loop multiple variables

static void Main(string[] args) { for (int a = 10, b = 0; b <= 10; a--, b++) { Console.Out.Write((a + b) + " "); } Console.Read(); }

“BREAK” AN D “CON TI N UE” STA TE M ENT S

The functionality of “break” and “continue” is same as that for while and do-while

loop. We do not provide example programs with for loop here. The reader is

encouraged to solve above given examples with the help of these statements.

9.1.7. NESTED LOOPS When a loop is used inside other loop, it is called the nested loop. In this way one

is called the outer loop whereas other is inner loop. Here is the skeleton code

showing nested loops:

Nested loops

while(<condition>) //outer loop { statement(s); // one or more statements While(<condition>) // inner loop { statement(s); // one or more statements } statement(s); }

do // outer loop { statement(s); // one or more statements. do // inner loop { statement(s); // one or more statements }while( <condition> );

Page 194: Programming Fundamentals

Programming Fundamentals Using C# 193

}while( <condition> );

for ( initialization; condition; step ) // outer loop { statement(s); // one or more statements for ( initialization; condition; step ) // inner loop { statement(s); // one or more statements } statement(s); // one or more statements }

You can nest any loop inside any other loop. The above code segment shows the

nesting to level two i.e. outer loop is at level one and inner loop is at level 2. You

can nest the loops to as many levels as you need. Theoretically there is no

restriction on nesting of loop levels. Following program shows the nesting of loops:

Figure 9 - 6: Nested Loops

P R O G R A M DE S C R I P T I O N : Outer loop repeats its body ten times. You can see that

there is another loop present in the body of loop (nested loop). Every time the

outer loop executes its body, the inner loop also runs one time. Inner loop also

runs its body ten time (prints star ten times on a single line). When inner loop

Page 195: Programming Fundamentals

Programming Fundamentals Using C# 194

execution ends, a new line is printed and outer loop counter is incremented. The

statements inside inner loop are executed 100 times at all whereas the statements

in outer loop body are executed ten times only.

Following example (without description) shows the use of nested for loops to find

out prime numbers between 1 and 100.

Finding Prime Numbers from 1-100

static void Main(string[] args) { int i, j; for (i = 2; i < 100; i++) { for (j = 2; j <= (i / j); j++) if ((i % j==0)) break; // if factor found, not prime if (j > (i / j)) Console.Out.WriteLine(i + " is prime"); } Console.Read(); } 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime

Page 196: Programming Fundamentals

Programming Fundamentals Using C# 195

Here are few more programs without description showing the use of loops:

Nest Loops Printing the Triangle

static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); for (int row = 1; row <= n; row++) { for (int col = 1; col <= row; col++) { Console.Write(col + " "); } Console.WriteLine(); } Console.Read(); } Output: 9 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9

Page 197: Programming Fundamentals

Programming Fundamentals Using C# 196

Chapter 10

Data Sequences Data processing normally require to work with a sequence of data items of same type.

Such sequences are known as arrays in computer programming. In this chapter, we

will get acquainted with creating arrays, using them, reading from console, displaying

on console and manipulation of individual items in the sequence. We will also study

different type of arrays and a special characteristic of arrays called multidimensional

arrays is discussed in detail.

10.1. DATA AND MEMORY Before looking at arrays in detail, we review some concepts about RAM installed in

computer and data representations. RAM consists of a big number of small electronic

devices that can store one bit of data at a time. A group of 8 such devices is considered as

a byte. We can count every byte in RAM. This counting process assigns a number to each

byte i.e. first byte is given a number 1, second byte is given 2 and so on. Every such number

is considered an address of particular byte. Hence it could be stated that RAM consists of

bytes to store data and their addresses. When we declare a variable in our program, three

characteristics are defined for that variable.

Characteristics Description

Data Type This characteristics define the way of data storage and number of bytes required to store data.

Name This name is specified by the programmer and the memory location reserved by operating system to store the variable is linked with this name

Address This is the number of byte where data is stored. If variable occupies 2 or more bytes, the first byte number is called the address of variable

Value This is the contents of the memory location that represent some number or value.

For example, “int temp=8;” defines a variable whose name is “temp” and data type is “int”.

“int” specifies the number of bytes required to store the variable (4 bytes in our case) and

the way of storage or interpretation for temp. For “temp”, left most bit will be used for

sign and rest for magnitude. The value to be stored in this variable is 8 and the location

where this variable will be made is decided by operating system. Let the operating system

assigns memory from 101 to 104 for our variable, the address of our variable will be 101.

Page 198: Programming Fundamentals

Programming Fundamentals Using C# 197

10.2. WHAT IS AN ARRAY If in our program, we need to read marks of three students, we will define same type of

three variables like “int marks1=5, marks2=6, marks3=7”. As these variables are

defined consecutively, they will be stored consecutively in RAM. Following table shows the

concept.

Variable name Address Value

Marks1 101 0000 0000

102 0000 0000

103 0000 0000

104 0000 0101

Marks2 105 0000 0000

106 0000 0000

107 0000 0000

108 0000 0110

Marks3 109 0000 0000

110 0000 0000

111 0000 0000

112 0000 0111

Programming languages provides a handy way to define such variables that will be

stored in consecutive memory locations. Instead of providing multiple names, in

array a single name is provided. In other words

“An array is set of consecutive memory locations used to store multiple values of

same data type and referred by single name”.

A term “homogeneous” is often used to define the array like “an array is collection

of values of homogeneous type stored consecutively in memory”. Here

homogeneous means that all values in an array have same data type. Now you

may ask a question, how we can differentiate the multiple values in an array. Let’s

look at following table again.

Variable name Address Value

Marks 101 0000 0000

102 0000 0000

103 0000 0000

104 0000 0101

105 0000 0000

106 0000 0000

107 0000 0000

108 0000 0110

109 0000 0000

110 0000 0000

Page 199: Programming Fundamentals

Programming Fundamentals Using C# 198

111 0000 0000

112 0000 0111

This array is defined as “int[] Marks=new int[3];”. The digit 3 shows that there will

be three integer values in marks. We can reference each value in above table by

using index i.e. Marks[0], Marks[1] and Marks[2]. Marks[0] will refer to first four

bytes (101-104), Marks[1] will refer to next 4 bytes (105-108) and Marks[2] will

refer to last 4 bytes (109-112).

The three values present in above array are called the “ELE M ENT S” of array and

total number of elements present in an array is called the LEN GT H OF ARRAY .

Here is the syntax of declaring array in C#.

Syntax: <data type>[] <identifier>=new int[size]; Example: int[] Marks=new int[3]; Data type : int Size: 3 Identifier: Marks

REF ER ENC E T YP E : For variables defined in the program, compiler makes two

tables. Let we call them “table1” and “table2”. Table1 contains the names of

variables and table2 contains the addresses of RAM where those variables are

stored. Making entry in first table is called the “VARIAB LE DE CL ARAT ION ”

whereas reserving RAM space for that variable and marking entry in second table

is called the “V ARIABL E D EF IN IT ION ”. For simple variables, the compilers makes

both entries at the same time and hence declaration and definition is done using

single statement. This is why we did not clarify the different in chapter discussing

about variables.

Compiler does not always make both entries at the same time for all type of

variables. Sometime it only makes entry in table containing variable names

(table1) i.e. declaration, it does not put other entry in table2 about RAM address.

The variables having only one entry are called the “Reference Type Variables”.

Their second entry is made later, using another program instruction. To better

understand, let’s consider the following declaration:

Array Syntax

int[] marks; // declaration marks=new int[3]; // definition

First statement informs the compiler that there will be an array of type integers

identified by “marks”. The compiler will make its entry in first table. Now as the

Page 200: Programming Fundamentals

Programming Fundamentals Using C# 199

RAM area is not reserved for this variable, you cannot assign any value to it. In

other words such variables are not useable in the program. In second statement,

“new” keyword reserves RAM space for 3 integers and makes entry in second

table. Now your variable is defined which could be assigned a value and could be

used in your program. C# allows you to declare and define the array in single

statement as shown below

Array Syntax

int[] marks=new int[3]; // declaration and definition

It is to note that size of array must always be positive number (zero or greater).

10.2.1. ARRAY DEFAULT VALUES AND INITIALIZATION Some programming languages may provide default values for variables whereas

other do not. If a language does not provide default value and we try to access,

there would be an error or some non-sense value will be accessed. C# is well

managed language and it will either restrict the programmer to use unassigned

variable or will provide default value for variable. For arrays C# provides default

values which are according to their data type as discussed in data type chapter.

Look at the following program:

S# Default values in Array

1 2 3 4 5 6

static void Main(string[] args) { int[] a=new int[3]; Console.Out.WriteLine(a[0]); Console.Read(); }

Output: 0

In this program, you can see that at line 3, an array is declared and defined. No

values are provided to the array elements so compiler has assigned them default

values which is “0” for integer. At line 4 when we print the value of first element,

0 is printed.

Array initialization refers to providing values to array at the point of declaration

and definition.

Syntax <data type>[] <identifier>=new <data type>[]{<comma separated values>}

Example int[] marks=new int[]{1,2,3};

Example Program

static void Main(string[] args) {

Page 201: Programming Fundamentals

Programming Fundamentals Using C# 200

int[] marks=new int[]{11,22,33}; Console.Out.WriteLine(marks[0]); Console.Read(); }

Output 11

In syntax, data type refers to the data type of array being declared. The set of

square brackets “[ ]” hints the compiler that this variable is array and identifier is

the name of array. "new” keyword means new memory space is required. “new”

operator needs to know that what type of memory is to be reserved and how

much. The first information is provided with <data type> written after “new” and

pair of square brackets “[ ]” tell the compiler that it is an array. The set of values

provided enclosed in curly brackets determines the size of array and values of

array elements.

To access single element of an array, array name and its index is provided i.e. in

output statement “Console.Out.WriteLine(marks[0])” access first array

element and prints it. The array elements should be printed using index. The

entries made by C# compiler in “table1” and “table2” are as shown:

Table 1 Table 2

Marks

Index 0 1 2

Address 101 105 109

Value 11 22 33

C# also provides you a short way of array declaration as shown below:

Syntax <data type>[] <identifier>= {<comma separated values>}

Example int[] marks={1,2,3};

Example Program

static void Main(string[] args) { int[] marks={11,22,33}; Console.Out.WriteLine(marks[0]); Console.Read(); }

Output 11

In syntax, you should note that “new int[ ]” is missing. If you omit it the language

automatically includes “new int[ ]” with array initialization statement. As a

programmer, you can use either way.

Page 202: Programming Fundamentals

Programming Fundamentals Using C# 201

In output statement, providing the name of array only will not generate the

expected results. For example, to print the complete array in above example, you

cannot use the statement “Console.Out.WriteLine(marks);” as shown below. It just

prints the type of array.

Syntax <data type>[] <identifier>=new <data type>[]{<comma separated values>}

Example int[] marks=new int[]{1,2,3};

Example Program

static void Main(string[] args) { int[] marks=new int[]{11,22,33}; Console.Out.WriteLine(marks[0]); Console.Read(); }

Output 11

10.2.2. ACCESSING ARRAY ELEMENTS Array elements are accessed using index of element. The count of array elements

in C# starts from zero i.e. first element will be numbered zero, second element will

be numbered 1 and so on. Following statement provides the syntax of accessing

array element:

Accessing Array Element

int[ ] ar={11,22,33}; Console.Out.WriteLine(ar[0]); // first element “11” is accessed Console.Out.WriteLine(ar[1]); // second element “22” is accessed Console.Out.WriteLine(ar[2]); // Third element “33” is accessed

ITER ATI NG ARR AY EL E ME NT S

Iterating means accessing each array element. There are different way to iterate

through an array. The simplest way is to access each element using array index as

shown in above program. The better way is to use repetition statements i.e. loops.

Loops provide a short way to iterate through an array. Here is the program that

declares an array of ten elements and prints its sum:

Line # Sum of Array Elements

1 2 3

static void Main(string[] args) { int[] arr = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 10 };

Page 203: Programming Fundamentals

Programming Fundamentals Using C# 202

4 5 6 7 8 9 10

// array indices 0 1 2 3 4 5 6 7 8 9 int sum = 0; for (int i = 0; i < 10; i++) sum += arr[i]; Console.Out.WriteLine("Sum of Array={0}", sum); Console.Read(); }

P R O G R A M DE S C R I P T I O N :

1. Main program starts

2. Main program body starts

3. Integer Array “arr” is defined and initialized

4. Comments showing the index of array elements

5. “sum” variable initialized with zero

6. for loop. The loop runs ten times and executes its single statement body.

In first loop iteration, value of i is zero and hence arr[i]=arr[0] will refer to

first element i.e. 11. In next iteration, the value of “i” is incremented that

access the second element and so on. Each time loop iterates, one

element of the array is added with sum and result is assigned back to sum.

So “sum” variable keep on updating until array ends.

7. Arithmetic expression calculating the sum of array.

8. Output statement. This statement is out of for-loop body. It prints the

value in “sum”.

9. Input statement used to stop output screen.

10. End of main program body

ARRAY BOU ND S

In C# first element of array is indexed “0”, second is indexed as 1 and so on. The

last array element is index as “n-1” if there are “n” total elements in the array. No

element is indexed with negative number as arr[-2] is invalid. Following table

shows the array indexing in detail:

Array 11 22 33 44 55 66 77 88 99 10

Index 0 1 2 3 4 5 6 7 8 9

element arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6] arr[7] arr[8] arr[9]

Following program uses array indexing:

Line # Finding Max of Three numbers

1 2 3

static void Main(string[] args) { int[] values = { 8, 7, 9 };

Page 204: Programming Fundamentals

Programming Fundamentals Using C# 203

4 5 6 7 8 9 10 11

int max = values[0]; if (max < values[1]) max = values[1]; if (max < values[2]) max = values[2]; Console.Out.WriteLine("Max Value is {0}", max); Console.Read(); }

P R O G R A M DE S C R I P T I O N : Line 1,2,10,11 are already explained.

3. Array of integers is declared and initialized

4. “max” variable is assigned the value of first element of array

5. In if-condition, value of “max” is compared with second element of array

and if value of “max” is smaller, line 8 is executed otherwise line 8 is

skipped

6. Value of second element is assigned to “max”.

7. In if-condition, value of “max” is compared with third element of array and

if value of “max” is smaller, line 8 is executed otherwise line 8 is skipped

8. Value of third array element is assigned to “max”.

9. Value of max is printed.

C# provides array bound checking at run time, If for an array of ten elements, you

try to read 11th element, the program raise exception and will shut down.

Figure 10 - 1: Unhandled Program Exception

Every array in C# provides a useful property called “Length” that allows to get the

length of array automatically. Following program uses this property.

Line # Array Length Property

1 2 3 4 5

static void Main(string[] args) { string[] days = { "mon", "tue", "wed", "thu", "fri", "sat", "sun" }; for (int day = 0; day <= days.Length-1; day++) Console.Out.WriteLine(days[day]);

Page 205: Programming Fundamentals

Programming Fundamentals Using C# 204

6 7

Console.Read(); }

Program Description: The program declares an array of string type, and using index

variable “day”, it prints all values of array. The loop runs from zero to array length-

1.

10.2.3. READING ARRAYS FROM USER You can read the array from user as well. We already have all required background

in this context so we directly move to program example.

Reading An Array from User

static void Main(string[] args) { decimal[] bills = new decimal[5]; Console.Out.Write("Enter internet bill:"); bills[0] = decimal.Parse(Console.ReadLine()); Console.Out.Write("Enter electricity bill:"); bills[1] = decimal.Parse(Console.ReadLine()); Console.Out.Write("Enter gas bill:"); bills[2] = decimal.Parse(Console.ReadLine()); Console.Out.Write("Enter water bill:"); bills[3] = decimal.Parse(Console.ReadLine()); Console.Out.Write("Enter cable TV bill:"); bills[4] = decimal.Parse(Console.ReadLine()); decimal totalBill = 0; for (int b = 0; b < 5; b++) totalBill = totalBill + bills[b]; Console.Out.WriteLine("Total of All Bills Rs.{0}",totalBill); Console.Read(); }

P R O G R A M DE S C R I P T I O N : The program declares an array of 5 decimals. It asks user

to enter internet bill and then reads its user entered value in first decimal of array.

Similarly electricity bill is read in second decimal and so on. Using for-loop, all read

decimals are summed up and finally the value in “totalBill” is displayed to user.

10.2.4. “FOREACH” LOOP In chapter related to loops, we did not explain this looping construct. It was due

to fact that this loop structure works with sequence of data or collection of data.

Now that the concept of arrays is clear to you, we can discuss foreach loop.

Page 206: Programming Fundamentals

Programming Fundamentals Using C# 205

“foreach” loop is very simple, precise and easy to use construct. The syntax of this

loop is given below:

for-each loop

foreach (var item in Array) { // body of loop }

In this syntax, “foreach” is keyword and called foreach-clause. It does not require

any specific conditional expression to be true to execute its body. Infact the loop

condition is the existence of next array element. If next array element is present,

the loop body will be executed otherwise the loop will terminate. The loop

executes its body as many times as there are elements in the “Array”. The counter

is automatically maintained with bound checking. Following program shows its

use.

Use of foreach construct

static void Main(string[] args) { int[] marks = new int[]{ 4, 5, 6, 7, 8, 9 }; foreach (int item in marks) Console.Out.WriteLine(item); Console.Read(); } Output: 4 5 6 7 8 9

In general foreach loop construct has the same properties like for loop. The main

difference is that the iteration is made always through all elements – from the start

to the end. You cannot access the individual elements of the array i.e. if you want

to access the 2nd element, foreach loop does not allow you to do this. You just

iterate the array from start to end. The foreach-loop statement is used, when we

do not need to change the elements, but just to read them.

10.3. MULTIDIMENSIONAL ARRAYS We know that programming is the process of modeling real life problem into

computer understandable form so that it could be solved in fast way by the

machine. In our real life we are familiar with different ways of data representation

Page 207: Programming Fundamentals

Programming Fundamentals Using C# 206

like sets in which values are arranged in sequential way and tables that are

arranged as rows and columns. Although data is stored sequentially in memory,

programming languages provide the way to model data in the form we are used

to. A dimension or rank of an array is represented by pair of square brackets.

Earlier in this chapter, we have discussed one dimensional arrays.

10.3.1. RECTANGULAR ARRAYS One dimensional arrays are known as “Vectors” in mathematics and two

dimensional arrays are known as “Matrices”. A multidimensional array could be

considered as collection of rows and columns of a “matrix”. Each row could be

viewed as sub-array and each column as an element in that array. An array having

equal number of elements, like a matrix, in each sub-array is called the

“rectangular array”. Vectors and Matrices are known as rectangular arrays. Each

dimension in multidimensional array starts at index zero. A two dimensional (2D)

array could be viewed in matrix form as follows:

Figure 10 - 2: 2D Array Conceptual View

Figure 10 - 3: 2D Array Index View

Element [0,0] [0,1] [0,2] [0,3] [1,0] [1,1] [1,2] [1,3] [2,0] [2,1] [2,2] [2,3]

Address 100 104 108 112 116 120 124 128 132 136 140 144

Value 1 3 6 2 8 5 9 1 4 7 3 0

Page 208: Programming Fundamentals

Programming Fundamentals Using C# 207

As shown in the table, for 2D array, we have used 2 indexes, first index represents

the row and second index represents the column of matrix. Here is the syntax of

two dimensional rectangular array.

Above discusses syntax creates an array that makes the compiler to put entries in

both table1 (reference) and table2 (memory address). Two dimensional array

could also be declared as reference variable for that compiler puts only one entry

i.e. in reference table. Such arrays could not be used in your program as they are

not yet defined (memory space is not allocated). Here is the syntax of declaring

reference array and then defining it.

Two Dimensional Array Syntax

<data type>[,] <identifier>; <identifier>= new <data type>[<size of dimension1>, <size of dimension2>]; double[,] marks; marks=new double[3,4];

You can define one dimensional array instead of two dimensional array having

equal number of elements and occupying same amount of space in memory. For

example, following two arrays occupy equal space in the memory and have same

number of elements but their programming view is different:

int[ ] marks=new int[12]; int[ , ] marks=new int[3,4];

The multidimensional view of arrays is suitable for modeling of real world things.

As an example, if you are required to read marks of 3 classes in your institute and

in each class there are 50 students, you can model then in one of the following

ways:

1. double[ ] marks=new int[150]; // simple way 2. double[ , ] marks=new int[3,50];// complex but more

// better way

You can see that second way of representing data is much better and more

understandable as compared to first one.

Two Dimensional Array Syntax

<data type>[,] <identifier> = new <data type>[<size of dimension1>, <size of dimension2>]; double[,] marks=new double[3,4];

Page 209: Programming Fundamentals

Programming Fundamentals Using C# 208

The use of two dimensional array is given in following program:

Line # 2D Array Program

1 2 3 4 5 6 7 8 9 10 11 12

static void Main(string[] args) { int[,] marks; marks = new int[3, 4]; for (int row = 0; row < 3; row++) for (int col = 0; col < 4; col++) { marks[row, col] = row + col; Console.Out.Write(marks[row, col]+" "); } Console.Read(); }

Output: 0 1 2 3 1 2 3 4 2 3 4 5

P R O G R A M DE S C R I P T I O N :

1. Start of main program

2. Main program body starts

3. Two dimensional (2D) array reference variable declaration.

4. Definition of 2D array “marks” with size 3*4=12 integers. As a matrix it

could be considered as 3 rows and 4 columns.

5. Outer “for-loop” that repeats its body 3 times

6. Nested inner “for-loop” that repeats its body 4 times. As inner loop is in

the body of outer loop, so inner loop and its body is repeated 3 times by

outer loop. Each time outer loop repeats its body, inner loop repeats its

body 4 times. So the body of inner loop is repeated 3*4=12 times in total.

7. Body of inner loop starts

8. Each element of “marks” array is assigned a value “i+j”

9. Value assigned to 2D array is displayed.

10. Inner loop body ends, outer loop body also ends here. Remember that if

curly brackets are not used to mark the start and end of loop body, only

one immediate statement is considered in the body of loop. So body of

outer loop consists of inner loop and its body.

11. Statement to hold output screen till user hits a key

12. Main program ends

10.3.2. INITIALIZING 2D RECTANGULAR ARRAYS A two dimensional array could be considered as a big array consisting of sub-

arrays. For example:

decimal[ , ] salaries=new decimal[3,4];

Page 210: Programming Fundamentals

Programming Fundamentals Using C# 209

“salaries” is a big array that contains 3 sub-arrays and in each sub-array, there

are 4 elements. We can initialize the arrays in the same way as shown in the figure:

decimal[ , ] salaries=new decimal[3,4]{ {9,5,4,3}, {6,7,8,2}, {2,4,6,8} }; decimal[ , ] salaries; decimal=new decimal[3,4]{{9,5,4,3},{6,7,8,2},{2,4,6,8}};

Both ways of initialization are equivalent, the difference is only use of multiple

lines for writing values in upper initialization whereas in lower initialization the

elements are written on same line. You may use either way in your programs.

Following program shows the use of 2D array initializations:

2D Array Initializations

static void Main(string[] args) { // Array size is automatically deduced from set of initialization values decimal[] salaries1 = new decimal[] { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 }; // Array Reference and definition decimal[] salaries2; salaries2 = new decimal[] { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 }; // 2D Array Initialization, multiple lines – // salaries of 3 departments each having 4 employees decimal[,] salaries3 = new decimal[3, 4]{ {9,5,4,3}, {6,7,8,2}, {2,4,6,8} }; // 2D Array Initialization, single line decimal[,] salaries4 = new decimal[3, 4] { { 9, 5, 4, 3 }, { 6, 7, 8, 2 }, { 2, 4, 6, 8 } }; // 2D Array - Seperate declaration and definition decimal[,] salaries5; salaries5 = new decimal[3, 4]{ {9,5,4,3}, {6,7,8,2}, {2,4,6,8} }; decimal[,] salaries6; salaries6 = new decimal[3, 4] { { 9, 5, 4, 3 }, { 6, 7, 8, 2 }, { 2, 4, 6, 8 } }; // displaying the array elements with foreach loop

Page 211: Programming Fundamentals

Programming Fundamentals Using C# 210

foreach (var element in salaries1) Console.Out.Write(" {0}", element); Console.Out.WriteLine(); //displaying the array element with for loop for(int i=0;i<salaries1.Length;i++) Console.Out.Write(" {0}", salaries1[i]); Console.Out.WriteLine(); // displaying 2D array with for loop for (int i = 0; i < salaries5.GetLength(0); i++) for (int j = 0; j < salaries5.GetLength(1); j++) Console.Out.Write(" {0}",salaries5[i, j]); Console.Out.WriteLine(); // displaying 2D array with foreach loop foreach (var item in salaries5) Console.Out.Write(" {0}", item); Console.Read(); } Output: 10 11 12 13 14 15 16 17 18 19 20 21 10 11 12 13 14 15 16 17 18 19 20 21 9 5 4 3 6 7 8 2 2 4 6 8 9 5 4 3 6 7 8 2 2 4 6 8

A two dimensional array has two dimensions indexed as “0” and “1”. In our

example, size of first dimension is “3” and second is “4”. Two new statements used

in this program are described below:

salaries1.Length: This property returns the total length of array i.e.

12 in above example.

salaries5.GetLength(0): It returns the length of particular

dimension of an array i.e. salaries5.GetLength(0) returns 3.

In previous examples of this chapter, we have specified the array size explicitly. C#

allows you to specify the size of array at run time, whether it is single dimensional

or multidimensional. Our next example demonstrates dynamic array size

specification:

Dynamic Array Specification

static void Main(string[] args) { uint rows, cols; Console.Out.Write("Please enter the number of Classes:"); rows = uint.Parse(Console.ReadLine());

Page 212: Programming Fundamentals

Programming Fundamentals Using C# 211

Console.Out.Write("Please enter the number of Students in each Class:"); cols = uint.Parse(Console.ReadLine()); decimal[,] marks = new decimal[rows, cols]; for(int row=0;row<rows;row++) for (int col = 0; col < cols; col++) { Console.Out.Write("Enter marks for student {1} of class {0}:", (row+1), (col+1)); marks[row, col] = decimal.Parse(Console.ReadLine()); } Console.Out.WriteLine("You have entered marks as follows"); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { Console.Out.Write("Marks of student {1} of class {0}:", (row+1), (col+1)); Console.Out.WriteLine(marks[row, col]); } Console.Out.WriteLine(); } Console.Read(); }

In this program statement “decimal[,] marks = new decimal[rows,

cols];” defines an array after reading its size from user.

10.3.3. HIGHER DIMENSIONAL RECTANGULAR ARRAYS C# allows you to define arrays of as many dimensions as you want. As the

dimension of array increases, its visualization becomes difficult. Following list of

syntaxes are used to define multidimensional arrays.

3D Array

<data type>[,,] <identifier> =new <data type>[<size1>,<size2>,<size3>]; Example: double[,,]=new double[2,3,4];

4D Array

<data type>[,,,] <identifier> =new <data type>[<size1>,<size2>,<size3><size4>]; Example: float[,,]=new float[2,3,4,5];

… …

ND Array

<data type>[,,,…,] <identifier> =new <data type>[<size1>,<size2>,…,<sizeN>]; Example: uint[,,…,]=new float[2,3,4,5,…,N];

Here is the modeling similarity with real world problems:

int[] marks=new int[5]; : List of marks of 5 students

Page 213: Programming Fundamentals

Programming Fundamentals Using C# 212

int[,] marks=new int[2,5];:List of marks of 5 students in each of

2 classes

int[,,] marks=new int[2,2,5];:List of marks of 5 students in each

of two classes of each of two departments.

...

If you recall the concept of arrays and sub-arrays presented earlier in this chapter

1D array could be considered as list of values.

2D array is considered as a large array consisting of sub-arrays and each

of sub-array consists of values

3D array is a large array which consists of sub-arrays, each of sub-array

further consists of sub-sub-arrays and each sub-sub-array consists of

values.

Initialization of higher dimensional arrays can be done in same way:

int[,,] marks; marks = new int[2, 3, 4]{ // Big Array starts { // Sub-Array 1 starts {1,2,3,4}, // Sub-Sub Array {5,6,7,8}, // Sub-Sub Array {9,10,11,12} // Sub-Sub Array }, // Sub-Array 1 ends { // Sub-Array 2 starts {13,14,15,16}, // Sub-Sub Array {17,18,19,20}, // Sub-Sub Array {21,22,23,24} // Sub-Sub Array } // Sub-Array 2 ends }; // Big Array ends

For further higher dimensional arrays, you should attempt to initialize yourself.

10.3.4. ARRAYS OF ARRAYS – JAGGED ARRAYS These are the arrays in which each sub-array contains its own array. Elements of a

jagged array are also arrays. The elements of a jagged array can be of different

dimensions and sizes. The declaration of one dimensional jagged array is shown

below:

Line # Jagged Array Declaration Syntax 1 2 3 4

uint[][] Customers; Customers = new uint[2][]; Customers[0] = new uint[2]; Customers[1] = new uint[2];

Page 214: Programming Fundamentals

Programming Fundamentals Using C# 213

SYN TA X DE SCR IPT IO N :

1. An array of arrays (jagged array) of data type unsigned integers (uint) with

name “Customers” is declared.

2. The array is “defined” (memory is allocated for it). It is to note that

memory representation of jagged arrays is different from regular arrays.

At line 2, memory is allocated for 2 uint type variables. Each variable will

not contain the value instead it will contain the address. So space of two

addresses is allocated by this statement.

3. A space for 2 uint values is allocated in RAM and starting address of that

location is moved to first location of “Customers” array.

4. A space for 2 uint values is allocated in RAM and starting address of that

location is moved to second location of “Customers” array.

The concept is explained pictorially step wise as follows:

STEP 1: Variable is declared

Compiler Tables

First Table (Reference) Second Table (Memory Addresses)

uint[][] Customers; - An entry is made in the “reference table” by compiler. No space in memory is

reserved.

STEP 2: Variable is defined

Compiler Tables

First Table (Reference) Second Table (Memory Addresses)

uint[][] Customers; 104 Defining jagged array, reserves memory. In our case the memory is reserved for

two values, these values will not be actual values but addresses of other two

arrays. The addresses are not reserved at this stage. Later when addresses will be

reserved, those will be moved into these two reserved locations as shown below:

Address … 104 105 106 107 108 109 110 111 … Value … x x x x x x x x …

STEP 3 & 4: Sub-Array is defined. Memory is reserved for sub-arrays. The

addresses of sub-arrays are moved to the memory locations reserved for this

Mem

ory

Page 215: Programming Fundamentals

Programming Fundamentals Using C# 214

purpose in step 2. The newly reserved spaces for sub-arrays may differ from each

other as shown in the following diagram:

Address … 104 105 106 107 108 109 110 111 … Value … 116 124 …

Address … 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 … Value … …

Above pictorial steps are summarized as follows:

Customers[][] Customers[0]

Customers[1]

5 6

7 8

2D jagged array is declared as follows whereas higher dimensional arrays could

be defined following same way:

2D Jagged Array Declaration

int[][,] jaggedArray = new int[3][,]; JaggedArray[0]=new int[2,3]; JaggedArray[1]=new int[3,4]; JaggedArray[2]=new int[2,2];

Following programs show the use of 1D and 2D jagged Array:

1D Jagged Array

static void Main(string[] args) { uint[][] Customers; // reference variable declaration Customers = new uint[2][]; // customers definition Customers[0] = new uint[2]; // One Sub-Array Customers[1] = new uint[2]; // second Sub-Array // Assigning values to indivisual elements for (uint i = 0; i < 2; i++) for (uint j = 0; j < 2; j++) Customers[i][j] = i + j;

uint[][] Customers; 104

Memory

Page 216: Programming Fundamentals

Programming Fundamentals Using C# 215

//displaying values for (uint i = 0; i < 2; i++) for (uint j = 0; j < 2; j++) Console.Out.WriteLine(Customers[i][j]); Console.Read(); }

And this program shows the use of 2D jagged array:

2D Jagged Array Program

static void Main(string[] args) { // marks of students of two departments // each department have different class size // but within a department class size is same int[][,] marks = new int[2][,]; // 2 depts marks[0] = new int[2, 2]; // dept 1 has 2 classes, each of size 2 marks[1] = new int[3, 3]; // dept 2 has 3 classes, each of size 3 // reading rollno and marks of class 1 for (int i = 0; i < 2; i++) { if (i == 0) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { Console.Out.Write("Dept {0} Class {1}: Enter marks for Roll No.{2}:",(i+1), (j + 1), (k + 1)); marks[i][j, k] = int.Parse(Console.ReadLine()); } } } else { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { Console.Out.Write("Dept {0} Class {1}: Enter marks for Roll No.{2}:",(i+1), (j + 1), (k + 1)); marks[i][j, k] = int.Parse(Console.ReadLine()); } } } } //displaying all the marks for (int i = 0; i < 2; i++) { if (i == 0) {

Page 217: Programming Fundamentals

Programming Fundamentals Using C# 216

for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) Console.Out.WriteLine("Dept {0} Class {1}: Marks for Roll No.{2}:{3}", (i+1),(j + 1), (k + 1),marks[i][j,k]); } else { for (int j = 0; j < 3; j++) for (int k = 0; k < 3; k++) Console.Out.WriteLine("Dept {0} Class {1}: Enter marks for Roll No.{2}:{3}",(i+1), (j + 1), (k + 1),marks[i][j,k]); } Console.Read(); } }

INIT IA LI Z IN G JAG G ED ARRAY S

Initialization of jagged array is done individually for each sub-array. C# provides

various ways to initialize the arrays. Here is the initialization of one dimensional

jagged array:

Initialization of 1D Jagged Array

uint[][] Customers; Customers = new uint[2][]; Customers[0] = new uint[2]{5,6}; Customers[1] = new uint[2]{7,8}; int[][] jaggedArray3 = { new int[] {1,3,5,7,9}, new int[] {0,2,4,6}, new int[] {11,22} }; int[][] jaggedArray2 = new int[][] { new int[] {1,3,5,7,9}, new int[] {0,2,4,6}, new int[] {11,22} };

Here is the initialization of 2D jagged array:

2D jagged array initialization

int[][,] jaggedArray4 = new int[3][,] { new int[,] { {1,3}, {5,7} }, new int[,] { {0,2}, {4,6}, {8,10} }, new int[,] { {11,22}, {99,88}, {0,9} }

Page 218: Programming Fundamentals

Programming Fundamentals Using C# 217

}; The use of these arrays is shown in programs of section 3.4.

Page 219: Programming Fundamentals

Programming Fundamentals Using C# 218

Chapter 11

Named Code Blocks In this chapter, we will study about creating named code blocks called methods. We will

discuss why we need to create such blocks, how they are created and what are the rules that

govern the linking of these blocks with main program, what type of parameters could be

passed and how values are returned from these blocks or methods. We will also study and

use important C# built-in methods. The concepts presented are explained with the help of

examples. At the end we will present best practices to write named code blocks.

After studying this chapter, it is expected that the reader will be able to write code in well

managed way using methods.

11.1. THE METHODS “Divide and conquer” is one of the best techniques used to solve complex problems. In

divide and conquer approach a big problem is divided into many small problems. Each

small problem is solved individually as they are easy to resolve and then they are combined

to formulate the solution of bigger problem.

Developing a software could be considered as a big problem. The set of instructions for

software development may consist of hundreds and thousands of lines of code or

instructions. As the size of code increases, it becomes difficult to manage and understand.

Programmers normally use “divide and conquer” approach to manage the code. The

software under development is divided into small sub-problems called sub-routines. Each

sub-routine is given unique name and is well defined i.e. it performs only one particular

task. When code for all sub-problems is written, it is then combined to form the solution

of bigger problem (software). There are different names used for these sub-routines. Some

languages call them functions, some other name them as procedures and C# calls them

“Methods”. There is little difference among these terminologies that we will explain later

in this chapter.

11.1.1. WHAT IS A METHOD A method is set of statements that performs a particular task and have its unique

name. Programmer can pass values to the methods and method may return some

result. Passed values are called the “parameters” and returned value is called the

“result”.

A method is basic unit of your program. Before discussing the methods in detail,

let look at an example method:

Page 220: Programming Fundamentals

Programming Fundamentals Using C# 219

Method Example

static int Square(int x) { int temp; temp=x*x; return x; }

This example method receives a value in variable “x”. It calculates square of given

value and returns back. You may not understand all the coding of this example

method but a view is worth at this stage.

11.1.2. WHY TO USE METHODS Although a complete program could be written in “main” program but there are

multiple reasons for using methods in your program and with practice and

experience, you will understand that methods are good enough to use in your

program and you cannot avoid them.

BE T T E R S T R U C T U R E D P R O G R A M : Better structure means to write code in a way

where different types of code, parts of code could easily be identified. Each part

of code must be solving one particular problem methods must be linked in natural

way of problem solving. By looking at code, one can understand that which code

part performs which job. It frees the programmer from considering “how task is

performed”.

BE T T E R RE A D A B I L I T Y : Code written in well-organized way is easy to read and

understand. As the use of methods moves reader focus from “how task is

performed” to “what task is performed”, it makes code readability faster and

easier. During software development, you may need to write statements, compile

them and test them. The logic build by you may be complex. If after few days you

are required to update your software consisting of thousands lines of code, may

take lot of your time in understanding the code if not properly structured and well

written. The time from start of software development to point where the use of

software ends is called the software development life cycle (SDLC). Normally the

code writing and testing time is 20% of SDLC whereas rest of the 80% time,

software remains in use where its maintenance may be required many times.

Software maintenance refers to the incorporating new features in software,

removing old features and changing features. The software is not only maintained

by its creator but by other programmers as well. It is therefore essential for code

to be well structured and as easily readable as possible.

Page 221: Programming Fundamentals

Programming Fundamentals Using C# 220

A V O I D A N C E O F C O D E D U P L I C A T I O N : If you have written a code to solve some

task, you can link it with main program as many times as you need. It saves you

from writing the code again and again to solve the same task.

C O D E R E U S E : If a piece of code repeatedly (or some task is done again and again)

in your program, it is better to write a method that does that particular task and

link it with your program. This approach enables the programmer to “reuse” the

same code without rewriting it. It also reduces the size of program. In contrast if

you repeat the code again and again that performs same task, it makes your

program complex and difficult to understand. If during maintenance phase, a piece

of code is found faulty, the programmer needs to changes all occurrences of that

code which increases the error chance as some occurrences are corrected and

few may be leftover but if a method is written for that task, the programmer will

need only to fix one occurrence only.

11.2. IMPLEMENTING METHODS Like variables in C# that are declared, defined and used, methods are also declared,

defined (implemented) and used. We will discuss the methods in same sequence.

11.2.1. METHOD DECLARATION Method declaration means telling compiler that a code block with this name and

other relevant features will exist in our program. Listing the name of a method

present in your program is called the method declaration. Here is the syntax of

declaring a method:

Method Declaration Syntax

[ static] <return_type> <method_name>([<parameter_list>])

Here is the description of syntax elements:

[ ] : Anything written is square brackets is optional. During declaration It

may exist or not.

S T A T I C : this is optional keyword used with method declaration. The

purpose of this word will be explained in later chapters. At present you

should know that it is necessary to write this keyword in start of method

declaration

RE T U R N -T Y P E : As said above, method may return some result or not. If

method has to return some value, there is some data type of that value,

data type of value being returned is written here.

ME T H O D -N A M E : It is the name that you provide to code block. You can

give name of your choice to method.

Page 222: Programming Fundamentals

Programming Fundamentals Using C# 221

PA R A M E T E R-L I S T : You can give one or more values to the method that

are manipulated by the method. These values are optional. Some methods

may have and some other may not.

It would be interesting for you to know that we have already used a method in our

example programs given previous chapters. Here is the listening:

static void Main(string[] args)

“Main” method is a special method which is used to start your program and when

it ends, program ends. You can see that optional keyword “static” is used, return

type “void” is used. “void” is special keyword or data type that specifies “nothing”.

Use of “void” with “Main” tells the compiler that this method will returning

nothing. “Main” is special keyword used to declared special method which is called

by the operating system to run your program.”(“ and “)” are part of syntax so these

are required to be written as they are. “string[] args” is one dimensional array of

strings passed as parameter. We have not used these strings till now. Its use will

be explored in next chapters. It is to note that when a program is compiled, it takes

the form of executable program. That executable program is run by the operating

system. Hence “string[] args” are passed by the operating system to our program

and if our program returns some value, it is given back to operating system.

When declaring a method, you should follow sequence of syntax elements strictly.

Change in this sequence is not accepted by the compiler and will generate an error.

ME T H O D S I G N A T U R E S : We have discussed elements of method declaration

syntax. These elements describe the method, its input (parameter list) and output

value type (return type). When a method is specified with all these elements, the

specification is called the method signatures. Some authors exclude return type

from signatures.

11.2.2. Method Definition (Implementation) A method is written to perform particular task. You are allowed by the compiler to

give method name of your choice. It is recommended that you should chose

method name that matches its functionality. For example, if a method performs

addition of two numbers, providing its name like “method1” is not a good idea. Its

suitable name could be “Add” or “Sum”. Following is the list of recommended rules

for method names:

Method name should start with capital letter

Page 223: Programming Fundamentals

Programming Fundamentals Using C# 222

If method name consists of multiple words, it should be written in

PascalCase i.e. if method name is “calculateprofit”, it should be

written as “CalculateProfit”

There should be no space between multiple word method name i.e.

“Calculate Profit” is not valid name but “CalculateProfit” is valid

A method name should consist of verb or verb and noun

A method cannot be used until it is defined in your program. Method definition

refers to writing instructions that performs method intended task. Here is the

syntax of writing the method:

Method Definition Syntax

[static] <return_type> <method_name>([<parameter_list>]) { // Body of Method }

A method definition consists of method signatures and its body. The body of

method is enclosed between curly brackets just like body of if-statement or loops.

You may write any statements in loop body. Following is a method definition:

Method Definition static void PrintSum() { int a=int.Parse(Console.ReadLine()); int b=int.Parse(Console.ReadLine()); Console.Out.WriteLine(a+b); }

11.2.3. WHERE TO WRITE METHOD C# program starts with “Main” method. The language does not allow you to write

method within another method. Following is the skeletal program code

automatically generated by IDE:

Skeletal Program

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BasicMethod { class Program { // Method definition goes here

Page 224: Programming Fundamentals

Programming Fundamentals Using C# 223

static void Main(string[] args) { } // or method definition goes here } }

In this program, there are two comments before and after the “Main” method.

You can place your methods either before or after the main method on indicated

places. You can observe another code block named “class Program” with its body

in which “Main” is written. All method should be written in the body of “class”.

You can write the methods in any order as the order of writing methods does not

matter. Here is the program that shows the definition of a method.

BasicMethod Program

class Program { static void Sum() { int a = 6, b = 5; Console.Out.WriteLine(a + b); } static void Main(string[] args) { } } class Program { static void Main(string[] args) { } static void Sum() { int a = 6, b = 5; Console.Out.WriteLine(a + b); } }

Above given both programs are equivalent. You may choose your way to write

methods.

11.2.4. USE OF METHODS Before we discuss the use of methods, we describe already discussed two

concepts. The program we write is a sequence of statements and these statements

Page 225: Programming Fundamentals

Programming Fundamentals Using C# 224

are executed in order of their listening. The statement which is written earlier is

executed first and one written later is executed later. C# program starts when the

body of “Main” method starts and ends when body of “Main” method ends.

To use our new methods, we need to link these methods with “Main” method.

This method linking is called “method calling”. A method is called by writing its

name in “Main” program as statement. The syntax for writing method call is given

below:

Method Call Syntax

<Method Name>([<argument-list>]);

Just specify the name of method with optional argument list. In this section we

look at methods with no arguments. Below given program shows this linking:

Line # Method Calling

1 2 3 4 5 6 7 8 9 10 11 12

class Program { static void Main(string[] args) { Sum(); // method linking or method calling } static void Sum() { int a = 6, b = 5; Console.Out.WriteLine(a + b); } }

P R O G R A M DE S C R I P T I O N : You must understand this description very clearly.

1. “class” named “Program” is starts. What is “class”? we have not yet

described it. You must take it as it is. The description will be provided in

next chapters.

2. Body of “class Program” starts.

3. “Main” program starts. From now onward we will call it “Main” method.

4. Body of “Main” method starts

5. Our defined function is linked with main program. It is to note again that

our program only confined to “Main” method or to those methods which

are linked with “Main”. After the execution of this statement, control of

program moves to line # 7.

7. Signatures of “Sum” method are written

8. Body of “Sum” method starts

9. Two integer variables “a” and “b” are defined and initialized

Page 226: Programming Fundamentals

Programming Fundamentals Using C# 225

10. Sum of “a” and “b” are printed out

11. Body of “sum” method ends. From this point the program control moves

back to NEXT line from where it has jumped to “sum” method. The

program took jump from line 5 and now from line 11, it jumps to line 6.

6. Body of main program ends

1. Control moves to end of “class Program” and program ends

We have deliberately changed the numbering of above list. This shows the flow of

program control. Whenever a method call is executed the program control jumps

to method definition. After executing the body of method, the control jumps back

to point from where it jumped and starts executing from next instruction.

Following figure explains the same concept:

Figure 11 - 1: Method Call and Program Control Flow

We have already used many methods in our programs. In above figure three

methods are used: “Main”, “Sum” and “WriteLine”. In previous programs we have

used “Write”, “Read”, “ReadLine” and “Parse” methods.

11.3. METHODS AND PARAMETERS Method parameters are either constants or variables. We can pass parameters

from the point where they are called. These passed parameters are received on

the point where method signatures are written. The values passed through

Page 227: Programming Fundamentals

Programming Fundamentals Using C# 226

parameters from method calling point are received in new variables on method

definition point.

11.3.1. PASSING SINGLE PARAMETER Passing parameters to methods is optional. There may be methods with no

parameters as discussed in previous section, there may be single parameters or

multiple parameters. Using one parameter, you can easily understand the

concept. Following program shows the passing of single parameter:

Line# Passing Parameter1

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

class Program { static void Square(int x) { int sqr; sqr = x * x; Console.Out.WriteLine(sqr); } static void Main(string[] args) { int a = 5; Square(a); //method call Console.Read(); } }

P R O G R A M DE S C R I P T I O N : You must understand this description clearly. Like

previous program description, the list numbering is important to consider.

1. “class” program starts

2. Body of class starts

9. Program “Main” method definition starts

10. Body of “Main” method starts

11. Integer variable “a” is defined and initialized with value “5”

12. Method “Square” is called. Variable “a” is passed as parameter. From this

point the program control moves to line 3

3. Method “Square” definition starts. In parenthesis a new integer variable

“x” is declared. The value of passed parameter “a” is copied into “x” so “x”

is defined.

4. Body of “Square” starts

5. An integer variable “sqr” is declared

6. This line contains arithmetic expression which multiplies “x” with itself and

result is assigned to “sqr”

Page 228: Programming Fundamentals

Programming Fundamentals Using C# 227

7. Value of “sqr” is printed on console using “WriteLine” method. You do not

see the body of “WriteLine” as this method is defined in .Net framework

and we link it as library with our program. When we compile our program,

library linker software links the library code with our program.

8. Body of method “Square” ends. At this point the program control jumps

back to the point from where it jumped to our method

13. Program control reaches to this line after completely executing our

method. At this line, we have called “Read” method that is also defined

inside the .Net framework library like “WriteLine” method. “Read”

method stops output screen for user view and on hitting some key, the

output screen vanishes

14. “Main” method body ends

15. “class Program” body ends

There is an “assignment” relationship between values passed during method call

and received in method definition as shown below:

int x=a;

It is to note that “Read” and “WriteLine” methods are not written individually like

“Square” method. Although there is “Console” and “Console.Out” written before

“Read” and “WriteLine”. We will explain it in later chapters.

P A R A M E T E R S A N D AR G U M E N T S : These are two terms used to identify passed

values to methods and received values in methods. The values which are passed

to method during method call are called the “Arguments” whereas the variables

that receive passed values are called the “Parameters”. Some authors use term

“Actual Parameters” for “Arguments” and “Formal Parameters” for

“Parameters”. From now onward, we will use the term parameters and

arguments.

In our “Passing Paramters1” example, method call at line 12 has one argument “a”

and line 3 of method definition contains one parameter “x”.

11.3.2. PASSING MULTIPLE PARAMETERS Multiple parameters of different types could be passed to methods. Each

parameter definition must be separated by “,” (comma) from other parameter.

Below is the syntax of passing multiple parameters:

Multiple Parameters Syntax

[static] <return type> <MethodName>(<param1 data type> <param1 name>,<param2 data type> <param2 name>,. . . ,<paramN data type> <paramN name>)

Page 229: Programming Fundamentals

Programming Fundamentals Using C# 228

Example: static void FindGreater(int a,int b)

It should be noted that data types of parameters must match the data types of

arguments. Parameters are new variables in which values of arguments are

copied. The sequence of arguments and parameters must match according to their

data types. It should also be noted that in method definition, data type of every

parameter must be specified separately. You may declare the variables in method

like “int a,b”. Both will be declared as integers correctly but in method

definition it is not allowed, you must write like “int a, int b”.

Let us consider the following example:

Arguments and Parameters Matching

class Program { static void Main(string[] args) { int a = 30,b = 40; FindGreater(a, b); Console.Read(); } static void FindGreater(int x, int y) { if (x > y) Console.Out.WriteLine("First value is greater"); else Console.Out.WriteLine("Second value is greater"); } }

data type of parameter “x” must match with argument “a” as value of “a” will be

copied into “x”. The value of “b” will be copied into “y” so data type of “y” must

match with that of “b”. It is emphasized that “a” , “b” are different variables and

“x”,”y” are different variables. There is no relationship between these except

values of argument copied into parameters. It is obvious that if value of x or y is

changed, there would be no effect on the value of a or b.

The relationship between arguments and parameters is of assignment type as

shown below:

int x=a; int y=b;

Page 230: Programming Fundamentals

Programming Fundamentals Using C# 229

Theoretically as many parameters could be passed as you need and you can mix

them in a way you require. Following program shows the use of multiple

parameters with mixed data types.

Passing Mixed Type Arguments

class Program { static void Main(string[] args) { int aa = 20; bool bb = true; long cc = 600; float ff = 23.56f; double dd = 78.9876; string ss = "Good Morning Pakistan"; Console.Out.WriteLine("This program shows use of mixed type parameters"); ShowParams(aa,bb,cc,ff,dd,ss); Console.Read(); } static void ShowParams(int a, bool b, long c, float f, double d, string s) { Console.Out.WriteLine("Showing Parameters\' Values"); Console.Out.WriteLine(a); Console.Out.WriteLine(b); Console.Out.WriteLine(c); Console.Out.WriteLine(f); Console.Out.WriteLine(d); Console.Out.WriteLine(s); } }

You can pass mathematical expressions as arguments to methods. An expression

being passed as argument must produce single value are result. We have already

seen such examples like “WriteLine(2+3)”. The expression is evaluated first

and single value is moved to called method.

11.4. USING DIFFERENT ARGUMENT AND PARAMETERS TYPES We can pass different type of arguments for different type of parameters. For

example, if argument is of type “float”, the receiving parameter could be of type

“double”. As discussed in previous section, there is assignment type of relationship

between arguments and parameters so rule of conversion and casting are

applicable here. If the data type of parameters is equal or larger than that of

argument, the data assignment is done automatically using conversion process.

Different Types of Parameters

class Program { static void Main(string[] args) {

Page 231: Programming Fundamentals

Programming Fundamentals Using C# 230

float rev=5000.75f; int cost=3250; CalculateProfit(rev,cost); Console.Read(); } static void CalculateProfit(double revenue, long cost) { Console.Out.WriteLine(revenue - cost); } }

In this program the relationship of arguments and parameters is as follows:

Double revenue=rev; Long cost=cost;

Variables on right side of assignment have smaller type whereas variables on left have larger types but it is to note that both belong to same class of data type. You may wonder that we have used same name of variable “cost” in calling method and called method. It is allowed and discussed in next section. In opposite case, where arguments have larger data type and parameters have smaller data types or moving one type of value into different type of parameter, you need to cast them yourself as shown in following example:

Different Type Parameters 1

class Program { static void Main(string[] args) { double rev = 5000.75f; long cost = 3250; CalculateProfit(Convert.ToSingle(rev), Convert.ToInt16(cost)); Console.Read(); } static void CalculateProfit(float revenue, int cost) { Console.Out.WriteLine(revenue - cost); } }

11.4.1. METHODS AND VARIABLES We have seen that variables could be declared in “Main” method. We have also

seen that our defined methods could also define variables either in method

declaration or in its body. There are two concepts associated with variables: scope

or visibility and variable life time. First concept is defined here whereas second will

be discussed later in next chapters.

Page 232: Programming Fundamentals

Programming Fundamentals Using C# 231

V A R I A B L E V I S I B I L I T Y refers to the code segment where that variable could be

accessed and used. A variable is visible only in code block where it is defined. Based

on visibility, we can divide variables into two categories: local variables and global

variables.

L O C A L V A R I A B L E S : These are the variables which are defined within some method

or code segment. A variable is visible from the point of its definition to end of its

enclosing code block. C# does not allow you to define more than one variables

with same name in a method or code block however a local variable defined in

some code block has no relation with variables defined in other code block.

Therefore two variables with same name could be defined in different code blocks.

We are using the term “code block” as it could refer to if-statement and its body,

loops and their bodies and methods etc. Following is the series of examples

showing the use of local variables:

Figure 11 - 2: Variable Visibility

In above program, you can see that variable “salary” is used before its declaration.

Compiler has raised error in this case and proper error message is displayed in

“Error List”. IDE has also marked the error point with read line.

Page 233: Programming Fundamentals

Programming Fundamentals Using C# 232

Figure 11 - 3: Local Variable and Visibility

In above figure you can see that a variable “temp” is defined inside body of if-

statement. Its visibility is in first code block that ends at line 14. At code line 16,

new code block starts. We have tried to use “temp” variable here. Now “temp” is

not visible in this block therefore its use has generated errors given in “Error List”.

As “temp” has been used at two places in second code block so two errors are

generated. The code editor has also marked the error points with red line.

Whenever you encounter with errors, try to understand the error message

displayed by the compiler. The same program would be error free if we define

“temp” as new variable in second block as shown below:

First code block

Second code block

Page 234: Programming Fundamentals

Programming Fundamentals Using C# 233

Figure 11 - 4: Variable Visibility in Code Blocks

New local

variable is

defined

Page 235: Programming Fundamentals

Programming Fundamentals Using C# 234

Following example shows the use of same name variables in different methods

that is perfectly right.

Figure 11 - 5: Local Variable and Visibility

Above program produces following output:

Calling the method 5 times I love my culture I love my culture I love my culture I love my culture I love my culture

Method “ShowMessage()” is called 5 times. The sequence of execution of

instructions is listed here. You are required to consider them carefully and for

programs presented later in chapter, list similar sequences.

Instruction Execution Sequence

12345678910111415161718101114151617181011141516171810111415161718101114151617181012131920

G L O B A L V A R I A B L E S : These are the variables which are visible among all code

blocks defined in your program. Such variables are defined outside methods or

code blocks. There are two types of global variables

Same Name Local

Variables

Page 236: Programming Fundamentals

Programming Fundamentals Using C# 235

Local-global variables

Global-global variables

L O C A L-G L O B A L VA R I A B L E S : A method may consists of multiple code blocks. Any

method local variable defined before those code blocks is global variable for those

code blocks. Any such code block can access and use that variable. Such variable

are local at method level and global at code blocks level.

In following program, a variable “price” is defined. This is local variable for method

“Main” but at the same time it is global variable for “if” code block and “else” code

block.

Local Global Variable

static void Main(string[] args) { double price; price = double.Parse(Console.ReadLine()); if (price < 100) { Console.Out.WriteLine("Tax should be:" + (price * 0.08)); } else { Console.Out.WriteLine("Tax should be:" + (price * 0.12)); } }

If you have defined a method local variable, C# does not allow you to define same

name variable within any code block inside method. Following program violates

this rules and compiler generates errors.

Page 237: Programming Fundamentals

Programming Fundamentals Using C# 236

Figure 11 - 6: Variables and Visibility

In above program, a variable “num” is defined which is local variable in method. Another

variable “num” is defined in if-code block. The compiler has generated error

“A local variable named 'num' cannot be declared in this scope because it would give a

different meaning to 'num', which is already used in a 'parent or current' scope to denote

something else”

It means that within a method, if visibility of one variable started, no other variable with

same name could be defined in its visibility.

G L O B A L -G L O B A L VA R I A B L E S : These are the variables which are defined outside

methods but within “class”. These are visible among all methods. Following example

program shows the use of global-global method.

Method Global Variable

class Program { static string msg = "Try to be well mannered citizen"; static void Main(string[] args) { Console.Out.WriteLine(msg); ShowMessage(); Console.Read(); } static void ShowMessage() {

Page 238: Programming Fundamentals

Programming Fundamentals Using C# 237

Console.Out.WriteLine(msg); } }

If you have declared a variable with some name at global-global level, C# allows

you to define same name variables within methods. Method local variables may

have same name as that of global variable. If a method contains any local variable

with same name as that of global variable, global variable will not be accessible in

that method. Consider the following program:

Global Local Variable

class Program { static string msg = "Best manner is tell to truth always"; static void Main(string[] args) { // Console.Out.WriteLine(msg); string msg = "We are peaceful nation"; Console.Out.WriteLine(msg); ShowMessage(); Console.Read(); } static void ShowMessage() { Console.Out.WriteLine(msg); } }

In this program, there is a global variable “msg”. “Main” method first try to access

the global variable “msg” but gets an error. This error is due to declaration of local

variable with same name “msg”. If there is local variable with same name, global

variable is now not visible in this code block. “ShowMessage()” method also try to

access the global variable “msg” and there is no error because no local variable

with same name is defined in this method.

11.5. USING MULTIPLE METHODS The problem for which software is going to be developed may be complex and could be

broken into multiple smaller sub-tasks. Each sub-task is separately coded in the form of

method and then all methods are linked with “Main” method. This method linking (method

calling) is done in logical way of problem solution. We explain this concept with the help

of example. Let we have to write a program that works like calculator that has only

following functions:

Addition of two numbers

Page 239: Programming Fundamentals

Programming Fundamentals Using C# 238

Subtraction of two numbers

Multiplication of two numbers

Division of two numbers

Each function could be coded in the form of method. Program to solve this problem is

listed below:

Calculator Program

using System; namespace Calculator { class Program { static void Main(string[] args) { int a = 9, b = 2; Addition(a, b); Subtraction(a, b); Multiplication(a, b); Division(a, b); Console.Read(); } static void Addition(double a, double b) { Console.Out.WriteLine("Sum: {0}", (a + b)); } static void Subtraction(double a, double b) { Console.Out.WriteLine("Difference:{0}", (a - b)); } static void Multiplication(double a, double b) { Console.Out.WriteLine("Product:{0}", (a * b)); } static void Division(double a, double b) { Console.Out.WriteLine("Quotient: {0}", (a / b)); } } }

11.5.1. NESTED METHOD CALLS We have seen that “Main” method can call other methods. Method which calls

other method is named as “calling method” and a method being called is named

“called method”. When a method can call other method and called method can

further call other method. This calling sequence could be as long as it is required

Page 240: Programming Fundamentals

Programming Fundamentals Using C# 239

for problem. Following program shows the nested method call (method call within

other method call):

Nested Method Calls

class Program { static void Main(string[] args) { int a = 5, b = 3; Divide(a, b); } static void Divide(int a, int b) { Validate(a, b); Console.Out.WriteLine(a / b); } static void Validate(int a, int b) { if (b == 0) Console.Out.WriteLine("Divide by zero is undefined"); else Console.Out.WriteLine("Valid operands, division possible"); } }

11.5.2. OVERLOADED METHODS C# allows you to declare and define methods of same name but such methods

differ in signatures. This difference in signature is due to two reasons: 1) difference

in number of parameters 2) difference in type of parameters. This difference

makes it easy for compiler to identify the methods from each other. Each such

method having same name but different signatures is called the overload and

collectively all such methods are called the overloaded methods.

Page 241: Programming Fundamentals

Programming Fundamentals Using C# 240

Overloaded Methods

class Program { static void Main(string[] args) { int a = 20, b = 40,c=99; double d = 11.44, e = 44.22; Sum(a, b); Sum(a, b, c); Sum(d, e); Sum(a, d, c); Console.Read(); } static void Sum(int a, int b) { Console.Out.WriteLine(a + b); } static void Sum(int a, int b, int c) { Console.Out.WriteLine(a + b + c); } static void Sum(double a, double b) { Console.Out.WriteLine(a + b); } static void Sum(int a, double b, int c) { Console.Out.WriteLine(a + b + c); } }

Compiler is intelligent enough to figure out which method is called. This decision

made by compiler is based on number and type of parameters passed to method.

11.6. RETURNING VALUES FROM METHOD Before discussing the way of returning values from methods, we look at following special

keyword:

V O I D : This key word is used to specify to compiler that no value will be returned from

method. We have seen in previous examples that our methods did not return any value so

the return type in method signatures was “void”. If the method is a void type, the return

statement can be omitted.

11.6.1. “RETURN” STATEMENT Methods can receive parameters and after processing them, can return the value

or result. A special statement “return” is used for this purpose. The “return”

Page 242: Programming Fundamentals

Programming Fundamentals Using C# 241

statement terminates execution of the method in which it appears and returns

control to the calling method. It can also return an optional value.

To summarize, the execution of return statement does three things:

Stops immediately the method execution

Transfers controls back to the point from where method was called

If as a parameter, a value is given, it returns that

Syntax of “return” is as under.

Syntax of “return” statement

return [<value/variable/expression>];

“return” statement can optionally take value or variable or expression resulting in

one value as operand. Only one value could be returned using “return” statement.

If “return” statement is used without operand, it simply returns the control back

to the point from where the method was called. Following example program

shows the use of “return” statement without operand.

Line # Return Without Operand

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

class Program { static void Main(string[] args) { int a = 5, b = 3; Divide(a, b); } static void Divide(int a,int b) { if (b == 0) return; else Console.Out.WriteLine(a / b); } }

P R O G R A M DE S C R I P T I O N : At line 6, method is called by passing two arguments. In

method “Divide” two parameters “a” and “b” are declared. At line 10, the value of

second parameter “b” is tested and if its value is zero, line 11 is executed. At this

line, “return” statement is used that simply moves program control to line 7.

Syntax of “return” statement shows that some value as operand could be provided

that is returned back to the point from where the method is called. The returned

value must be of same data type which is specified in method declaration.

Following example explains the concept:

Page 243: Programming Fundamentals

Programming Fundamentals Using C# 242

Line# Returning a Value

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

class Program { static void Main(string[] args) { int height=5, width=6; int area=0; area = AreaofTriangle(height, width); Console.Out.WriteLine("Area of triangle is:{0}", area); Console.Read(); } static int AreaofTriangle(int h, int w) { int temp; temp = (h * w) / 2; return temp; } }

P R O G R A M DE S C R I P T I O N : At line 7, method “AreaofTriangle” is called by

passing two variables as arguments. Program control moves from line 7 to line 11.

After executing other statements of method body when program control reaches

at line 15, value is returned. It is to note that in method signatures, we have

provided “int” as return type, type of “temp” is also “int” so it matches according

to syntax. From line 15 control moves back to line 7. Execution of statement at line

7 is not yet complete so program control does not moves to line 8. Value of “temp”

is assigned to variable “area”. Now execution of line 7 completes and program

control moves to line 8 where the value of line 8 is printed.

Value returned from method may or may not be received by calling method. If

calling method does not receive returned value, returned value is simple wasted.

Sometime calling method does not receive returned value but it directly passes to

other method that uses it. Following statement related to above program shows

the idea:

Console.Out.WriteLine(AreaofTriangle(a,b));

Value returned from method “AreaofTriangle” is directly given to

“WriteLine” method that prints it on console.

Page 244: Programming Fundamentals

Programming Fundamentals Using C# 243

11.6.2. MULTIPLE “RETURN” STATEMENTS Normally we write the “return” statement at the end of the method. But it is not

necessary to write it there. You may write “return” statement anywhere in method

body, where it is required to send result or control back to calling method.

Following program shows the use of multiple return statements.

Multiple Return Statements

using System; namespace MultipleReturnStatements { class Program { static void Main(string[] args) { int operand1, operand2; char option; double result; PrintMenu(); Console.Out.Write("Please enter first operand::"); operand1 = int.Parse(Console.ReadLine()); Console.Out.Write("Please enter second operand::"); operand2 = int.Parse(Console.ReadLine()); Console.Out.Write("Please enter operation choice::"); option = char.Parse(Console.ReadLine()); result = Evaluate(option, operand1, operand2); Console.Out.WriteLine("The result is {0}", result); Console.Read(); } static void PrintMenu() { Console.Out.WriteLine("A-Addition"); Console.Out.WriteLine("S-Subtraction"); Console.Out.WriteLine("M-Multiplication"); Console.Out.WriteLine("D-Division"); } static double Evaluate(char option, int operand1, int operand2) { double result=0; if (option == 'A') { result = (operand1 + operand2); return result; } else if (option == 'B')

Page 245: Programming Fundamentals

Programming Fundamentals Using C# 244

{ result = (operand1 - operand2); return result; } else if (option == 'M') { result = (operand1 * operand2); return result; } else if (option == 'D') { result = (operand1 / operand2); return result; } return 0; } } }

11.7. PASS BY VALUE AND PASS BY REFERENCE Parameters are passed in three different ways from one method to another methods.

These are

Pass by value

Pass by reference

Pass by pointer

11.7.1. PASS BY VALUE

When a simple variable is passed as the parameter to any method, it is passed as a value. This means that the value contained by the variable that is passed as the parameter is copied to the variables of the method, and if inside the method these values are changed or modified, the change is not reflected in the actual passed variable. Passing variable by value is useful in cases where the actual value of the variable should not be modified by the method and the change is only limited to the called method whereas the value of the variables in the calling method remain unchanged. All examples given previously in this chapter passed arguments by values. Normally basic data types are passed by value.

11.7.2. PASS BY REFERENCE USING “REF”

When variable is defined, it is given some space in memory. Different features become associated with the variable as listed below:

Page 246: Programming Fundamentals

Programming Fundamentals Using C# 245

Feature Name Description

Name Identifier that identifies the variable

Address The location where variable is stored

Value What value is stored in the variable

In passing by value, value of the argument is copied to parameter. In pass by reference, address of variable is passed to parameter. Parameter becomes an alias (another name) for the same memory location. Hence changes made through alias is reflected in original variable.

Above figure shows the concept of pass by reference. An argument to be passed

is stored at location 500 in memory and its value is 300. Pass by reference causes

parameter to point to same memory location as that of argument i.e. 500. Now if

the value of parameter is changed in called method, the content (value) 300 will

be changed. Following program shows the concept.

Pass By Reference

using System; namespace PassingValByReference { class PassingValByRef { static void SquareIt(ref int x) // The parameter x is passed by reference. // Changes to x will affect the original value of x. { x *= x; System.Console.WriteLine("The value inside the method: {0}", x); } static void Main() { int n = 5; Console.WriteLine("The value before calling the method: {0}", n); SquareIt(ref n); // Passing the variable by reference. Console.WriteLine("The value after calling the method: {0}", n); Console.Read(); } } } Output: The value before calling the method: 5

300 500

Address Value Argument

Parameter

Figure 1- 17: Pass by Reference

Page 247: Programming Fundamentals

Programming Fundamentals Using C# 246

The value inside the method: 25 The value after calling the method: 25

P R O G R A M DE S C R I P T I O N : Main program passes variable “n” by reference when

calling the method “SquareIt”. “SquareIt” method also receives the parameter by

reference. Now one memory location has two names “n” and “x”. A change made

on same memory location through “x” is reflected when this location is accessed

through “n”.

“R E F” K E Y W O R D : The “ref” keyword causes an argument to be passed by

reference, not by value. The effect of passing by reference is that any change to

the parameter in the called method is reflected in the calling method as shown in

above example. To use a ref parameter, both the method definition and the calling

method must explicitly use the ref keyword. “ref” parameter must be initialized

before passing it.

11.7.3. PASS BY REFERENCE USING “OUT” “O U T” K E Y W O R D : Normally we can return only one value from a method using

“return” statement. There may be the requirement to return more than one values

from method. To achieve this objective, C# provides a specific way to pass

arguments (output arguments) to methods which are only intended to take some

value from called method to back calling method. Such arguments could be mixed

with other type of arguments. “out” keyword causes the arguments to be passed

by reference. Their memory locations are copied to “stack” of called method.

Called method assigns values to the “out” parameters and when called method

returns, calling method observes the change in “out” variables. Here are few

rules about “out” parameters.

It is not necessary to initialize “out” variables.

“out” parameters are passed by reference. Their memory locations are

copied like “ref” variables.

“out” parameters must be assigned some value before “called” method

ends

“out” parameters could be used in called method but before that some

value must be assigned to it in “called” method.

Following example shows the use of “out” keyword.

Pass by “out”

using System; namespace OutKeyword { class Program

Page 248: Programming Fundamentals

Programming Fundamentals Using C# 247

{ static void Main(string[] args) { int a = 20, b = 30, c = 40; Change(out a, out b, out c); Console.Out.WriteLine("a={0} b={1} c={2}", a, b, c); Console.Read(); } static void Change(out int x,out int y,out int z) { // "x" could not be used before value assignment //Console.Out.WriteLine(x); x = 100; y = 200; z = 400; Console.Out.WriteLine(x); } } }

“R E F” V S “O U T” : The “ref” and “out” keywords are treated differently at run-time,

but they are treated the same at compile time. Therefore methods cannot be

overloaded if one method takes a “ref” argument and the other takes an “out”

argument. These two methods, for example, are identical in terms of compilation,

so this code will not compile:

ref vs out

class Program { static void Main(string[] args) { int a=20; passvalue(out a); // error passvalue(ref a); // error } // compiler error CS0663: "cannot define overloaded // methods that differ only on ref and out" static void passvalue(out int i) { i=20; } static void passvalue(ref int i) { i=30; } }

Declaring an out method is useful when you want a method to return multiple

values. Overloading can be done, however, if one method takes a ref or out

argument and the other uses neither, like this:

Page 249: Programming Fundamentals

Programming Fundamentals Using C# 248

Overloading without parameter

class OutOverloadExample { static void Main(string[] args) { int a=20; passvalue(out a); passvalue(a); } static void SampleMethod(int i) { i=30; } static void SampleMethod(out int i) { i = 5; } }

11.7.4. PASS BY POINTER The use of pointers is restricted in C#. However this book chapter discussing

“pointers” will describe the “pass by pointer”.

11.8. PASSING AND RETURNING ARRAYS

11.8.1. PASSING AND RETURNING ONE DIMENSIONAL ARRAYS Like any other variable of any data type, you can pass array as an argument to the

methods. So far, using simple variables, we have been passing fixed number of

arguments but arrays provide a way to pass variable number of arguments. An

array contains values of same data type so using array, you can pass variable

number of values of same data type. Here is the syntax to pass variable number of

arguments:

Syntax: Passing Variable No. of Arguments

static <return_type> <method_name>(<parameters_list>) { // Method's body }

Following program shows the use of arrays to pass the variable number of

arguments:

Line# Passing Array

1 2 3 4 5 6 7

class Program { static void Main(string[] args) { int[] array1 = new int[] { 2, 3, 4, 5 }; int[] array2 = new int[] { 2, 3, 4 }; SumIt(array1);

Page 250: Programming Fundamentals

Programming Fundamentals Using C# 249

8 9 10 11 12 13 14 15 16 17 18

SumIt(array2); Console.Read(); } static void SumIt(int[] array) { int sum=0; foreach (var item in array) sum += item; Console.Out.WriteLine("Sum of Array:{0}", sum); } }

P R O G R A M DE S C R I P T I O N : “Main” method defines two integer arrays, first array

“array1” consists of four elements whereas second array “array2” consists of three

elements. On line 7, first array is passed to method “SumIt” and on line 8, second

array “array2” is passed. “SumIt” is summing the passed array and displaying it.

The method is called two times with different number of parameters. The output

is “14” and “9”.

Arrays are passed by reference. If called method changes some value of array, the

calling method observes this change.

Array Pass by Reference

class Program { static void Main(string[] args) { int[] nums = new int[] { 2, 3, 4, 5 }; ChangeArray(nums); for (int i = 0; i < nums.Length; i++) Console.Out.Write(“ “+nums[i]); Console.Read(); } static void ChangeArray(int[] array) { array[1] = 456; } } Output: 2 456 4 5

Arrays are by default passed by reference. There is no need to put “ref” word in

method call or method definition. In this example, we have passed one 1D array.

You can pass multiple 1D arrays too.

Page 251: Programming Fundamentals

Programming Fundamentals Using C# 250

As arrays are passed by reference, any change made in them by the called method

is reflected in calling method and there is no need to return an array explicitly.

However C# provides you the way to return an array from called method. Here is

the syntax of returning an array:

Syntax: Returning An Array

static <data-type>[] <method-name>(<parameters>) { // body of method }

Following program describes the use of above syntax:

Returning 1D Array

class Program { static void Main(string[] args) { int numfactors; int[] factors; factors = FindFactors(1000, out numfactors); Console.WriteLine("Factors for 1000 are: "); for (int i = 0; i < numfactors; i++) Console.Write(factors[i] + " "); Console.Read(); } static int[] FindFactors(int num, out int numfactors) { int[] facts = new int[80]; int i, j; for (i = 2, j = 0; i < num / 2 + 1; i++) if ((num % i) == 0) { facts[j] = i; j++; } numfactors = j; return facts; } } Output: Factors for 1000 are: 2 4 5 8 10 20 25 40 50 100 125 200 250 500

Page 252: Programming Fundamentals

Programming Fundamentals Using C# 251

P R O G R A M DE S C R I P T I O N : In this program, method “FindFactor” is passed a

number. Its job is to find all factors of passed number. A factor is another number

that divides the passed number. In our example program, for “1000”, there are

multiple numbers which can divide it as shown in the output. All divisors of “1000”

are placed in “facts” array and returned using “return” statement that is received

in “factors” array by “Main” method.

11.8.2. PASSING AND RETURNING MULTI-DIMENSIONAL ARRAYS C# allows you to pass multi-dimensional arrays too. These are also passed by

reference. Following program shows the passing of multi-dimensional array(s):

Passing Multi-Dimensional Array

class Program { static void Print2DArray(int[,] arr) { arr[0, 0] = 1122; } static void Main() { // Pass the array as an argument. int[,] arr = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; Console.Out.WriteLine("Before method call"); for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) { Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]); } } Print2DArray(arr); Console.Out.WriteLine("\nAfter method call"); for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) { Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);

} } // Keep the console window open in debug mode. Console.ReadKey(); } } Output: Before method call Element(0,0)=1 Element(0,1)=2 Element(1,0)=3 Element(1,1)=4

Page 253: Programming Fundamentals

Programming Fundamentals Using C# 252

Element(2,0)=5 Element(2,1)=6 Element(3,0)=7 Element(3,1)=8 After method call Element(0,0)=1122 Element(0,1)=2 Element(1,0)=3 Element(1,1)=4 Element(2,0)=5 Element(2,1)=6 Element(3,0)=7 Element(3,1)=8

“Print2DArray” method changes one value of the array. “Main” method prints the

array before and after calling method. The output shows that array is passed by

reference.

Using similar syntax, like 1D array, multidimensional array could be returned from

a method in C#. Here the syntax.

Syntax: Returning Multi-Dimensional Array

static <data-type>[,] <method-name>(<parameters>) { // body of method }

Here is the program returning multidimensional array.

Returning 2D Array

class Program { static void Main(string[] args) { int[,] ret_marks; ret_marks = Returning2DArray(); foreach (int item in ret_marks) Console.Out.Write(" "+item); Console.Read(); } static int[,] Returning2DArray() { int[,] Marks = new int[,] { { 3, 4, 5 }, { 6, 7, 8 } }; return Marks; } }

Page 254: Programming Fundamentals

Programming Fundamentals Using C# 253

11.8.3. “PARAMS” ARRAY An array needs to be defined with its size and element values before passing to

methods. There may be the requirement to send a comma-separated list of

arguments of the type specified in the parameter declaration or an array of

arguments of the specified type. You also can send no arguments. To send zero or

more arguments to a method (which is decided at run time), C# provides a special

keyword “params”. With params, the arguments passed to a method are changed

by the compiler to elements in a temporary array. This array is then used in the

receiving method. Following rules must be followed to pass “params” array:

1. If passing multiple parameters, “params” array must be the last parameter

2. Only one “params” array can be passed to a method

For example, following statements will violate the first rule:

static void DoSomething(params int[] x, string str) { // body of method }

And following code will violate the second rule:

static void DoSomething(params int[] x, params string[] z) { //body of method }

Following program shows the use of “params” array.

Passing “params” Array

class Program { static void Main(string[] args) { ShowArray(99); ShowArray(99,1); ShowArray(99,1, 2, 3); ShowArray(99,5, 6, 7, 8, 9); Console.Read(); } static void ShowArray(int a,params int[] array) { foreach (int item in array) Console.Out.WriteLine(a+"-"+item); } }

Page 255: Programming Fundamentals

Programming Fundamentals Using C# 254

The “params” keyword is most useful when designing a library for other

programmers to widely use. If you have complete control over all usages of the

method, you may not need “params” because you can simply add the necessary

overloads

11.8.4. PASSING AND RETURNING JAGGED ARRAY The syntax of passing jagged array is:

Syntax: Passing Jagged Array static <return-type> <method-name>(<data-type>[][] <array-name>)

Here is the program using jagged array as an argument to method call.

Passing Jagged Array

class Program { static void Main(string[] args) { int[][] jagged = new int[3][]; jagged[0] = new int[2]; jagged[1] = new int[1]; jagged[2] = new int[3] { 3, 4, 5 }; jagged[0][0] = 1; jagged[0][1] = 2; DisplayJaggedArray(jagged); Console.Read(); } static void DisplayJaggedArray(int[][] arr) { for(int i=0;i<arr.Length;i++) foreach (int element in arr[i]) Console.Out.WriteLine(element); } }

Similarly, we can return the jagged array from a method. The syntax to return

jagged array is:

Syntax: Returning Jagged Array

static <return-type>[][] <method-name>(<parameters>)

Here is the program that returns jagged array:

Page 256: Programming Fundamentals

Programming Fundamentals Using C# 255

Returning Jagged Array

class Program { static void Main(string[] args) { string[][] test=GetResult(); for (int i = 0; i < test.Length; i++) foreach (string el in test[i]) Console.Out.WriteLine(el); Console.Read(); } static string[][] GetResult() { string[][] result = new string[2][]; result[0] = new string[] { "1", "2" }; result[1] = new string[2]; result[1][0] = "a"; result[1][1] = "b"; return result; } }

11.8.5. OPTIONAL PARAMETERS AND NAMED ARGUMENTS These two features in the C# language syntax are very useful in cases, when we

invoke a method with a different combination of its parameters.

OPTI ONA L PARA ME TER S :

These allow some parameters to be skipped when a method is invoked.

Declaration of optional parameters can be done just by using a default value in the

way shown below:

static void SomeMethod( int x, int y = 5, int z = 7) { }

If during method call, value of some parameter which is assigned value in

definition is missing, the assigned value is used instead. Following program shows

the use of optional parameters:

Line # Optional Parameters

1 2 3 4 5 6 7 8 -- >

class Program { static void Main(string[] args) { SumUp(1); // equivalent to SumUp(1,7,10) SumUp(1, 2);// equivalent to SumUp(1,2,10) SumUp(1, 2, 3);// equivalent to SumUp(1,2,3) //SumUp(1,,4);

Page 257: Programming Fundamentals

Programming Fundamentals Using C# 256

9 10 11 12 13 14 15

Console.Read(); } static void SumUp(int x, int y = 7, int z = 10) { Console.Out.WriteLine(x + y + z); } }

Output:

18 13 6

C# does not allow you to skip an inner parameter. As shown on line 8, first and

third parameter values are provided but an inner parameter, second parameter,

is missing. Compiler will generate an error for this statement.

NA MED ARGU M ENT S

These allow method parameter values to be set by their name, instead of their

exact position in the parameters list. We can pass a value by a particular parameter

name, by setting the parameter’s name, followed by a colon and the value of the

parameter. Syntax for named argument is as under:

Syntax: Named Arguments

<method-name>(<parameter:<argument>,[…,<parameter>:<argument>]);

An example of using named arguments is shown below:

Line # Named Arguments

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

class Program { static void Main(string[] args) { int a = 4, b = 5, c = 6; PrintValues(a, b, c); // pass by position // b by position, a and c by name PrintValues(b,z: a, y:c); Console.Read(); } static void PrintValues(int x, int y, int z) { Console.Out.WriteLine("x={0} y={1} z={2}", x, y, z); } }

Page 258: Programming Fundamentals

Programming Fundamentals Using C# 257

P R O G R A M DE S C R I P T I O N : In this program, method “PrintValues” at line six is as

usual where position of argument specifies that to which parameter it will be

assigned. “argument” and “parameter” matching using line 8 is as under:

x=a, y=b, z=c

This position wise assignment is known as positional assignment. Named

arguments allows us to change positional assignment according to our choice. Line

8 does named assignment as shown below:

x=b, y=c, z=a

This is called the named argument assignment. In named argument assignment,

you do not need to follow the positional sequence. You just specify that which

argument should be assigned to which parameter.

11.9. RECURSION Recursion is a special technique used in programming. Before discussing recursion, let we

consider its definition

“An object is said to be recursive if it contains itself or is defined by itself.”

There are many problems in real world which are defined recursively. For example factorial

is defined in terms of factorial:

N!=N*(N-1)!

We can see that to find factorial of some number N, we need to first find factorial of N-1

and then multiply it with N hence factorial is defined in terms of factorial. In other words,

if we consider factorial as method, such method can be computed by computing itself

again and again. Recursion in programming is defined as:

“It is a programming technique in which a method calls itself again and again to solve

particular problem”

Use of this technique can provide an elegant way to map real life problems like factorial in

programming. Such kind of problem-solution mapping leads in the development of

efficient and simplified algorithms. There are two conditions that need to be true for

recursive methods:

Stopping condition or criteria of recursion

Method calling itself with problem size approaching to stopping criteria

To understand the recursion, consider the following example:

Page 259: Programming Fundamentals

Programming Fundamentals Using C# 258

Line # Simple Recursion

1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19 20 21 22 23

using System; namespace SimpleRecursion { class Program { static void Main(string[] args) { int a = 5; int fact = 0; fact = Factorial(a); Console.Out.WriteLine("Factorial of {0} is {1}", a, fact); Console.Read(); } static int Factorial(int f) { // stopping criteria if (f == 1) return 1; // recursion with reduced problem size // approaching to stopping criteria return f * Factorial(f - 1); } } }

P R O G R A M DE S C R I P T I O N : In this program, method “Factorial” first tests the

stopping condition. If it is reached the method returns value “1” otherwise it

multiplies pass value with factorial of decremented value. Let we try to understand

recursion processing with input value 3. This value is passed to “Factorial” method.

If-test fails and second return statement is executed. The value of “f” is 3 that is

multiplied with “Factorial” of 2. “Factorial” of 2 is unknown so this multiplication

is not possible at this point. This multiplication process [3*Factorial(2)] is left

incomplete and program control jumps to line 14. Now “f” has value 2. If-test again

fails and [2*Factorial(1)] is tried to evaluate which is not possible due to

method call so program control again jumps to line 14. In new method call value

of “f” is 1.

Now If-test passes and 1 is returned to the point from where previous jump was

made. This was line 20 [2*Factorial(1)]. Now Factorial(1) has returned

value 1, this multiplication is possible. [2*1]. Its result 2 is returned back to

calling point which was line 20 [3*Factorial(2)]. Here this multiplication is

possible as [3*2] and finally it returns to “Main” method.

Page 260: Programming Fundamentals

Programming Fundamentals Using C# 259

11.9.1. DIRECT AND INDIRECT RECURSION If a method calls itself this is called the direction recursion. Above given program

example of “Factorial” is direct recursion. Method A calls itself.

In indirect recursion, method A calls method B and method B calls back to method

A. Or this this calling chain may be longer as method A calls method B, method B

calls method C, method C calls back method A and so on.

11.9.2. RECURSION VS ITERATION Any task that could be done using recursion could also be done using iterations.

Consider the following “Factorial” program again:

Iterative Factorial

using System; namespace IterativeFactorial { class Program { static void Main(string[] args) { int a = 5; Console.Out.WriteLine("Factorial of {0} is {1}", a, Factorial(a)); Console.Read(); } static int Factorial(int f) { int fact = 1; for (int i = 1; i <= f; i++) fact = fact * i; return fact; } } }

This program correctly calculates the factorial but using iterative algorithm. It is

obvious question that which approach is better?

If the algorithm solving of the problem is recursive, the implementation of

recursive solution can be much more readable and elegant than iterative solution

to the same problem. In certain cases by using recursion we can accomplish much

simpler, shorter and easy to understand solutions. On the other hand, recursive

calls can consume much more resources (CPU time and memory). Recursion is

powerful programming technique, but we have to think carefully before using it.

If used incorrectly, it can lead to inefficient and tough to understand and maintain

solutions. In certain situations the recursive solutions can be much more difficult

to understand and follow than the relevant iterative solutions.

Page 261: Programming Fundamentals

Programming Fundamentals Using C# 260

“if you do not understand how recursion works, avoid using it”

11.10. BEST PRACTICES WHEN USING METHODS Good programming always comes by developing good programming style. A

programming style is set of rules that you define for yourself when writing code.

Experienced programmers and developers have also devised different set of rules

for the ease of programming learners and new developers. Language vendors like

Microsoft also provide documents for “good programming style”. You are, as

learner, advised to follow particular style that will help you write easy to

understand and manageable code. Here are few principles regarding using of

methods. Try to follow them in your code:

S T R O N G C O H E S I O N : Each method must do distinct, well defined task.

Incorporating multiple tasks in one method does not provide atomic view

and it may confuse you sometime to find which task is being done in which

method.

G O O D NA M I N G : A method should be provided a good name. A good name

is one that is descriptive and clearly mentions that task of method. For

example, a method that sorts a list of numbers must be given the name

“SortNumbers”. Its bad names may include “Processing”, “Method” or

“Number”. If you cannot find a good name for your method, probably you

need to break it down more.

ME T H O D NA M E S H O U L D B E AC T I O N : A method name must describe an

action. This could be done by using verb or verb and noun for naming

PA S C A L C A S I N G : The rule of PascalCase says that first letter of every word

of method name must be capital. By just looking at such names, you can

point that they are method names.

PR E C I S E N E S S : A method should precisely produce the result as described

by its name. In any other cases it must raise proper error. Errors and

Exceptions will be discussed in later chapters

L O O P C O U P L I N G : A method must have minimum dependency of other

methods. It means that method must try to complete its task using data

provided as parameters. There should be minimum use of global data or

any other data which is not passed using parameters

AV O I D S I D E EF F E C T S : A method should “only and only” do for what it is

written. It should not do anything which is not related to it. For example it

should not change the global data which is not intended or it should not

raise unrelated errors

Page 262: Programming Fundamentals

Programming Fundamentals Using C# 261

AC C U R A C Y : The methods should accurately perform their task with

minimum number of statements. The use of multiple temporary variables

or expressions and statements may affect the performance of software

WE L L S T R U C T U R I N G : The code should be properly structured. Each task

should be divided into its atomic sub-tasks. If any sub-task seems to

consist of further smaller sub-tasks, break the code and create sub-sub-

tasks.

Page 263: Programming Fundamentals

Programming Fundamentals Using C# 262

Chapter 12

Indirect Variables Indirect variables, also known as pointers, have been of very importance in C and C++.

This type of variables allow user to manipulate memory directly. The idea and use is

simple but most of the programmers fined them complex and difficult to understand.

In this chapter we will discuss the concept of pointers, their usefulness in developing

efficient and fast programs, memory management with pointers and multi-level

indirection with pointers. A special feature provided by .NET framework, garbage

collection, is also discussed. This chapter lays the foundation for low level

programming and resource management.

12.1. WHAT ARE INDIRECT VARIABLES Simple or direct variables contain values and their memory locations are managed by

operating system. Indirect variables are the variables that contain memory address. This

memory address points to other variable that may either value or another memory

address. C# provides two types of indirect variables: pointers and reference types.

Using pointer variables, programmer can directly manipulate memory and can bypass the

operating system. C# does not provide full scale support for pointers however a limited

functionality is available. There are various uses of pointers including:

Accessing array elements

Passing arguments to a method when the method needs to modify the

original argument

Passing arrays and strings to methods

Obtaining memory from the system

Creating different data structures

Another type of variables, known as reference types, could be considered as alternate to

pointers. All tasks that could be done using pointers could also be done using reference

types however reference types are better and safer way to write code. We discuss the

pointers and reference types in order.

12.2. POINTERS “A pointer is nothing but a variable that holds the memory address of another type or

variable”

Page 264: Programming Fundamentals

Programming Fundamentals Using C# 263

In recent past, C has been leading software development language. The availability of

pointers was the core functionality used by programmers to create high efficiency code.

Today, in the world of managed code and modern languages such as C#, pointers are still

holding their ground, although they are rarely used and they are usually associated with

"advanced programming". The core C# language, differs notably from C and C++ in its

omission of pointers as a data type.

WHY SH O ULD WE LE ARN T HE POIN TE RS ?

Pointers allow you to write low level code. The philosophy of high level and 3rd to

4th generation of languages do not recommend to program the hardware directly

i.e write low level code. Even if it is required, one should not play with pointers

unless the concept and functionality of pointers is clearly understood. There are

alternatives and that are recommended too to use in your code. However there

may be the requirement where you need to use pointers. Finally, you should learn

about them just for the sake of knowledge, even if hopefully you will never make

use of them.

Before discussing pointer in more detail, we recall few concepts about variables:

V A L U E : It is the content that is stored in memory location identified by variable

name. It is also known as data which is manipulated by our program and

transformed from one form to another form.

AD D R E S S : Every variable is stored or located somewhere in memory. Every

memory location is numbered and memory location number where variable is

stored is called the address of that variable.

R E F E R E N C E : A value that enables the program to indirectly access a particular

variable or value from memory locations or from somewhere else like storage

device. A reference is said to refer to an item. Using reference, accessing the data

item is called “dereferencing the reference”.

P O I N T E R : It is a variable that is used to store address of some variable or other

pointer variable.

12.2.1. UNSAFE CONTEXT Pointers allow programmers to access memory directly. The managed language

like C# consider any such code that directly access the system resources as

“unsafe”. Such code is given special treatment and is handled in different way.

“U N S A F E” K E Y W O R D

Any code that uses pointers is considered unsafe. Such part of code in your

program must be marked using “unsafe” keyword and is known as “unsafe

Page 265: Programming Fundamentals

Programming Fundamentals Using C# 264

context”. An unsafe context is introduced by including an unsafe modifier in the

declaration of a type or member, or by employing an unsafe-statement:

Like other compound statement structures, “unsafe” key word also has its body

marked by curly brackets. Here is the syntax:

unsafe { // body of unsafe }

Keyword “unsafe” could be used as block of statements or as part of method signature. If used with method signatures, complete method becomes unsafe. There are other points in code where unsafe could be used and we will explore them as we will proceed through the book. A program that contains “unsafe” block of code must be compiled using unsafe option. TU R N I N G “U N S A F E” O P T I O N O N : Following below given steps to turn “unsafe”

option on.

1. Go to menu Project Properties item

2. On the project properties dialogue box, select the “Build” page and select the

“Allow unsafe Code” option.

Page 266: Programming Fundamentals

Programming Fundamentals Using C# 265

3. Save project

Now you can write and compile “unsafe” code in your program. If “Allow unsafe

code” option is not selected, your program will generate error and will not

compile. Remember that you will need to selection this option for every program.

12.2.2. DECLARING POINTER VARIABLE Idea behind pointers is simple. Every byte in computer memory has an address.

Addresses are numbers, just as they are for houses on a street. The numbers start

at 0 and go up from there—1, 2, 3, and so on. If you have 1MB of memory, the

highest address is 1,048,575. Your program, when it is loaded into memory,

occupies a certain range of these addresses. It means that every variable and every

method in your program starts at a particular address.

Page 267: Programming Fundamentals

Programming Fundamentals Using C# 266

Figure 12 - 1: Memory and Variables

P O I N T E R O P E R A T O R *

“*” is called the dereference operator and is used to declare a pointer variable. It

specifies that this variable will contain the address not the value. Following is the

syntax of declaring a pointer variable.

<datatype>* <identifier>;

void* <identifier>; //allowed but not recommended

Example: int* a;

“Identifier” is the name of your choice given to pointer variable. “*” is necessary

to use as it classifies the variable as pointer. Any of following data types could be

used for pointer declaration:

sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or

bool

Any enum type (enum will be explained later)

Any pointer type

Any user-defined struct type that contains fields of unmanaged types only

Data type of pointer variable specifies that “this pointer variable will contain

address of variable of this data type”. The variable whose address is contained in

“pointer” variable is called the “variable pointed by”. The data type specified with

pointer variable is not its own data type but it is the data type of “variable pointed

by”. If pointer variable intends to contain address of integer, data type with

pointer will be integer, if pointer intends to point to “double” data type, data type

Page 268: Programming Fundamentals

Programming Fundamentals Using C# 267

with pointer will be double. As a pointer contains an address, this address is called

the value of pointer and is always “unsigned integer” or “unsigned long”

depending upon the quantity of RAM installed in your system.

S Y N T A X Q U I B B L E S : it is common to write pointer definitions with the asterisk

closer to the variable name than to the type as shown below:

int* ptr1; int *ptr2;

It doesn’t matter to the compiler, but placing the asterisk next to the type helps emphasize that the asterisk is part of the variable type (pointer to int), not part of the name itself. So placing “*” just after type is recommended style. If you define more than one pointer of the same type on one line, you need only insert the type-pointed-to and asterisk once if following recommended syntax.

int* ptr1,ptr2,ptr3;

P O I N T E R S M U S T HA V E A V A L U E

An integer variable can be assigned a constant like “int a=234;”. Here “a” is variable and “234” is constant. Similarly an address can be thought of as a pointer constant that is assigned to pointer variable. When we first define a variable, it holds no value (unless we initialize it at the same time). It may hold a garbage value, but this has no meaning. In the case of pointers, a garbage value is the address of something in memory, but probably not of something that we want. So before a pointer is used, a specific address must be placed in it. A pointer variable could either be initialized or assigned like value variables.

int* ptr1; int a=500; ptr1=&a;

In this piece of code, ptr1 is given the address of a. Now pointer variable has some value so it could be used in program. In following table arrows show the dereferencing of *ptr1

Feature\variable a ptr1

Value 500 107015800

Address 107015800 107015796

Value pointed by NA 500 .

A pointer variable can be initialized too. int a=500; int* ptr1=&a;

Page 269: Programming Fundamentals

Programming Fundamentals Using C# 268

Following program shows the use of pointer initialization:

Pointer Initialization

static void Main(string[] args) { unsafe { int a = 30; double b = 40.55; int* c = &a; double* d = &b; Console.Out.WriteLine("{0}-{1}", *c, *d); Console.Read(); } }

Following code will generate an error because pointer variable “a” has not been assigned any memory address:

int* a; *a = 30; //error

A pointer variable must be assigned memory address through value variable. Direct address assignment to pointer variable is not permitted due to memory and data security reasons. Following statements will generate an error as they intend to assign address directly.

int* a; a = 30; // error: Direct address assignment

TO S U M M A R I Z E : A pointer can hold the address of any variable of the correct type; it’s a receptacle awaiting an address. However, it must be given some value, or it will point to an address we don’t want it to point to, such as into our program code or the operating system. Rogue pointer values can result in system crashes and are difficult to debug, since the compiler gives no warning. TH E M O R A L : Make sure you give every pointer variable a valid address value before using it. Remember that the asterisk used as the dereference operator has a different meaning than the asterisk used to declare pointer variables. The dereference operator precedes the variable and means value of the variable pointed to by. The asterisk used in a declaration means pointer to.

int* ptr; //declaration: pointer to int *ptr = 37;//indirection: value of variable pointed to by ptr

DA N G L I N G PO I N T E R S – A M I S S I N G B U G

As defined, a pointer contains address of some other variable. If an address of

some variable is assigned to a pointer and later on that variable is removed from

Page 270: Programming Fundamentals

Programming Fundamentals Using C# 269

memory, the pointer variable now points to memory location which is not

accessible. Such a pointer is called the dangling pointer. In the core C# language it

is simply not possible to have an uninitialized variable as stated above, a "dangling"

pointer, or an expression that indexes an array beyond its bounds. This feature

eliminates a whole category of errors and bugs caused by dangling pointers.

P O I N T E R C O N S T A N T S A N D PO I N T E R V A R I A B L E S

It is important to differentiate the change in address and change in value when

working with pointers. Let we explain it using increment operators. Consider the

following statement:

byte b = 60; byte* ptr=&b;

Console.Out.WriteLine(“{0}”,++*ptr); Console.Out.WriteLine(“{0}”,*++ptr);

pointer variable ptr points to memory location of b. The dereference operator is used to access the value pointed by address in pointer variable. Dereference operator is right associative and will be evaluated first. In “++*ptr” statement, dereference operator will first access the value pointed by ptr and then will increment it. The returned value will be “61”. There will be no change in address, however the “*++ptr” will first increment the address in ptr and then using dereference operator, the value pointed by ptr will be accessed. As the address in ptr has been changed so returned value will be different from expected value. Look at the following two statements:

Console.Out.WriteLine("{0}", *++ptr); Console.Out.WriteLine("{0}", *--ptr);

First statement increments the address contained in ptr and then pointed value is printed. The output will be something else but not “60”. The second statement first decrements the address in ptr, now ptr points to old memory location and then value from there is accessed which is “60” correctly. This shows that the address contained in ptr is CONSTANT and should not be changed. You should be attentive when changing values of pointers whether pointed value is being changed or the address contained in pointer is being changed.

Any variable declared in your program is allocated a fixed address. POIN TE R

V ARIAB LE S are assigned these fixed addresses that are considered as CON STA NT

AD D R E S S O F O P E R A T O R &

Any value variable defined in your program is allocated a space in memory. Using

“&” operator, its address can be found. It is to note that memory addresses are

Page 271: Programming Fundamentals

Programming Fundamentals Using C# 270

positive values only. No memory address is given negative value. Now look at the

following program:

Line # Simple Pointer Program

1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17

static void Main(string[] args) { unsafe { int a = 500; int* b; b = &a; Console.Out.WriteLine("Value of a:{0}",a); Console.Out.WriteLine("Address of a:{0}\n",(uint)&a); Console.Out.WriteLine("Value of b:{0}",(uint)b); Console.Out.WriteLine("Address of b:{0}",(uint)&b); Console.Out.WriteLine("Value Pointed by b:{0}",*b); Console.Read(); } }

Output Value of a: 500 Address of a: 107015800 Value of b: 107015800 Address of b: 107015796 Value Pointed by b: 500

P R O G R A M DE S C R I P T I O N : The program uses pointers hence all of the code is

written in “unsafe” block that starts from line 5 and ends at line 14 as indicated

above.

1. Start of “Main” method

2. Main method body starts

3. Start of “unsafe” code block

4. Body of unsafe code block starts

5. Value variable “a” of type int with value 500 defined

6. Pointer variable “b” is defined that will contain address of an integer variable

7. Using address of operator “&”, address of “a” is moved in “b”

8. Variable “a” has two features: value and address. This statement prints its

value

9. Address of “a” could not be printed directly, so we need to cast it into unsigned

integer value and then we print it.

Page 272: Programming Fundamentals

Programming Fundamentals Using C# 271

10. In this output statement, “b” is used in same way as “a” on line 8. But

remember, “b” contains an address and that need to be printed so it is casted

into unsigned integer

11. At this line, address of “b”, the pointer, itself is being printed so it is casted

too.

12. “*b” is important to understand. Remember “b” has address of “a”. So

program will take content of “b” and will move there and value present there

will be printed. *b means value pointed by

Output of your program may differ depending upon the memory addresses

allocated to your variables.

In output, you can see that address of “a” and value of “b” are same. Following

figure shows this concept visually:

Variable Address Value

… 107015792

b 107015796 107015800

a 107015800 500

… 107015804

… 107015808

Arrow in above table shows that in evaluating “*b”, value of b is taken that is

address, program goes to that address and value from there is returned. This is

“INDIR ECT ION”.

P O I N T E R T O void A pointer with void data type has special meaning. It can point to any other data

type. It means address of any other data type variable could be moved in pointer

variable of type void.

int a=40; double d=59.78; char ch=’Z’; void* ptr; ptr=&a; // valid assignment ptr=&d; // valid assignment ptr=&ch; // valid assignment

Page 273: Programming Fundamentals

Programming Fundamentals Using C# 272

Following program shows the use of void pointer:

Void Pointer

static void Main(string[] args) { unsafe { char theChar = 'Z'; char* pChar = &theChar; void* pVoid = pChar; //pVoid points to theChar int* pInt = (int*)pVoid; Console.WriteLine("Value of theChar = {0}", theChar); Console.WriteLine("Address of theChar = {0:X2}", (int)pChar); Console.WriteLine("Value of pChar = {0}", *pChar); Console.WriteLine("Value of pInt = {0}", *pInt); Console.Read(); } } Output Value of theChar = Z Address of theChar = 62EE848 Value of pChar = Z Value of pInt = 90

12.2.3. POINTER ARITHMETIC It is possible to perform arithmetic and other operations on pointer variables using

dereference operator with an exception that no operation is allowed on void

pointer variable. Following program shows the use of arithmetic with pointers:

Pointer Arithmetic

unsafe static void Main(string[] args) { int a = 30; int b = 40; int* ptra = &a; int* ptrb = &b; Console.Out.WriteLine(*ptra + *ptrb); Console.Out.WriteLine(*ptra - *ptrb); Console.Out.WriteLine(*ptra * *ptrb); Console.Out.WriteLine(*ptra / *ptrb); Console.Read(); }

Page 274: Programming Fundamentals

Programming Fundamentals Using C# 273

12.2.4. POINTER CONVERSIONS A pointer variable contains address of other variable. As discussed above, “void”

type pointer can point to variable of any type but we can also make a pointer

variable pointing to one type to point variables of other types. This could be done

using conversion and casting of pointers.

SI ZE O F OP ERATOR

“sizeof()” operator is used to find the size of memory occupied by the variable

of particular data type. This operator takes “data type” as parameter and returns

its size in memory. It is equivalent to find the size of variable or size of data type

of variable. For example, “int a;” statement defines a variable of type “int”.

Data type describes the amount of memory to store “a”. sizeof operator tells

the memory requirement of data type that is eventually memory requirement of

any variable of that type. Look at following statement:

sizeof(int);

This will return the value “4” showing that “int” type will occupy 4 bytes in RAM.

Following program shows the use of this operator with value variables and pointer

variables:

Sizeof Operator Program

using System; namespace SizeofOperator { class Program { unsafe static void Main(string[] args) { Console.Out.WriteLine("Size of Basic Data Types"); Console.Out.WriteLine("bool={0} byte={1} char={2} int={3} float={4} double={5}", sizeof(bool),sizeof(byte), sizeof(char), sizeof(int), sizeof(float),sizeof(double)); Console.Out.WriteLine("Size of Pointer Types"); Console.Out.WriteLine("bool*={0} byte*={1} char*={2} int*={3} float*={4} double*={5}", sizeof(bool*), sizeof(byte*), sizeof(char*), sizeof(int*), sizeof(float*), sizeof(double*)); Console.Read(); } } }

Page 275: Programming Fundamentals

Programming Fundamentals Using C# 274

Output: Size of Basic Data Types bool=1 byte=1 char=2 int=4 float=4 double=8 Size of Pointer Types bool*=4 byte*=4 char*=4 int*=4 float*=4 double*=4

We can see that different data types have different sizes but all pointer data types

have same size i.e. 4 bytes. It is clear from this pointer sizes that data type written

with pointer variable is actually data type of variable that will be pointed by

pointer.

IM PL IC IT POI NT ER CON V ERS IO N S

Implicit pointer conversion refers to automatic conversion of pointer of one data type to other. The implicit conversions are

1. From any pointer type to void * type. 2. From null type to any pointer type.

Any pointer type could be converted into void pointer. Similarly a pointer of null type can be converted to any other type. Implicit type conversion does not cause the loss of data due to size of data types. Data type of pointer specifies the amount of memory pointed by. “void” pointer is dynamic in this context as size of memory pointed by “void” pointer could be changed dynamically. Following program shows the concept of implicit pointer conversion:

Implicit Pointer Conversion

using System; namespace PointerConversions { class Program { unsafe static void Main(string[] args) { bool bol = true; byte b = 60; char ch = 'A'; int a = 0x78765432; long lng = 786; float f = 78.88f; double d = 78.98; void* ptr; ptr=&bol; //Implicit Conversion bool* bptr = (bool*)ptr; //Explicit Conversion Console.Out.WriteLine("{0}",*bptr);

Page 276: Programming Fundamentals

Programming Fundamentals Using C# 275

ptr = &b; //Implicit Conversion byte* byptr = (byte*)ptr; //Explicit Conversion Console.Out.WriteLine("{0}", *byptr); ptr = &ch; //Implicit Conversion char* chptr = (char*)ptr; //Explicit Conversion Console.Out.WriteLine("{0}", *chptr); ptr = &a; //Implicit Conversion int* intptr = (int*)ptr; //Explicit Conversion Console.Out.WriteLine("{0}", *intptr); ptr = &lng; //Implicit Conversion int* lngptr = (int*)ptr; //Explicit Conversion Console.Out.WriteLine("{0}", *lngptr); ptr = &f; //Implicit Conversion byte* fptr = (byte*)ptr; //Explicit Conversion Console.Out.WriteLine("{0}", *fptr); ptr = &d; //Implicit Conversion double* dptr = (double*)ptr; //Explicit Conversion Console.Out.WriteLine("{0}", *dptr); Console.Read(); } } }

EXP L ICI T POI NTER C ON V ERS IO N S

Like value variables, when size of value being assigned to variable is different,

explicit conversion is required. This is to ensure that any data loss due to change

in memory size must be considered by the programmer and dealt carefully,

different data type pointers are required to be explicitly converted before

assignment. Syntax of explicit pointer conversion is given below:

<target-pointer variable> = ( target-data-type *) <pointer to be converted>;

Following is the list of possible explicit pointer conversions:

From any pointer-type to any other pointer-type. From sbyte, byte, short, ushort, int, uint, long, or ulong

to any pointer-type.

Page 277: Programming Fundamentals

Programming Fundamentals Using C# 276

From any pointer-type to sbyte, byte, short, ushort, int, uint, long, or ulong

Conversions between two pointer types never change the actual pointer value. In other words, a conversion from one pointer type to another has no effect on the underlying address given by the pointer.

When one pointer type is converted to another, if the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined if the result is dereferenced. In general, the concept "correctly aligned" is transitive: if a pointer to type A is correctly aligned for a pointer to type B, which, in turn, is correctly aligned for a pointer to type C, then a pointer to type A is correctly aligned for a pointer to type C. Following program shows the explicit pointer conversion:

Line # Explicit Conversion

1 2 3 4 5 6 7 8 9

static unsafe void Main(string[] args) { int a = 100; int* ptr=&a; byte* b; b = (byte*)ptr; // Explicit Conversion Console.Out.WriteLine(*b); Console.Read(); }

P R O G R A M DE S C R I P T I O N : line 3 defines a value variable with value 100. Line 4 declares a pointer variable “ptr” that points to some integer variable and address of “a” is assigned to it. Line 5 declares another pointer variable “b” of type byte. Line 6 is core code in this example. It converts int ptr to byte ptr.

int ptr points to two bytes of memory but after this explicit conversion, byte ptr points to only one byte of memory.

L I T T L E EN D I A N V S B I G EN D I A N

These two phrases are derived from "Big End In" and "Little End In." They refer to

the way in which memory is stored. On an Intel computer, the little end is stored

first. This means a Hexadecimal word like 0x1234 is stored in memory as (0x34

0x12). The little end, or lower end, is stored first. The same is true for a four-byte

value; for example, 0x12345678 would be stored as (0x78 0x56 0x34 0x12). Some

computers store data in “Big End In” way. "Big End In" does this in the reverse

fashion, so 0x1234 would be stored as (0x12 0x34) in memory. Windows store

variables in Little Endian way on any platform. Following figure shows the concept

pictorially:

Page 278: Programming Fundamentals

Programming Fundamentals Using C# 277

Figure 12 - 2: Little Endian vs Big Endian

To test the endian way of your computer, you can use the following program:

Find Endian of your system

class Program { static unsafe void Main(string[] args) { long d = 0x123456789Abcdef1; unsafe { byte* pb = (byte*)&d; for (int i = 0; i < sizeof(long); ++i) Console.Write("{0:x2} ", *pb++); Console.WriteLine(); } Console.Read(); } } Output: f1 de bc 9a 78 56 34 12

This program lists every byte of long data separately using hexadecimal notation.

It is clear that my computer is using “Little Endian” way of data storage in RAM.

When using pointer conversions, the “endian” of system must be considered. To better understand this concept, let we consider following program:

Page 279: Programming Fundamentals

Programming Fundamentals Using C# 278

Accessing Part of Data

class Program { static unsafe void Main(string[] args) { ulong d = 0x123456789Abcdef1; unsafe { uint* pi = (uint*)&d; // Explicit Conversion Console.WriteLine("{0:x2}", *pi); Console.WriteLine(); } Console.Read(); } } Output: 9Abcdef1

Using little endian way, the variable d is stored in memory as:

MEMORY ADDRESS

500 501 502 503 504 505 506 507 508 509

VALUE … F1 de Bc 9a 78 56 34 12 …

If program is run on system using little endian “uint* pi = (uint*)&d” will return the value “9Abcdef1” but on system with big endian it will return “12345678”. Program written and compiled on one architecture may behave differently due to such explicit pointer conversions.

12.2.5. POINTER TO POINTER A pointer can point to another pointer. It means we can move the address of

pointer into pointer, this is called pointer to pointer. Following statements show

the use:

int A = 30; int* B; int** C; B = &A; C = &B;

The pointer to pointer is declared by placing double dereference operator. It

shows the two level of indirection. The statement “**c” first “*” will look at the

address in c and will goto that memory location, the memory location further

contains address, second dereference operator will goto that memory address and

from there value is retrieved. Following memory map shows the idea:

Page 280: Programming Fundamentals

Programming Fundamentals Using C# 279

Address Contents Variable

100 …

104 30 A

108 104 B

112 108 C

116 …

120 …

124 …

This chain of dereferencing may be increased as much as you like. For example,

“int*** a” will make three dereferences and “int**** a” will make four.

Following program uses pointer to pointer:

Pointer to Pointer

using System; namespace PointerandArrays { class Program { static unsafe void Main(string[] args) { int a = 30; int* b; int** c; b = &a; c = &b; Console.Out.WriteLine("Value Variable a:"); Console.Out.WriteLine("Value:{0}", a); Console.Out.WriteLine("Address:{0}\n",(uint)&a); Console.Out.WriteLine("Pointer Variable b:"); Console.Out.WriteLine("Address in b:{0}",(uint)b); Console.Out.WriteLine("Address of b:{0}",(uint)&b); Console.Out.WriteLine("Value Pointed By b:{0}\n", *b); Console.Out.WriteLine("Pointer to Pointer Variable c:"); Console.Out.WriteLine("Address in c:{0} ", (uint)c); Console.Out.WriteLine("Address of c:{0}",(uint)&c); Console.Out.WriteLine("Address Pointed By c:{0}", (uint)*c); Console.Out.WriteLine("Value pointed by address pointed by c:{0}",**c); Console.Read(); } } }

Page 281: Programming Fundamentals

Programming Fundamentals Using C# 280

You may seldom need to use pointer to pointer however in array processing, you

may use them.

12.2.6. MEMORY MANAGEMENT: NEW AND DELETE C# provides different ways for memory management. Memory management

involves memory allocation and freeing memory for variables and other data

items. Memory area where variables are stored and removed is called the heap.

Heap is managed by Microsoft Virtual Machine.

N E W K E Y W O R D

C# provides implicit and explicit ways of memory allocation. Variables of basic data

types are normally allocated memory implicitly. Following statement allocates 4-

byte of memory for specified variable:

int a=20;

C# uses “new” keyword is used to explicitly allocate memory for variables. Syntax

of new is given below:

new <data-type>();

You can also use the New keyword to initialize a value type. The memory allocation

occurs at heap area of application. The allocated memory is according to the size

of <data type>. C# is extendable language that provides the ways to user to

defined new data types. If a user defined data type is provided, allocated memory

will be of that size. In implicit memory allocation, compiler automatically adds

“new” functionality. Memory reserved by “new” keyword is bound with some

identifier that stands for name of that variable. Following statement allocates

memory for a double variable and bounds variable name “myvar” with it:

double myvar=new double();

We have seen the use of new keyword to allocate memory for arrays. The syntax

and example is given below:

Syntax: new <data type>[Number of values]; Example: int[] marks=new int[5];

Memory allocation is required at multiple points during code writing i.e. objects,

methods. The advanced uses of memory allocation will be discussed in later

chapters. Below listed program shows the use of implicit and explicit memory

allocation:

Page 282: Programming Fundamentals

Programming Fundamentals Using C# 281

Implicit and Explicit Memory Allocation

static void Main(string[] args) { int a = 20; // implicit memory allocation int b=new int(); // explicit memory allocation b = 40; int[] marks=new int[5]; // explicit memory allocation for (int i = 0; i < 5; i++) // implicit memory allocation for "i" marks[i] = i * i; Console.Out.WriteLine(b); foreach (int j in marks) Console.Out.Write(j+" "); Console.Read(); }

D E L E T E K E Y W O R D ( M I S S I N G)

C# does not provide a way to free allocated memory. C++ contains “delete”

operator for this purpose. However in C# freeing of allocating memory is shifted

to Garbage Collector (GC).

12.2.7. GARBAGE COLLECTION AND POINTERS Garbage collection is one of the core features provided in .Net framework. The

idea is simple whenever lifetime of a variable ends, memory occupied by it must

be freed. For example if a variable is declared in a method, a local variable, on

completion of method execution, its memory must be freed even if the program

is running. This is done by a special software called garbage collector or GC in short.

This software keeps track of all memory locations and their lifetimes. GC helps to

keep minimum utilization of memory resulting in efficient running of system.

From memory perspective every program is divided into two memory areas, data

and code. Both parts are known as HEAP S i.e. data heap and code heap. For a

method, all local variables and passed parameters are collectively called the

method state. When a method calls other method, calling method state need to

be saved and when called method returns, calling method state needed to be

restored. STACK is a memory area that is used to store and retrieve the state of

a method. There may be nested method calls in program, for such situation,

multiple method states are stored on stack. The stored state of each method is

called the STAC K FRA M E .

Above discussion shows that variables could be stored either on heap or on stack.

If after end of lifetime of a variable, it is not removed from memory, it remains

there without any use. This is known as MEMOR Y L EAK . Although C# provides

you the way to allocated and de-allocate memory in your code but programmers

Page 283: Programming Fundamentals

Programming Fundamentals Using C# 282

normally forget to de-allocate after the use of variable. GC keeps an eye on heap,

if an object/variable that is allocated and not being used, it removes it. STATIC

variables are special in this context. Their life time starts from the point of

declaration and lasts till end of program. When you mark a method or variable as

static, the runtime creates a global instance of that.

In short automatic garbage collection is just a bunch of code that runs periodically,

looking for allocated objects/variables that are no longer being used by the

application. It frees developers from the responsibility of explicitly freeing memory

of variables they create, avoiding the problem of variables being left uncleaned

behind and building up as classic memory leaks.

Pointer normally contain the address of some memory location. A pointer variable

can change its pointer any time. Following example shows the use of GC with

“Reference Types”:

Line# GC with Reference Variables

1 2 3 4 5 6 7 8 9

10 11 12 13

14 15 16 17 18 19 20 21

using System; using System.Collections.Generic; namespace GCandPointers { class Program { static void Main(string[] args) { List<int> lst; lst= new List<int>(); lst.Add(5); lst.Add(6); lst = new List<int>(); // previous list reference lost lst.Add(9); lst.Add(10); foreach (var v in lst) Console.Out.WriteLine(v); Console.Read(); } } }

P R O G R A M DE S C R I P T I O N : The program declares a reference variable of type

“List” that will contain integers. At line 10, memory for list is allocated on heap

and its reference (start address) is given to “lst”. Next two statements adds few

items in this list. At line 13, a new List is allocated memory on heap and its

reference is given to lst. Now lst has lost reference to old List. There is no other

Page 284: Programming Fundamentals

Programming Fundamentals Using C# 283

reference to old list in our program, hence this old list is eligible for garbage

collection. GC will run automatically now or sometime later and will free memory

occupied by old List. Next code, adds few elements in new list and then displays it.

12.2.8. FIXED AND MOVABLE VARIABLES Variables defined by program could be relocated or remain fixed. This change of

address is caused by the garbage collector. In this way variables are divided into

two categories: fixed and movable.

F I X E D V A R I A B L E S

These variables have permanent address in memory that are not changed during

program execution. GC can remove them but cannot change their address. They

are usually allocated on local stack and their address can be obtained using &

operator. A variable is fixed if it is:

Local variable or value parameter

Member of fixed composite data type

Retrieved using a pointer either with indirection expression “*p” or using

pointer notation p->item or array element access p[i].

All other variables are movable.

MO V A B L E V A R I A B L E

They are subject to garbage collection. As a result, obtaining and using address of

such variables. You cannot be sure about their exact memory address. So obtaining

address of such variables becomes difficult. A special statement “fixed” is used to

pinup variables in memory. During execution of fixed statement, address of

variable is ensured not to change.

F I X E D S T A T E M E N T

This statement allows getting and using address of movable variable. During the

execution of fixed statement, such variables cannot be moved or deleted by

garbage collector. Therefore pointers to such variables can be used. You should

not put too much code in fixed statement as it will stop GC to work in that area

causing the fragmentation of memory that is undesirable. Following is the syntax

of “fixed”:

Syntax of Fixed fixed(<expression>) { // body of fixed code block }

Page 285: Programming Fundamentals

Programming Fundamentals Using C# 284

A pointer variable is normally declared in fixed expression and given address of some variable which is required to be kept fixed. During the execution of the body of fixed statement, the variable is guaranteed to remain at its location. Look at the following program using fixed statement:

Fixed Statement

using System; namespace fixedStatement { class Program { static void Main(string[] args) { Display(); Console.Read(); } static unsafe void Display() { string value = "this is pakistan"; fixed (char* pointer = value) { // start of fixed block for (int i = 0; pointer[i] != '\0'; ++i) Console.Out.Write(pointer[i]+" "); } // end of fixed block } } }

12.2.9. POINTERS AND ARRAYS A pointer can point to an array. The name of array is infact pointer to that array

i.e. name of array contains address of memory location where array is stored. The

memory representation is shown below:

int myInt=400;

int[] myIntArray=new int[3]{4,5,6};

Address Contents Variable

100 …

104 30 myInt

108 116 myIntArray

112 …

116 4

120 5

124 6

Page 286: Programming Fundamentals

Programming Fundamentals Using C# 285

It could be seen from above figure that simple value variables are stored in

memory and their identifier directly points to that memory location whereas an

array identifier point to memory location that contains address where the array

elements are stored. In same way a pointer stores the memory address.

Following two programs shows use of array as pointer:

Pointer and Array

static unsafe void Main(string[] args) { char[] ch = new char[] { '1', '2', '3', '4' }; // Simple assignment not allowed without being fixed //char* ptr=ch; fixed (char* ptr = ch) // it is ok { for (int i = 0; i < ch.Length; i++) Console.Out.WriteLine(*(ptr+i)); } Console.Read(); } static unsafe void Main(string[] args) { int[] ar = new int[] { 1, 2, 3, 4, 5, 6 }; fixed (int* ptr = &ar[0]) { for(int i=0;i<ar.Length;i++) Console.Out.WriteLine(*(ptr+i)); Console.Read(); } }

In this program, we need to fix array before assigning its address to ptr. Array ar

is movable variable that could be relocated by the GC but after fixing it, its address

will not change now.

ptr now contains the address of first element of the array and now it has too

become a pointer constant. You cannot change its value. In expression *(ptr+i)

address of first array element is added with index i, resulting in address of ith

element and dereference operator access the value present at that address.

A pointer can also point to multidimensional array. Here is the program showing

the use of pointer with multi-dimensional array:

Page 287: Programming Fundamentals

Programming Fundamentals Using C# 286

Pointer and Multi-Dimensional Array

static unsafe void Main(string[] args) { int[,] ar = new int[,] { {1, 2, 3},{ 4, 5, 6} }; fixed (int* ptr = &ar[0,0]) { for (int i = 0; i < ar.Length; i++) Console.Out.WriteLine(*(ptr + i)); Console.Read(); } }

S T A C K A L L O C O P E R A T O R

stackalloc operator allows you declare pointer array in unsafe context. The

syntax of pointer array is shown below:

Syntax: stackalloc <data type>[size];

Example: stackalloc double[5];

stackalloc operator allocates memory in memory area called stack and returns

starting address of allocated area. There is different between array pointer and

pointer array. Following statements show the difference:

Array Pointer: int[] myIntArray=new int[5]; fixed(int* ptr=myIntArray);

Pointer Array: double[] myDoubleArray=stackalloc double[5];

The lifetime of the memory block is limited to the lifetime of the method that

defines it. You cannot free the memory before the method returns. Following

program shows the creation of pointer array:

Pointer Array

using System; namespace PointerArray { class Program { static unsafe void Main(string[] args) { double* ptrArray = stackalloc double[5]; for (int i = 0; i < 5; i++) *(ptrArray + i) = i * i; for(int j=0;j<5;j++) Console.Out.WriteLine(*(ptrArray+j)); Console.Read(); }

Page 288: Programming Fundamentals

Programming Fundamentals Using C# 287

} }

JA G G E D A R R A Y S

Jagged array is an arrays of arrays. It could also be handled using pointers in similar

way. As stated earlier, an array name is pointer to array contents. Jagged array

contains multiple arrays hence each sub array is pointer to different memory

location. The use of jagged array with pointer is shown below:

Pointer and Jagged Array

using System; namespace JaggedArrayPointer { class Program { static unsafe void Main(string[] args) { char[][] jaggedArray = new char[3][]; jaggedArray[0] = new char[] {'a','b','c','d' }; jaggedArray[1] = new char[] { 'e', 'f' }; jaggedArray[2] = new char[] { 'g', 'h', 'i'}; //char[]* ptr = jaggedArray; //Array name contains an address of for(int j=0;j<3;j++) fixed (char* ptr = jaggedArray[j]) { for (int i = 0; i < jaggedArray[j].Length; i++) Console.Out.WriteLine(*(ptr+i)); } Console.Read(); } } }

P O I N T E R S A N D S T R I N G

String pointers and pointers to strings works in same way as for other arrays. We

present following two programs without description:

Pointer String

using System; namespace StringPointer { class Program { unsafe static void Main(string[] args)

Page 289: Programming Fundamentals

Programming Fundamentals Using C# 288

{ string myMessage = "Always speak truth"; //a string is an array of characters fixed(char* strPtr = myMessage) { for(int i=0;i<myMessage.Length;i++) Console.Out.Write(*(strPtr+i)); } Console.Read(); } } }

And following example shows the use of pointer string:

String Pointer

using System; namespace PointerString { class Program { unsafe static void Main(string[] args) { //a character array is a pointer char* strPtr = stackalloc char[10]; for (int i = 0; i < 10; i++) *(strPtr + i) = (char)(65 + i); for(int j=0;j<10;j++) Console.Out.Write(*(strPtr+j)); Console.Read(); } } }

12.2.10. POINTERS AND FUNCTIONS Pointer variables can be passed as function parameters and can also be returned

as result.

P A S S I N G S C A L A R V A L U E P O I N T E R S

You need to pass addresses of arguments that will be received in parameters. Any

change made through pointers in called methods is reflected in calling method as

shown below:

Page 290: Programming Fundamentals

Programming Fundamentals Using C# 289

Passing Pointers to Methods

using System; namespace PointersAsParamter { class Program { unsafe static void Main(string[] args) { int x = 20, y = 40; int* p = &x, q = &y; Console.Out.WriteLine("Values before swaping:"); Console.Out.WriteLine("x={0} y={1}",x,y); swap(p, q); Console.Out.WriteLine("Values after swaping:"); Console.Out.WriteLine("x={0} y={1}", x, y); Console.Read(); } unsafe static void swap(int* a,int* b) { int temp; temp = *a; *a = *b; *b = temp; } } }

Following program shows the returning value by pointer:

Return by Pointer

using System; namespace ReturningPointers { class Program { unsafe static void Main(string[] args) { int x = 30, y = 50; int* result=sum(x, y); int res = *result; Console.Out.WriteLine(res); // output: 80 Console.Read(); } static unsafe int* sum(int a, int b) { int c;

Page 291: Programming Fundamentals

Programming Fundamentals Using C# 290

int* r=&c; *r = a + b; return r; } } }

P A S S I N G V E C T O R V A L U E P O I N T E R S

Pointers containing address of arrays can also be passed. The use of array pointer

is shown below:

Passing Vector Values

using System; namespace BubbleSort { class Program { unsafe static void Main(string[] args) { int[] marks = new int[] { 45, 55, 23, 67, 12, 9, 78, 98,50,44 };

fixed (int* ptr = marks) { BubbleSort1(ptr); } for (int i = 0; i < 10; i++) Console.Out.Write(marks[i] + " "); Console.Read(); } unsafe static void BubbleSort1(int* ar) { int temp,i,j; for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) if (*(ar + i) < *(ar + j)) { temp = ar[i]; ar[i] = *(ar + j); ar[j] = temp; } } } } Output: 9 12 23 44 45 50 55 67 78 98

Page 292: Programming Fundamentals

Programming Fundamentals Using C# 291

12.3. REFERENCE TYPES In C#, there are three types of variables exist:

Value type

Pointer types

Reference type

We have already studied the first two type of variables. Here we discuss the third type.

“Reference type variables are the variables that contain reference of other variables”

A reference type contains a pointer to another memory location that holds the data. These

are also referred as objects. Reference types can provide similar functionality like pointers

but in more safer, managed and cleaner way. Reference types include the following:

String All arrays, even if their elements are value types Class types, such as Form Delegates

In this section, we will only describe “strings” and “arrays”. Other reference types will be

discussed in chapters discussing advanced language features.

12.3.1. DECLARING REFERENCE TYPE VARIABLES Every reference type represents an underlying .NET Framework class therefore

“new” keyword is used to define and initialize the reference type variables.

Single[] totals = New Single[3]

{56.45f,34.78f,88.8f};

In case of value variable, only one space in memory is allocated but above statement will allocate two spaces (one on stack and other on heap) in memory.

One for “totals” and one for “{56.45f, 34.78f, 88.8f}”, three values. The starting address of second memory allocation is assigned to “totals”.

Address Contents Variable

100 …

104 …

108 116 totals

112 …

116 56.45

120 34.78

124 88.8

Heap

Memory Part

Stack

memory

part

Page 293: Programming Fundamentals

Programming Fundamentals Using C# 292

A reference variable can be assigned “null” value to point nowhere in memory

A reference variable can be assigned “null” value to point nowhere in memory. It is to note that we do not need to use “unsafe” context to use reference types. Following program shows the use of reference type variable:

Use of Reference Variable

using System; namespace ReferenceTypes { class Program { static void Main(string[] args) { Single[] sd = null; // Reference variable sd = new Single[3] { 4, 5, 6 }; for (int i = 0; i < 3; i++) Console.Out.WriteLine(sd[i]); Console.Read(); } } }

If a reference variable is assigned some address, it may point to other memory location leaving previous location reference free. Following program shows this concept:

Changing Reference

using System; namespace ChangingReference { class Program { static void Main(string[] args) { Single[] sd = null; // Reference variable sd = new Single[3] { 4, 5, 6 }; for (int i = 0; i < 3; i++) Console.Out.WriteLine(sd[i]); // New space allocated, old has no reference // old space is eligible for Garbage Collection now sd = new Single[4] { 3, 4, 5, 6 }; // New data for (int i = 0; i < 4; i++) Console.Out.WriteLine(sd[i]); Console.Read(); } }

Page 294: Programming Fundamentals

Programming Fundamentals Using C# 293

}

The Common Language Runtime (CLR) allocates memory for objects in two places: the stack and the heap. The stack is a simple first-in last-out memory structure, and is highly efficient. When a method is invoked, the CLR bookmarks the top of the stack. The method then pushes data onto the stack as it executes. When the method completes, the CLR just resets the stack to its previous bookmark—“popping” all the method’s memory allocations is one simple operation.

In contrast, the heap can be pictured as a random jumble of variables. Its advantage is that it allows variables/objects to be allocated or deallocated in a random order. The heap requires the overhead of a memory manager and garbage collector to keep things in order.

The following programming elements do not qualify as types, because you cannot specify any of them as a data type for a declared element:

Namespaces Modules Events Properties and procedures Variables, constants, and fields

12.3.2. REFERENCE TYPES AND METHODS Reference type variables can be passed to and returned from methods. There are

two ways to pass reference type variables to methods:

Passing reference types by value

Passing reference types by reference

P A S S I N G R E F E R E N C E T Y P E S B Y V A L U E

As listed above, arrays are reference types. A method receiving a value parameter

by value, can change its value but this change is not reflected in calling method.

However if a reference type variable is passed, its values could be changed by

called method but its “reference” could not be changed. Consider the following

program:

Reference Type Pass by Value

using System; namespace ReferenceTypePassByValue { class Program { static void Main(string[] args) { decimal salary = 5000.50m;

Page 295: Programming Fundamentals

Programming Fundamentals Using C# 294

decimal[] salaries = new decimal[3] { 1000.50m,2000.50m,3000.50m}; Console.Out.WriteLine("Before method call"); Console.Out.WriteLine("Salary={0}", salary); Console.Out.Write("Salaries = "+salaries[0]+"---"+salaries[1]+"---"+salaries[2]);

Change(salary, salaries); Console.Out.WriteLine("After method call"); Console.Out.WriteLine("Salary={0}", salary); Console.Out.Write("Salaries = " + salaries[0] + "---" + salaries[1] + "---" + salaries[2]);

Console.Read(); } static void Change(decimal sal, decimal[] sals) { sal = 1100; sals[0] = 3498; // following statement changes the reference // this reference change is local only sals = new decimal[2] { 4590, 6785 }; Console.Out.WriteLine("\n\nInside Change Method"); Console.Out.WriteLine("New Salary={0}", sal); Console.Out.WriteLine("New Salaries:{0} {1}\n",sals[0],sals[1]); } } } Output: Before method call Salary=5000.50 Salaries = 1000.50---2000.50---3000.50 Inside Change Method New Salary=1100 New Salaries:4590 6785 After method call Salary=5000.50 Salaries = 3498---2000.50---3000.50

The “values” passed, if changed in method are not reflected in calling method. In

method “Change()” first parameter value is passed and second parameter is

address, so if called method changes value of first parameter or address of second

parameter, calling method does not see the change.

P A S S I N G R E F E R E N C E T Y P E S B Y R E F E R E N C E

Page 296: Programming Fundamentals

Programming Fundamentals Using C# 295

You can pass either value types or reference types by reference to methods. If

calling method makes any change to parameters passed by reference, the change

is reflected in calling method. Consider the following program:

Reference Types Pass By Reference

using System; namespace ReferenceTypePassByValue { class Program { static void Main(string[] args) { decimal salary = 5000.50m; decimal[] salaries = new decimal[3] { 1000.50m, 2000.50m, 3000.50m }; Console.Out.WriteLine("Before method call"); Console.Out.WriteLine("Salary={0}", salary); Console.Out.Write("Salaries = " + salaries[0] + "---" + salaries[1] + "---" + salaries[2]);

Change(ref salary, ref salaries); Console.Out.WriteLine("After method call"); Console.Out.WriteLine("Salary={0}", salary); Console.Out.Write("Salaries = " + salaries[0] + "---" + salaries[1] + "---" + salaries[2]);

Console.Read(); } static void Change(ref decimal sal, ref decimal[] sals) { sal = 1100; sals[0] = 3498; // following statement changes the reference // this reference change is reflected in calling method sals = new decimal[3] { 4590, 6785,8888 }; Console.Out.WriteLine("\n\nInside Change Method"); Console.Out.WriteLine("New Salary={0}", sal); Console.Out.WriteLine("New Salaries:{0} {1}\n", sals[0], sals[1]); } } } Output: Before method call Salary=5000.50 Salaries = 1000.50---2000.50---3000.50 Inside Change Method New Salary=1100 New Salaries:4590 6785

Page 297: Programming Fundamentals

Programming Fundamentals Using C# 296

After method call Salary=1100 Salaries = 4590---6785---8888

As stated above, anything passed to a method by reference could be changed. In

above program method “Change()” received two parameters by reference. First is

value type variable whose reference is passed. A change made in “Salary” variable

by Change() is directly made in memory location of “Salary” so is visible in calling

method. Second parameter is reference type passed by reference. An address is

passed that points to some memory location. By reference allows to change this

address. A new memory space is allocated inside “Change()” method which is

reflected in calling method.

It is possible to convert a value type to a reference type, and back again to a value

type, by using boxing and unboxing. With the exception of a boxed value type, you

cannot convert a reference type to a value type. This conversion is out of scope of

current discussion.

Page 298: Programming Fundamentals

Programming Fundamentals Using C# 297

Chapter 13

User Defined Data types C# is extendable language that allows programmers to create new data types

according to their requirements. By creating new data types, users can enhance the

language functionality.

In this chapter, we will study how to create new user defined data types. What are

different ways to create new types and how are they used in our programs:

13.1. WHAT IS USER DEFINED DATA TYPE All programming languages provide some built-in data type which are normally sufficient

for programming small tasks. However during large scale software development,

situations may often arise where programmer need to define his own data type. Language

developers consider this requirement and build extensibility features in language. Using

these features, a programmer can create new data types to ease his programming task.

We summarize the need of user defined data types below:

WH Y U S E R D E F I N E D D A T A T Y P E S A R E R E Q U I R E D

There are numerous reasons to extend existing data types or build new data types:

C O M P O S I T E DA T A TY P E S : The basic data types provided by the languages consists

of single value (scalar variables) or single type of values (arrays). There may be

requirement in software development to create composite data type like Distance

that consists of meters and kilo-meters.

BE T T E R AB S T R A C T I O N : Programming is the job of mapping real world entities and

processes into code using abstraction (how we visualize the thing in code). For

example, a chair is one entity in real world, why not we write code where chair is

referenced as “chair”. It mean we can create a variable of chair that possess all

features of chair and all chair related operations could be performed on it.

EN H A N C E D C O D E RE A D A B I L I T Y : Better abstraction allows the programmer to

write code which looks like more natural and near to real world. Anyone reading

the code can easily understand the code

IM P R O V E D C O D E MA N A G E M E N T : Identifying variables, methods and other code

blocks in your program improves code readability and understanding resulting in

better code management. As a result code maintenance could be done in short

time.

Page 299: Programming Fundamentals

Programming Fundamentals Using C# 298

C# provides multiple ways for creating new data types. These could be categorized as:

Basic features for creating new data type

Advanced features for creating new data type

In this chapter, we will only study the basic or primitive ways of defining new data type.

The advanced features are out of scope of this book so left. Two basic features are

available in C#:

Enumerations

Structures

Every data type in a programming language is characterized by two features

Set of values

Operations defined on them

New data types, defined by users, either define set of values only or both set of values as

well as operations on them. If only set of values are defined, these values are based on

already defined data types and new data type operations are same as that of underlying

built-in base data type. C# provides both type of constructs: only define set of values and

set of values along with operations on them. Enumerations and Structures are both first

type of construct i.e. only set of values are defined by the user and their operations are

borrowed from underlying base data type operations.

13.2. ENUMERATIONS Word enumeration is used in mathematics. It is used to refer listening of all elements of a

set. C# provides “enum” keyword to define enumeration. An enumeration is user defined

set of same type of values given new name. An enumeration is a set consisting of named

constants. Every element of enumeration set is referred as enumerator.

13.2.1. DEFINING ENUMERATIONS The set of values defined using enumeration are actually named constants and are

known as enumeration list. The syntax of enumeration definition is given below:

Syntax: enum <enumeration name>{<val1>,<val2>,…,<valn>};

Example: enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

An enumerator cannot contain white space in its name. In C# enumeration is

defined out of methods as shown in the following program:

Defining Enumeration

using System; namespace DefiningEnumeration

Page 300: Programming Fundamentals

Programming Fundamentals Using C# 299

{ class Program { enum Days { sat, sun, mon, tue, wed, thu, fri }; enum Days1 { sat = 10, sun, mon, tue, wed, thu, fri }; static void Main(string[] args) { Console.Out.WriteLine(Days.sun); Console.Out.WriteLine((int)Days.sun); Console.Read(); } } } Output:

sun

1

sun

11

Looking at the output produced by this program, we can see that elements of

enumeration list can be accessed using enumeration name , placing dot after that

and then name of constant as “Days.sun”. Every such named constant is given

a sequence number automatically. For example, in Days enumeration, first

element “sun” has index number “0”, next has “1” and so on. Second output

statement shows this sequence number.

In C#, all enumerations are based on unsigned integers by default. The sequence

number of enumeration list could be forced to start with any other number.

Definition of Days1 enumeration causes the sequence of enumeration list start

with 10, every next element is given next number hence Days1.sun is given

sequence number 11. If you do not specify values for the elements in the

enumerator list, the values are automatically incremented by 1. You can also

assign separate value to each enumerator. Even negative values could be assigned

like

enum Days { Sun = -1, Mon = -2, Tue = 3 };

We can define variables of enumeration. Values, present in enumeration list, could

only be assigned to the variable of enumeration.

Line # Enumeration Variable 1 2 3

using System; namespace EnumerationVariable {

Page 301: Programming Fundamentals

Programming Fundamentals Using C# 300

4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19 20

class Program { enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; static void Main(string[] args) { Months m = Months.Jan; Console.Out.WriteLine(m); //Jan m = (Months)4; Console.Out.WriteLine(m); // May m = (Months)11; // Dec m = (Months)12; // 12 Console.Out.WriteLine(m); // 12 Console.Read(); } } }

Output Jan May 12

Above program defines an enumeration named “Months” to represent year

months. At line 10, a variable m of type Months is defined. Values assigned to m

should be from enumeration list so Months.Jan is assigned to it. The dot

operator specifies that “jan” belongs to Months data type.

Assigning “Jan” only will be an error as it is not clear that what is “jan”. When we

print the variable at line 12, value from enumeration list “Jan” is printed. We can

assign integer values to enumeration variable. As values in enumeration list and

integers are not compatible, hence assigned integer needs to be casted into

“Months” and then assigned to Month type variable as shown on line 13 above.

Now if we print out this value, we see that May is printed that is exactly right.

During casting at line 13, a constant from the enumeration list that corresponds to

4 i.e. May is assigned to m. And finally if the assigned number can correspond to

some member of enumeration list, that member is assigned to variable, if it is out

of bounds of enumeration list, only number is assigned to variable. No member of

enumeration list is assigned as shown on line 16 and 17.

13.2.2. INITIALIZING ENUMERATIONS Enumeration type variable are not initialized automatically hence could not be

used as following statements show:

enum Days { Mon,Tue,Wed,Thu,Fri,Sat,Sun }; ... ...

Page 302: Programming Fundamentals

Programming Fundamentals Using C# 301

Days d; Console.Out.WriteLine(d); // Error, unassigned variable.

However a variable created using “new” keyword is automatically initialized with

value zero.

enum Days { Mon,Tue,Wed,Thu,Fri,Sat,Sun }; ... ... Days d=new Days(); Console.Out.WriteLine(d); // OK, Mon will get printed

13.2.3. UNDERLYING DATA TYPES OF ENUMERATION Every enumeration has some underlying built-in data type. This is integer except

char. Approved types of enumeration are

byte, sbyte

short, ushort int, uint long, or ulong

The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type, as shown in the following example: enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is necessary to convert from enum type to an integral type. For example, the following statement assigns the enumerator Sun to a variable of the type int by using a cast to convert from enum to int.

int x = (int)Days.Sun;

Following example shows the creation of enumeration of different data type:

Different Data Type Enumeration

public class Program { enum Range : long { Max = 2147483648L, Min = 255L }; static void Main() { long x = (long)Range.Max; long y = (long)Range.Min; Console.WriteLine("Max = {0}", x);

Page 303: Programming Fundamentals

Programming Fundamentals Using C# 302

Console.WriteLine("Min = {0}", y); } } Output: Max = 2147483648 Min = 255

Enumerations are strongly typed constants. From strongly typed, we mean that

variable of one enumeration type cannot be assigned to enumeration of other

type. For example, following code tries to assign variable of one enumeration to

other. The compiler generates an error message “Cannot implicitly convert one

type to another”.

enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; enum Months { Jan, Feb, Mar, Apr, May }; Days d=Days.Sun; Months m=Months.Jan; d=m;

In above code two variables “d” and “m” of different enumerations are assigned

first enumerator of respective enumerations. Although by default Days.Sun and

Months.Jan both are given value “0” but being strongly typed, both are not

compatible. All assignments between different enum types require an explicit cast.

13.2.4. ENUMERATIONS AND POINTERS Enumeration variables are like other variables and their pointers can be defined.

The pointers work in the same as for basic data types. Following shows the use of

pointer with enumeration variable:

Enumeration and Pointers

using System; namespace EnumerationPointers { class Program { enum Range : long { max = 4000, min = 1000 }; static void Main(string[] args) { unsafe { Range r = Range.max; Range* a = &r;

Page 304: Programming Fundamentals

Programming Fundamentals Using C# 303

Console.Out.WriteLine(*a); // max Console.Out.WriteLine((int)*a); // 4000 } Console.Read(); } } }

13.2.5. ENUMERATIONS ARRAYS Like any other data type, you can define an array of enumeration variables.

Enumeration list members are named constants. Such constants can work in code

and can be displayed too but reading them in named constant way is not possible

as every input in C# from console is a string and a string is different from named

constant. Following program shows the use of enumeration array.

Program: Enumeration Array using System; namespace EnumerationArray { class Program { enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main(string[] args) { Days[] workDays = new Days[5]; workDays[0] = Days.Mon; workDays[1] = Days.Tue; workDays[2] = Days.Wed; workDays[3] = Days.Thu; workDays[4] = Days.Fri; foreach (var d in workDays) Console.Out.WriteLine(d); Console.Out.WriteLine(); } } }

13.2.6. ENUMERATIONS AND METHODS Like other value variables, enumeration variables could be passed to methods and methods can return the enumeration variables. In following program, we have passed an enumeration variable:

Page 305: Programming Fundamentals

Programming Fundamentals Using C# 304

Program: Enumeration As Parameter using System; namespace EnumerationAsParameter { class Program { enum studentType {Certificate,Diploma,Undergraduate,Graduate}; static void Main(string[] args) { studentType s1=studentType.Undergraduate; int fee = CalculateFee(s1); Console.Out.WriteLine(fee); Console.Read(); } static int CalculateFee(studentType s) { switch (s) { case studentType.Certificate: return 1000; break; case studentType.Diploma: return 2000; break; case studentType.Undergraduate: return 3000; break; case studentType.Graduate: return 4000; break; default: return -1; } } } }

It is to note that enumeration variable is value type and when we pass an enumeration variable to a method, it is passed by value. However, if we explicitly pass it by reference, its reference is passed and any change made by called method is reflected in calling method. Following skeletal code shows the use of enum pass by reference:

Program: Enumeration As Parameter . . . static void Main(string[] args) { studentType s1=studentType.Undergraduate; int fee = CalculateFee(ref s1); Console.Out.WriteLine(s1); // Graduate will be printed . . . } static int CalculateFee(ref studentType s) {

Page 306: Programming Fundamentals

Programming Fundamentals Using C# 305

. . . case studentType.Undergraduate: s=studentType.Graduate; return 3000; break; . . . } . . .

In the same way, enumeration value can be returned from called method. Pointer to enumeration can also be defined. The reader is encouraged to try enumeration pointers.

13.3. STRUCTURES We have seen that simple variables are used to represent single quantity at a time.

For example, int width; can only keep information about width, it cannot hold

the height quantity. There are so many quantities in life that are not single valued

like distance that may consists of feet and inches, a bill of shopping may contain

items counts and price of each item along with tax, an employee information may

include his name, CNIC number, salary and home address. To represent such type

of quantities, we need to organize simple variables into a complex set, identified

with single name. C# construction called structure provide a way to model such

multiple and heterogeneous quantities.

13.3.1. WHAT IS STRUCTURE? A structure is collection of simple variables identified by a unique name. A

structure may contain variables of same type like arrays or of different types. If a

construction that contains same type of values or variables, it is called the

homogeneous data type and if it contains different type of variables, it is called

heterogeneous data type. Usually a structure is considered as a heterogeneous

data type. The variables present in structure are known as S T R U C T U R E M E M B E R S .

A structure is collection of data and could be considered as record. Below is the

syntax of structure:

Structure Syntax struct <identifier> { <Access Specifier> Member variable1; <Access Specifier> Member variable2; … <Access Specifier> Member variable n; }; Example: struct Employee { public string name;

Structure

delimiters

struct

keyword

Name of

structur

e

Body of

Structur

e

Page 307: Programming Fundamentals

Programming Fundamentals Using C# 306

public float salary; public string homeAddress; }

In producing material products like fans in industry, stencils or plates are used. A

product gains the shape as that of stencils. There are constructions in languages

that provide similar functionality known as templates. They serve as blue print for

the variables of that data type.

Figure 12 - 3: Structure and Structure Variables

AC C E S S S P E C I F I E R S are the keywords that make variable accessible outside the

structure. Recall that variable defined in a method are local and are not accessible

outside that method. Similarly variables written in structure declaration

(definition, structure definition is term used for structure declaration and it does

do anything with memory, we will use both terms alternatively) are not accessible

outside structure. “public” is special keyword that makes particular variable

accessible anywhere outside structure. There are different access specifiers that

will be discussed in later chapters. For this chapter we take “public” as must

keyword before every structure variable.

In our Employee structure, we have three variables. Now every variable defined of

type Employee will contain these three members. The specification of structure

given in program does not create any memory for it. It is just a declaration. Like

Page 308: Programming Fundamentals

Programming Fundamentals Using C# 307

enumerations, structures are also defined outside methods. Memory is only

reserved when we create variables of that data type. Let we get practically familiar

using following example program:

Defining Structure

using System; namespace DefiningStructure { class Program { struct Employee { public string name; public float salary; public string homeAddress; }; static void Main(string[] args) { Employee emp; // structure is value type emp.name = "Sajid Iqbal"; emp.salary = 50000f; emp.homeAddress = "Multan"; Console.Out.WriteLine(emp.name); Console.Out.WriteLine(emp.salary); Console.Out.WriteLine(emp.homeAddress); Console.Read(); } } }

This program declares a structure named Employee, consisting of three variables,

before Main method. In Main method a variable “emp” is defined like any other

data type variable and memory is allocated for it. Now according to structure

specification above Main method, this “emp” contains three variables. The size of

allocated memory is equal to total size of all variables.

A structure is value type so its variable could be defined without using “new”

operator as shown in above program.

13.3.2. ACCESSING STRUCTURE MEMBERS Structure member variables are accessed through structure variable using

following syntax:

Syntax <structure variable> dot operator <public member variable>

Example emp.name

Page 309: Programming Fundamentals

Programming Fundamentals Using C# 308

Only those variables of structure will be accessible in Main or other methods which

are declared using “public” keyword. When you write dot operator after structure

variable, VS IDE shows you all accessible variable names. Following VS IDE shows

this feature:

Figure 13 - 1: Access Specification in Structures

In above figure, you can see that in structure definition “salary” is declared

without “public” keyword. In Main method, when we write dot operator after

structure variable, a list of methods and variables is automatically displayed. This

list only contains names of “public” variables. Salary is not listed here hence it

cannot be used in Main method.

13.3.3. INITIALIZING STRUCTURE VARIABLES Structure variables could not be initialized in simple way. C# provide a specific way

for initialization. A method of same name as that of structure with no return type

is defined within structure definition first as shown below for our Employee

structure:

Page 310: Programming Fundamentals

Programming Fundamentals Using C# 309

struct Employee {

public string name; public float salary; public string homeAddress; public Employee(string n, float s,string ha) { name=n; salary=s; homeAddress=ha; } };

Note again that Employee() method defined within structure definition has no

return type and same name as that of structure. Such special methods are called

“Constructors”. More on constructors will be given in next chapters. Like other

normal methods, three parameters are passed to this constructor which are

assigned to structure variables. A constructor must be defined with “public”

keyword. After writing complete specification for structure, we can initialize the

structure variable as follows:

. . . Employee emp=new Employee(“Aman Ullah”,89,90,99,0); Console.Out.WriteLine(emp.name); // Aman Ullah . . .

Following is complete listing of program using structure variable initialization:

Structure Variable Initialization

using System; namespace StructureVariableInitialization { class Program { struct Employee { public string name; public float salary; public string homeAddress; public Employee(string n, float s, string ha) { name = n; salary = s; homeAddress = ha;

Page 311: Programming Fundamentals

Programming Fundamentals Using C# 310

} }; static void Main(string[] args) { Employee emp = new Employee("Aman Ullah Khan", 500001, "DG Khan"); Console.Out.WriteLine("Name:{0} Salary:{1} Home Address:{2}", emp.name, emp.salary, emp.homeAddress); Console.Read(); } } }

13.3.4. STRUCTURE AND STRUCTURE VARIABLES Like any built-in data type, multiple variables of structure (user defined data type)

could be defined and each variable is given separate memory location. Off course

every structure variable will be similar as it belongs to same data type (same

structure). Continuing Employee structure example, multiple variables could be

defined and initialized as:

Employee minhaj=new Employee(“Minhaj Ahmed Khan”,167865,”Lahore”); Employee qaiser=new Employee(“Qaiser Rasool”, 170000,”Karachi”); Employee israr=new Employee(“Israr Hanif”,110000,”Peshawar”);

Their memory allocation is shown below:

Memory Contents Member Variable Structure Variable

… minhaj Minhaj Ahmed Khan

Name

167865

Salary

Lahore

Home Address

Qaiser Rasool

Name qaiser

170000

Salary

Karachi

Home Address

Israr Hanif

Name israr

110000 Salary

Page 312: Programming Fundamentals

Programming Fundamentals Using C# 311

Peshawar

Home Address

Following program shows the use of multiple variables of a structure:

Multi Structure Variables

using System; namespace MultipleStructureVariables { class Program { struct Employee { public string name; public float salary; public string homeAddress; public Employee(string n, float s, string ha) { name = n; salary = s; homeAddress = ha; } }; static void Main(string[] args) { Employee minhaj = new Employee("Minhaj Ahmed Khan", 167865, "Lahore"); Employee qaiser = new Employee("Qaiser Rasool", 170000, "Lahore"); Employee israr = new Employee("Israr Hanif", 110000, "Lahore"); Console.Out.WriteLine("Name:{0} Salary:{1} Home Address:{2}",minhaj.name, minhaj.salary, minhaj.homeAddress); Console.Out.WriteLine("Name:{0} Salary:{1} Home Address:{2}", qaiser.name, qaiser.salary, qaiser.homeAddress); Console.Out.WriteLine("Name:{0} Salary:{1} Home Address:{2}", israr.name, israr.salary, israr.homeAddress); Console.Read(); } } }

S T R U C T U R E V A R I A B L E A S S I G N M E N T

Variables of same structure could be assigned to each other. Consider the

following structure:

Page 313: Programming Fundamentals

Programming Fundamentals Using C# 312

Struct student { public uint rollno; public string name; public float marks; public student(uint r,string n,float m) { rollno=r; name=n; marks=m; } }; . . . student s1 = new student(1,“sumera” ,78); student s2=new student(2,”yumna”,80); s1=s2; // structure variable assignment

Although there are three member variables in each structure variable but

assignment operator correctly copies the corresponding member variables i.e.

s2.name into s1.name, s2.rollno into s1.rollno and s2.marks into

s1.marks. If we have structure with dozen of variables, this single assignment will

do lot of programmer work.

13.3.5. MULTIPLE STRUCTURES AND STRUCTURE ARRAYS You can define multiple data types in a program using structures. Following

program defines two new data types and an array variables of each structure:

using System; namespace MultipleStructures { class Program { struct chair { public int legs; public bool arms; public bool moveAble; public decimal price; }; struct table { public int legs; public bool drawer; public bool footrest; public decimal price; }; static void Main(string[] args)

Page 314: Programming Fundamentals

Programming Fundamentals Using C# 313

{ Console.Out.WriteLine("Please enter details of furniture, you purchased:"); Console.Out.Write("How many chairs:"); int chair_count = int.Parse(Console.ReadLine()); chair[] chairs = new chair[chair_count]; for (int i = 0; i < chair_count; i++) { Console.Out.WriteLine("Enter data for chair {0}:", (i + 1)); Console.Out.Write("Legs(count):"); chairs[i].legs = int.Parse(Console.ReadLine()); Console.Out.Write("Arms(true/false):"); chairs[i].arms = bool.Parse(Console.ReadLine()); Console.Out.Write("Moveable(true/false):"); chairs[i].moveAble = bool.Parse(Console.ReadLine()); Console.Out.Write("Price(decimal):"); chairs[i].price = decimal.Parse(Console.ReadLine()); } Console.Out.Write("How many tables:"); int table_count = int.Parse(Console.ReadLine()); table[] tables = new table[table_count]; for (int i = 0; i < table_count; i++) { Console.Out.WriteLine("Enter data for table {0}:", (i + 1)); Console.Out.Write("Legs(count):"); tables[i].legs = int.Parse(Console.ReadLine()); Console.Out.Write("Drawer(true/false):"); tables[i].drawer = bool.Parse(Console.ReadLine()); Console.Out.Write("Footrest(true/false):"); tables[i].footrest = bool.Parse(Console.ReadLine()); Console.Out.Write("Price(decimal):"); tables[i].price = decimal.Parse(Console.ReadLine()); } Console.Out.WriteLine("Your items and total bill is:"); decimal totalPrice = 0; foreach (chair a in chairs) totalPrice += a.price; foreach (table a in tables) totalPrice += a.price; Console.Out.WriteLine("No. of Items:{0} and Total Price:{1}", (chair_count + table_count), totalPrice); Console.Read(); } } }

An array of structure variables is just like simple variables array except each array

element consists of multiple items. Let in our program an array of structure

variables is defined as

chair[] chairs=new chair[3];

Page 315: Programming Fundamentals

Programming Fundamentals Using C# 314

Following figure shows the array allocation in memory:

13.3.6. NESTED STRUCTURES A structure could be defined within other structure like nested loops. It means a

structure could be declared within body of other structure. The syntax is as

follows:

Syntax: struct <outer struct name> { Struct <inner struct name> { . . . // inner member variables }; . . . // outer member }; Example: struct Room { public struct Distance { public int feet; public int inches; };

chairs[]

chairs[2]

chairs[1]

chairs[0]

legs

arms

moveable

price

legs

arms

moveable

price

legs

arms

moveable

price

Page 316: Programming Fundamentals

Programming Fundamentals Using C# 315

public Distance width; public Distance length; };

Member variables of such structure could be accessed using multiple dot

operators. The count of dot operator is equivalent to nesting level of structures.

Following statements show the access of member variables and nested structure

member variables:

Room m; m.width.feet=40; m.width.inches=10;

Although above syntax allows to declare structures within structures but it makes

coding more complex and sometimes difficult to read. C# also provides a more

clean way to declared nested structures. This use is described with the help of

following example:

public struct Distance { public int feet; public int inches; }; struct Room { public Distance width; public Distance length; };

Method to access the member variables is same as shown below:

Room m; m.width.feet=40; m.width.inches=10;

We have used word “Stack” in chapter discussing pointers and methods. Stack is a

data structure that is maintained by Common Language Runtime (CLR) for your

program. A data structure is a way of organizing data in RAM. A stack could be

considered as last in first out (LIFO) list or pile of plates. A stack is “over flown” if

all memory space reserved for stack is used. Stack “underflow” occurs when all

elements from stack are removed. A plate present on top is removed first. Using

structure, following program implements this data structure:

Page 317: Programming Fundamentals

Programming Fundamentals Using C# 316

Stack Implementation using System; namespace StackImplementation { class Program { struct Stack { public int[] stack_elements; public int top; public Stack(int t) { top = t; stack_elements = new int[10]; } }; static void Main(string[] args) { Stack s=new Stack(0); int choice; do { Console.Out.Write("1-Push 2-Pop -1-Exit:"); choice = int.Parse(Console.ReadLine()); switch (choice) { case 1: Console.Out.WriteLine("Enter value to be pushed on stack:"); int a = int.Parse(Console.ReadLine()); Push(a, s); break; case 2: Console.Out.WriteLine("Poped value is:{0}",Pop(s)); break; default: Console.Out.WriteLine("Invalid choice, please try again"); break; } } while (choice != -1);

Page 318: Programming Fundamentals

Programming Fundamentals Using C# 317

} static void Push(int element, Stack s) { if (s.top < 10) { s.stack_elements[s.top++] = element; Console.Out.WriteLine("Elemented pushed into stack"); } else Console.Out.WriteLine("Stack overflow"); } static int Pop(Stack s) { if (s.top < 0) { Console.Out.WriteLine("Stack underflow"); return -1; } else return s.stack_elements[s.top--]; } } }

13.3.7. STRUCTURES AND POINTERS Like any other variable, pointer to structures could be defined. Member variables

could also be pointers. Let first we see that how pointer member variables could

be declared and used in structures.

Struct Employee { String name; Decimal* salary; };

The use of pointer member variable is given in following program:

Pointer Member Variables

using System; namespace PointerMemberVariable { unsafe class Program { struct Employee { public string name; public decimal* salary;

Page 319: Programming Fundamentals

Programming Fundamentals Using C# 318

} static void Main(string[] args) { Employee emp; Console.Out.Write("Enter employee name:"); emp.name = Console.ReadLine(); Console.Out.Write("Enter Salary:"); // an unassigned variable is not allowed //*(emp.salary) = decimal.Parse(Console.ReadLine()); Error decimal sal = decimal.Parse(Console.ReadLine()); emp.salary = &sal; Console.Out.WriteLine("You have entered:"); Console.Out.WriteLine("{0}---{1}", emp.name, *(emp.salary)); Console.Read(); } } }

We can also declare pointer variables of structures. If using structure pointer

variable, the syntax to access its members changes i.e. emp.salary to emp-

>salary. Here is the program showing the use of pointer structure variables:

Pointer Structure Variable

using System; namespace PointerStructureVariable { unsafe class Program { public struct Employee { public int grade; public decimal* salary; } static void Main(string[] args) { Employee emp; Employee* ePtr = &emp; Console.Out.Write("Enter employee grade:"); ePtr->grade = int.Parse(Console.ReadLine()); Console.Out.Write("Enter Salary:"); decimal sal = decimal.Parse(Console.ReadLine()); ePtr->salary = &sal; Console.Out.WriteLine("You have entered:"); Console.Out.WriteLine("{0}---{1}", ePtr->grade, *(ePtr->salary)); Console.Read();

Page 320: Programming Fundamentals

Programming Fundamentals Using C# 319

} } }

NOT E: Working with pointers is interesting but becomes nightmare if anything

goes wrong. The situation becomes worse when using pointers in managed

environment like C#. The reader is encouraged to change “grade” in Employee

structure with “string name” and try to do the same program to get the real taste.

13.3.8. STRUCTURES AND FUNCTIONS Structure variables can be passed to and returned from methods like other value

type variables. We present following program without description:

Structures and Methods using System; namespace StructuresFunctions { class Program { struct Distance { public int feet; public int inches; }; static void Main(string[] args) { Distance d1=new Distance(); Distance d2=new Distance(); ReadData(ref d1); ReadData(ref d2); Distance d3 = FindTotal(d1, d2); Console.Out.WriteLine("The total distance is: "+d3.feet + "--- "+d3.inches); Console.Read(); } static void ReadData(ref Distance d) { Console.Out.Write("Enter Feet:"); d.feet = int.Parse(Console.ReadLine()); Console.Out.Write("Enter Inches:"); d.inches = int.Parse(Console.ReadLine()); } static Distance FindTotal(Distance d1, Distance d2) { Distance d; d.inches = d1.inches + d2.inches; d.feet = d1.feet + d2.feet; if (d.inches > 11) { d.feet+=d.inches / 12;

Page 321: Programming Fundamentals

Programming Fundamentals Using C# 320

d.inches = d.inches % 12; } return d; } } }

Page 322: Programming Fundamentals

Programming Fundamentals Using C# 321

Chapter 14

Errors and Exceptions

Committing an error is human feature. How accurate you are, you will commit

mistakes because you are naturally error prone. In doing any task, either you forget

or overlook details which are discovered later on. And if you are good enough, you

accept and return to correct them. Computer programming is carried by professionals

i.e. humans, hence errors are unavoidable. Language developers, considering this

aspect, have also developed mechanisms to find and correct errors and omissions in

your program.

In this chapter, we will learn what errors are, how are they introduced in the code and

what are their different types. We will also look at different tools and ways provided

by C# to trace and remove errors in your program. At the end of this chapter, you

should be able to apply error tracing and removal related features of C#.

14.1. THE ERRORS A computer program is written in formal way where each rule must be followed either

implicitly by the language or explicitly by the programmer. Any violation of language

defined rules is known as error or we can define error as follows:

“Any inconsistency in the program”

These inconsistencies are introduced in program due to multiple reasons. That may include

lack of knowledge about the language rules, overlook on coding details, insufficient

knowledge about the problem for which software is being developed. A software is

normally built considering some expectations i.e. availability of sufficient memory and

presence of required libraries. Unavailability of required expected computing resources

may also cause errors in program execution.

Even the most experienced programmers make mistakes, which are known as bugs or

errors. Before discussing the error removal process, however it is important to know about

different types of errors.

14.1.1. ERROR TYPES Errors are grouped into different categories as listed below:

Syntax Errors

Page 323: Programming Fundamentals

Programming Fundamentals Using C# 322

Semantic Errors

SYN TA X ERROR S

Compiler translates high level language program into low level language. During

compilation process, it ensures that all language rules are followed by the

programmer. The errors produced by the code statements which are not written

according to language syntax are known as syntax errors. These errors are the

easiest to find and correct. Some syntax errors are very common, especially for

beginning programmers, and the examples that follow should help you identify

and correct:

Missing Semicolon

int num;

float value // semicolon missing

double bigNum;

Undeclared Variable Name

int num;

float value;

double bigNum;

bignum = num + value; // undeclared variable

Unmatched Parentheses

result = (firstVal - secondVal / factor; //

parenthesis missing

Unterminated Strings

string className=”City District Government;

SE MAN TI CS ERR OR S

A semantic error is violation of the rule of “meaning” of a statement. Compiler can

successfully translate the program with semantic errors however when program

is run, it produces erroneous results. Semantic errors usually are detected by the

programmer or user of the program, often while reading output and finding it is

incorrect. These are most common type of errors and hardest to trace and correct.

Common semantic errors may include:

Infinite loop

Misunderstanding of operator precedence

Dangling else

Inaccurate loops – less or more iterations than required

Code inside a Loop that does not Belong There

Page 324: Programming Fundamentals

Programming Fundamentals Using C# 323

Array index bound error

Errors are also grouped according to time of their occurrence:

Compilation Errors

Run Time Errors

Logic Errors

COM PI LAT IO N ERROR S

A piece of code that does not follow the rules is not understandable for compiler

and compiler warns the programmer about such parts of code in the form of error

list. Most of the compiler errors are generated due to code which is miss typed.

For example, when writing and if-statement, you may place its body opening brace

but forget to write closing brace or you write “freach” instead of “foreach”. All

syntax errors and some of the semantic errors are detected by the compiler.

Semantic errors detected at compile time are called the static semantic errors.

RUNTI M E ERROR S

These are the errors that occur during program execution. At the time of

compilation such errors are not detectable. Such errors occur due to two major

reasons. A program may expect to communicate with operating system but

operating system does not respond or during network communication, other end

does not respond in time. Such errors are generated because of insufficient

resources or unavailability of resources. Other reason for these errors is attempt

to perform impossible operations. For example if program attempt to divide some

value with zero as shown below:

share = totalAmount / workers_count;

If the value of workers_count is zero, a run time error will occur. Similarly if

program try to use a reference variable which does not point to a value, run time

error will be generated. Such errors are harder to find and fix. Some semantic

errors are detected at runtime which are called the dynamic semantic errors.

LOG IC ERR ORS

As a programmer, we tend to solve some problem. For example, calculating daily

sale of a store. If a program compiles successfully, does not generate error at run

time but do not produce the expected results is said to contain logic errors. For

example, tax from hotel bill is calculated at the rate of 5% but software is

calculating at 6% rate. Logic errors are the hardest to find and fix. A logic error is

also known as bug.

There are tools present in VS2010 to assist the programmer in tracing type of

errors and eliminate them.

Page 325: Programming Fundamentals

Programming Fundamentals Using C# 324

14.1.2. PROGRAM COMPILATION METHODS There are multiple program compilation methods in C# as listed below:

Using command line compiler

Using IDE Debug Menu

US IN G CO M MAND L IN E COM PI LER

C# comes with command line compiler that is called C Sharp Compiler (CSC). A file

named CSC.EXE is installed on your system when you install Visual Studio. On my

system, the compiler is located at:

C:\Program Files (x86)\MSBuild\12.0\Bin

You should search your system for the location of C# compiler. Before writing a

program and compiling it using C#, compiler, you need to set the path on your

system such that you can run compiler from any directory of your choice. There

are two ways to set the path of compiler: Using environment variable manually

and running batch file “vsvars32.bat”. Using batch file is easy and fast method of

setting environment variables. The file could be located on any of following two

locations

C:\Program Files (x86)\Microsoft Visual Studio

10.0\Common7\Tools

C:\Program Files\Microsoft Visual Studio

10.0\Common7\Tools

To run VSVARS32.BAT:

1. At a command prompt, change to the Program Files\Microsoft Visual Studio 10.0\Common7\Tools or Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools subdirectory of your installation.

2. Run VSVARS32.bat by typing VSVARS32.

Following figure shows the run of this file:

Running this file will automatically set all required environment variables. Now you

can go to any directory and run the C Sharp Compiler. As a short way, you can also

run the Visual Studio command prompt, that will automatically set the

Page 326: Programming Fundamentals

Programming Fundamentals Using C# 325

environment variables and you can run the compiler easily from anywhere in your

directory tree structure. Following screen capture shows the location of Visual

Studio Command Prompt in start menu.

And you can run the compiler as shown below:

You can write your program using any text editor i.e. Notepad++ and compile it

using command line compiler. Let we assume that you have written following

program in C#.

using System; namespace CommandLineCompilation { class Program { static void Main(string[] args) { int a = 8; int b = 2; Console.Out.WriteLine(a / b); Console.Read(); } } }

Page 327: Programming Fundamentals

Programming Fundamentals Using C# 326

Let you write above program and save it with name “Program.cs”. Now you can

compile the file using command “csc program.cs” as shown below:

The file is compiled and a new file “Program.exe” is produced which could be run

using command “Program” as shown below:

US IN G IDE DEBU G MEN U

Visual Studio IDE allows to build program in two ways:

Start with debugging

Start without debugging

Both commands are found under “Debug” menu of IDE as shown below:

START DE BUG GIN G VS START WI THO UT DE BUG GIN G

Debugging is the process of

removing errors from your

program. A special

software called debugger is

used for this purpose.

Almost every programming

language compiler comes with debugger.

When we use “START DEBUG GI N G” option, VS IDE attaches debugger with your

program that keeps an eye on execution of each statement. Microsoft describes

the working of debugger as follows:

“The Visual Studio debugger is a powerful tool that allows you to observe the

run-time behavior of your program and locate logic errors. The debugger

works with all Visual Studio programming languages and their associated

libraries. With the debugger, you can break, or suspend, execution of your

program to examine your code, evaluate and edit variables in your program,

Page 328: Programming Fundamentals

Programming Fundamentals Using C# 327

view registers, see the instructions created from your source code, and view

the memory space used by your application”

VS IDE allows you to compile your program using “Start Debugging” in two modes:

Debug Mode and Release Mode. The

difference between two modes is very

little. For example, using “Debug” mode,

user can send “debugging related

messages” to command line but in

“Release” mode, such messages are not

allowed. The different is not worth at this

stage of learning so you can easily ignore it. Let we go with “Debug” mode. When

an error occurs in your program, the compiler stops there and allows user to

correct the error. Using “Start Debugging”, you can run your program line by line

and see results of each line.

START W ITH OUT DE BU G GIN G runs the program without using debugger. So if

a program is run using “start without debugging”, no debugging related operation

could be performed. The process of debugging is explained next. Another

difference between “Start Debugging” and “Start without Debugging” is that “Start

Debugging” compiles and runs the program using Visual Studio Command Line tool

whereas “Start without Debugging” uses system command prompt. If you run a

Console application with plain old F5 (Start Debugging), the console window

flashes on the screen and disappears, unless you add a Console.ReadLine() to

your code; with Control_F5 (Start without Debugging), the console window is held

on the screen until you hit the Return key. There are few other little difference

which are not worth to discuss here.

You build an executable application by clicking Build on the Build menu. Visual

Studio uses the MSBuild tool to create assemblies. MSBuild can also be run from

the command line and can be customized in many ways. You can build and start

the application in one operation by pressing F5 or clicking Run on the Debug menu.

Building a project involves multiple steps. In first phase, user program is compiled

using C# compiler that converts the program into Microsoft Intermediate

Language (MSIL). In next phase, IL program and program’s Meta data are

combined together to form an Assembly. An assembly is runnable program either

in the form of exe file or dll file. A “Debug” version of software is created to test

and see how program will run after proper building it. A Debug build could be

considered as test build. Finally, when everything is correct, you will create a

“release” version that you will deploy to customers.

Page 329: Programming Fundamentals

Programming Fundamentals Using C# 328

Debugging a Program

A bug is defined as “a bug is error, flaw,

failure or fault in the software that

causes it produce incorrect or

unexpected result”. A bug could be

introduced due to any mistake in any

phase of software engineering life cycle.

The process of finding and fixing bugs in

software is called the debugging. C# is

supported with powerful debugging

software. I have experienced that if a

student can learn the proper use of

debugger, coding becomes easier. So it

is recommended that you should

understand the debugging concepts and

their application in Visual Studio

debugger.

All debugging related options are

provided in debug menu of VS IDE. This

is shown below. It is clear from the figure

that there are lot of options with

debugging related process. We explore

each menu item and its use in detail.

Debugging process could be started in multiple ways. We start discussing

debugging using one way, other will be discussed as menu items are explored.

Pressing F11 will start debugging process. It allows you to execute one program

statement at a time and look into its results. Usually debugging process starts from

Main method. Following is the snapshot of our example program after pressing

F11. A yellow arrow points to the statement being executed.

Page 330: Programming Fundamentals

Programming Fundamentals Using C# 329

Figure 14- 1: Debugging a Program

STE P IN TO

The statement being executed is also colored in yellow background. The option

“STEP INT O” or pressing F11, will compile and execute the yellow highlighted

statement and next statement is highlighted showing that next statement is ready

to be compiled and executed. Every time you press F11, current statement is

executed and next is highlighted. Two other windows are automatically become

visible with the start of debugging process. “LOCAL S” window shows all the local

variables of method and passed parameters along with their current values. “Call

Stack” window is used to display the method calling sequence.

VARI ABLE V ALUES

Page 331: Programming Fundamentals

Programming Fundamentals Using C# 330

Although LOCALS window displays the

vlaues of local variables, you can also

watch and understand the values by

bringing mouse cursor over those

variables in the program code.

Following figure shows the demo.

When we bring mouse cursor over

variable “b”, intelligent code editor

automatically displays its value. When

we move cursor away from variable,

the popup box shown variable value

disappears. However if pin icon

(showed on right of 5) is pressed, the

popup box does not disappear and

remains permanently in the editor as

shown below. Value of variable “b” is

pinned in editor and cursor is moved

to variable “y” showing its popup

value box.

This inline value inspection is very

useful for understanding the incorrect values in your program data.

QUICKWATCH…

This menu allows you to quickly watch the result of an expression which is either

present in program or not. As shown in above figure, debugger is “Stepping into”

marked statement “result=x+y;”, quick watch window contains a text box and list

box. User can enter any expression in “Expression” box and by pressing

Page 332: Programming Fundamentals

Programming Fundamentals Using C# 331

reevaluate button, the result is calculated and displayed in the list box. In our

example expression “x-y”, the result is “-2” that is displayed in the list box. If you

press the “Add Watch” button, the expression is added into “Watch 1” window

(watch 1 window is marked in ) Error! Reference source not found.. The result of

peration is shown here.

Continue

If you are in debugging session of your program and press F5 or choose Debug

Continue. Debugging will be stopped and all of your program will be run. You

would no more be able to execute your program line by line or step by step.

STO P DEBUGGIN G

This option causes the debugging session to end and program execution is

terminated from the current point of execution.

Added

Expression

Page 333: Programming Fundamentals

Programming Fundamentals Using C# 332

MORE OPTIONS

“Restart” option will restart the debugging session from first statement of your

program. Other options shown in this figure are concerned with advanced

concepts which are yet to be learned so left for future discussion.

STE P OVE R

This option causes the program not to enter into any called method that comes in the way of calling method “stepping into”. For example in our program, if user presses F10 when “int c = Add(a, b);” statement is highlighted. The stepping process will not enter into “Add()” method. All method will be executed and debugger will move to “Console.Out.WriteLine();” statement. In other words, F10 causes the debugger to jump over the Add method. This command is useful when we are sure about the working of a method but we need to look into every statement of current method.

STE P OUT

We explain this option using our example program. If you have started stepping into from Main method, on “Add” method call statement, stepping into takes you into Add method. If during the stepping into Add method, you decide to go back to Main method without completing Add method, you can choose this option or Shift+F11, it will take you back into Main method and stepping into Main method continues. In short, Step Out option allows you to move out of called method back into calling method.

Breakpoint

Page 334: Programming Fundamentals

Programming Fundamentals Using C# 333

A BREAKPOINT is a place in user code marked by user to pause execution. It is also

some time referred as “Pause”. It is used to pause program execution explicitly by

the user and user can inspect the program current state to understand its

execution and intermediate results to find out whether the program is functioning

as expected.

You can insert Breakpoint into your code in two ways: by choosing New Breakpoint

option from Debug menu or by clicking on vertical status bar in the code editor.

Following picture shows the inserted break point in the code.

A breakpoint is shown with red circle on status vertical bar. The statement under

breakpoint is also shown in red background in code editor. Now if you press F5, all

code before this breakpoint will be compiled and executed automatically but when

compiler will reach to statement of Breakpoint, it will pause execution and will

wait for user further command. I usually place breakpoint on statement before

which I am sure about the correct working of program. After breakpoint

statement, I am doubtful and want to explore each statement about any expected

error.

Toggle breakpoint option allows you to change breakpoint status from active to

inactive. An active breakpoint causes compiler to pause program execution

whereas inactive breakpoint does not affect the compilation process.

Delete All Breakpoints removes all break points inserted by user in the program.

WINDO WS

Status Vertical Bar

Breakpoint

Page 335: Programming Fundamentals

Programming Fundamentals Using C# 334

Windows option of debug menu allows you to open more windows to look at

different data items or program features. A brief description of few of options is

given below:

Option Description

Breakpoints A new window that displays the list of all breakpoints inserted into user program.

Output This window displays the various action taken by compiler or IDE to obey user commands

Watch This is further expandable window that allow user to open further watch windows. Each watch window is user to look at current values of program variables. A user can open upto four watch windows

Autos A window that is used to display values of automatic variables

Locals A windows used to display values of local variables

Call Stack A window used to display method call sequence

Memory Window used to show the values stored in memory

Disassembly This windows shows the “Assembly Language Code” produced for your program

Registers This window is used to show the values in registers of CPU

Page 336: Programming Fundamentals

Programming Fundamentals Using C# 335

REM AININ G OPTI ONS

These options are useful but not too much important. I will not explain them here.

The reader is encouraged to explore these commands himself. Microsoft

Developer Network (MSDN) is best place to explore detailed features of VS IDE.

14.2. EXCEPTIONS An algorithm is step by step procedure to solve the given problem. Usually our program is

a fine tuned version of algorithm and we do expect that program will work in the way steps

are defined. This is normal flow of program execution. But there may be cases when

normal flow is not followed due to some unexpected situation. For example, we have

written a software to communicate with remove computer and during communication

other computer goes off or communication path is broken. This unwanted situation causes

problem in normal program execution. Such situation is considered as Exception in

computer programming. The languages or compilers are supposed to report this situation

to programmer or program user. Hence an exception could be defined as

A notification or report to inform program user that something has occurred

stopping the normal program execution

Exceptions are either created automatically depending upon the program

execution status i.e. some resource is missing and your program reports it, or it

could be generated by programmer. A creation or occurrence of Exception is

referred as raising or throwing exception. There may be multiple reasons of

exceptions. Exception handling is a main feature of object oriented programming

paradigm. However, till now, we have not discussed object oriented programming

in this book, so it is tried to avoid to discuss object oriented concepts in discussing

exceptions.

When an exception is raised or thrown, it must be caught in program to preserve

normal program execution flow. C# provides an elegant way of catching

exceptions. The processing of creating and catching exceptions is called the

exception handling. C# provides special constructs to create or catch exceptions.

Real exception handling is done in CLR. It propagates the exceptions to the code

that handles them.

Page 337: Programming Fundamentals

Programming Fundamentals Using C# 336

As code is written inside methods, so exception generated is either caught inside

the method or it returns this exception to its calling method. If an exception is

returned to calling method, the process is called the exception delegation.

Exceptions are categorized based on their type. For example all exceptions all

exceptions which are related to communication could be called

“CommunicationExceptions”. There could be sub-categories of this first level

category and each sub-category may further have sub-sub categories. This

grouping gives a hierarchical arrangement to the exceptions. It is to note that code

handling the error handles a whole category, not a single exception. For example,

there may be multiple situations where division by zero can occur. All type of

division by zero are considered as one “DivisionByZero” exception.

Exceptions in Dot NET are objects, variables of user defined data types, used to

signal or report unanticipated events in the program. A variable of a particular user

defined data type is called object. From now onward, we will use the term object

for variable of that particular user defined data type. When some unwanted event

occurs, the executing method “throws” the exception by creating an object. This

object contains information about the type of error, place of error in code and

program state at the time of error. “Stack Trace” is special area of memory that

contains information about error occurred. Each exception also contains this stack

trace. Here is the program that causes an exception to occur.

using System; using System.IO; namespace CreatingException { class Program { static void Main(string[] args) { int a = 4; int b = 0; Console.Out.WriteLine(a / b); Console.Read(); } } }

The program compiles successfully as it has no syntax error. However when we try

to run the program, following error message will be shown.

Page 338: Programming Fundamentals

Programming Fundamentals Using C# 337

You can read the text “Unhandled Exception: System.DivideByZeroException:

Attempt to divide by zero”. Similarly, if we read both operands “a” and

“b” from user, user may enter zero for second operand value and result will again

generate same error message.

When an exception occurs in the program, its normal flow of execution is

interrupted and CLR tries to find any code that can handle it in user program. If no

such code is found an error message is displayed and your program is shutdown

abnormally by the operating system.

14.3. EXCEPTIONS HANDLING IN C# To understand the handling of exceptions in C#, we need to understand a

concept “Call Stack”. In chapter about Methods, we learnt that when a method

calls another method, it saves calling method local variables, passed parameters

and the address of instruction which will be executed after returning from called

method along with other information. This all information is saved in a memory

area called the stack (working of stack is already discussed in Methods chapter).

Let we call this information as “Method Context”. Dot NET programs (Console

Programs) start from Main(…) method. This method is considered as entry point

of your program. Let there is a method called Method1() which is called from

Main(). This Method1() calls another method Method2() and so on. When last

method returns, control goes back to second last called method and continuing

this pattern, control moves back to Main() method.

When a method is called, context of calling method is pushed on stack and when

it finishes, saved context is retrieved from stack and remaining execution of

calling method continues. Let if Main() calls Method1(), Method1() calls

Method2() and so on. Context of each method Main, Method1, Method2,… are

stored on stack. All these context collectively form the “Call Stack”. At any point

during execution, Call Stack contains the list of method which have been called

and not returned yet.

“Exception Handler” is the code that is executed when an exception occurs in

the program. handler in user program. The Exception Handling Mechanism

follows a reverse process. At the moment, an exception occurs, CLR tries to find

exception handler from the method that generated exception back to first calling

method. In our example of N Method calls , CLR will first look for exception

handler in MethodN(), if found ok otherwise it will try to find in MethodN-1() and

Page 339: Programming Fundamentals

Programming Fundamentals Using C# 338

so on till it reaches to Main() method using call stack. If no Exception handler is

found using call stack, CLR itself catches the exception and handles it, usually

displaying an error message as shown above.

TR Y-CATC H CON S TRUC T (SIN G LE CAT CH-BL OC K)

C# provides a special programming construct to handle exceptions. The code

which is expected to raise an exception is surrounded by the try-catch construct.

Here is the syntax of try-catch:

Try { // Code that is expected to raise an exception } catch(<ExceptionType> <object name>) { // exception handler: Code to handle exception }

There are two code blocks in try-catch construct: try block and catch block. First

block is used to encapsulate the code that is expected to generate exception

whereas second block is used to hold the code called “exception handler” to

handle the exception if one occurred. Following figure shows the flow diagram of

try-catch:

Page 340: Programming Fundamentals

Programming Fundamentals Using C# 339

Here is the program showing the use of try catch block:

L # TryCatch1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

using System; namespace TryCatch1 { class Program { static void Main(string[] args) { int a = 40,b=0; try { int c = a / b; Console.Out.WriteLine(c); } catch (DivideByZeroException ex) { Console.Out.WriteLine("Division by zero exception occurred"); } } } }

PRO GRA M DES CRI PTI O N : In this program two integer variables have been

declared. Second variable “b” is initialized with zero. Now on line 11, we try to

divide a number by zero. This is invalid operation and it raises

“DivideByZeroException”. If the code raising exception is not enclosed in try-block,

the exception raised by code is handled by the operating system which usually

terminates the program. If the code is enclosed in try block, control moves to

No

Exception Handler

try

Code Throws

exception?

Code Execution yes

Page 341: Programming Fundamentals

Programming Fundamentals Using C# 340

catch-block. Arrow in above code shows the flow of control. The catch-block is

exception handler. All statements in catch block are executed. Normally you write

the statements which handles the error in elegant way by showing appropriate

message and error recovery operations.

Multiple catch-blocks with single try block

User code may produce multiple exceptions of different type. If multiple

exceptions of same type are generated by code then single exception handler

(catch-block) is enough because each exception of same type is handled by single

catch-block. But if user code generates multiple exceptions of different types, then

for each type of instruction a separate catch-block (exception handler) is required.

Syntax for multiple try-multiple_catch block is shown below:

Try { // code that may generate exceptions } catch(<ExceptionType1> <objectName>) { //exception handler 1 code } catch(<ExceptionType2> <objectName>) { //exception handler 2 code } . . . catch(<ExceptionTypeN> <objectName>) { //exception handler N code }

As discussed above, the exceptions are grouped into different categories resulting

in a hierarchical structure as shown below:

Page 342: Programming Fundamentals

Programming Fundamentals Using C# 341

Let we name level three exceptions as “Child Class”, level 2 as “Parent Class” and

level 1 as “Grand Parent Class”. Each child category has parent category called the

super category. In other words we can say that each sub-category class has a super

category class. For example sub-category1 is child class of category1 and category1

is super class of sub-category1 and sub-category2. Let user code has generated

two exceptions of each child class i.e. sub-category1, subcategory2. A user need

to write exception handler (catch-block) for each type of exception resulting in two

catch blocks. Following skeleton code shows the concept.

Try { // code that may generate exceptions } Catch(Sub-Category1 obj1) { //exception handler 1 to handle Sub-Category1 type exception } catch (Sub-Category2 obj2) { //exception handler 2 to handle Sub-Category1 type exception }

Following example shows the use of multiple catch blocks:

using System; using System.IO; namespace MultipleCatchBlocks { class Program {

Level 1

Level 2

Level 3

Page 343: Programming Fundamentals

Programming Fundamentals Using C# 342

static void Main( string[] args) { // Exceptions could be thrown in the code below string filename="abc.txt"; try { TextReader reader = new StreamReader(fileName); string line = reader.ReadLine(); Console.WriteLine(line); reader.Close(); } catch (FileNotFoundException fnfe) { // Exception handler for FileNotFoundException // We just inform the user that there is no such file Console.WriteLine("The file '{0}' is not found." , fileName); } catch (IOException ioe) { // Exception handler for other input/output exceptions // We just print the stack trace on the console Console.WriteLine(ioe.StackTrace); } } } }

This is very specialized way of catching exceptions. C# also provides a generalized

way of catching exceptions. If catch-block catches an exception of type category1,

both type of exceptions will be dealt by same exception handler block. Following

skeleton code shows this generalized exception handling:

Try { // code that may generate exceptions } Catch(Category1 obj1) { //exception handler to handle all type of exceptions in category1 }

In the same way if your code generates exceptions of following types:

Category1

Category2

Sub-category1

Page 344: Programming Fundamentals

Programming Fundamentals Using C# 343

Sub-category2

Sub-category3

Sub-category4

An exception of type “Exception” is caught in catch-block will suffice for all above

exception types.

To summarize, if an exception of upper level is caught, all its lower level exceptions

are automatically dealt. However if your code may generate exceptions of type

sub-category1, sub-category2 and sub-category3, catching exception of type

“category1” will not be sufficient. You will need to handle “sub-category3” type

exception separately. In case of multiple catch-blocks, only that block will be

executed that will match the exception generated. Here is the code showing

general exception handling:

using System; using System.IO; namespace MultipleCatchBlocks { class Program { static void Main(string[] args) { // Specialized way of Exception Handling // Exceptions could be thrown in the code below string fileName = "abc.txt"; try { TextReader reader = new StreamReader(fileName); string line = reader.ReadLine(); Console.WriteLine(line); reader.Close(); Console.Read(); } catch (Exception generalException) { // Generalized Exception Handler Console.WriteLine("Some exception has occurred"); Console.Read(); } }}}

If you are mixing the superclass exceptions and sub-class exceptions in catch

blocks, be sure that superclass exceptions are written after sub-class exceptions.

Page 345: Programming Fundamentals

Programming Fundamentals Using C# 344

14.4. FINALLY-BLOCK C# provides a special keyword “finally” to mark a code block that will be executed in any

case. This “finally” keyword is used with try-catch control flow. It is to note that it has

nothing to do with error handling. As already stated that executable code is normally

written within method body and try-catch construct is also used in method body. Similarly

“finally” keyword is also used in method body. The syntax of writing finally block is as

under:

try { // code that may generate exceptions } catch(Category1 obj1) { //exception handler to handle exception of category1 } catch(Category2 obj2) { //exception handler to handle exception of category2 } . . . catch(CategoryN objN) { //exception handler to handle exception of categoryN } finally { }

A method can be completed or exited in following ways

Method execution has completed successfully

Return statement is used to transfer control flow out of method

An exception has occurred that transferred the control flow to catch-

block.

If “finally” block is used with try-catch in user program, in all three cases, this finally block

will be executed. Programmers normally use finally block for resource management like

file closing, objects destroying, memory management etc. Here are three self-explanatory

programs showing the use of finally-block.

using System; namespace MultipleCatchBlocks { class Program { static void Main(string[] args)

Page 346: Programming Fundamentals

Programming Fundamentals Using C# 345

{ // Specialized way of Exception Handling // Exceptions could be thrown in the code below string fileName = "abc.txt"; int a = 5; Console.Out.Write("Please enter some value:"); int b = int.Parse(Console.ReadLine()); try { int c = a / b; } catch (Exception e) { Console.Out.WriteLine("Exception occurred"); } finally { Console.Out.WriteLine("Finally block executed:"); Console.Read(); } } } } Output: (if no exception occurs) Please enter some value:9 Finally block executed:

Output: (if exception occurs) Please enter some value:0 Exception occurred Finally block executed:

In this program, finally block is executed whether error has occurred or not. Following

program shows the execution of finally-block with return statement. In order to finally-

block get executed, “return” statement must be written within try block. If it is written

outside try-block, finally will not get executed.

using System; namespace MultipleCatchBlocks { class Program { static void Main(string[] args) { string fileName = "abc.txt"; int a = 5; Console.Out.Write("Please enter some value:"); int b = int.Parse(Console.ReadLine()); try {

Page 347: Programming Fundamentals

Programming Fundamentals Using C# 346

return; int c = a / b; } catch (Exception e) { Console.Out.WriteLine("Exception occurred"); } finally { Console.Out.WriteLine("Finally block executed:"); Console.Read(); } } } } Output: Please enter some value:9 Finally block executed:

CATCH IN G EXC EPT IO N AT HI G HER L EV E L S

It is better idea to catch exception in the method where it occurs however C#

allows you to catch an exception generated in a method, in its calling method.

Following program shows the catching of an exception at different levels.

using System; namespace MultipleCatchBlocks { class Program { static void Main(string[] args) { int a = 5; Console.Out.Write("Please enter some value:"); int b = int.Parse(Console.ReadLine()); try { int c = Divide(a,b); } catch (Exception e) { Console.Out.WriteLine("Exception occurred"); Console.Read(); } } static int Divide(int x, int y) {

Page 348: Programming Fundamentals

Programming Fundamentals Using C# 347

return x / y; } } } Output: Please enter some value:0 Exception occurred

In this program, DivideByZeroException is generated in method “Divide”. The

method is called from main method. The method call in main method is enclosed

in try block. So any exception generated by called method is propagated to calling

method. If calling method has exception handler for generated exception, it is

handled there otherwise it is propagated to next higher level. If no exception

handler is found on any level, operating system catches the exception and

terminates the program.

Page 349: Programming Fundamentals

Programming Fundamentals Using C# 348

?

?: operator, 169

“If” statement, 161

“if-else” statement, 168

A

A ternary operator, 170

abstraction, 56

A C C E S S S P E C I F I E R S , 312

A D D R E S S , 269

A D D R E S S O F O P E R A T O R & , 275

algorithm, 58

A L G O R I T H M R E P R E S E N T A T I O N , 60

Application SOFTWARE, 10

A R I T H M E T I C O P E R A T O R S , 126

Array, 202

Array Bounds, 207

array elements, 206

Array initialization, 204

Arrays of Arrays, 218

Assignment operator, 136

associativity, 125

B

basic data types, 107

B I G E N D I A N , 282

B I N A R Y A D D I T I O N , 39

B I N A R Y C O U N T I N G , 38

Binary number system, 38

B I N A R Y T O D E C I M A L C O N V E R S I O N , 39

B I N A R Y T O H E X A -D E C I M A L C O N V E R S I O N , 44

B I T W I S E O P E R A T O R S , 133

B O O L E A N V A L U E T Y P E S , 107

boxing, 302

break, 185

BREAKPOINT, 339

bug, 334

Built-in Libraries, 26

C

casting, 142

C H A R A C T E R L I T E R A L S , 113

C L O S E D S O U R C E S O F T W A R E ., 24

C O D E E D I T O R , 80

command line compiler, 330

Comments, 119

Common Intermediate Language (CIL), 75

Common Language Infrastructure, 75

C O M M O N L A N G U A G E S P E C I F I C A T I O N S , 75

C O M M O N T Y P E S Y S T E M S , 75

Comparison operators, 132

Compilation Errors, 329

C O M P I L E R , 14

Compiler, 24

Compound Statement, 181

Computer hardware, 10

Computer Programming, 11

C O N C A T E N A T I O N O P E R A T O R , 135

C O N D I T I O N A L O P E R A T O R , 138

conditional operators, 157

conditional statements, 161

Console Application, 96

constant, 111

continue, 187

C O N T I N U O U S D A T A , 33

D

D A N G L I N G P O I N T E R S , 274

Data, 33

Quantitative Data. See

data types, 106

Debug Mode, 333

debugger, 67

Debugger, 25

decimal addition, 36

decimal number system, 34

D E C I M A L T O B I N A R Y C O N V E R S I O N , 39

D E C I M A L T O H E X A -D E C I M A L C O N V E R S I O N , 43

Declarative / Functional Programming, 22

D E C R E M E N T O P E R A T O R , 129

deployment, 66

dereference operator, 272

Designing an algorithm, 59

direction recursion, 265

D I S C R E T E D A T A , 33

D I S C R E T E V A L U E T Y P E S , 107

do – while, 189

D O T N ET R E D I S T R I B U T A B L E , 79

dynamic type checking., 105

Page 350: Programming Fundamentals

Programming Fundamentals Using C# 349

E

enumeration, 304

error, 327

E S C A P E S E Q U E N C E S , 113

Event driven programming, 105

Event Driven Programming, 23

Exception, 341

Exception Handler, 343

Executable Code, 28

Explicit Conversion, 142

expression, 144

F

Fifth generation languages (5GL), 21

finally, 350

First generation languages, 17

F I X E D S T A T E M E N T , 289

F I X E D V A R I A B L E S , 289

Flow Chart, 164

F L O W C H A R T S , 60

for loop, 192

foreach loop, 210

F O R M A L W A Y , 58

format, 147

Formatted Output, 146

Fourth generation languages (4GL), 20

framework, 68

G

Garbage collection, 287

generations of languages, 16

G L O B A L V A R I A B L E S , 240

G L O B A L -G L O B A L V A R I A B L E S , 242

H

Hexa-Decimal number system, 41

H E X A -D E C I M A L T O B I N A R Y C O N V E R S I O N , 43

H E X A -D E C I M A L T O D E C I M A L C O N V E R S I O N , 43

H E X A -D E C I M A L T O O C T A L C O N V E R S I O N , 44

H I G H L E V E L P R O G R A M M I N G L A N G U A G E S : , 14

I

Imperative/Procedural Programming:, 22

Implicit Conversion, 141

I N C R E M E N T O P E R A T O R , 128

I N D E N T A T I O N , 121

indirect recursion, 265

Indirect variables, 268

indirection, 277

informal way, 57

Information, 34

integer division, 127

I N T E G E R L I T E R A L S , 111

Integrated Development Environment, 28

integrated development environment (IDE);, 82

I N T E R M E D I A T E L A N G U A G E ( I L) , 77

Interpreter, 25

I S O P E R A T O R , 140

J

jagged array, 218

J A G G E D A R R A Y S , 293

J IT C O M P I L E R , 122

L

L E F T A S S O C I A T I V I T Y , 125

Linker, 27

literal, 111

L I T T L E E N D I A N , 282

L O C A L V A R I A B L E S , 236

L O C A L -G L O B A L V A R I A B L E S , 241

Logic Errors, 329

Logic Programming, 23

Logical operators, 130

loop, 180

L O W L E V E L L A N G U A G E S , 12

M

Managed Code, 79

M E M O R Y L E A K , 287

Menu bar, 93

M E T A D A T A , 75

method, 223

Method Context, 343

Method declaration, 225

Method Definition, 226

Method parameters, 231

M E T H O D S I G N A T U R E S , 226

Microsoft Dot NET Framework, 68

M O V A B L E V A R I A B L E , 289

Multidimensional Arrays, 211

N

Named arguments, 262

nested loop, 196

Page 351: Programming Fundamentals

Programming Fundamentals Using C# 350

Nested Structures, 320

nesting of statements, 170

new, 205, 286

N O N - A S S O C I A T I V I T Y , 125

N U L L -C O A L E S C I N G O P E R A T O R , 139

number system, 34

O

Object Code, 27

Object oriented programming, 22

O B J E C T V A L U E T Y P E S , 108

O C T A L C O U N T I N G , 40

Octal number system, 40

O C T A L T O D E C I M A L C O N V E R S I O N , 41

O C T A L T O H E X A - D E C I M A L C O N V E R S I O N , 44

O P E N S O U R C E S O F T W A R E , 24

operators, 124

optional parameters, 261

O U T , 252

Overloaded Methods, 245

P

params, 259

Pass by Reference, 251

Pass by Value, 250

platform, 68

pointer, 269

positional notation, 35

precedence, 125

Program, 56

programming languages, 11

Programming paradigms, 21

Project or Solution, 26

Properties, 95

P R O P E R T I E S O F A L G O R I T H M , 59

P S E U D O - C O D E , 60

Q

Quality Assurance, 65

Q U A N T I T A T I V E D A T A , 33

quick watch, 336

R

Read(), 118

ReadKey(), 153

ReadLine(), 119

R E A L D I V I S I O N , 128

R E A L L I T E R A L S , 112

R E A L V A L U E T Y P E S , 107

Rectangular Arrays, 211

Recursion, 263

R E F , 252

Reference type, 297

R E F E R E N C E T Y P E , 203

R E F E R E N C E T Y P E S B Y R E F E R E N C E , 300

R E F E R E N C E T Y P E S B Y V A L U E , 299

Release Mode, 333

return, 247

R I G H T A S S O C I A T I V I T Y , 125

Runtime Errors, 329

S

S C A L A R V A L U E P O I N T E R S , 294

Second generation languages (2GL), 18

Semantics, 23

Semantics Errors, 328

semi-formal way, 57

S H O R T C I R C U I T I N G , 160

simple statement, 181

sizeof(), 279

software design, 65

software engineering stages, 64

solution explorer, 99

Solution Explorer, 95

S O U R C E C O D E , 11

Source Code, 24

Source Code Editor, 24

S T A C K F R A M E , 287

S T A C K A L L O C , 292

Start Debugging, 332

S T A R T P A G E , 94

S T A T I , 288

static type checking, 105

Step Into, 335

Step Out, 338

Step Over, 338

S T R I N G L I T E R A L S , 114

strongly typed language, 104

structure, 311

switch-case statement, 175

Syntax, 23

Syntax Errors, 328

System Analysis, 64

system bugs, 66

S Y S T E M I M P L E M E N T A T I O N , 65

System SOFTWARE, 10

T

Text value types, 108

Page 352: Programming Fundamentals

Programming Fundamentals Using C# 351

T H E C O M M O N L A N G U A G E R U N T I M E , 76

Third generation languages, 19

Toolbar, 94

Toolbox, 95

try-catch, 344

Turing machine, 63

Type Error, 105

U

unboxing, 302

unsafe, 270

user defined data types, 303

using, 99

V

variable, 106

V A R I A B L E A S S I G N M E N T , 115

V A R I A B L E D E C L A R A T I O N , 115

V A R I A B L E D E F I N I T I O N , 115

V A R I A B L E I N I T I A L I Z A T I O N , 115

V A R I A B L E V I S I B I L I T Y , 236

V E C T O R V A L U E P O I N T E R S , 296

V I R T U A L E X E C U T I O N S Y S T E M , 76

Visual C# Project Types, 109

V O I D , 246

W

ways of writing instructions, 57

While Loop, 180

Write(…), 110

WriteLine(…), 111

Page 353: Programming Fundamentals

Programming Fundamentals Using C# 352

References

[1] Encyclopedia Britannica. http://www.Britannica.com

[2] Merriam Webster Dictionary. http://www.merriam-webster.com/dictionary/computer