Book1_IntroToProgramming_Handouts_with_Sept2023
Book1_IntroToProgramming_Handouts_with_Sept2023
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
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
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
• 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
• 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.
6
The Basic architecture of a computer
The Von Neumann architecture and components
Main components
• The processor is the brain of the computer system. It is the processor that follows
instructions and performs calculations
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
9
The more bits, the more combinations
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.
10
Figure 4 Buses
How does the CPU manage the execution of a set of instructions (program) :
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
• 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.
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
14
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
15
Chapter 3 : Computer Programs
▪ 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
• 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!)
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?
18
Step 2 - Coding –
• Taking the solution and putting into a form that the computer can understand
This programming process is often referred to as the Software Development Lifecycle and is
illustrated in more detail below
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.
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.
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
…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.
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
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.
29
Chapter 4 - Programming languages and Introduction to C#
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#:
• 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.
• 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
// 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
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.
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
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.
4. Statements Keywords: There are total 18 keywords which are used in program
instructions.
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:
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
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).
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
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
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.
43
Declaring a variable
We must declare (make it) before we can use it. To declare a variable in c#, use the
following:
Or
<type> <identifier>;
<identifier> = <value>;
Or
<type> <identifier1>,<identifier2>,<identifier3>;
Examples declarations
int num1 = 8;
int myAge;
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;
}
}
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.
• 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
45
Introduction to Printing
Fundamental to most programs is the need to obtain input from the user of the program
and output our results.
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[])
{
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}");
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
48
Chapter 6: Operators and precedence
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;
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
50
Note on Assignment
• The right and left hand sides of an assignment statement can contain the same
variable
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.
average= 1
• is this what you want? You can fix this using brackets.
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
Exercise….Consider
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
53
Avoiding Magic Numbers
• 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
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.
Console.WriteLine("Hello");
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 :
• 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.
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> ..."
• This would output the value of x with 6 digits and two decimal places:
x: 001234.57
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
• 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}");
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
59
class Program
{
static void Main(string[] args)
{
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();
Console.WriteLine("Float format");
Console.WriteLine($"x = {x:f2}");
Console.WriteLine();
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
• 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.
• 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.
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}");
• 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 )
64
Logical Operators
C# provides additional operators to combine logical values, these are called logical
operators
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:
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 ||.
!(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
is logically equivalent to
( !condition1 || !condition2 )
Also,
!( condition1 || condition2)
is equivalent to
Use De Morgan’s laws to write equivalent expressions for each of the following,
66
Selection statements
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)
{
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
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)
{
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="";
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="";
72
A better strategy would be to use an the if ..else if statement, here once a condition is
satisfied, the statement is exited
if (condition_1)
{
Statement1
}
else if (condition_2)
{
Statement2
}
else if (condition_3)
{
Statement3
}
else
{
Else body
}
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;
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.
• 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.
75
Figure 15 Switch Syntax
76
Example
class Program
{
static void Main(string[] args)
{
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)
{
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.
Structure
// 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?
C# Loop statements
• while statement
• do/while statement
• for statement
• foreach statement
while loop
while (condition)
{
statement or block
}
80
How it works
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!
Try this
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
82
Example Event and counter controlled –password validation with a maximum of 5 attempts
int myAttempts = 0;
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.
• The loop continues an arbitrary amount of times, until a specific value is entered / event
occurs, causing the loop to break
int numIn;
int sum = 0; // accumulator
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
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?
Console.WriteLine("Hello Gamer");
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");
menuChoice = int.Parse(Console.ReadLine());
} // end loop
87
Messing with 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
// 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);
}
Console.WriteLine(sum);
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
}
Console.WriteLine($”Student {studentCounter} had an average score
of {studentTotal/3}");
studentCounter++; // increment student count
}
89
Nested if Statements
class Program
{
static void Main(string[] args)
{
double discountPercent;
if (customerType == "R")
{
if (salesTotal >= 100)
discountPercent = .2;
else
discountPercent = .1;
}
else
discountPercent = .4;
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.
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
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.
– …
• 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
[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
• 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
{
Console.WriteLine("Hello”)
}// end main
The same program, now with the greeting placed inside a method
class Program
{
PrintGreeting();
Calling a method
• 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.
PrintGreeting();
Console.WriteLine("I am back”);
PrintGreeting();
Console.WriteLine("I am back again”);
PrintGreeting();
Console.WriteLine("I am back for good”);
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
{
PrintCollege();
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
PrintCollege();
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
{
Console.WriteLine("back in Main");
PrintGreeting_Two("John");
PrintGreeting_Two(studentName);
PrintGreeting_Three(studentName, "sligo");
(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
100
Example Full Program with return type methods
class Program
{
static void Main(string[] args)
{
int a, b;
a = 10;
b = 50;
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");
}
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;
={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.
• This will create a variable which can hold a single integer value
• 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
• 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]
104
• Console.Writeline($“Sales 1 = {sales[0]}”)
Prints
Sales 1 = 5
• 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 );
}
• 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 sum;
}
Initialising Arrays
• An initialiser list can be used to instantiate and initialize an array in one step
106
Two – Dimensional Arrays
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;
• Copy (array1,array2,length);
• BinarySearch(arrayName,value);
• Sort(arrayName)
107
Chapter 13 - The Math Class & Miscellaneous
Provides constants and static methods for trigonometric, logarithmic, and other common
mathematical functions.
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.
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;
// Display Result
Console.WriteLine($"Int value {i}");
Console.WriteLine($"Long value {l}”);
Console.WriteLine($"Float value {f}”);
}
}
}
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
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 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.
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.
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:
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.
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