0% found this document useful (0 votes)
5 views

Book1_IntroToProgramming_Handouts_with_Sept2023

The document outlines an introductory programming course focused on C#, emphasizing the importance of coding in modern society and its potential impact on job markets. It includes a list of recommended resources, tools, and a structured curriculum covering fundamental programming concepts and skills. The course aims to develop problem-solving abilities and foundational knowledge for further studies in software development or networking.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Book1_IntroToProgramming_Handouts_with_Sept2023

The document outlines an introductory programming course focused on C#, emphasizing the importance of coding in modern society and its potential impact on job markets. It includes a list of recommended resources, tools, and a structured curriculum covering fundamental programming concepts and skills. The course aims to develop problem-solving abilities and foundational knowledge for further studies in software development or networking.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

1

Sources I have referenced when writing up these notes


1. How to think like a programmer : Vickers
2. C# yellow Book : Rob Miles
3. Murach’s c# 2012
4. https://www.thecodingguys.net/tutorials/csharp/csharp-tutorial/
5. https://www.geeksforgeeks.org/c-sharp-namespaces/
6. https://rubygarage.org/blog/most-basic-git-commands-with-examples
7. Some helpful notes/feedback/comments from students over the years

Book Recommendations
1. All the above +
2. Visual c# 2017, An introduction to object-oriented programming, Joyce Farrell

Tools
1. Notepad++ (https://www.microsoft.com/en-us/p/notepad-
unofficial/9phsctzmkc27#activetab=pivot:overviewtab)
2. Visual Studio 2022 and other free tools for students
(https://azureforeducation.microsoft.com/devtools)
3. Free to all version of Visual Studio
(https://visualstudio.microsoft.com/vs/community/)
4. A really super learning website you should sign up to:
a. Codewars – here you will be presented with a number of coding challenges
(at different levels of difficulty – start at Kata 8) and gain honour as you
progress. Once we’ve covered some of the fundamental- you can go to war!
5. JDoodle
6. Git/GitHub

Cover : Cutting Corners (detail), acrylic on canvas Elizabeth Kinsella 2022

2
Contents

Chapter 1 :Introduction 3
Chapter 2 : What is a computer 5
Chapter 3 : Computer Programs 15
Chapter 4 : Programming languages and Introduction to C# 27
Chapter 5 : Variables & printing 39
Chapter 6 : Operators and precedence 48
Chapter 7 : User Input & Output 54
Chapter 8 : Selection 62
Chapter 9 : Loops 79
Chapter 10 : Nested Control 88
Chapter 11 : Methods 91
Chapter 12 Arrays 103
Chapter 13 : The Math Class & Miscellaneous 107

3
Chapter 1 : Introduction
Why do a course like this?

Code is the language of the modern world. Whether it’s the app that allows you chat to your
friends or the fridge that knows you are running low on milk.

Any smart device needs code instructions to tell it how to operate and communicate with
the outside world.

This modern language is so central to business life that we need to learn to code.

AI-powered robots and programs are on course to be so sophisticated that that as many as
400m to 800m jobs are predicted to be taken over by robots, these jobs will range from fruit
pickers, drivers to lawyers.

Also, we must remember, that coding is a lot more than just sitting at a desk tapping on a
keyboard it is about critical thinking and solving problems.

These are the skills than can open up a multitude of career paths and entrepreneur
opportunities.

And the money isn’t bad either, in the context of software development, programmers earn
a median salary of of €73,500. If you decide to work as a contractor, who works without the
security of a full-time job, you can expect to earn a lot more

https://www.bloomberg.com/news/articles/2017-11-29/robots-are-coming-for-jobs-
of-as-many-as-800-million-worldwidto be lost to the technology by 2030.”

https://www.cpl.com/ie/salary-guide/technology-salary

The course is intended mainly as your first programming course. It is an introductory


programming course which will provide a foundation for more advanced courses.
We will build on what we learn this semester in semester2. If you decide to go down the
software development or games route you will do more advanced modules in year 2, year 3
and year 4.
For those who are more interested in networking, a sound knowledge of programming will
be a great benefit and you will see some of the skills you learn here, directly and indirectly
coming in very useful in later modules you will do, such as scripting and software defined
networking.

4
• The objectcive of this course is to
1. Getting you thinking like a programmer – solve problems
2. Learn fundamental programming techniques
3. Learn how to develop small programs
4. Learn the the C# programming language
5. Learn about the software development process
6. Learn to use software development tools
7. Learn how to keep learning

• We will start with some paper base exercises

• We then use a simple text editor and a compiler

• Then we will use a very powerful programming tool called Visual Studio.

• We will also look at some online tools that allow us play around with code, for example
CodeWars, JDoodle

5
Chapter 2. What is a computer?
Definition - What does Computer mean?
A computer is a machine or device that performs processes, calculations and operations
based on a sequence of instructions provided in a program. These instructions may include
reading to memory, performing operations like decisions or mathematical calculations or
writing to memory.
Categories of Computer

• Micro Computer (Personal Computer)


o Desktop Computer
o Notebook, laptop, tablet
o PDA – Personal Digital Assistant, Smartphone, Game Console

• Mid Range Computer


o Since the 1990s, when the client–server model of computing became
predominant, computers of the comparable class are instead usually now
known as servers to recognize that they usually "serve" end users at their
"client" computers.

• Mainframe
o designed to handle very high volume input and output (I/O) and emphasize
throughput computing
o Mainframe computers are used in large institutions such as government,
banks and large corporations. They are measured in MIPS (million
instructions per second) and respond to up to 100s of millions of users at a
time.

• Super Computer (https://www.youtube.com/watch?v=HBpkSIJ9KwU)


o frontline of current processing capacity, particularly speed of calculation
o tasks involving intense numerical calculations such as weather forecasting,
fluid dynamics, nuclear simulations, theoretical astrophysics, and complex
scientific computations
o Titan reached a speed of 17.59 petaflops (quadrillion calculations per second

6
The Basic architecture of a computer
The Von Neumann architecture and components

Figure 1 Von - Neumann Architecture

Main components

• A Central processing unit (CPU)

• The processor is the brain of the computer system. It is the processor that follows
instructions and performs calculations

• Processors have different instruction sets with low-level simple instructions

o Has 2 components to execute program instructions --


▪ Arithmetic/Logic Unit performs arithmetic operations, and makes
logical operations.
▪ Control Unit controls the order in which your program instructions
are executed.

• Memory – stores programs and data


• Input/output devices

7
Figure 2 Input / Output devices

Memory
Data used by the computer is stored in the computer’s memory. To access a specific piece
of data, we use its address, which is a unique identifier for its memory location. Each
memory location consists of 8-memory cells. Each cell stores one bit, and thus, each
location stores 8 bits of information (one byte)

8
Figure 3 Memory Organisation

Bits and bytes


All information digitally, e.g. numbers, program instructions, text, audio, and video

Letters in the alphabet and other


Hi, Heather. characters have corresponding
ASCII codes e.g.
72 105 44 32 72 101 97 116 104 101 114 46
H has code of 72

Which is stored as 01001000


A binary digit (bit) is the smallest unit of data on a computer. A bit can store either a 0 or a
1, that is 2 possible states.

9
The more bits, the more combinations

4 bits = 24 16 combinations, that is 16 different values can be stored

Memory Types
o Primary memory is accessed directly by the CPU
o Secondary Memory is not directly accessible by the CPU. Programs and data
are stored long term here, for example hard disk drives can act as secondary
memory.

Bus
Computers Buses are the connections between and with the CPU, memory and I/O devices.
All buses consist of two parts - an address bus and a data bus. The address bus transfers the
address of where the data is to be read from or written to and the data bus transfers actual
data.

As we said above, the width of the address bus determines the size of the memory which
can be addressed
32 lines = 232 addressable memory locations = 4GB.

What will a 64 bit bus be able to access?

10
Figure 4 Buses

How does the CPU manage the execution of a set of instructions (program) :

Figure 5 Fetch Exceute Cycle

11
1. Fetch the instruction

• The CPU presents, on the address bus, the value stored in the Program Counter.
• This is the memory address of the next instruction that is to be executed.
• The CPU then fetches the instruction from main memory via the data bus, and it
is then placed into the current instruction register (CIR).
• The Program Counter is incremented to contain the address of the next
instruction.
2. Decode the instruction

• The instruction decoder interprets the instruction, i.e. determines is it to add, to


do subtraction, etc.
3. Data Fetch

• Instructions typically work on data, for example if we want to add two numbers,
these are our data
• Any required data is fetched from main memory to be processed and then placed
into data registers.
4. Execute the instruction

• The control unit (CU) passes the decoded information as a sequence of control
signals to the relevant function units of the CPU to perform the actions required
by the instruction such as reading values from registers, passing them to the ALU
to perform mathematical or logic functions on them, and writing the result back
to a register.
• If the ALU is involved, it sends a condition signal back to the CU.
5. Store results

• The result generated by the operation is stored in the main memory, or sent to
an output device.
• Based on the condition of any feedback from the ALU, Program Counter may be
updated to a different address from which the next instruction will be fetched.

12
The Computer Clock
Within a computer system there needs to be a timing system to decide how often
instructions are executed.
A CPU's clock speed represents how many cycles per second it can execute. Clock speed is
also referred to as clock rate, PC frequency and CPU frequency.
This is measured in megahertz which refers to millions of pulses per second and is
abbreviated as MHz and gigahertz, which refers to billions of pulses per second and is
abbreviated as GHz.
For example 1 MHZ is one million cycles every second. 8GHz is eight billion cycles every
second. Since the computer does one instruction per cycle in principle, the speed of a
computer depends on the number of Fetch/Execute Cycles it completes per second,.
So, clock speed is an indicator of performance and how rapidly a CPU can process data. A
higher frequency (bigger number) suggests better performance in common tasks.
A CPU with higher clock speed is generally better if all other factors are equal, but a mixture
of clock speed, how many instructions the CPU can process per cycle (also known as
instructions per clock cycle/clock, or IPC for short) and the number of cores the CPU has all
help determine overall performance.

Figure 6 Clock speeds are getting faster

13
Operating System
An operating system (OS), in its most general sense, is software that allows a user to run
other applications on a computing device. While it is possible for a software application to
interface directly with hardware, the vast majority of applications are written for an OS,
which allows them to take advantage of common libraries (bits of code) and not worry
about specific hardware details.
The operating system manages a computer's hardware resources, including:
Input devices such as a keyboard and mouse
Output devices such as display monitors, printers and scanners
Network devices such as modems, routers and network connections
Storage devices such as internal and external drives
The OS also provides services to facilitate the efficient execution and management of, and
memory allocations for, any additional installed software application programs and users

Figure 7 Operating System

E.g., Linux, Unix, Mac OS X, Android, Windows 10

14
File System

Figure 8 File System

You can manage the file system through the GUI of your operating system or you could
impress your friends by using some command line commands

• mkdir prog // creates a directory named prog


• cd prog // changes current directory to prog
• cd .. // changes current directory one level up
• dir // list the files of current directory
• del <filename> // delete the file
• Batch Files – here we can put together a bunch of regularly used commands into a file
Ref : http://www.computerhope.com/batch.htm

15
Chapter 3 : Computer Programs

• Programming is all about solving problems-


Example
▪ Calculate your take home pay
▪ Determine the grade that you got in an exam
▪ Calculate your CAO points
▪ Drive a car from Sligo to Dublin
▪ Can you think of some more?

• Programming consists of two steps:


Step 1 : Problem solving /Algorithmic design (the architects)
▪ You must know how to solve the problem before you write the program

▪ If you do not know how to calculate your take home pay, how can you
expect to be able to write a program to do it

▪ Throughout this course we are going to work on solving problems


presented to you in lab sheets, but in the commercial world you may be
presented with problem by a customer. Or you might spot a problem
yourself that needs a solution and become the next tech billionaire!

• So, a useful skill for programmers is to learn how to work with customers
– that is, be a good communicator, if you are good at this you will go far.
Also, generally you will have to work within a team – that is one reason

16
why the Personnel Development module is in this course! (its ABC – All
About Communictaion!)

Figure 9 Its All about communication

17
Watch out for solving the wrong Problem

• This is one of the most common reasons why software programs fail
• The programmers created a solution to the wrong problem
• Can you, think what are the reasons why this may happen?

Figure 10 Solve the right problem

18
Step 2 - Coding –

• Taking the solution and putting into a form that the computer can understand

• A computer program is a sequence of instructions which a computer can


understand and execute

The Essential Programming Process

Figure 11 The Essential Programming Process

This programming process is often referred to as the Software Development Lifecycle and is
illustrated in more detail below

Figure 12 The SDLC

19
In an ideal world this seems like a straightforward linear process, and there was a time when
programmers worked like this, It was called the waterfall model of software development.
Now we recognise that developing software solutions is quite a complex task and we need
to have a lot of toing and froing between the programmer and customer along the way.
Also, it might be best to break the problem into a number of smaller, more manageable
parts – this is referred to as Agile Software Development.

Figure 13 The Agile SDLC

I like this way of developing a lot because it tells us that it is ok to get a really small part of
the problem solved, get some feedback and go again. – remember this over the coming
months, just write a few lines, get it working, build up your confidence and then try some
more.

We will be concentrating on the building part of the SDLC this year, but all of the other steps
will be covered in detail over the next few years, we also look how the whole process can be
managed – wow you have a lot to look forward to!

20
Problem solving - “thinking like a programmer” (Ref Vickers)
Let’s talk a little about problem solving.
Ok, there are some people who seem have a really good natural problem solving
ability….but most of us need a little guidance in how to go about solving problems
effectively.

Some fun - Try these:


• Using six pencils, I want you to create four equilateral triangles.
o You can’t bend or cut the pencils

A Strategy for Problem solving


These are some steps that give can helps us find our way to a valuable solution. These can
be applied to any problem, not just problems that will lead to a programmed solution.
Repeat
1. Identify and understand the problem
2. Devise a plan to solve the problem
3. Carry out the plan: List the instructions that enable you to solve the
problem
4. Check the result and reflect upon it
Until Solution correct
5. Describe what you have learned from the process
6. Explain your results (document solution)

Let’s look at these steps in more detail:

21
1. Identify and understand the problem
• What are you been asked to do? What is required?
• What is unknown
• Write down what you do know
• Have you made any assumptions?
• What are the principal parts of the problem? Are there several parts?
2. Devising a plan
• Start thinking about the information you have and what the solution is required to
do.
• Have you solved it before? (Maybe with different values)
• Is this problem like one you have met before? Lot of the problems we will be
working on are everyday problems that you will have solved before, like
working out the total pay you are due after a weeks work.
• Divide & Conquer
• Most problems can be broken down into several sub problems. Are some of
these more easily solved than others?
• You need to cook a 3-course dinner party for your friends – preparing one
course at a time seems like a good idea.
• If it’s too hard – can you solve a simpler version – , think about the simplest version
of the problem and solve it and built on this?
• Given the problem to determine your pay, just see if you can do it without
considering overtime, etc..
• There are common elements to many solutions
– Provide Input
– Determine process necessary to turn given Input into desired Output
– Display Output
• Making a cake
• Ingredients are input
• The way you combine them is the processing
• What is baked is the output

22
Example :
• Given the number of hours worked and the hourly rate rate we need to calculate:
– The amount to be paid

Hours, hourly
rate Process Pay due

Figure 14 Input - Process- output

…planning continued..
• Does restating the problem help?
– Tell it in your own words
– Try describing the problem in a different language
• Diagrammatically
• Pictorially
• Using mathematics
• Build a physical model

23
3. Carrying out the plan
• Write down the basic sequence of actions necessary to solve the problem
• Software developers will call this an algorithm (finite set of steps for solving a
problem) – A chief will call it a recipe.
• Pay attention to things done
– In order (sequence)
– Conditionally (selection)
– Repeatedly (iteration)
Getting up in the morning
1. Get dressed;
2. Shower/wash face, brush teeth, etc; These steps seem a bit odd!
3. Switch off alarm;
4. Get out of bed;

Try this

A man, a wolf, a sheep and a cabbage need to get across a river. The man and one
other item can only fit in the boat and when the man is not around the wolf will eat
the sheep, the sheep will also do the same when alone with the poor little cabbage.

Devise a set of instructions to solve this problem

4. Assessing the result


• Examine the results obtained when using your solution
• Get someone else to use or follow your solution
5. Describing what you learned
– Reflect on the process
– Record you achievements .. and difficulties
– Don’t under estimated how important this step is
6. Document the solution
– Explain your solution
– If you look back at this solution in five years.. Will you/someone else
understand it

24
A language for solution description
In step 3, we talked about carrying out the plan, we may need to capture this somehow so
that we can follow it ourselves or we can pass it on to others, software developers will use
one or a combination of the following techniques/ tools:
• Pseudocode - Uses English-like phrases with some C# terms to outline the solution
• Flowcharts / Activity charts- Graphically depict the logical steps to implement a
solution and show how the steps relate to each other.
• Hierarchy charts/ Class Diagrams - Show how the different parts of a solution relate
to each other.
Pseudocode to Add 2 numbers
1. Read the first number and store in n1 (I/O)
2. Read the second number and store in n2(I/O)
3. Add contents of n1 and n2 and store the result in sum
(PROCESS)
4. Print sum (I/O

Try this

A solution is required to determine how many times a car must be filled to


completed a journey. The inputs are the fuel tank capacity in liters, the fuel
consumption in KM/L and the distance of the journey in KM.
The algorithm should also determine how many miles the car can travel on
10gallons of fuel

25
Top tip - Test Driven Development
In recent years there has been a move by programmers to think about the test they will use
to check their solution before they derive a solution.
This is called Test Driven Development (TDD). It ensures that you will test your solution, it
will also help clarify the problem for you (e.g. if I was to make a chair, and I know that a
250kg person may sit on that chair, I might put a few extra screws in!!)
Test Data for the above exercise
• Capacity = 60 litres
• Consumption = 14 m/l
• Distance = 2000 miles
Expected Results
• Fills = 3
• Miles = 395

Solution
Read capacity;
Read fuel consumption;
Read distance;
Cars range = capacity * consumption;
Fills = distance / range;
Round fills to the next whole number;
Miles per litre = consumption / 1.609344;
Miles per gallon = miles per litre / 0.2199;
Miles for 10 gallons = miles per gallon * 10;
Write Fills
Write Miles for 10 gallons

Try This
• A student sits three tests, determine and report the grade they got in each test, <40
is an F, 40-59 is a C and 60-100 is an A
• Devise test cases
• Write an algorithm documenting the solution to this problem

26
FlowCharts / Activity Diagrams
A flowchart is a type of diagram that represents a workflow or process. A flowchart can also
be defined as a diagrammatic representation of an algorithm, a step-by-step approach to
solving a task.
The flowchart shows the steps as boxes of various kinds, and their order by connecting the
boxes with arrows. This diagrammatic representation illustrates a solution model to a given
problem. Flowcharts are used in analyzing, designing, documenting or managing a process
or program in various fields

27
Figure 15 Sample Flowchart

Try these
• Draw a flow chart for getting up in the morning and coming to college
• Draw a flow chart for fuel consumption problem
• Draw a flowchart depicting the solution to the student grade problem

28
Hierarchy Chart
A Hierarchy Chart (hierarchical diagram) shows the breakdown of a system to its lowest
manageable parts. It is a top-down modular design tool, constructed of rectangles (that
represents the different modules (groups of instructions) in a system/solution) and lines
that connect them. The lines explain the connection and/or ownership between the
different modules among the system.
Shows how a problem may be broken up into fundamental building blocks that are simple
enough not to require further detail.
Helps illustrates our divide and conquer strategy.

Figure 16 Hierarchy Chart

29
Chapter 4 - Programming languages and Introduction to C#

• We can’t just use English to tell a computer what to do


– Computers aren’t clever enough to understand it.
– English is much too vague, it can be interpredated in too many ways
• Instead we have to use special, unambiguous, languages which can be converted
into computer instructions
• There are hundreds of different programming languages
– each has its own fans and critics
– can you name some?
• They all do the same job though... that is
– provide a way to tell a computer what to do
• Which programming language you use can be as personal (or company choice) as the
choice of bicycle /computer/phone that you use. All bicycles/computers/phones do
the same thing (nearly!), but people can have their own preferences. The same thing
happens with programming languages. Over your career you will have to learn
several languages, each language has features that make it good in particular
situations, just like some bikes are good for racing, others for mountain biking (check
out Sligo -Coolaney MB trail!).
• I currently use C# – but I ve used lots of other languages over the years (First was
COBOL, (the latin of code, and its still thriving!)). Others have been Pascal, Java,
Visual Basic and Python – I am sure there were more.
• Inevitably, todays hot coding topics will be replaced by something new. The
important skill is to learn how to keep learning. For example, AI is going to have a big
impact on Coding in the next few years – How do you think this will impact you?
• Once you get good at one language, it is generally straight forward (hopefully!) to
pick up a new one.
Common elements of a programming language
• Key words/Reserved Words - Some items in a program are keywords which are part
of the C# language design
• Programmer-Defined Names / identifiers - These are the words or names that are
defined by the programmer. They are used to identify storage locations in memory
and parts of the program that are created by the programmer
• Operators - tell the compiler to generate code that performs an action:

30
• Punctuation These serve specific purposes, such as marking the beginning or ending,
or separating items in a list
• Syntax The syntax rules of a language define how we can put symbols, reserved
words, and identifiers together to make a valid program
• The semantics of a program statement define what that statement means (its
purpose or role in a program)
• A program that is syntactically correct is not necessarily logically (semantically)
correct
• A program will always do what we tell it to do, not what we meant to tell it to do
C#
C# (pronounced C sharp) is a general-purpose, multi-paradigm programming language
encompassing strong typing, lexically scoped, imperative, declarative, functional, generic,
object-oriented (class-based), and component-oriented programming disciplines – phew!.
It was developed around 2000 by Microsoft within its .NET initiative and later approved as a
standard by ECMA (ECMA-334) and ISO (ISO/IEC 23270:2018). C# is one of the programming
languages designed for the Common Language Infrastructure.
At time of writing, the most recent version is C# 10.0, which was released in 2022 alongside
.Net 6.0. – but like everything in tech….a newer version comes along very regularly – this
can bring benefits but sometimes it be a bit annoying having to update your system
…..but…this is something you will just have to get used to – you are on a journey of life long
learning!.
Getting Started with C#
A few important points to keep in mind about C#:

• The language is case-sensitive (So A and a are different)

• Lines terminate with semi-colons ;

• Code is put in code blocks { }

• Comments are lines in our code which are not executed but put in to explain our
solution:
o Inline comments start with // - these are on one line.
o Block comments start with /* */ these are comments that run over a number
of lines

• XML comments start with /// these are comments that we can extract from our
programs

31
Writing a C# program
When we write a program, we need an editor and a compiler. We can use a standalone
editor and compiler or we can used and integrated development environment (IDE) such as
Visual Studio.
We can write the program in plain text format and save with a .cs extension. This is our
source code. The machine will not understand it, so we need to compile the program to
turn into what is called bytecode. The bytecode is store in a.exe file.
Bytecode is a highly optimised set of instructions designed to be executed by a CLR,
common language runtime. A CLR interprets the bytecode and runs it on a machine.

Figure 7 Compiling and running c# program

Common Language Runtime (CLR)


The CLR is just another program. The CLR allows the same .cs files to run on any machine.

• Windows pc
• Mobile phones
• Linux pc
• etc

32
Steps to Writing Programs
1. Develop an algorithm (using our problem solving skills)
2. Write a software implementation of the algorithm
Repeat
3. Compile it
4. Fix any compilation errors
5. Test it – does it give the expected results
6. Fix any errors
Until done

Our First Simple c# program

This is the name of the class. The job


this class does is print “Hello World”!

// my first program
class HelloWorld
{
static void Main(String args[])
{
System.Console.WriteLine("Hello World");
}
}

Create the source file with a text editor, say Notepad++ and save as HelloWorld.cs on to
your h: drive

Compile the source into bytecode


H:>cs HelloWorld.cs

Have a look on your h: drive, there will be a new file, which we can exrecute

H:>HelloWorld.exe

33
The same program with the introduction of a library reference (things our program will
make use of, very important strategy for writing programs) and some comments.

Multi line comment

• A class is a container which can holds data and methods.


• A method is a block of code with a name.
• The body of a method is a block of statements that are obeyed when the method
runs.
• The statements are enclosed in { and }
• Main() is the one special method the CLR looks for and provides an entry point to
your program.
• The keyword static allows Main() to be called directly from outside the class by the
CLR
• The keyword void tells us that the Main method does NOT return a value.
• Note that in the most recent edition of VS2022, the main method can be excluded

34
Good Programming Practice

From the very beginning it is a smart idea to follow good programming practices when
writing a program, these will lead to programs that are easier for you to read, easier for me
to read and easier for classmates to read and give you a hand. A program that is easier to
read is a program that will be easier to find problems in and easier to maintain (over the
lifetime of a program up to 70% of all money spent on the program can got to maintenance
work)

Top tips

• Use comments to explain why you do something when necessary.


• Use blank lines – don’t try to squash your code into the smallest space possible
• Have a clean and consistent layout
o Use the same format for common constructions, if..while..for etc
• Use indentation to highlight related blocks of code
• Use good names for items in your program, the name should reflect the meaning of
the item. This helps reduce the number of comments you need and makes your
code easier for yourself and others to undertand., myPay is better than x
• Use naming conventions to identify different categories of items in your program,
we ‘ll look at some of these later
• Well managed
o It should be clear who wrote the code and the reasons for any changes.

Get into good habits from the beginning!

Keywords/ reserved words


C# contains reserved words, that have special meaning for the compiler. These reserved
words are called "keywords". Keywords cannot be used as a name for programmer defined
items in our program.
• Keywords are used in a particular way to allow the compiler to make sense of your
program
• Keywords are in blue (if using a language sensitive editor!)

35
Keywords in C# are distributed under the following categories. We will come across a good
few of them this semester, but it may be a few years before you have used come across
them all. Let’s have a quick overview of them.
1. Reference Type Keywords: There are 6 keywords in reference types which are used
to store references of the data or objects. The keywords in this category are: class,
delegate, interface, object, string, void.

2. Value Type Keywords: There are 15 keywords in value types which are used to
define various data types.
Bool Byte char Decimal
Double Enum float Int
Long Sbyte short Struct
Unit Ulong ushort

3. Modifiers Keywords: There are 17 keywords in modifiers which are used to modify
the declarations of type member.

Public Private internal protected Abstract


Const Event extern new Override
Partial Readonly sealed static Unsafe
Virtual Volatile

4. Statements Keywords: There are total 18 keywords which are used in program
instructions.

If Else switch do For


Foreach In while break Continue
Goto Return throw try Catch
Finally Checked unchecked

5. Method Parameters Keywords: There are total 4 keywords which are used to
change the behavior of the parameters that passed to a method. The keyword
includes in this category are: params, in, ref, out.
6. Namespace Keywords: There are total 3 keywords in this category which are used in
namespaces. The keywords are: namespace, using, extern.

36
Namespaces are used to organize the classes. It helps to control the scope of
methods and classes in larger programming projects. In simpler words you can say
that it provides a way to keep one set of names (like class names) different from
other sets of names. The biggest advantage of using namespace is that the class
names which are declared in one namespace will not clash with the same class
names declared in another namespace.

7. Operator Keywords: There are total 8 keywords which are used for different
purposes like creating objects, getting a size of object etc. The keywords are: as, is,
new, sizeof, typeof, true, false, stackalloc.

8. Conversion Keywords: There are 3 keywords which are used in type conversions.
The keywords are: explicit, implicit, operator.

9. Access Keywords: There are 2 keywords which are used in accessing and referencing
the class or instance of the class. The keywords are base, this.

10. Literal Keywords: There are 2 keywords which are used as literal or constant. The
keywords are null, default.

37
Dealing with errors – yes errors will happen!
As we mentioned before, it is very rarely that we go from problem to working program to
celebration in a single go. We can hit lots of problems in our code along the way. The types
of errors we encounter can be:

1. Syntax – language errors in our code.


2. Logical – mistakes in the way we solve the problem.
3. Runtime - things that go wrong when the code is running – these can be caused
by logical errors or failure to deal with things that might go wrong.

Syntax errors
A syntax error occurs when the source code contains something that is not valid c# code

Classic syntax errors to try an avoid – watch out – you make these

1. Not having a Main method(), pre 2022!


2. Missing a ; at the end of a statement
3. Mismatched brackets {} [] () ………………aaah!
4. Using a keyword as a variable name.. e.g. can’t use while as as variable name
5. Using an invalid identifier (name for something), e.g my salary , spaces are not
allowed
6. Using storage before you’ve asked for it, that is, not declaring a variable,
7. Not take account of c# case sensitivity, mySalary and MySalary are different thing
8. Misspelling keywords... e.g. whle instead of while
9. Misspelling variable name after they have been declared

Logical Errors
The program compiles but does not give the expected answer. We find these when we test
our program.

1. When we start to program, syntax errors tend to break our hearts, but once we ‘ve
mastered the syntax, we quickly realise that logical errors are the real heart
breakers.
2. Sometime this can be something simple like using the wrong operator.
3. It could be that we solved the wrong problem
4. There are great debugging tools available that help us find out where in our code
things might be going wrong -we’ll use these through the course
5. Generally, if we spend enough time planning our solution, we can minimise logical
errors.

38
Run-time errors
Here, the program, compiles but crashes when executing.

Examples
• Your program asks a user to enter a number, but they enter text.
• Your program references a memory location that does not exist.
• Your program tries to read from a source that does not exist, e.g. your program tries
to look up a contacts list on your hard drive but it isn’t there.

You can include code in your program to try and prevent some of these things happening
(data validation) and/or you can put special code into your program that well catch these
errors if they happen and try and deal with them in some way (this is called exception
handling).

We will explore these techniques in detail in semester 2.

39
Chapter 4 : Variables and Printing
Most programs contain data and instructions that make use of this data. Variables are
where we store this data.
• A variable is a place you can store values in the computers memory.
• You can think of it as a box with a name.
• A variable has three features, name, type and value.
• You choose the name (identifier) for your variables:
– It is used to identify your variable
– Can only contain letters, digits and the underscore (_) character
– Must start with a letter or underscore (_)
– The case is significant – remember C# is case sensitive
• Fred is a different identifier from fred
– Illegal identifiers
• My Name
• 1stPlace
• ac/dc
• class
– The identifier should reflect what the variable is being used for – correct
naming of variables makes our life easier later on e.g.
studentAge highScore taxRate are clear.
• By convention, we will use camelCase – if we all adopt the same style, it makes code
sharing a lot easier.

• The type of the variable determines what you can put in it – whole number, real
number, text etc
• value is the contents of the variable
• The value that we assign (put into) a variable must be compatible with its type. This
is a big deal in C#, more later.

40
C# data Types

Storing Integers
• Integers are whole numbers.
• Integer values are held exactly:
– i.e., the pattern of bits held in computer memory exactly matches the integer
value it is supposed to represent
• Remember, the more bits that are used to hold an integer value, the greater the
range

C# Integer Types

Figure 18 Integer Data types

41
Using Real Numbers
• Real numbers are used when you need a fractional part
– Working out averages
– Any kind of real-world calculations
• C# provides a range of real number types which have different range and precision
• You choose the one that fits the problem

Range and Precision


• Floating point values are held in C# to a particular range and precision
– Range: the biggest and smallest numbers it can store
– Precision: the number of digits of accuracy available
• Each type has a particular range and precision

Type Size Range


Float 32 ±1.5×10−45 to ±3.4×1038
7 digits of precision
Double 64 ±5.0×10−324 to ±1.7×10308
15 digits of precision
Decimal 128 ±1.0×10−28 to ±7.9×1028
28 digits of precision

Strings
• You can use a string everywhere you need to store some text:
– Names – “Bob Marley”
– Addresses – “Jamaica”
– The title of a song “One Love”
• Strings can get very long.
• They also provide a bunch of useful built-in functions that allow us to manipulate
strings, for example find the length of a string, convert its case, etc. We touch on
some this semester and look at in some more detail next semester.
• There is only one string type.
• String storage is managed automatically by the C# runtime system
– A storage area of the right size is created for each string that is stored

42
• You do not need to worry about reserving memory for strings or releasing it when
you have finished.
Char
• You use a char type if you want to store a single character.
• It can be a letter, digit, punctuation character, control character or space.
• This character will be held as a single value using the UNICODE standard.
• Computers store everything as patterns of bits.
• For a computer to store text we have to map these patterns to particular characters.
• C# uses the UNICODE standard to perform this mapping.
• UNICODE is a standard for characters.
• Each character is stored in a 16-bit value.
• This allows for over 64,000 characters.
• You may have heard of an 8-bit code called ASCII
• The ASCII character set is mapped onto the first 128 values of UNICODE.
• A character literal value is written in the program enclosed in single quotes.
• This is how the compiler can tell which character is to be used.
• Upper- and lower-case characters are different.

The bool type


• Some things that are to be stored are not values as such, but instead are states
– “is a member of the club”
– “input is valid”
– “network OK”
• C# provides a bool type which is used to hold the states true or false
• The bool type can only hold two possible values
– true or false
• These could be held by a single bit in the computer memory
– This is not usually how it is done however, as such a value would be hard to
address
Declaring and assigning a value to a Boolean variable

43
Declaring a variable
We must declare (make it) before we can use it. To declare a variable in c#, use the
following:

<type> <identifier> = <value>;

Or
<type> <identifier>;
<identifier> = <value>;

Or
<type> <identifier1>,<identifier2>,<identifier3>;

Examples declarations

int num1 = 8;

int myAge;

int myAge = 34;

int num2, num3, num4;

int num5 = 9, num6 = 5, num7 =0;

double num8 = 45.78;

string myName = "Bob Marley";

char myFirstInitial = 'B';

bool lotteryWin = false;

44
Example program to declare 3 variables and assign values, then output their values.

class Program
{
static void Main(string[] args)
{
// declare variable and assign values
int number1 = 6;
int number2 = 8;

double number3 = 78.6;

// print contents of a variable to the screen


Console.WriteLine("The value of number 1 is : " + number1);
Console.WriteLine("The value of number 2 is : " + number2);
Console.WriteLine("The value of number 3 is : " + number3);

}
}

Scope of Variables in C#
The part of the program where a particular variable is accessible is termed as the Scope of
that variable.
A variable can be defined in a class, method, loop etc.

So C# scope rules of variables can be divided into three categories as follows:

• Block Level Scope – the variable can’t be accessed outside the brackets of the code
block in which it is defined {}. Trying to do this will give you a syntax error.
• Method Level Scope – the variable can only be accessed within the method.
• Class Level Scope -– the variable can only be accessed within the class.
• Initially we will work at method level
Assignment

• How to give/assign a value to variable.


• The value on the right is stored in the variable on the left.
• You can only assign a value to a variable that is consistent with the variable's
declared type.
• You can declare and assign initial value to a variable at the same time, e.g.,
int number2 = 8;
• The value that was in number2 is overwritten.

45
Introduction to Printing
Fundamental to most programs is the need to obtain input from the user of the program
and output our results.

• The Console object is part of the runtime environment for a C# program


• It provides methods to communicate with the user (by letting the program read and
write things to the console).
The important output methods are:

Console.WriteLine();//Write text to screen and goto next line

Console.Write();//Write text to screen, stay on current line

Using Concatenation
• If we want to merge text and values we have to use the + operator to concatenate
the strings
• This can make the write statements look quite complicated
using System;
class Program
{
static void Main(String args[])
{

int myAge = 39;

string myName = "Bob Marley";

string myCountry = "Jamaica";

Console.WriteLine("My name is " + myName + "my age is " + myAge);

Console.WriteLine("I am from " + myCountry);


}
}

or
C# string interpolation allows us to insert variables into the string. It uses simple syntax and
looks like a template. An interpolated string returns a string as a result.
A typical structure of interpolated string is given below.

Syntax
$"<text> {<interpolated-expression> [,<field-width>] [<:format-string>] } <text> ..."

46
Console.WriteLine($"My name is {myName} and my age is {myAge}");

Console.WriteLine($"I am from {myCountry}");

47
Special Characters
• Some characters are not printed on the screen, but instead have a control behaviour
– Carriage return
– Take a new line
– Sound an alert
– Tab
• C# uses escape sequences to allow a program to use these codes
• The escape sequence is the backslash (\) character followed by a letter that identifies
the required control character
• Letter n means “newline”
Console.WriteLine("Hello\nWorld");

will print
Hello
World

Escape Sequence Values

Ignoring escape characters


• If you don’t want to use escape sequences in your string literal you can put an @ in
front of it
• This means that the string is used verbatim - WYSIWYG
Console.WriteLine(@"c:\network");

48
Chapter 6: Operators and precedence

A program that does some simple arithmetic.

class WindowCalculations
{
// program to calculate the perimeter and area of a window
// with a width of 2 meters and a height of 4 meters(Ref RMiles
static void Main(string[] args)
{
//declare variables
double width, height, woodLength, glassArea;

// assign values to two of the variables


width = 2;
height = 4;

// calculate the perimeter of the window


woodLength = 2 * (width + height);
// calculate the are of the window
glassArea = 2 * (width * height);

// print out the results

Console.WriteLine($"Length = {woodLength} meters");


Console.WriteLine($"Area = {glassArea} sq meters");

Arithmetic Operators

• Operators
o +-* /
o % (modulus remainder after division)
• Example
o 11 + 5 ➔ 16
o 11 / 2 ➔ 5.5
o 11 % 2 ➔ 1
o % 2.2 ➔ 0.6

49
static void Main(string[] args)
{
int n1, n2, result;
n1 = 8;
n2 = 5;

result = n1 + n2;
Console.WriteLine($"{n1} + {n2} = {result }");

result = n1 * n2;
Console.WriteLine($"{n1} * {n2} = {result}");

result = n1 / n2;
Console.WriteLine($"{n1} / {n2} = {result}");

result = n1 % n2;
Console.WriteLine($"{n1} / {n2} = {result}");

A note on Modulus

• This operator calculates the remainder after a division operation has taken place.

50 % 5 give a remainder of 0
48 % 5 gives a remainder of 3

• It can be very useful, for example


• Helps in deciding if a number is odd or even

• Helps in deciding if a year is a leap year

50
Note on Assignment

• The right and left hand sides of an assignment statement can contain the same
variable

Exercise.. fill in the blanks

Action required statement Value of x after statement executed

Assign 0 to X
Add 4 to x
Subtract 3 from x
Multiplies x by 10
Divides x by 2
Assign the remainder of x
divided by 4 to x

51
Operator Precedence

• Mathematical expressions are evaluated left to right. When two operators share an
operand, the operator with the highest precedence works first.

• Consider int average = 12 + 6 + 3 / 3;

• What value will be stored in average?

average= 1

• is this what you want? You can fix this using brackets.

Precedence rules for Arithmetic Operators

1. ( ) parentheses
2. - (unary negation)
3. *, / , %
4. + –
5. If equal precedence, left to right

You can consider assignment as another operator, with a lower precedence than the
arithmetic operators

Figure 9 Operator Precedence

Exercise….Consider

Expression Value in result


double result = 18 / 6 + 2;
double result = 18 / 6 % 2;
double result = 15 + 3 /3;
double result = 5 - 3 * 5;
double result = 5 % 2;
int result = 13 / 6;
double result = 13 / 6;

52
Operator Shorthand
• There are certain things that programs do a lot
– For example adding one to a variable to increment it
• C# provides “shorthand” ways to write these statements
• The ++ operator adds 1 to the contents of a variable
• There is also a – operator which will reduce a variable by 1
• Note that this is a “monadic” operator

– myScore++; // adds 1 to myScore


– myScore = myScore + 1; // adds 1 to myScore

• Quite often we also want to add one value to another


• The C# language provides a quick way to do this as well
• The += operator adds a value to a variable
– myScore += 5; // adds 5 to myScore

• There are -=, *= and /= operators too
• Shorthand is good because it makes your program smaller
• It can also make it execute more quickly as the compiler might be able to generate
machine code that better matches the action to be performed
– Many processors have an “increment memory” instruction
• These make the program shorter, but I reckon they are a bit harder to understand
▪ I am not sure it’s a great idea to use shorthand, particularly when you
are starting out.
▪ This is because I think it is more important to place more emphasis on
making sure the code is easy to understand than I do about anything
else.

53
Avoiding Magic Numbers

myTax = grossPay * 0.40;

• The value .40 is a magic number, - we don’t know what it represents


• It actually means “the rate of tax you pay”
• But this is not very clear to a reader
• It would be a lot more readable with:

myTax = grossPay * TaxRate;

• We can create a variable which contains the tax rate

• If we use this it makes the code much clearer

• By adding const in front of the declaration we can make a variable that is constant

• This stops other programmers from changing the value and making the program
misbehave

• Not only do constants (magic number variables) make the program clearer, but they
also make it simpler to maintain

• If the customer wants us to change the tax rate it is now very easy to do this, just by
changing the magic number declaration

• by convention we have used CAPITALS when naming a constant, for some, this is
now out a little of favour and PascalCase is used, I still use capitals

Declaring constants

const double TAX_RATE =.40;

54
Chapter 7 - User Input & Output

We need to be able to get the value of a variable from the user of the program. Initially we
look at getting input from the keyboard. Later in the course will look at how we can get
data from other sources, for example from a file on your hard drive.

• The important method is:

Console.ReadLine(); // read a string value from the screen

To read in a piece of text and store in the variable myName

Console.WriteLine("Hello");

// prompt user for input, I like to use Write rather


// than WriteLine
Console.Write("Please enter your name : ");

string myName = Console.ReadLine();

55
Data Conversion

• C# is strongly typed. This does not mean we need to hit the keyboard hard, it means,
if data types are not compatible, the compiler will not automatically convert from
one type into a variable of an incompatible type,

• The compiler uses type information to make sure that all operations that are
performed in your code are type safe. For example, if you declare a variable of type
int, the compiler allows you to use the variable in addition and subtraction
operations. If you try to perform those same operations on a variable of type string,
the compiler generates an error, as shown in the following example:
• For example :

int x = "2" + 8; //will raise a type error

• In weakly (loosely) typed languages: data will be automatically converted from one
type to another: for example JavaScript won’ t raise an error in this case, it will give
a result of '28' which is obviously not what we want.

• When data is read from the user with Console.ReadLine(), it is entered as a


string, therefore if we want to do an arithmetic operation on that data, we must
convert the value to a numeric type.
• We can do this by using Parse methods, for example int.Parse converts a string
to an integer

Console.Write("Please enter your salary : ");

string userInput = Console.ReadLine();

int mySalary = int.Parse(userInput);

• We can do the same thing in two steps

Console.Write("Please enter your salary : ");

int mySalary = int.Parse(Console.ReadLine());

• If we wanted to store the inputted value in a variable of type double, use


double.Parsee.g.

double myBankBalance = double.Parse(Console.ReadLine());

56
Neater Printing
The format in which the output of a program is presented is very important, we want it to
be informative and readable, therefore we need to look at some techniques which allow us
controlling print behaviour.
Recall : A typical structure of interpolated string is given below.
Syntax
$"<text> {<interpolated-expression> [,<field-width>] [<:format-string>] } <text> ..."

• Additional formatting information added to them


double x = 1234.56789;
Console.WriteLine($“x = {x:000000.00}");

• This would output the value of x with 6 digits and two decimal places:
x: 001234.57

• in this case the display process will automatically round up

Suppressing Leading Zeroes


• If you use # rather than 0 this prints a space if the digit is a leading zero
double x = 1234.56789;

Console.WriteLine($“x = {x:#####0.00}");

• Note that we need at least one zero so that the value 0 is printed correctly:
x: 1234.57

Adding other Formatting


• By putting extra characters in the format string we can add commas for thousands
double x = 1234.56789;
Console.WriteLine($”x = {x:###,##0.00}");

• If the leading digits are spaces the extra characters are not printed:
x = 1,234.57

57
Setting the Print Width
• You can add a width value which will cause the output to be right justified that width
double x = 1234.56789;
Console.WriteLine($"x = {x,15:###,##0.00}");

• In the example the width is 15 characters:


x= 1,234.57

Left Justifying the Output


• If you give the width as a negative value the number is left justified
double x = 1234.56789;
Console.WriteLine( $"x = {x,-15:###,##0.00}End");
In the example the width is 15 characters:
x= 1,234.57 End

Outputting a Table
• We would like to output a table in which the columns have a fixed width.
• Say, we wanted to print out a list of people’s names and their phone numbers
• We might want to align names to the left of the column of width 10 and numbers to
the left of a column of width 15.
• To achieve this format we use the specification {0, -10} to left-align names in a field
of width 10, and {1, -15} to left-align numbers in a field of width 15.

class Program
{
static void Main(string[] args)
{
Console.WriteLine($"{"Name",-10}{"Phone Number",-15}");
Console.WriteLine($"{"Sheila",-10}{0712345,-15}");
Console.WriteLine($"{"Frances",-10}{087241,-15}");
Console.WriteLine($"{"Michael",-10}{0834141,-15}");

}
}

58
Formatting Codes
These codes allow us to format our output more

Code Format Description

C or c Currency Formats the number as currency with the specified number


of decimal places

P or p Percent Formats the number as a percent with the specified number


of decimal places

N or n Number Formats the number with thousands separators and the


specified number of decimal places

F or f Float Formats the number as a decimal with the specified number


of decimal places

D or d Digits Formats an integer with the specified number of integer

E or e Exponential Formats the number in scientific notation with the specified


number of decimal places

G or g General Formats the number as a decimal or in scientific notation


depending on which is more compact

59
class Program
{
static void Main(string[] args)
{

static void Main(string[] args)


{
// demo of formatting codes

double x = 1234.56789;
int i = 5;

Console.OutputEncoding = System.Text.Encoding.UTF8;

Console.WriteLine("Currency Format");
Console.WriteLine($"x = {x:c} ");

Console.WriteLine();

Console.WriteLine("Percentage Format");
Console.WriteLine($"x: = {x/10000:p}");

Console.WriteLine();

Console.WriteLine("Number Format, Note you can specify the number of


decimal places");
Console.WriteLine($"x = {x:N2}");

Console.WriteLine();

Console.WriteLine("Float format");
Console.WriteLine($"x = {x:f2}");

Console.WriteLine();

Console.WriteLine("Digits format for Integers only -- also left


justified");
Console.WriteLine($"i = {i,-12:d2}End");

Console.WriteLine();

Console.WriteLine("Exponent Format");
Console.WriteLine($"X = {x:E}");

Console.WriteLine();
Console.WriteLine("General Format");
Console.WriteLine($"X = {x:G}");

}
}
}

60
Output

61
Chapter 8 Selection

Introduction

• There are basically three types of program flow


o Straight line (sequence):
▪ Perform one statement after another
o Decision (selection):
▪ Choose a statement based on a given condition
o Loop (iteration)
▪ Repeat statements based on a given condition

• At the moment every program we have written has just run through its statements
in a straight line / linear sequence

• This form of linear program flow will not solve all problems e.g. we may need to
choose a statement based on a given condition

• For example when you go to take money from an ATM, there will be one set of
instructions for when you have enough money and another set of instructions for
when you have insufficient funds.

• Can you think of some more examples?

• Also, we may wish to repeat statements based on a given condition, for example,
you may have entered an incorrect PIN and wish to re-enter your PIN until the right
one is entered.

• In this section we will look at how we to choose a statement based on a given


condition.

Building Conditions – Boolean expressions


Relational Operators
• You use relational operators to perform comparisons
• A relational operator works between two operands
• It returns a Boolean result, that is a result which is either true or false

62
The following table shows all the relational operators supported by C#. Assume variable A holds 10
and variable B holds 20, then

Operator Precedence

Following table lists the precedence for relational operators and others.

Category Operator(s)
Postfix / Prefix ++, --
Unary +, -, !, ~
Multiplicative *, /, %
Additive +, -
Shift <<, >>
Relational <, <=, >, >=
Equality ==, !=
Bitwise &, |, ^
Logical &&, ||
Conditional ?:
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

63
What will be the output of this code snippet?

int x = 20, y = 5, z = 4;

int result = x / y + z;
Console.WriteLine($"Result1: {result}");

bool result2 = z <= y + x;


Console.WriteLine($"Result2: {result2}");

Watch out for :


== operator

• Don’t confuse this with the = (assignment) operator


== operator and strings

• Strings can be compared for equality too. The comparison is based on the Unicode
characters that make up the string
( name == "Rob" )

• Note that this is case sensitive. The string "rob" would not be recognised by the
above code, it would return false
• We will look at things like ToUpper later, which we can use to get around this
problem
== operator and Floating Point
( average == 1.0 )

• Floating point values are not held exactly.


• This means that comparing them for equality is a dangerous thing to do.
• Can cause errors …. and much frustration when trying to find
• If you really want to do this you must decide on some tolerance and then check to
see if the difference between the two values is greater than this.
Watch out for “off-by-one” errors
Should it be (age > 18) or should it be (age >= 18)

64
Logical Operators

Combining logical expressions


Sometimes we want to combine conditions, to make more complicated choices, for example
to test for a person’s age being valid to enter a disco (Lolas!) we have to test that their age is
greater than the minimum and less than the maximum.

C# provides additional operators to combine logical values, these are called logical
operators

&& - The And operator


If the operands on each side of the && are true the result of the && is true. If one of them is
false the result is false, for example

((age >= 18) && (age <= 23))

This would be true if the age was valid according to our above description. I’ve put brackets
around each of the conditions in this example, so that it is easier to see what is going on.

However, the compiler is able to work out that the && needs to be applied between the
result of the two logical expressions, so they are not actually required.

|| - The Or operator

If either of the operands each side of the || are true the result of the expression is true. The
expression is only false if both operands are false, for example:

((age < 18) || (age > 23))

this would be true if the age was invalid. We are saying that the age is invalid if it is less than
the minimum or larger than the maximum.

Note that to reverse the sense of the condition (i.e. true when the value is invalid) we not
only have to change the > into <= in each expression, but also change the && into an ||.

! - The Not operator


The inverts the value of a boolean expression

!(true)

65
Truth tables

Truth tables show the result of combining any two Boolean expressions using the AND
operator and the OR operator (or the NOT operator).

De Morgan’s Law:

De Morgan’s law can sometimes make it more convenient for us to express a logical
expression. These laws state that the expression

!( condition1 && condition2)

is logically equivalent to

( !condition1 || !condition2 )

Also,
!( condition1 || condition2)

is equivalent to

(!condition1 && !condition2)

Use De Morgan’s laws to write equivalent expressions for each of the following,

bool comparison1 = ((x >= 5 ) || ( y < 7 ));

bool comparison2 = (!(x < 5 ) && ! ( y >= 7 ));

66
Selection statements

Types of selection statement

1. if statement (no alternative)


2. if..else statements (one alternative)
3. if else if statements (many alternatives)
4. switch statement (many alternatives)
5. Ternary operation

If statement

We will use this when there is no alternative code

The structure of the if statement

if (condition)
{

Statement(s)
}

If the condition is true, the statement(s) in the body of the if statement will be executed,
otherwise they are skipped.

67
Example
Program to read in an exam score, if the score is less than 40, print a message

class Program
{
static void Main(string[] args)
{

Console.Write("Enter exam score : ");


int examScore = int.Parse(Console.ReadLine());

if (examScore < 40) // check if examScore is greater than/equal 40


{
Console.WriteLine("You have not passed the exam ");
}

Console.WriteLine("this line will always be printed");


}
}

Note If there is more than one statement in the body THEY MUST be enclosed in brackets. I
tend to always use the brackets for clarity even in cases when there is only one statement in
the body

68
if else statement

We will use this when there is a single alternative.


For example:
• you pass or you don’t pass the exam.
• You have enough money in your account or you don’t have enough money in your
account to satisfy a withdrawal

The structure of the if statement

if (condition)
{
Statement(s)
}
else
{
Statement(s)
}

If the condition is true, the statement(s) in the first set of {} be executed, otherwise the
code in the second set of {} will be executed.

69
Example program to print a particular message if you pass an exam or a different message if
you don’t.

class Program
{
static void Main(string[] args)
{

int examScore = 23;

if (examScore < 40) // check if examScore is less than 40


{
Console.WriteLine("You have not passed the exam");
}
else
{
Console.WriteLine("Congratulations, You have passed");
}

Console.WriteLine("this line will always be printed");


}
}

Note you do not need to put a condition on the else line. If your score is not less than 40
it must be equal or greater.

70
if else if statement

Consider a situation when we have multiple alternatives, for example rather than just pass
or fail, a student may be awarded an A, a B, a C or a D in an exam.

Can you think of other examples where there are multiple alternatives?

// program to determine the grade a student has received based on their examScore
// 0-39 = 'F'
// 40-59 = 'C'
// 60-84 = 'B'
// 85-100 = 'A'
class Program
{
static void Main(string[] args)
{
int examScore = 67;
string grade="";

if (examScore >= 85)


{
grade = "A";
}
if (examScore >= 60)
{
grade = "B";
}
if (examScore >= 40)
{
grade = "C";
}
if (examScore < 40)
{
grade = "F";
}

Console.WriteLine($”Your grade is {grade}");


}
}

What will the output be when executed?

71
Another go at the same problem : What will the output be when executed?

// program to determine the grade a student has received based on their examScore
// 0-39 = 'F'
// 40-59 = 'C'
// 60-84 = 'B'
// 85-100 = 'A'
class Program
{
static void Main(string[] args)
{
int examScore = 67;
string grade="";

if (examScore >= 85)


{
grade = "A";
}
if (examScore >= 60 && examScore < 85)
{
grade = "B";
}
if (examScore >= 40 && examScore < 60)
{
grade = "C";
}
if (examScore < 40)
{
grade = "F";
}

Console.WriteLine($"Your grade is {grade}");


}
}

What do you think of the efficiency of this code?

72
A better strategy would be to use an the if ..else if statement, here once a condition is
satisfied, the statement is exited

The structure of the if else if statement

if (condition_1)
{
Statement1
}
else if (condition_2)
{
Statement2
}
else if (condition_3)
{
Statement3
}
else
{
Else body
}

Figure 23 if.. else .. if

73
Our program with an if .. else.. if

// program to determine the grade a student has received based on their examScore
// 0-39 = 'F'
// 40-59 = 'C'
// 60-84 = 'B'
// 85-100 = 'A'
class Program
{
static void Main(string[] args)
{
int examScore = 67;
string grade;

if (examScore >= 85)


{
grade = "A";
}
else if (examScore >= 60)
{
grade = "B";
}
else if (examScore >= 40)
{
grade = "C";
}
else
{
grade = "F";
}

Console.WriteLine($"Your grade is {grade}");


}
}

Note that I don’t’ print the grade in the selection statement, why might this be a good idea?

74
Switch statement

• The switch statement provides another means to decide which statement to execute
next when there are more than 1 alternative.

• The switch statement evaluates an expression, then attempts to match the result to
one of several possible cases.

• Each case contains a value and a list of statements.

• The flow of control transfers to statement list associated with the first value that
matches.

• The expression of a switch statement must result in an integral data type, like an
integer or character or a string.

• Note that the implicit boolean condition in a switch statement is equality - it tries to
match the expression with a value

• A switch statement can have an optional default case as the last case in the
statement

• The default case has no associated value and simply uses the reserved word default

• If the default case is present, control will transfer to it if no other case value matches

• If there is no default case, and no other value matches the expression, control falls
through to the statement after the switch

• A break statement is used as the last statement in each case's statement list

• A break statement causes control to transfer to the end of the switch statement.

• We can group cases that have corresponding statements.

75
Figure 15 Switch Syntax

76
Example

class Program
{
static void Main(string[] args)
{

// read in a number between 1 and 7 representing days of the week


// output the correspoding day name
int dayNum;
string message;

Console.WriteLine("Enter day number : ");


dayNum = int.Parse(Console.ReadLine());

switch (dayNum)
{
case 1: // when dayNum has a value of 1 execute this case
message = "Monday";
break;
case 2:
message = "Tuesday";
break;
case 3:
message = "Wednesday";
break;
case 4:
message = "Thursday";
break;
case 5:
message = "Friday";
break;
case 6:
message = "Saturday";
break;
case 7:
message = "Sunday";
break;

default:
message = "error";
break;
}

Console.WriteLine(message);

77
Example : multiple cases that result in the same outputs

class Program
{
static void Main(string[] args)
{

// read in a number between 1 and 7 representing days of the week


// output a message indicating if a weekday or a weekend day
int dayNum;
string message;

Console.WriteLine("Enter day number : ");


dayNum = int.Parse(Console.ReadLine());

switch (dayNum)
{
case 1:
case 2:
case 3:
case 4:
case 5:
message = "Midweek day"; // when dayNum has a value of 1,2,3,4 or
5 execute this case

break;
case 6:
case 7:
message = "Weekend day";
break;

default:
message = "error";
break;
}

Console.WriteLine(message);

78
Ternary Operator
I am just including this for completeness, initially we may not use it that much as it is a little
less readable, but as your skills build up you might want to consider using it.

The conditional operator (? : ), commonly known as the ternary conditional operator,


returns one of two values depending on the value of a Boolean expression. Following is the
syntax for the conditional operator.

Structure

condition ? first_expression : second_expression;

static void Main(string[] args)


{

int input = Convert.ToInt32(Console.ReadLine());


string classify;

// if-else construction.
if (input > 0)
classify = "positive";
else
classify = "negative";

Console.WriteLine(classify);

// ?: conditional operator.
classify = (input > 0) ? "positive" : "negative";

Console.WriteLine(classify);

79
Chapter 9 Loops – doing it again and again
There are many times when we may wish to repeat the execution of a piece of code, can
you think of some examples?

In general, loops can be :

1. Counter controlled – do loop a specific number of times


e.g. Print out the grades of all 100 students in a class

2. Event controlled – do loop until some event occur


e.g. the correct password is entered
e.g until a specific value is entered, which terminates the loop

3. Event and counter controlled –combination of both


e.g. : Keep asking for a password until the correct password is entered or you have
used all your attempts, for example with an ATM you will be given only 3 attempts to
enter the correct PIN

C# Loop statements

• while statement
• do/while statement
• for statement
• foreach statement

while loop

while (condition)
{
statement or block
}

// print your name 3 times


// we must keep track of the number of times loop is executed, so we need a counter
int count = 1; // initialise control variable

while (count <= 3) // check the condition


{
Console.WriteLine("pat ryan");
count++; // update the control variable
}

80
How it works

1. The variable count is initially assigned a value of 1

2. The condition is evaluated as true, so the loop body is executed


a. Name is printed
b. Count is incremented by 1 to 2

3. Control returns to the condition, where it is evaluated as true, so the body is


executed again
a. Name is printed
b. Count is incremented by 1 to 3

4. Control returns to the condition, where it is evaluated as true, so the body is


executed again
a. Name is printed
b. Count is incremented by 1 to 4

5. Control returns to the condition, where it is evaluated as false, so the body is skipped

6. Note that if the condition of a while statement is false initially, the statement is
never executed

7. Therefore, the body of a while loop will execute zero or more times

8. Watch out for infinite loops – loops that never exit – remind me to tell my infinite
loop joke!

// print your name 3 times


int count = 1;
while (count <= 3)
{
Console.WriteLine("pat ryan");
}
What will happen when this is executed?

Try this

Get 10 grades from the user and compute the average.

81
static void Main(string[] args)
{
// program to calculate the average of 10 scores entered
by user

int scoreIn;
int total = 0; // accumulator
int counter = 1; // counter

while (counter <= 10) // do loop 10 times


{
Console.Write($"Enter score for student {counter}:
");
scoreIn = int.Parse(Console.ReadLine());

total = total + scoreIn; // accumulate score

counter++; // increment counter


}

int average = total / counter; // calculate average -


note may be a loss of precision here

Console.WriteLine($”Averge score = {average}");

Example : Event Controlled while loop - password validation example

Console.Write("Enter password : ");


string myPassword = Console.ReadLine();

while (myPassword != "blackfriday")


{
Console.WriteLine("Invalid Password");

Console.Write("Enter password : ");


myPassword = Console.ReadLine();

Console.WriteLine("Welcome to our lovely system");

82
Example Event and counter controlled –password validation with a maximum of 5 attempts

int myAttempts = 0;

Console.Write("Enter password : ");


string myPassword = Console.ReadLine();

while (myPassword != "blackfriday" && myAttempts < 5)


{
Console.WriteLine("Invalid Password");

Console.Write("Enter password : ");


myPassword = Console.ReadLine();

myAttempts++;
}

if (myPassword == "blackfriday")
Console.WriteLine("Wecome to our lovely system");
else
Console.WriteLine("all attempts used - calling the gardai!");

83
Sentinel Controlled while Loops

• Sometimes, loop control may need to be based on the value of what we are processing.
In this case, we would use sentinel-controlled repetition.

• Sentinel-controlled repetition is sometimes called indefinite repetition because it is not


known in advance how many times the loop will be executed. It is a repetition procedure
for solving a problem by using a sentinel value (also called a signal value, a dummy value
or a flag value) to indicate "end of data entry". The sentinel value itself is not a part of
the processed data.

• This is typical of an input-driven program

• An example of when we would use sentinel-controlled repetition is when we are


processing data from a file and we do not know in advance when we would reach the
end of the file.

• The loop continues an arbitrary amount of times, until a specific value is entered / event
occurs, causing the loop to break

static void Main(string[] args)


{
// program to sum a series of numbers terminated with -999

int numIn;
int sum = 0; // accumulator

Console.Write("Enter number, -999 to quit : "); // get first value - read


ahead, if this is sentinel value, we skip loop entirely
numIn = int.Parse(Console.ReadLine());

while (numIn != -999) // check for sentinel value


{
sum = sum + numIn; // accumulate input values

Console.Write("Enter number, -999 to quit : "); // get next value


numIn = int.Parse(Console.ReadLine());

Console.WriteLine($”Sum = {sum}");

84
Do while loop

This is very similar to the while loop, the major difference is that the loop is executed 1 time
before the condition is checked.

Structure

do
{
Statement(s);
}
while (condition);

85
For Statement

This

Note : we can rewrite a counter contr9olled while loop as a for loop

// print your name 3 times


for (int i = 1; i <= 3; i++)
{
Console.WriteLine("pat ryan");
}

86
A menu driven program

Let’s look at a skeleton menu driven program for a game – could you rewrite this using a do..while
loop?

static void Main(string[] args)


{

Console.WriteLine("Hello Gamer");

Console.WriteLine(" Game Menu");


Console.WriteLine("1 One player game");
Console.WriteLine("2 Two player game");
Console.WriteLine("3 Multi player game");
Console.WriteLine("4 Exit");
Console.Write("\nEnter Choice : "); // note the escape character \n which
creates a new line

int menuChoice = int.Parse(Console.ReadLine());

while (menuChoice != 4) // loop to show the menu repeatitly until the


user enter a menu choice of 4
{

if (menuChoice == 1)
{
Console.WriteLine("option 1 selected ");
// place code here to handle option1
}
else if (menuChoice == 2)
{
Console.WriteLine("option 3 selected ");
// place code here to handle option2
}
else if (menuChoice == 3)
{
Console.WriteLine("option 3 selected ");
// place code here to handle option3
}
else
Console.WriteLine("Invalid choice");

// show the menu again


Console.WriteLine(" Game Menu");
Console.WriteLine("1 One player game");
Console.WriteLine("2 Two player game");
Console.WriteLine("3 Multi player game");
Console.WriteLine("4 Exit");
Console.Write("\nEnter Choice : ");

menuChoice = int.Parse(Console.ReadLine());

} // end loop

// will only get here when option 4 selected


Console.WriteLine("Good Bye");
}

87
Messing with a loop

o break and continue statements allow us modify the normal behavior of a


loop
o You use the break statement to jump to the end of a loop
o You use the continue statement to jump to the start of a loop

I don’t really like doing this- generally its best to aim for one entry point and one exit point
from a loop

Breaking out of a loop

// sum all numbers between 1 and 100, if sum becomes greater than 20
// exit the loop
string message = null;
int sum = 0;
int i = 1;
while (i <= 100)
{
sum = sum + i;
if (sum > 20)
{
message = “sum is too large";
break; // jump out of the loop
}
i++;
}
Console.WriteLine(message);

Try this : How might you do this without using a break?

Skipping an iteration with continue

// sum all numbers between 1 and 6 except 4


int sum = 0;
for (int j = 1; j <= 6; j++)
{
if (j == 4)
continue; // skip rest of this iteration
sum = sum + j;

}
Console.WriteLine(sum);

Try this : How might you do this without using a continue?

88
Chapter 10 - Nested Control
This occurs when we insert one control structure inside another
– Loops within loops
– Ifs within if statements
– If within loops
– Loops within if statements

Nested loops – loops with loops


• Nested loops are necessary when a task performs a repetitive operation and that
task itself must be repeated.
• For example, a program to calculate the average test score for a class of 5 students,
where each student has 3 test scores.
class Program
{
static void Main(string[] args)
{
int studentCounter = 1;
int examCounter;
int score;
int studentTotal; // accumulator
while (studentCounter <= 5) // outer loop
{
studentTotal = 0; // must be initialised for each student
examCounter = 1;

while (examCounter <= 3) //inner loop, done 3 times for each


student
{
Console.WriteLine($”Enter score in exam {examCounter} for
student {studentCounter}";
score = int.Parse(Console.ReadLine());
studentTotal = studentTotal + score;
examCounter++; // increment exam count

}
Console.WriteLine($”Student {studentCounter} had an average score
of {studentTotal/3}");
studentCounter++; // increment student count
}

89
Nested if Statements

• The statement executed as a result of an if statement will be another if statement


• These are called nested if statements
• When you code nested statements it is good practice to indent the nested
statements and their clauses
• An else clause is matched to the last unmatched if (no matter what the indentation
implies)
Example
Write a program to determine the discount applicable to a customer, customers of type “R”
with sales of 100 or greater, receive a discount of 20%, if their sales are less than 100 they
receive a discount of 10%. All other customers receive a discount of 10%.

class Program
{
static void Main(string[] args)
{
double discountPercent;

Console.Write("Enter customer type : ");


string customerType = Console.ReadLine();

Console.Write("Enter customer type : ");


int salesTotal = int.Parse(Console.ReadLine());

if (customerType == "R")
{
if (salesTotal >= 100)
discountPercent = .2;
else
discountPercent = .1;
}
else
discountPercent = .4;

Console.WriteLine($"Your discount percentage is {discountPercent}",);


}
}

Try this :
Write a program to determine whether a student qualifies for a grant. To qualify the
student must earn less than €20,000 and must be aged between 18 and 23 inclusive

90
If within loops
For example a program to read in the exam result of 10 student, and count the number that
have passed and the number that have failed.

Initialize passes to zero


Initialize failures to zero
Initialize student to one

While student counter is less than or equal to ten


Input the next exam result

If the student passed


Add one to passes
Else
Add one to failures

Add one to student counter

Print the number of passes


Print the number of failures

If more than eight students passed


Print “Hooray!”

Try this : Write up the c# code for this algorithm

91
Chapter 10 - Methods
A method is a group of statements that together perform a task. Every C# program has at
least one class with a method named Main(). This has been the structure of our programs
up to now.

But as our programs have started to get bigger and the problems we are solving more
complex, this simple structure become very unwieldly and doesn’t reflect our divide and
conquer approach to problem solving. A better approach would be to use multiple methods
where each method performs a specific task.

92
Why use methods

• Allow use realise our divide-and-conquer problem solving strategy.


• Allow us to reuse code.
• Allow for better testing of our programs.
• Programs will be easier to maintain.
• Allow us allocate task to different programmers.
We’ll look later at how methods can be organised into classes.

We have already come across the methods Main(), WriteLine() and ReadLine().

WriteLine() and ReadLine()are in the Console class and were provided by the
creators of C# to give us a way of displaying text and reading information from the user.

Your programs will contain methods that you create to solve parts of the problem and they
will also use methods that have been provided by other people.

• Pre-defined with no return value


– Console.WriteLine(”Island”);
– Console.Write(”Matrix”);

– …
• Predefined with return value, i.e. The method sends a value back to the method that
called it.
– string st=Console.ReadLine();

– int x=Convert.ToInt32(”123”);
– int y=Math.Pow(2, 3);

93
How to write our own methods?
Basic Structure of a method

[static] [public|private] return-type MethodName ([parameter list])

[const/variable declaration];

[statement(s)]

• static
– Method can be called directly without having to create an instance of the
class that it is in (more on this later!)
• Access modifier - public | private | protected
– public any program can call this method

– private – can only be called from within this class

– protected – can be accessed within the current namespace

• return-type can be
- a data type like int, double, string, etc. When a return type is specified, a
return statement must be include in the method body. This ends the
execution of the current method and returns the specified value to the calling
method
- the keyword void , this is used when the method does not return data.
- Method name
- Use identifier naming rules when naming

94
Example
class Program
{

static void Main(string[] args)


{

Console.WriteLine("Hello”)
}// end main

The same program, now with the greeting placed inside a method
class Program
{

static void Main(string[] args)


{

PrintGreeting();

}// end main

// non return type method


static private void PrintGreeting()
{
Console.WriteLine("Hello”);
}

Calling a method

• Note that we must call a method in order for it to be executed.

• If we don’t call it, it will be not be executed. (it’s a bit like, if you don’t call the plumber
they aren’t going to come to your house).

• We call a method by just using the Method name (and giving it any values it might need
in brackets if it needs any).

• Note that control always returns to the calling method when the called method is
finished executing. A method call is a bit like throwing a boomerang! – it always comes
back to where it was trhrown from.

• Methods may be written anywhere within a class, it is the order in which they are called
that dictates when they are executed

95
• The great thing is that once we have it written, we can call it as many times as we like.
We can even call methods that are in different projects/namespaces. For example we
might have a method that we wrote in a project 2 years ago that does a task we want to
do in our current project. So, instead of reinventing the wheel, we can reference this
project and call this method from our current project. Doing this is a little beyond what
we want to do this semester, but if I’ve time we will look at how to do it – it’s a pretty
neat thing to be able to do.

• What will be the output of this?


class Program
{

static void Main(string[] args)


{

PrintGreeting();
Console.WriteLine("I am back”);
PrintGreeting();
Console.WriteLine("I am back again”);
PrintGreeting();
Console.WriteLine("I am back for good”);

}// end main

// non return type method with no parameters


static private void PrintGreeting()
{
Console.WriteLine("Hello”);
}

96
Sharing data between methods.
Remember that if there is a variable declared in a method, this variable can only be used in
this method, its scope is local to the method it has been declared in.
Therefore is we want to share data between methods we have to use one of two strategies
1. Use class level variables
o This is where we declare the variable outside of any method
o Easy to implement
Example – this program will not work, because the PrintCollege() method does not
have access to the myCollege variable
class Program
{

static void Main(string[] args)


{
string myCollege = "ATU Sligo";

PrintCollege();

}// end main

// non return type method with no parameters


static private void PrintCollege()
{
Console.WriteLine($"I study at {myCollege}”); // ERROR – out of scope

Example – this program will work, because the PrintCollege() method does have
access to the myCollege variable
class Program
{
static string myCollege = "ATU Sligo"; // can be seen in all methods

static void Main(string[] args)


{

PrintCollege();

}// end main

// non return type method with no parameters


static private void PrintCollege()
{
Console.WriteLine($"I study at {myCollege}”);
}

97
98
2. Using a Method’s Parameters

• This allows us to pass our local data over to the called method
• Particularity useful when working with methods in a different class
• Generally this is a good idea as it makes modules that are independent of each
other and therefore easier to maintain as it encourages the design notions of
encapsulation and information hiding which lead to loosely coupled systems
(phew!).
Example Program with void Methods
class Program
{

static void Main(string[] args)


{
PrintGreeting();

Console.WriteLine("back in Main");

PrintGreeting_Two("John");

Console.WriteLine("Enter student name : ");

string studentName = Console.ReadLine();

PrintGreeting_Two(studentName);

PrintGreeting_Three(studentName, "sligo");

}// end main

// non return type method with no parameters


static private void PrintGreeting()
{
Console.WriteLine("Hello");
}

// non return type method with 1 parameters


static private void PrintGreeting_Two(string studentNameIn)
{
Console.WriteLine($"Hello {studentNameIn}");
}

// non return type method with 2 parameters


static private void PrintGreeting_Three(string studentNameIn, string townIn)
{
Console.WriteLine($"Hello {studentNameIn} from {townIn}”);
}
}

(Note that it is possible to have many methods with the same name and different parameter
lists, this is called method overloading, will have a look at it in semester 2)

99
Return type methods
All the methods we have looked at so far, are void methods, they did not return a value to
the calling method. There are many occasions when we will want to get a value back from
the called method. Let’s say we have a method that calculates the area of a rectangle, we
want to be able to say something like “Hey here’s the width and height of a rectangle, give
me be back its area” to the method

Example Return type method that receives the width and height of a rectangle returns the
area of a rectangle

static private int CalcArea(double w, double h)


{
int myResult;
myResult = w * l;
return myResult; // sending the value back to the calling method

Calling a Method with a return value (


o you can use this type method very much as you would a variable
o you can think of it as a variable that dynamically determines its value
o Assign the returned value to a variable
▪ double area = CalcArea(w,h);
o Use the returned value as an argument in a method call
▪ Console.WriteLine(CalcArea(w, h));
o Use the returned value in a Boolean expression
▪ if (CalcArea(w, h) > 20)….
o Use the returned value in an arithmetic expression
▪ X = CalcArea(w, h) + 20);

100
Example Full Program with return type methods
class Program
{
static void Main(string[] args)
{
int a, b;
a = 10;
b = 50;

int answer = Adder(a, b); // calling Adder method(), it returns a value to


answer variable

Console.WriteLine(answer);

// can use a return type method in the same manner as we use a regular variable
// you could think of it as a variable that determines its own value

Console.WriteLine(Adder(30, 20));

if (Adder(4,5)< 10)
Console.WriteLine("small");

int answer2 = (Adder(5, 2) - 10);

Console.WriteLine(CheckTemp(10)); // checkTemp() returns a string

bool r = CheckGrade(56); // CheckGrade() returns a bool


Console.WriteLine(r);
}

static private int Adder(int x, int y)


{
int myResult;
myResult = x + y;
return myResult; // sending the value back to the calling method

}
static private string CheckTemp(int temp)
{
string msg;
if (temp < 0)
msg = "cold";
else
msg = "its ok";

return msg;

}
static private bool CheckGrade(int score)
{
bool passCheck;
if (score >= 40)
passCheck = true;
else
passCheck = false;

return passCheck;
}

101
Passing data by value and passing data by reference
Something else we need to consider when passing data…
Do we allow the called method change the value of our data or do we just give them a copy?
• The safest option and the default option is that we just give them a copy. This is
called pass by value.
• That means that the value of each passed variable is assigned to the corresponding
parameter in the method. (a copy of the calling method’s variable is passed to called
methods parameter).
• Because of this, any change made to the parameter in the called method, DOES NOT
affect the variable in the calling method.
• In some cases, though, you’ll want to change the value of the variable in the calling
method from the called method.
• To do this, you pass the argument by reference
• Here the ref keyword is code before the argument and before the parameter
declaration.
• The out keyword causes arguments also to be passed by reference. This is like the
ref keyword, except that ref requires that the variable be initialized before it is
passed. To use an out parameter, both the method definition and the calling method
must explicitly use the out keyword.
class Program
{
static void Main(string[] args)
{
int bankBalance;
int withdrawAmount;
bankBalance = 100;
withdrawAmount = 60;

Console.WriteLine($"Balance Before = {bankBalance}");


//bankBalance is passed by reference and withdrawAmount is passed by value
//bankBalnce may have a new value on return, withdrawAmount will still be
60
Withdrawal(ref bankBalance, withdrawAmount);
Console.WriteLine($"New balance after taking out {withdrawAmount} is

={bankBalance}");

}
static void Withdrawal(ref int bankBalance, int withdrawAmount)
{
// bankBalance is passed by reference, we have read/write access
bankBalance = bankBalance - withdrawAmount;
withdrawAmount = 0;
}
}

102
Try these
• Write method IsOdd()
– Passed an single integer, Return true if the value is an Odd number otherwise
false
• Write method SumAll()
– Passed 2 integers, returns the sum of all integers (inclusive) between the two
• Write a method Swap() which is passed two integers and swaps their contents, for
example if we pass a and b with the values 4 and 6 respectively, when control is
returned, a will have a value of 6 and b a value of 4

103
Chapter 12 - Arrays
An array stores a fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, it is often more useful to think of an array as a collection of variables of
the same type stored at contiguous memory locations.

• We know how to create a variable:


int sales1;

• This will create a variable which can hold a single integer value

• The variable has the identifier sales

• If we want to store more data, one approach is to create more variables:


int sales1;
int sales2;
int sales3;
int sales4

• But if we have a lot of sales, image 4000, this could get very tedious and make
coding to manage these very difficult

• An array lets us create a row of variables which we can index using a subscript

• Declaring and initialising an array


int [] sales = new int [4];

• sales is a reference to an array of integers which contains 4 elements

• Once you have your array you can place values into the elements in it:
int [] sales = new int [4];
sales [0] = 5;
sales [1] = 7
sales [2] = 8
sales [3] = 10;
5 7 8 10
[0] [1] [2] [3]

• The value in the square brackets is called a subscript /index

104
• Console.Writeline($“Sales 1 = {sales[0]}”)

Prints
Sales 1 = 5

• Note that the initial element has a subscript of 0

• Note the last element has a subscript of 3 (length of array – 1)

• Watch out! - It’s common to introduce off-by-one errors when using arrays

• If you try to access an element which is not in the array (perhaps by using a subscript
which is too large or less than zero) your program will fail

• For example, if the array sales can hold 4 values, it can only be indexed using the
numbers 0 to 3

Subscripts

• Subscripts become very powerful when we discover that we can use a variable as a
subscript:
int [] sales = new int [4] ;
// fill array with values from keyboard
for ( int i=0; i<4; i=i+1 )
{
string salesString = Console.ReadLine();
sales [i] = int.Parse(salesString );
}

• This will read in and store 4 sales values

• Subscripts start at 0, end at 3

• Each array has a public property called Length that stores the size of the array
- once an array is created, it has a fixed size
- It is referenced using the array name:
sales.Length

• Note that Length holds the number of elements, not the largest index

105
• This can be very handy when we want to write a method that will work with an array
of any length

// return the sum of all values stored in an array


// note how array is decared in parameter list
// note that by default arrays are passed by reference
// why do you think this is so?
static int AddUp(int[] myArray)
{
int sum = 0;
for ( int i = 0; i < myArray.Length; i++ )
sum = sum + myArray[i];

return sum;
}

Initialising Arrays

• An initialiser list can be used to instantiate and initialize an array in one step

• The values are delimited by braces and separated by commas


o Allocate space for the array – number of elements in initialiser list
determines the size of array
o Elements in array are initialized with the values in the initialiser list
Examples:
int[] units = {147, 323, 89, 933, 540};
char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};
string[] wordList = {“cs101“, “computer", “television"};

106
Two – Dimensional Arrays

• You can add an extra dimension by creating another subscript:


int [,] board = new int [3,3];
board [1,1] = 34; // board(row,column)
board [0,2] = 56;
board [2,0] = 78

• The subscripts are now row and column values

56
34
78

class Program
{
static void Main(string[] args)
{
// print contents of all elements in a 2d array
int[,] board = new int[3, 3];
board[1, 1] = 34; // board(row,column)
board[0, 2] = 56;
board[2, 0] = 78;

for (int row = 0; row < 3; row++)


{
for (int column = 0; column < 3; column++)
{
Console.Write(board[row,column] + " ");
}
Console.WriteLine();
}

Arrays have many built in methods, a few are:

• Copy (array1,array2,length);

• BinarySearch(arrayName,value);

• Sort(arrayName)

• Example: sort an array of values into ascending order


Array.Sort(myArray);

107
Chapter 13 - The Math Class & Miscellaneous

Provides constants and static methods for trigonometric, logarithmic, and other common
mathematical functions.

• Five methods of the math class ( there are many more)


1. Math.Round(decimalNumber[,precisio])
2. Math.Pow(number, power);
3. Math.Sqrt(number)
4. Math.{Min|Max}(number1,number2)

class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Round(23.75));
Console.WriteLine(Math.Round(23.5));
Console.WriteLine(Math.Round(23.4));
Console.WriteLine(Math.Round(23.754,2));
Console.WriteLine(Math.Round(23.755,2));
Console.WriteLine(Math.Pow(5,2));
Console.WriteLine(Math.Sqrt(25));
Console.WriteLine(Math.Min(23.73,20.25));
Console.WriteLine(Math.PI);
}
}

Output

108
Type casting
Type conversion happens when we assign the value of one data type to another.
Implicit Type Casting / Automatic Type Conversion
If the data types are compatible, then C# does Automatic Type Conversion.
It happens when:
• The two data types are compatible.
• When we assign value of a smaller data type to a bigger data type – this is
often referred to as widening
▪ For example, assigning an int value to a long variable.
• Before converting, the compiler first checks the compatibility according to
the following figure and then it decides whether it is alright or there some
error.
• No automatic conversion is supported from numeric type to char or boolean.

Figure 16 Narrow to Wide data types

Following table shows the implicit types of conversion that is supported by C# :

Convert from Data Type Convert to Data Type

Byte short, int, long, float, double

Short int, long, float, double

Int long, float, double

Long float, double

Float Double

109
// C# program to demonstrate the
// Implicit Type Conversion
using System;
namespace Casting{

class program {

// Main Method
public static void Main(String []args)
{
int i = 57;

// automatic type conversion


long l = i;

// automatic type conversion


float f = l;

// Display Result
Console.WriteLine($"Int value {i}");
Console.WriteLine($"Long value {l}”);
Console.WriteLine($"Float value {f}”);
}
}
}

Explicit Type conversion


If not comparable, then they need to be converted explicitly which is known as Explicit Type
conversion.
There will be a compiler error when types are not compatible with each other. For example,
assigning double value to int data type. (This is often referred to as narrowing)
So, if we want to assign a value of larger data type to a smaller data type we perform explicit
type casting.
• This is useful for incompatible data types where automatic conversion cannot be
done.
• Here, target-type specifies the desired type to convert the specified value to.
• Sometimes, it may result into the lossy conversion.

110
// C# program to demonstrate explicit Type Conversion

using System;
namespace Casting{
class Program {
// Main Method
public static void Main(String []args)
{
double d = 765.12;
// Explicit Type Casting
int pay = (int)d;
// Display Result
Console.WriteLine($"Value of pay is {pay}");
}
}
}

• Placing (int) in front of a variable/literal value means we want to cast this value to an
int type, we can do the same for all numeric types.
• Here due to lossy conversion, the value of pay becomes 765 and there is a loss of
0.12 value.
• You, the programmer are saying you are happy with this loss – are you sure? if this
was my pay, I would not be happy
• Also, what starts out as a small loss may be multiplied in later calculations. (check
out the first superman movie !)
• We have seen other built-in methods for Type-Conversions as follows :
int.Parse, double.Parse etc

111
Mixed type expressions
• The result produced by an operator depends on the items it is working on
• If all the items in an expression are of type int, the result will be of type
int

• If it is a mixed type expression, the result will be of the widest type


static void Main(string[] args)
{
int result1 = 6 + 5 + 7.2; // error cannot implicity convert double to
type int
Console.WriteLine(result1);

int result2 = 6 + 5 + (int) 7.2; // ok but there is a lossy conversion


Console.WriteLine(result2);

double result3 = 6 + 5 + 7.2; // ok, result3 is wide enough


Console.WriteLine(result3);

Integer division, consider


double d;
d = 1/2;
Console.WriteLine ( "d is : " + d ) ;

• You might think this will result in d having a value of 0.5


• But, no, it will result in d having a value of 0, since both items are of type
integer, the compiler uses integer division.
• This is a sneaky little error, that can catch you out
• We can get around this by explicit casting
double d;
d = (double) 1/2;
Console.WriteLine ($"d is : {d}" )

112
Version Control System (ref Basic Git Commands With Examples "git add . or git add -A" [Git
Cheat Sheet] (rubygarage.org)

Programs are generally developed by team(s) of developers who might be in many different
geographical locations. How do we allow all the developers work on the same projects and
effectively manage application versions?
The answer is to use a Version Control System (VCS), these are programs that help software
developers to effectively manage application versions.

Git is probably the most popular version VCS.

Git is a distributed version control system (DVCS). "Distributed" means that all developers
within a team have a complete version of the project on their own machine.

Thanks to Git, you'll be able to do the following:

1. Keep track of all files in a project


2. Record any changes to project files
3. Restore previous versions of files
4. Compare and analyse code
5. Merge code from different computers and different team members.

Git works quite simply: you first need to create a local repository in your project's root
directory (folder). Afterwards, Git can track all project files and directories.

Local & Remote repositories?

If you store your code (or any project items) on your own machine (with a Git
repository/directory), you are storing your stuff locally. So a repository on your own
computer will be called local.

A remote repository is like a public warehouse located in a different building. You may have
heard about remote repositories such as GitHub, BitBucket, and GitLab.

They're like warehouses for code. Thanks to Git, you can copy your entire project to a
remote repository while keeping it in a local repository as well.

113
Remote warehouses store exactly the same code that you have in your local repository.

If your code disappears from your local repository, you can restore absolutely the same
code from a remote repository.

A remote repository also serves as a central hub to which members of a development team
can connect to access project code.

Git Workflow
In development, a Git workflow might look like this:

1. Create local repository (or clone an existing remote repository)


2. Create a remote repository (if not already there)
3. You work on a feature and commit files to a branch (master or any other branch) in
local repository.
4. You push commits to the remote repository
5. Other developers pull your commits to their computers to have the latest version of
the project. This will:
• Pull changes in the current branch made by other developers; and
• Synchronize the local repository with the remote repository.

Git Commits
A commit to a repository is a snapshot of the current state of the project's root directory.

Let's say you're working with a bunch of papers. You've written ten pages about your friends
on ten separate sheets of paper and you want to note what pages there are and when you
wrote them. You take out another sheet of paper, call it a "commit," and write on this
commit paper: "I've written page #1. It's about Harry. I've written page #2. It's about
Sebastian..." Then you create a copy of each page. The last thing you do is you gather those
ten copies, pin the commit paper on top of them, and lay them (commit) in a drawer.

The next day you rewrite the original pages, then get the copies from your drawer and
compare the pages. This time, you only record the changes/differences that you have made
to each page – it would be wasteful of paper if we kept complete duplicates of the new
pages.

114
This is basically what Git does.

You create files and write code in them. When you're ready, you commit your files to a
repository: that is you create copies of files and lay them in a drawer (a repository).

Over time, you make more commits. Git creates a history of your commits, so you can trace
back to the very beginning of the project development to see what files have been changed
or added, who added or changed them, and when.

How to Run Git Commands

There are different methods to run Git commands. You can use programs with graphical
user interfaces for Git (https://git-scm.com/downloads/guis)

But you can also run terminal commands for Git or you can run the command from within
Visual Studio.

We will explore some of these in our labs and build on this over the coming years

115

You might also like