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

CS Software Development Made Easy Objective 1 Core Programming Study Guide (1) - 2

Uploaded by

ggreed641
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

CS Software Development Made Easy Objective 1 Core Programming Study Guide (1) - 2

Uploaded by

ggreed641
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

OBJECTIVE 1 STUDY GUIDE

Sonia Cross
Sold to
[email protected]
OBJECTIVE 1 STUDY GUIDE: CONTENTS

Introduction

Knowledge Area 1: Computer storage and data types

Knowledge Area 2: Computer decision structures

Knowledge Area 3: Identify the appropriate method for handling repetition

Knowledge Area 4: Understand error handling

Appendix A: Next steps towards passing the ITS 305 international exam

Appendix B: Objective 1 exercises list

References

Acknowledgements

Software Developer

2 Objective 1 Study Guide


Introduction
This study guide simplifies and summarizes the content of Core C# Programming and
offers simple, yet adequate, explanations of concepts with review questions and exercises.
The following knowledge areas are covered in this objective:

Computer storage and data types: How a computer stores programs and the instructions in computer
memory, memory stacks and heaps, memory size requirements for the various data storage types,
numeric data and textual data.
Computer decision structures: Various decision structures used in all computer programming
languages; If decision structures; multiple decision structures, such as If…Else and switch/Select Case;
reading flowcharts; decision tables; evaluating expressions.
Identify the appropriate method for handling repetition: For loops, while loops, do...while loops and
recursion.
Error handling: Structured exception handling.

After working through this Study Guide, also work through the following study guides:

ITS 305 C# Software Development made easy Objective 2 Study Guide – Object oriented programming
ITS 305 C# Software Development made easy Objective 3 Study Guide – Software Development
principles
ITS 305 C# Software Development made easy Objective 4 Study Guide – Web Applications
ITS 305 C# Software Development made easy Objective 5 Study Guide - Databases
The Study guide consists of the following:

80 pages in total.
Coding examples as required by topics.
+-40 pages of definitions, explanations and summaries of topics and concepts.
+-30 coding exercises.
Questions and answers with explanations and coding as required.

Each knowledge area consists of:

To-the-point explanations and definitions of topics and concepts.


Examples and coding examples as required by each topic or concept.
Coding exercises as applicable to topics and concepts, which the student can do practically. Look out for
this prompt and start coding!

Review questions per knowledge area, with answers, explanations and practical application in code
where required.

3 Objective 1 Study Guide


How to use the study guide
For Beginner Coders:
Work through the guide from beginning to end.
Follow Instructions for setting up your Visual Studio Integrated Development Environment (IDE) on p.11.
Follow the instructions for creating your first application, adding comments to your code and running your
application on p.11-14.
Follow the simple and applicable practical coding exercises to guide you into getting familiar with coding,
while learning topics required by each knowledge area.
Work through each Knowledge area’s Q&A carefully to verify your knowledge.
Repeat the process and work through the study guide again, until you know the content well
Use the Objective 1 exercises list to work through specific exercises, per knowledge area and topic, again.

For students already familiar with content and coding :


Use the guide to organize your knowledge and as a summary of Objective 1.
Scan through topics, content and exercises of areas you are familiar with.
Study areas of which you are unsure of carefully and do the exercises.
Work through all Q&A’s to verify your knowledge.
Use the Objective 1 exercises list to work through specific exercises, per knowledge area and topic, again.

How does the study guide fit into the bigger step-by-step preparation process for the
ITS 305 exam?
In the ITS 305 - How to approach and pass the exam guide, the following process is recommended to pass
the exam:
Summary of steps to take

PASS!

7 TAKE THE EXAM WITH CONFIDENCE!

6 REGISTER FOR THE EXAM AND WORK THROUGH


THE EXAM TIPS SECTION IN THE HOW-TO GUIDE

5 PRACTICE WITH THE IT SPECIALIST SOFTWARE


DEVELOPMENT - ITS 305 EXAM PREP TESTS ON
4 UDEMY
STUDY NEW CONTENT
3
WORK THROUGH THE ITS 305 OBJECTIVE STUDY GUIDES
Start
Here!
2
INSTALL SOFTWARE
1 STUDY THE HOW TO APPROACH AND PASS THE ITS 305 EXAM GUIDE

This study guide fits into Step 3. To complete Step 3, you can continue with the Objective 2 study guide, then
Objective 3, 4 and 5.

4 Objective 1 Study Guide


Knowledge Area 1
Computer storage and data types
KNOWLEDGE AREA 1: CONTENTS

How a computer stores instructions in computer memory


Stacks and Heaps
Types in C#
Boxing and Unboxing
Built-in value types
Reference types
Constants
Date and time types fundamentals
Computer storage Q & A

5 Objective 1 Study Guide


6 Objective 1 Study Guide
How a computer stores programs and instructions in computer memory

Computers deal only with binary information.


Data received by the computer is converted to simple numbers that are easy for a computer to store.

Every piece of data in a computer is stored as a number. For example, letters are converted to numbers and
photographs are converted to a large set of numbers that indicate the color and brightness of each pixel. The
numbers are then converted to binary numbers.

Binary numbers use two digits, 0 and 1, to represent all possible values.

Binary numbers are exceptionally long but, with binary numbers, any value can be stored as a series of items
which are true (1) or false (0).

The numbers are recorded by hardware inside the computer.

The main data storage in most computers is the hard disk drive.

Binary numbers are recorded as a series of tiny areas on the disk. In computing (specifically data transmission
and data storage), a block, sometimes called a ‘physical record’, is a sequence of bytes or bits. A block usually
contains some whole number of records with a maximum length, called a block size.

Some new laptop computers use solid state drives for primary data storage. These have memory chips that
are like memory chips in USB keys, SD cards, MP3 players, cell phones and so on. Binary numbers are
recorded by charging or not charging a series of tiny capacitors in the chip. Electronic data storage is more
rugged than magnetic data storage, but after several years the capacitors lose their ability to store electrical
charges.

CDs and DVDs use optics to store binary numbers. As the disk spins, a laser is either reflected or not reflected
by a series of tiny, mirrored sections on the disk. Writable disks have a reflective layer that can be changed by
the laser in the computer.

To process data, it is loaded into temporary storage, like memory chips

Temporary data storage areas are designed to be smaller but faster than long-term storage, and do not retain
the data when the computer is turned off.

The numbers are organized, moved to temporary storage and manipulated by


programs, or software.
Data is stored as lots of binary numbers, by magnetism, electronics or optics. While the computer is operating,
data is also stored in many temporary locations. Software is responsible for organizing, moving and
processing all those numbers. The computer's BIOS contains simple instructions, stored as data in electronic
memory, to move data in and out of different storage locations and around the computer for processing. The
computer's operating system, for example, contains instructions for organizing data into files and folders,
managing temporary data storage, and sending data to application programs and devices, such as printers

Finally, application programs process the data.

Programmers use modern programming languages to communicate instructions to computers. Compilers


read the instructions from programming languages and convert it into binary code which computers
understand.

7 Objective 1 Study Guide


Stacks and Heaps
The stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the
computer's RAM.

The heap is the memory available to a program at runtime for dynamic memory allocation.

Objects are always allocated memory on the heap, as well as objects with dynamic memory allocation (usually
created with the new keyword).

In contrast, some data items can be created on the execution stack or the call stack. Only objects of fixed size
known at compile time can be allocated on the stack.

Items created on the stack are method parameters and local variables declared within a method. The stack
memory is reclaimed when the stack unwinds (when a method returns, for example).

The memory allocated in the heap is automatically reclaimed by the garbage collector when the objects are
not in use anymore (for example, no other objects are holding a reference to them).

Read the following for more information: https://www.c-sharpcorner.com/article/C-Sharp-heaping-vs-


stacking-in-net-part-i/

STACK HEAP

Static memory allocation


Stores mostly objects of fixed
size Dynamic memory allocation

e.g., Method parameters, local Objects initialized with the


variables within a method, new keyword
built-in value types (when not Reference types
declared inside a reference
type). Memory is reclaimed by
garbage collector (in .Net)
Memory reclaimed when stack when objects are not in use
unwinds, e.g., when method anymore.
returns
Stores objects, like classes,
Types deriving from System. strings, arrays, delegates
Value type class is stored on and interfaces.
the stack (when not declared
inside a reference type, like an Pointers to objects on the
array). heap are stored on the
stack.
Pointers to objects on the
heap are stored on the stack.

8 Objective 1 Study Guide


Types in C#

A variable can be defined as a placeholder for a value of a certain type, for example:

string firstName = “Dan”;


The is firstName.
The variable’s is string.
The variable has a of “Dan”.

Every variable and constant have a type, as does every expression that evaluates to a value.
Every method signature specifies a type for each input parameter and for the return value, for example:
internal GetFullName( firstName, lastName)
{
return firstName + “ “ + lastName;
}

Value types are usually stack-allocated.


Reference types are heap-allocated.

The Object type is the base type of all other variables in C#. Object is a class in the System namespace:
System.Object.

Category Description
Generally stored on the Stack (but not always. May be stored on the heap if it is
contained in an Object or Reference Type, like an array of ints. The array is
stored on the heap and because the int items in the array are stored in the
array, the int items in the array will be stored on the heap.)
Contains data in its own memory allocation.

Value type Top level class: System.Object, but the ValueType class overrides the virtual
methods from Object with more appropriate implementations for value types
(https://docs.microsoft.com/en-
us/dotnet/api/system.valuetype?view=netframework-4.7.2).
Includes structs and enums and Built-in Value types.
Examples of Value types include Boolean, Date, structs, and enums.

A reference pointer to the type is stored in a stack while the object is allocated
in the heap.
Variables of reference type point to a location in the memory that contains the
actual data.
Reference type
Variables allocated on the heap have their memory allocated at run time and
accessing this memory is a bit slower.
Examples of reference types include strings, arrays, classes, objects of classes,
delegates, interfaces.

9 Objective 1 Study Guide


Boxing and Unboxing

Unboxing is defined as the The conversion of a value


process of converting a type to a reference type is
reference type to a value known as boxing.
type.

The following code snippets illustrate boxing and unboxing in C#:


int i = 100;

i = (int) obj; //Unboxing obj = i; //Boxing

10 Objective 1 Study Guide


Built-in value types
Built-in Value Types are mostly stored in the stack, unless contained in a reference type like an array.

C# .Net Type Size/Range/Description Variable declaration and


Type initialization
bool System.Boolean • Size: 2 Bytes bool smoker = false;
• Can be either true or false, e.g., are you a
smoker?
• default value: false
byte System.Byte • Size: 1 Byte byte age = 100;
• 0-255
• Unsigned 8-bit integer
• Default value: 0
sbyte System.SByte • -128 to 127 sbyte negByte = -100;
• Signed 8- bit integer
• Default value: 0
short System.Int16 • Size: 2 Bytes short shortNum = -32768;
• -32,768 to 32,767
• signed 16-bit integer
• Default value: 0
ushort System.UInt16 • 0 to 65,535 ushort UShortNum = 65535;
• Unsigned 16-bit integer
• Default value: 0
int System.Int32 • Size: 4 Bytes Int num = 90946;
• Signed 32-bit integer
• -2,147,483,648 to 2,147,483,647
• Default value: 0
uint System.UInt32 • 0 to 4,294,967,295 uint unimNum =
• Unsigned 32-bit integer 4000000000;
• Default value: 0
long System.Int64 • 8 Bytes long longNum =
• -9,223,372,036,854,775,808 to 9223327036854775807;
9,223,372,036,854,775,807
• Signed 64-bit integer
• Default value: 0L
ulong System.UInt64 • 0 to 18,446,744,073,709,551,615 Ulong ulongNum =
• Unsigned 64-bit integer 18000000000;
char System.Char • 2 Bytes char myInitial = ‘S’;
• A Unicode character, 16-bit
• Default value: '\0'
Built-in value types continued – Floating point types
float System.Single • Size: 4 bytes float x = 3.5F;
• 32-bit floating-point type
• Precision: 6-9 digits
• Default value: 0.0F
double System.Double • Size: 8 Bytes double x = 30D;
• 64-bit floating-point type
• Precision 15-17 digits
• Default value: 0.0D
decimal System.Decimal • 128-bit floating point type Decimal price = 50.55M;
• Has more precision and a smaller range
than other floating-point types.

11 Objective 1 Study Guide


C# .Net Type Size/Range/Description Variable declaration and
Type initialization

• Appropriate for financial and monetary


calculations.
• Precision: 28-29 digits
• Default value: 0M
GUID System.GUID • GUID stands for Global Unique Identifier. Generate 6 new GUID’s:
• A GUID is a 128-bit integer (16 bytes) that static void
you can use across all computers and GenerateGUID()
networks wherever a unique identifier is {
for(int x=0; x<=5;
required.
x++)
• Remember, GUID is also a built-in value {
type. Guid obj =
Guid.NewGuid();

Console.WriteLine("New
Guid is " +
obj.ToString());
}
Console.ReadLine();

}
enum System.Enum • Used to declare an enumeration, a distinct enum Day {Sat, Sun, Mon,
type that consists of a set of named Tue, Wed, Thu, Fri};
constants, called the enumerator list.
• By default the underlying type of each enum Month : byte { Jan,
element in the enum is int. Feb, Mar, Apr, May, Jun, Jul,
• You can specify another integral numeric Aug, Sep, Oct, Nov, Dec };
type by using a colon -= (see example).
• The approved types for an enum enum Titles : int { Mr, Ms,
are byte, sbyte, short, ushort, int, uint, long, Mrs, Dr };
or ulong.
• By default, the first enumerator has the
value 0, and the value of each successive
enumerator is increased by 1.
struct user-defined • A struct type is a value type that is public struct Book
value type typically used to encapsulate small groups {
of related variables, such as the public decimal
coordinates of a rectangle or the price;
characteristics of an item in an inventory. public string
• The struct type is suitable for representing title;
lightweight objects, such public string
as Point, Rectangle and Color. author;
}

12 Objective 1 Study Guide


Setting up your IDE and Built-in Types exercises

Before you can start coding, you will need Visual Studio.

Download and install the latest version of Visual Studio according to the steps in this article:
https://docs.microsoft.com/en-us/visualstudio/install/install-visual-studio?view=vs-2019

You can choose between the following versions:

Professional and Enterprise will be trials only, but the Community edition is free.

✓ Select to Download the Community edition.


✓ Select a location on your PC to download the VSCommunity.exe installation file to.
✓ Open the .exe file once it has been downloaded
✓ When asked which Workload to install, select .Net Desktop Development and ASP.Net and Web
Development and start the download and installation.
✓ When your installation is complete, open Visual Studio and start creating the application below.

Create a new C# Console Application


Create a new C# Console app in Visual Studio:

** These instructions are based on Visual Studio Community 2019.


✓ On the Visual Studio Start page, under the new project section, select Create new project.
✓ On the New Project Dialog box, select Visual C#.
✓ Select the Console app (.Net Framework) project template.
✓ Name the project “Types” and select OK.

Once the project is created, your screen should look as follows (I named my project Types1):

13 Objective 1 Study Guide


To run a project, press the Start button.

This is the Coding


Window. This is the
Solution
The entry point for a Explorer,
console app is the Main showing the
method of the Program Solution,
class. Projects in
the solution
and all
Project
Properties,
References,
This is the Output Window, with Output and Error List tabs. files and
classes

Let’s first add some comments to our project:

Expand the Main method by placing your cursor inside the curly brackets {} of the Main method and pressing
enter:

14 Objective 1 Study Guide


Comments
What are comments and why would you use them?

✓ Comments are used to explain code or make notes about code. It is necessary to make comments in
your code, especially when working in teams, so that you and other developers can understand what
you coded and why.

✓ The compiler ignores text which is placed in comments.

✓ You can add single line comments by prefixing your lines with a double forward slash // or by
selecting the line you want to comment on and pressing the Comment button on the Text Editor

Toolbar .

Tip: If your Text Editor Toolbar is not visible, press View-> Toolbars->Text Editor on the Menu Bar. The Text Editor

Toolbar looks like this:

✓ Add multiline comments by prefixing the first line you want to place in comments with /* and ending
the last line with */

In the Main method, add the following lines as comments:

Press F5 or the Start button on the Standard Toolbar to Run your project. You will find your console window
opening and closing if your app was successfully built and run. The Output window at the bottom of the IDE
(Integrated Development Environment) will display a message:

When you press Ctrl + F5, instead of F5, or Debug->Start without debugging instead of Start, the console
window will open and display the following message:

15 Objective 1 Study Guide


To keep your console window open until you hit any key on the keyboard when pressing F5, add the following
line to your Main method:

Press F5 or Start again. Your console window will now stay open until you hit any key on your keyboard.

You have successfully created, and run, the first part of your Types app!

16 Objective 1 Study Guide


Add a bool variable
Add the following code to the Main method in the previous exercise, between the comments you added and
the Console.ReadKey() line:

static void Main(string[] args)


{
//Using Comments - compiler does not read this code, but handy for developers
//Declaring some built-in Value types and returning the values to the Console:

//bool
//Declaring a bool variable to confirm Instructor status - are you an instructor or not?
//Declare variable and assign value of false
bool isInstructor = false;
//Write a result to the Console:
Console.WriteLine("Value of bool variable isInstructor is {0}.", isInstructor);

Console.ReadKey();

Press F5 or Start again. Your console window will display the following:

Notes:
The {0} in the output string is a placeholder for the first variable after the comma, in this case it is Instructor. You
can use this technique, called composite formatting, to list a few variables in an output string, e.g.

Console.WriteLine("Prime numbers less than 10: {0}, {1}, {2}, {3}",2, 3, 5, 7);

Still busy with the same project…

17 Objective 1 Study Guide


Add a byte variable
Let’s add another variable of type byte. Add this code just before the Console.ReadKey line, just after your
bool variable section:

//byte
//Declare a byte variable named age and assign an initial value of 25
byte age = 25;
//return the value of age to the Console:
Console.WriteLine("Value of byte variable age is {0}.", age);

Press F5 or Start again. Your console window will display the following:

Still busy with the same project…


Add float, double and decimal variables
Add the following code after your byte section and before the Console.ReadKey() line:

//declaring a float, double and decimal variable


//!!study your tables to know the difference between float, double and decimal
float temperature = 13.25F;
double circumference = 631.3945D;
decimal price = 350.15M;
//returning the values to the Console:
Console.WriteLine("The value of the temperature variable is {0}°F." +
"\nThe value of the circumference variable is {1}." +
"\nThe value of the price variable is ${2}.", temperature, circumference, price);

Press F5 or Start again. Your console window will display the following:

Notes:
What did we do here?
• We used one Console.WriteLine statement to return the value of the three variables.
• The {0}, {1} and {2} are placeholders for the variables in the returned string.
• The variables are listed after the returned string, separated with commas, so {0} is the placeholder for the
temperature variable in the string, {1} is for circumference and {2} for price.
• \n is the new line character, ensuring the text after \n is displayed on a new line.
• You can use the + sign to combine strings.

18 Objective 1 Study Guide


Still busy with the same project…
Add a char variable
Add the following code after your float, double and decimal section and before the Console.ReadKey() line:

//Declare a char variable and assign a value of S


char initial = 'S';
Console.WriteLine("The value of the initial variable is {0}.", initial);

Press F5 or Start again. Your console window will display the following:

Still busy with the same project…


Add a GUID variable
Add the following code in the Main method, after your char section, before the Console.ReadKey() line:

//Guid
//Declare a variable of type Guid for globally unique client numbers:
Guid clientNo = Guid.NewGuid();
Console.WriteLine("The value of the clientNo variable is {0}.", clientNo);

Press F5 or Start again. Your console window will display the following:

19 Objective 1 Study Guide


Still busy with the same project…
Declare and use an enum

Declare the following enum – above or below the Main method in the Program class:
//Declare an enum
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
In the Main method, add the following code below the GUID section, above the Console.ReadKey() line:
//enum
//Work with the Day enum:
string DayName;
int Dayno;
DayName = Day.Sun.ToString();
Dayno = (int)Day.Sun;
Console.WriteLine("DayName for Sunday is {0}, and Dayno is {1}", DayName, Dayno);
//enums are 0-based...first enumerator has the value of 0

Press F5 or Start again. Your console window will display the following:

Well Done! You have now declared some Built-in Value Types, assigned values to them and returned
those values to the console.

20 Objective 1 Study Guide


Here is the full code for exercise VT3:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Types1
{
class Program
{
static void Main(string[] args)
{
//Using Comments - compiler does not read this code, but handy for developers
//Declaring some built-in Value types and returning the values to the Console:

//bool
//Declaring a bool variable to confirm Instructor status - are you an instructor or not?
//declare variable and assign value of false
bool isInstructor = false;
//Write a result to the Console:
Console.WriteLine("Value of bool variable isInstructor is {0}.", isInstructor);

//byte
//Declare a byte variable named age and assign an initial value of 25
byte age = 25;
//return the value of age to the Console:
Console.WriteLine("Value of byte variable age is {0}.", age);

// float_double_decimal
//declaring a float, double and decimal variable
//!!study your tables to know the difference between float, double and decimal
float temperature = 13.25F;
double circumference = 631.3945D;
decimal price = 350.15M;
//returning the values to the Console:
Console.WriteLine("The value of the temperature variable is {0}°F." +
"\nThe value of the circumference variable is {1}." +
"\nThe value of the price variable is ${2}.", temperature, circumference, price);
//What did we do here?
//Used one Console.WriteLine statement to return the value of the 3 variables
//The {0}, {1} and {2} are placeholders for the variables in the returned string
//The variables are listed after the returned string, separated with commas:
//So {0} is the placeholder for the temperature variable in the string,
//{1} is for circumference and {2} for price.
//\n is the new line character, ensuring the text after \n is displayed on a new line
//you can use the + sign to combine strings

//char
//Declare a char variable and assign a value of S
char initial = 'S';
Console.WriteLine("The value of the initial variable is {0}.", initial);

//Guid
//Declare a variable of type Guid for globally unique client numbers:
Guid clientNo = Guid.NewGuid();
Console.WriteLine("The value of the clientNo variable is {0}.", clientNo);

21 Objective 1 Study Guide


//enum
//Work with the Day enum:
string DayName;
int Dayno;
DayName = Day.Sun.ToString();
Dayno = (int)Day.Sun;
Console.WriteLine("DayName for Sunday is {0}, and Dayno is {1}", DayName, Dayno);
//enums are 0-based...first enumerator has the value of 0

Console.ReadKey();
}

//Declare an enum
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
}
}

You have successfully completed and run, your Built-in Types app!

22 Objective 1 Study Guide


Reference types
The table contains a summary of the most important reference types: class, interface, delegate, object, string,
array.

C# Type .Net Type Size/Range/Description Variable declaration and initialization


class A type that is defined as public class Customer
a class is a reference type – {
// Fields, properties, methods
Objective 2, OOP, is all about
and events go here...
classes. }
interface An interface in Declaration:
C# contains only the interface ILog
declaration of the {
void Log(string msgToLog);
methods, properties and }
events, but not the Implementation:
implementation. class ConsoleLog: ILog
It is left to the class that {
implements public void Log(string
the interface by providing msgToPrint)
{
implementation for all the
members of the interface. Console.WriteLine(msgToPrint);
Interface makes it easy to }
maintain a program. }
delegate System.Delegate A delegate is a reference public delegate int MyDelegate
type variable that holds the (string s);
reference to a method.
This delegate can be used to reference
Delegates are especially
any method that has a single-
used for implementing
string parameter and returns an int-type
events and the call-back
variable.
methods.
A delegate can refer to a
method, which has the same
signature as that of the
delegate.
object System.Object The root of the object Object o = new object;
hierarchy
string System.String Zero or more Unicode String firstname = “Sonia”;
characters
arrays System.Array An array in C# is commonly int[] numbers = { 1, 2, 3, 4, 5 };
used to represent a
collection of items of similar
type.
Any array item can be
directly accessed by using an
index. In the .NET
Framework, array indexes
are zero-based.
This means that you use the
index 0 to access the first
element of an array, and
index 1 to access the second
element, and so on.

23 Objective 1 Study Guide


Reference types exercises

Create a new C# console application in Visual Studio and name it “ReferenceTypes”.

Add a string variable


Add the following string variables to the Main method and assign a value of your choice to it:

namespace ReferenceTypes
{
class Program
{
static void Main(string[] args)
{
string firstname = "Sonia";
string surname = "Cross";

Console.WriteLine("Your full name is: {0} {1}. ", firstname, surname);

Console.ReadKey();
}
}
}

Press F5 or Start. Your console window will display the following:

Enabling a variable to accept user input


Modify the code in the Main method to look as follows:
class Program
{
static void Main(string[] args)
{
string firstname = "";
string surname = "";
Console.WriteLine("Please enter your first name:");
firstname = Console.ReadLine();
Console.WriteLine("Thank you {0}, please enter your surname:", firstname);
surname = Console.ReadLine();
Console.WriteLine("The name and surname you entered is {0} {1}.", firstname, surname);
Console.ReadKey();
}
}

24 Objective 1 Study Guide


When you run your application, the console will prompt you to enter a first name:

Enter a first name and press enter.


The console will prompt you to enter your surname:

Enter a surname and press enter. The console will display the following:

Congrats!
Now you have created string variables and have enabled the user to assign values to the string variables by
communicating with the console app.

Still busy with the same project…

25 Objective 1 Study Guide


Creating and using an array
After the last line of code, just before the ReadKey() statement in the Main method of the previous app, add
the following code:
static void Main(string[] args)
{
//strings
string firstname = "";
string surname = "";
Console.WriteLine("Please enter your first name:");
firstname = Console.ReadLine();
Console.WriteLine("Thank you {0}, please enter your surname:", firstname);
surname = Console.ReadLine();
Console.WriteLine("The name and surname you entered is {0} {1}.", firstname, surname);

//arrays
Console.WriteLine("Array Structure: ");
//Declare an array of type int
int[] numbers = { 2, 3, 1, 4 };
//loop through the array and write the values to the Console
foreach (int no in numbers)
Console.Write("{0}, ", no);

Console.ReadKey();
}

The console will return the following:

Congrats! You have created and array and wrote its values to the console using a loop.

You have successfully completed and run, your Reference types app!

** Objects, classes, interfaces and delegates are covered in Objective 2.

26 Objective 1 Study Guide


Constants
Constants are data fields or local variables of which the values cannot be modified.

Constants are declared by using the const keyword.

For example, a constant can be declared as follows:

const int i = 10;

This declares a constant i of data type int and stores a value of 10.
Once declared, the value of the constant cannot be changed.

So thankful for
a constant
among so
many variables!

27 Objective 1 Study Guide


Date and Time type fundamentals
Although there are very few questions in the ITS 305 exam about date and time, it is important to have some
knowledge about Date and Time types.

In the .Net Framework, provision for working with dates are made with the following structs:

C# Type Description Variable declaration


/struct /enum & initialization
DateTime Represents an instant in time, typically expressed as a date DateTime date1 =
struct and time of day. new DateTime(2019,
8, 13); - see
The DateTime value type represents dates and times with
exercise DT1
values ranging from 00:00:00 (midnight), January 1, 0001
Anno Domini (Common Era) through 11:59:59 P.M.,
December 31, 9999 A.D. (C.E.) in the Gregorian calendar.
https://docs.microsoft.com/en-
us/dotnet/api/system.datetime?view=netframework-4.7.2
DateTimeOffset An alternative to the DateTime structure for working with DateTimeOffset
struct date and time values in particular time zones is dateOffset1 =
DateTimeOffset.Now;
the DateTimeOffset structure. The DateTimeOffset structure
- see exercise DT2
stores date and time information in a private DateTime field
and the number of minutes by which that date and time
differs from UTC in a private Int16 field. This makes it possible
for a DateTimeOffset value to reflect the time in a particular
time zone, whereas a DateTime value can unambiguously
reflect only UTC and the local time zone's time.
(https://docs.microsoft.com/en-
us/dotnet/api/system.datetimeoffset?view=netframework-
4.7.2
TimeSpan Represents a time interval. Use the TimeSpan struct if you TimeSpan interval =
struct want to determine the difference between two dates and new TimeSpan(); -
see exercises DT3
display it in a specified internal, e.g., days, hours, etc.
The largest unit of time that the TimeSpan structure uses to
measure duration is a day. Time intervals are measured in
days for consistency, because the number of days in larger
units of time, such as months and years, varies.
https://docs.microsoft.com/en-
us/dotnet/api/system.timespan?view=netframework-4.7.2
DateTimeKind Specifies whether a DateTime object represents a local time, a Use the
enum Coordinated Universal Time (UTC) or is not specified as either DateTime.Kind
property – see
local time or UTC.
Exercise DT4
A return value of 2 represents local time, 0 unspecified and 1
represents UTC time.
https://docs.microsoft.com/en-
us/dotnet/api/system.datetimekind?view=netframework-4.7.2
DayOfWeek Fields: Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Use the
enum Thursday = 4, Friday = 5, Saturday = 6 DateTime.Dayofweek
property – see
exercise DT5
TimeZoneInfo Represents any time zone in the world. see Exercise DT6
class A TimeZoneInfo object can represent any time zone, and
methods of the TimeZoneInfo class can be used to convert the
time in one time zone to the corresponding time in any other
time zone. The members of the TimeZoneInfo class support
the following operations:
Retrieving a time zone that is already defined by the
operating system.

28 Objective 1 Study Guide


Enumerating the time zones that are available on a
system.
Converting times between different time zones.
Creating a new time zone that is not already defined by
the operating system.
Serializing a time zone for later retrieval.

29 Objective 1 Study Guide


Date and Time type exercises

Create a new C# console application in Visual Studio and name it WorkingWithDates.

Add the following code to the Program class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WorkingWithDates
{
class Program
{
static void Main(string[] args)
{
//Call WorkWithDateTime method
WorkWithDateTime(); Add your code here
//Press any key to exit
Console.ReadKey();
}

static void WorkWithDateTime()


{
//Declaring a DateTime variable
//Setting year, month, day parameters - parameters are all of type int:
DateTime date1 = new DateTime(2019, 8, 13);
//Setting year, month, day, hour, minute, seconds - parameters are all of
type int:
DateTime date2 = new DateTime(2019, 8, 13, 14, 15, 45);
//Write output to the Console.
//{0} and {1} in the output string refers to the first
//and 2nd variables listed after the string:
Console.WriteLine("DateTime: date1 value: {0}, date2 value: {1}.", date1,
date2);
}
}
}

Press F5, or the Start button on the Standard toolbar, or Debug -> Start Debugging on the Menu bar to run the
app.

Still busy with the same project…

Add another method to the Program class of your previous exercise to illustrate DateTimeOffset:

static void WorkWithDateTimeOffset()


{
//Create a DateTimeOffset object that is set
//to the current date and time on the current
//computer, with the offset set to the local time's
//offset from UCT(Coordinated Universal Time)
DateTimeOffset dateOffset1 = DateTimeOffset.Now;
Console.WriteLine("Adds Difference (offset) between the current date and
UtcNow: {0}", dateOffset1);
}

Add a method call to the Main method of the Program class after the WorkWithDateTime method call:

30 Objective 1 Study Guide


//Call WorktWithDateTimeOffset method
WorkWithDateTimeOffset();

Press F5, or the Start button on the Standard toolbar, or Debug -> Start Debugging on the Menu bar to run the
app.

The console will now display the following:

Still busy with the same project…

You would like to determine the total time of your trip – from departure time at your local airport to the time
you arrive back to your local airport.

Add the following method to the Program class in your WorkingWithDates console app:

static void WorkingWithTimeSpan()


{
//Determine your total trip time
DateTime departToDestination = new DateTime(2019, 8, 28, 8, 15, 0);
DateTime arriveFromDestination = new DateTime(2019, 9, 1, 10, 20, 0);
TimeSpan tripTime = arriveFromDestination - departToDestination;
Console.WriteLine("Total time of Trip:{2}", arriveFromDestination,
departToDestination, tripTime);
}

Add the following method call to the Main method in your WorkingWithDates app:

static void Main(string[] args)


{
//Call WorkWithDateTime method
WorkWithDateTime();
//Call WorkWithDateTimeOffset method
WorkWithDateTimeOffset();
//Call WorkWithTimeSpan method
WorkingWithTimeSpan();
//Press any key to exit
Console.ReadKey();

Press F5, or the Start button on the Standard toolbar, or Debug -> Start Debugging on the Menu bar to run the
app. It should output the following to the console:

31 Objective 1 Study Guide


Still busy with the same project…

You would like to determine the DateTime kind of two dates.

Add the following method to the Program class in your WorkingWithDates console app:

static void WorkingWithDateTimeKind()


{
DateTime toDay = DateTime.Now;
DateTime todayUCT = DateTime.UtcNow;
Console.WriteLine("toDay kind: {0}", toDay.Kind);
Console.WriteLine("todayUCT kind: {0}", todayUCT.Kind);
}

Add the following method call to the Main method in your WorkingWithDates app:

static void Main(string[] args)


{
//Call WorkWithDateTime method
WorkWithDateTime();
//Call WorktWithDateTimeOffset method
WorkWithDateTimeOffset();
//Call WorkWithTimeSpan method
WorkingWithTimeSpan();
//Call WorkingWithDateTimeKind method
WorkingWithDateTimeKind();
//Press any key to exit
Console.ReadKey();
}

Press F5, or the Start button on the Standard toolbar, or Debug -> Start Debugging on the Menu bar to run the
app. It should output the following to the console:

Still busy with the same project…

You would like to determine what today’s day of week name is.

Add the following method to the Program class in your WorkingWithDates console app:

static void DayOfWeek()


{
//Determine today's day of week.
DateTime toDay = DateTime.Now;
Console.WriteLine("The day of week today is: {0}", toDay.DayOfWeek);
}

32 Objective 1 Study Guide


Add the following method call to the Main method in your WorkingWithDates app:

static void Main(string[] args)


{
//Call WorkWithDateTime method
WorkWithDateTime();
//Call WorkWithDateTimeOffset method
WorkWithDateTimeOffset();
//Call WorkWithTimeSpan method
WorkingWithTimeSpan();
//Call DayOfWeek method
DayOfWeek();
//Press any key to exit
Console.ReadKey();

Press F5, or the Start button on the Standard toolbar, or Debug -> Start Debugging on the Menu bar to run the
app. It should output the following to the console:

Still busy with the same project…

In this exercise, you are going to do the following:

Enumerating the time zones that are available on a system


Add the following method to the Program class in your WorkingWithDates console app:

static void EnumTimeZonesOnSystem()


{
ReadOnlyCollection<TimeZoneInfo> timeZones =
TimeZoneInfo.GetSystemTimeZones();

foreach (TimeZoneInfo timeZone in timeZones)


{
bool hasDST = timeZone.SupportsDaylightSavingTime;
TimeSpan offsetFromUtc = timeZone.BaseUtcOffset;
string offsetString;
Console.WriteLine("TimeZone Info");
Console.WriteLine("ID: {0}", timeZone.Id);
Console.WriteLine(" Display Name: {0, 40}", timeZone.DisplayName);
Console.WriteLine(" Standard Name: {0, 39}", timeZone.StandardName);
Console.Write(" Daylight Name: {0, 39}", timeZone.DaylightName);
Console.Write(hasDST ? " ***Has " : " ***Does Not Have ");
Console.WriteLine("Daylight Saving Time***");
offsetString = String.Format("{0} hours, {1} minutes",
offsetFromUtc.Hours, offsetFromUtc.Minutes);
Console.WriteLine(" Offset from UTC: {0, 40}", offsetString);
Console.WriteLine("-------End------");
}
}

33 Objective 1 Study Guide


Remove open page. Add the following method call to the Main method in your WorkingWithDates app:

static void Main(string[] args)


{
//Call WorkWithDateTime method
//WorkWithDateTime();
//Call WorktWithDateTimeOffset method
//WorkWithDateTimeOffset();
//Call WorkWithTimeSpan method
//WorkingWithTimeSpan();
//Call WorkingWithDateTimeKind method
//WorkingWithDateTimeKind();
//Call DayOfWeek method
//DayOfWeek();
//Call Enum Timezones on System method
EnumTimeZonesOnSystem();
//Press any key to exit
Console.ReadKey();

Press F5, or the Start button on the Standard toolbar, or Debug -> Start Debugging on the Menu bar to run the
app. It should output the following info about each time zone on the system to the console:

Still busy with the same project…


Converting times between different time zones

The following example illustrates the use of the ConvertTime(DateTime, TimeZoneInfo,


TimeZoneInfo) method to convert from local time to the time in a time zone of your choice.

Add the following method to the Program class in your WorkingWithDates console app:

34 Objective 1 Study Guide


static bool ConvertBetweenTimeZones(string ConvertTo)
{
DateTime convertFromTime = DateTime.Now;
try
{
TimeZoneInfo convertFromZone = TimeZoneInfo.Local;
TimeZoneInfo convertToZone =
TimeZoneInfo.FindSystemTimeZoneById(ConvertTo);
Console.WriteLine("{0} {1} is {2} {3}.",
convertFromTime,
convertFromZone.StandardName,
TimeZoneInfo.ConvertTime(convertFromTime, TimeZoneInfo.Local,
convertToZone),
convertToZone.StandardName);
return true;
}
catch (TimeZoneNotFoundException)
{
Console.WriteLine("The registry does not define this zone.");
return false;
}
catch (InvalidTimeZoneException)
{
Console.WriteLine("Registry data on this zone has been corrupted.");
return false;
}
}

Add the following code to the Main method in your WorkingWithDates app:

EnumTimeZonesOnSystem();
getTimeZoneValue: Console.WriteLine("Please enter the TimeZone you wish
to convert the local time to:");
string strTimeZoneTo = Console.ReadLine();
if(ConvertBetweenTimeZones(strTimeZoneTo)==false)
goto getTimeZoneValue;
//Press any key to exit
Console.ReadKey();

Press F5, or the Start button on the Standard toolbar, or Debug -> Start Debugging on the Menu bar to run the
app. It should output the following to the console:

35 Objective 1 Study Guide


Computer Storage Q & A

Examples of the type of questions you can expect in the international exam from this
knowledge area in Objective 1.

You are creating a variable for an application. You need to store data that has the following characteristics in
this variable:

• characters as well as numbers


• includes numbers that have decimal points

Which data type should you use – float, string, char or decimal?

Answer: string

Explanation:
✓ You should use a string variable. Of the possible options, only a string can store characters and numbers.

You are creating variables for an application. You need to store data that has the following characteristics in
this variable:

· consists of numbers only


· includes numbers that have decimal points
· requires more than seven digits of precision

You need to use a data type that will minimize the amount of memory that is used.

Which data type should you use – decimal, double, byte or float?

Answer: double

Explanation:
✓ All these types consist of numbers only.
✓ byte cannot take decimal values.
✓ float takes 6 to 9 digits of precision. It may not be enough to take 7 digits.
✓ Both double and decimal have decimal points and more than 7 digits of precision, but you should select
the one that will minimize the memory used.

✓ Therefore, the answer is double.

36 Objective 1 Study Guide


Which of the following statements would declare a string variable named firstname and assign a value of
"John" to it in one statement?

· string John as firstname


· string firstname;
firstname = “john”;
· string firstname = “John”;
· firstname “john” as string;

Answer:
✓string firstname = “John”;

How would you declare a decimal variable named price and assign a value of 245.77 to it in one statement?

Answer:
Decimal price = 245.77M;

37 Objective 1 Study Guide


Knowledge Area 2
Computer decision structures
KNOWLEDGE AREA 2: CONTENTS

If decision structures
Multiple decision structures – Switches
Operators
Reading flowcharts
Decision tables
Evaluating expressions
Computer decision structures Q & A

38 Objective 1 Study Guide


Ifs, elses, switches, operators, flowcharts, expressions…
If decision structures

An if condition (expression) can either evaluate to true or false.


If the condition evaluates to true, the code block or statement related to (inside of) the if condition will be
executed.
If the condition evaluates to false, the code block will not be executed.
If you use multiple statements inside the if block, use {} to open and close the code block.
If the code inside the if block is only one statement, you do not need to use {}.

int x = 1;
if (x == 0)
Console.WriteLine("x is equal to 0."); //one statement only

If (x>=0)

Console.WriteLine(“x is equal to 0”); //more than one statement

Console WriteLine(“x is also greater than 0”);

//if-else
if (x >= 0)
Console.WriteLine("x>=0");
else
Console.WriteLine("x<0");

if (x == 0)
Console.WriteLine("x = 0");
else if (x != 0)
Console.WriteLine("x!=0");

//if -else if -else


if (x < 0)
Console.WriteLine("x < 0");
else if (x > 0)
Console.WriteLine("x > 0");
else
Console.WriteLine(x = 0);

39 Objective 1 Study Guide


static int EvalIfElse()
{

bool cupFull = true;


bool sugarAdded = false;
int result = 0;

if (cupFull) //will evaluate to true, so if will be executed


{
if(sugarAdded) //will evaluate to false, so else will be executed
{
result = 1;
}
else
{
result = 2; //2 will be returned
}
}
else
{
result = 3;
}
return result;
}

This method will return 2. See the comments in the code.

40 Objective 1 Study Guide


If Exercises
Using an If
Create a new C# console application in Visual Studio and name it Ifs

This application will illustrate the following:


• prompt the user for input and capture input in variables
• the goto statement
• the if statement
• the if-else statement
• the if-elseif-else statement
• writing and calling a method with a return value and responding to the return value

Declare the following variables in the Program class, above the Main method:

class Program
{
static string username = "";
static string response = "";
static void Main(string[] args)
{
}
}

Add the following code to the Main method:

static void Main(string[] args)


{
Console.WriteLine("Welcome to Ifs!");
EnterName://this is a label
Console.WriteLine("Please enter your name: ");
username = Console.ReadLine();
//If: if username not entered, ask again
if (username == "")
goto EnterName; //return to EnterName
Console.ReadKey();
}

Press F5 to run and try out your application.

Still busy with the same project…

41 Objective 1 Study Guide


Adding and calling a method using If-else
Add the following method to the Program class, below the Main method:
static bool IfElse()
{
Console.WriteLine($"Hallo {username}, are you well today? (I can only handle
yes, so please answer yes!)");
response = Console.ReadLine();
//Even though you requested a yes, the user can still enter any other value,
which is handled by else
if (response == "yes")
{
Console.WriteLine("So happy to hear you are well!! Have an awesome day!");
return true;
}
else
return false;
}

Now add the following code to the Main method, to call the IfElse() method:
static void Main(string[] args)
{
Console.WriteLine("Welcome to Ifs!");
EnterName://this is a label
Console.WriteLine("Please enter your name: ");
username = Console.ReadLine();
//If: if username not entered, ask again
if (username == "")
goto EnterName; //return to EnterName

//If-else
if (IfElse() == false)
{
Console.WriteLine("Sorry I can only handle yes...");
}

Console.WriteLine("If i add more else's to my if, I can handle yes and no - so


let's try that..");

Console.ReadKey();
}

Still busy with the same project…

42 Objective 1 Study Guide


Adding and calling a method using If-elseif-else
Add the following method in your Program class below your IfElse() method:
static bool If_ElseIf_Else()
{
Console.WriteLine($"Hallo {username}, are you well today? (yes or no)");
response = Console.ReadLine();
if (response == "yes")
{
Console.WriteLine("So happy to hear you are well!! Have an awesome day!");
return true;
}
else if (response == "no")
{
Console.WriteLine("So sad to hear you are not well. Wishing you will get well soon!");
return true;
}
else //to make provision for something other than yes or no...
return false;

Now add the following code to the Main method, to call the If_ElseIf_Else() method:
static void Main(string[] args)
{
Console.WriteLine("Welcome to Ifs!");
EnterName://this is a label
Console.WriteLine("Please enter your name: ");
username = Console.ReadLine();
//If: if username not entered, ask again
if (username == "")
goto EnterName; //return to EnterName

//If-else
if (IfElse() == false)
{
Console.WriteLine("Sorry I can only handle yes...");
}

Console.WriteLine("If i add more else's to my if, I can handle yes and no - so


let's try that..");
Ifelseif:
if (If_ElseIf_Else() == false)
{
Console.WriteLine("Enter yes or no only - please try again...");
goto Ifelseif;
}
Console.ReadKey();
}

You have successfully completed and run, your Ifs app!

43 Objective 1 Study Guide


And here is the complete code for the Ifs app:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ifs
{
class Program
{
static string username = "";
static string response = "";
static void Main(string[] args)
{
Console.WriteLine("Welcome to Ifs!");
EnterName://this is a label
Console.WriteLine("Please enter your name: ");
username = Console.ReadLine();
//If: if username not entered, ask again
if (username == "")
goto EnterName; //return to EnterName
//If-else
if (IfElse() == false)
{
Console.WriteLine("Sorry I can only handle yes...");
}

Console.WriteLine("If i add more else's to my if, I can handle yes and no - so let's try that.");
Ifelseif:
if (If_ElseIf_Else() == false)
{
Console.WriteLine("Enter yes or no only - please try again...");
goto Ifelseif;
}
Console.ReadKey();
}

static bool IfElse()


{
Console.WriteLine($"Hallo {username}, are you well today? (I can only handle yes, so
please answer yes!)");
response = Console.ReadLine();
//Even though you requested a yes, the user can still enter any other value, which is
//handled by else
if (response == "yes")
{
Console.WriteLine("So happy to hear you are well!! Have an awesome day!");
return true;
}
else
return false;
}

static bool If_ElseIf_Else()


{
Console.WriteLine($"Hallo {username}, are you well today? (yes or no)");
response = Console.ReadLine();
if (response == "yes")
{
Console.WriteLine("So happy to hear you are well!! Have an awesome day!");
return true;
}
else if (response == "no")
{
Console.WriteLine("So sad to hear you are not well. Wishing you will get well soon! ");
return true;
}
else //to make provision for something other than yes or no...
return false;
}
}
}

44 Objective 1 Study Guide


Switches
In C#, a Switch is a selection statement which will execute a single case statement from the list of
multiple case statements based on the pattern match with the defined expression.

You can use a switch statement to replace an if-elseif or if-elseif-else statement:

static int EvalSwitch()


{

bool cupFull = true;


bool sugarAdded = false;
int result = 0;

switch (cupFull) //will evaluate to true


{
case true:
switch (sugarAdded)
{
case true: //will evaluate to false
result = 1;
break;
case false:
result = 2; //this result will be returned
break;
}
break;
case false:
switch (sugarAdded)
{
case false:
result = 3;
break;
case true:
result = 4;
break;
}
break;
}

return result;
}

The method will return 2.

45 Objective 1 Study Guide


Switch Exercise

Create a new C# console application in Visual Studio and name it Switches.

You are going to code a basic calculator. The user must enter one number, an operator (+, -, *, or /) and a
second number. The application will then calculate and output the answer to the console.

The app will illustrate the following:

• swithces
• TryParse
• using operators

In the Program class, below the Main method, first add the Calculate method:
static double Calculate(double no1, double no2, string op)
{
double answer = 0;
switch (op)
{
case "+":
answer = no1 + no2;
break;
case "-":
answer = no1 - no2;
break;
case "*":
answer = no1 * no2;
break;
case "/":
answer = no1 / no2;
break;
}
return answer;
}

46 Objective 1 Study Guide


Now add the following code to the Main method:
static void Main(string[] args)
{
double no1 = 0;
double no2 = 0;
string op = "";
string answer = "";
Console.WriteLine("Welcome to the basic calculator.");
EnterNo1:
/*Prompt user to enter 1st no, validate no &
capture value in no1 variable*/
Console.WriteLine("Please enter a valid number:");
if (!double.TryParse(Console.ReadLine().Trim(), out no1))
{
goto EnterNo1;
}

EnterOperator:
/*Prompt user to enter an operator, validate
operator and capture value in op variable*/
Console.WriteLine("Please enter one of the following operators: +, -, *, /");
op = Console.ReadLine().Trim();
if (op!="+" && op!="-" && op!="*" && op!="/")
{
goto EnterOperator;
}

EnterNo2:
Console.WriteLine("Please enter a valid 2nd number:");
if (!double.TryParse(Console.ReadLine().Trim(), out no2))
{
goto EnterNo2;
}
//Calculate and output answer:
answer = Calculate(no1, no2, op).ToString();
Console.WriteLine($"{no1} {op} {no2} = {answer}.");
Console.ReadKey();
}
Press F5 to run and test the application.

You have successfully completed and run, your Switches app!

47 Objective 1 Study Guide


And here is the complete code for the Switches app:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Switches
{
class Program
{
static void Main(string[] args)
{
double no1 = 0;
double no2 = 0;
string op = "";
string answer = "";
Console.WriteLine("Welcome to the basic calculator.");
EnterNo1:
/*Prompt user to enter 1st no, validate no &
capture value in no1 variable*/
Console.WriteLine("Please enter a valid number:");
if (!double.TryParse(Console.ReadLine().Trim(), out no1))
{
goto EnterNo1;
}

EnterOperator:
/*Prompt user to enter an operator, validate
operator and capture value in op variable*/
Console.WriteLine("Please enter one of the following operators: +, -, *, /");
op = Console.ReadLine().Trim();
if (op!="+" && op!="-" && op!="*" && op!="/")
{
goto EnterOperator;
}

EnterNo2:
Console.WriteLine("Please enter a valid 2nd number:");
if (!double.TryParse(Console.ReadLine().Trim(), out no2))
{
goto EnterNo2;
}
//Calculate and output answer:
answer = Calculate(no1, no2, op).ToString();
Console.WriteLine($"{no1} {op} {no2} = {answer}.");
Console.ReadKey();
}

48 Objective 1 Study Guide


static double Calculate(double no1, double no2, string op)
{
double answer = 0;
switch (op)
{
case "+":
answer = no1 + no2;
break;
case "-":
answer = no1 - no2;
break;
case "*":
answer = no1 * no2;
break;
case "/":
answer = no1 / no2;
break;
}
return answer;
}
}
}

49 Objective 1 Study Guide


Operators

Operator Description
== e.g., if(x==0) – Checks if the two operands are equal – returns true or false
!= e.g., if(x!=0) – Checks if the two operands are not equal – returns true or false
> e.g., if(x>0) - Checks if the left operand is greater than the right operand
< e.g., if(x<0) - Checks if the left operand is smaller than the right operand
>= e.g., if(x>=0) - Checks if the left operand is greater than, or equal to, the right
operand
<= e.g., if(<>=0) - Checks if the left operand is greater than, or equal to, the right
operand

Operator Description
Performs action on two operands, to the left and right of the operator.
* Multiplication e.g., result = x*2 – Multiplies two operands
/ Division e.g., result = x/2 – Divides two operands
% Modulus e.g., result = x%2 – Returns the remainder of two operands
+ Addition e.g., result = x+2 – Adds two operands
- Subtraction e.g., result = x-2 – Subtracts two operands
Performs action on one operand only.
++ Increment Increments the operand by 1
Prefix: First adds 1 before returning a result, e.g.:
int x = 1;
Console.WriteLine(x); // output: 1
Console.WriteLine(++x); // output: 2
Console.WriteLine(x); // output: 2

Postfix: First returns the variable, then adds 1, e.g.:


int x = 1;
Console.WriteLine(x); // output: 1
Console.WriteLine(x++); // output: 1
Console.WriteLine(x); // output: 2
Decrement -- Decrements the operand by 1 – Prefix and Postfix, same as for ++
+ Returns the value of its operand
- Computes the numeric negation of its operand.
Operator Precedence: *, /, % will be executed first, then + and -.

Operator Description
&& And e.g., if(x==0) && (y==0) – Both conditions will be evaluated and if both return true,
the statements in the if block will be executed.
|| or e.g., if(x==0) ||(y==0) – If either of the conditions returns true, the statements in the
if block will be executed.
! not e.g., if!(x==0)&&(y==0) – If the reverse of the outcome is true, the statements in
the if block will be executed.

Operator Description
= : Equal to assignment int x = 5;
+= : Addition assignment x += 2 is an equivalent of x = x + 2, returns 7
-= : Subtraction assignment x -= 2 is an equivalent of x = x – 2, returns 3
*= : Multiplication assignment x*-= 2 is an equivalent of x = x * 2, returns 10
/= : Division assignment x/= 2 is an equivalent of x = x / 2, returns 2
%= : Modulus assignment x%= 2 is an equivalent of x = x % 2, returns 1

50 Objective 1 Study Guide


By using a ternary operator, we can replace if-else statements:

int x = 1;

Console.WriteLine((x > 0) ? "x greater than 0" : "x less than or equal to 0");

▪ The condition expression will evaluate to either true or false.


▪ If condition evaluates to true, the result of the first expression after the ? will be returned.
▪ If the condition evaluates to false, the second expression after the : will be returned.

Operators Exercises
Create a new C# console application and name it Operators.

This application will be used to calculate price increases.

Add the following method to the Program class, underneath the Main method:

static void CalculateIncrease(decimal price)


{
if (price == 0)
price = 0;
else if (price > 0 && price <= 10)
price = price * 1.1m;
else if (price > 10 && price <= 20)
price += 10;
else if (price > 20 && price <= 50)
price -= 10;
else
price++;
Console.WriteLine($"New price is {price}.");

Now add the following code to the Main method:

static void Main(string[] args)


{
decimal price = 0.00m;
Console.WriteLine("Enter current price: ");
decimal.TryParse(Console.ReadLine(), out price);
CalculateIncrease(price);
Console.ReadKey();
}

Run and test your app.

You have successfully completed and run, your Operators app!

51 Objective 1 Study Guide


Flowcharts
and are two different ways of presenting the process of solving a problem.
- Algorithms consist of a set of steps for solving a particular problem.
- Flowcharts can be used to present algorithms graphically.
For the purposes of the ITS 305 exam, you should be familiar with the following flowchart symbols:

Let’s look at some Flowchart examples:

(extract from https://www.edrawsoft.com/algorithm-flowchart-examples.php)

Algorithm:
- Step 1: Read amount
- Step 2: Read years
- Step 3: Read rate
- Step 4: Calculate the interest with formula "Interest=Amount*Years*Rate/100
- Step 5: Print interest

Flowchart:

52 Objective 1 Study Guide


Q1. What value will be returned by
the algorithm, or what will the
X=20
output value be?

X>Y Answer: 100 (Z will be the output


Y=30
No value)

No
Yes Yes
Z=300 X= Z=100
Z=400
Y
Q2. What will the value of X be at
Return Z X=Z-Y output time of the algorithm?
X=Z+Y
Answer: 70 (Z-Y)

Start

Input x Input y
If x=70 and y=100, what would the
output of the flowchart be?
x>y
The output would be 100.
no
yes

Output x Output y

Stop

53 Objective 1 Study Guide


Decision tables
Decision tables are useful for presenting algorithms with large numbers of conditions and actions in a compact
and readable format.

In a decision table, conditions are usually expressed as true (T) or false (F).

This Decision table represents an algorithm for calculating discount:

Conditions Rule 1 Rule 2 Rule 3 Rule 4


Quantity < 10 T F F F
Quantity < 25 T T F F
Quantity < 50 T T T F
Quantity < 100 T T T T
Actions
Discount 5% 10% 15% 20%

(From: https://reqtest.com/requirements-blog/a-guide-to-using-decision-tables/)

Conditions Rule 1 Rule 2 Rule 3


Withdrawal amount <=Balance T F F
Credit granted - T F
Actions
Withdrawal granted T T F
**Notes – In the exam, no questions about Decision tables were asked.

54 Objective 1 Study Guide


Evaluating expressions
An expression is a sequence of one or more operands and zero or more operators that can be evaluated to a
single value, object, method or namespace.

static int EvalLogicalOr()


{
int x = 10, y = 20, z = 30, result = 0;
if (x <= y || z > x)
result = 10;
else if (x<=y||z<=x)
result = 20;
else
result = 30;

return result;
}
The answer is 10.
The conditional logical OR operator ||, also known as the "short-circuiting" logical OR operator, computes the
logical OR of its bool operands. The result of x || y is true if either x or y evaluates to true. Otherwise, the
result is false. If the first operand evaluates to true, the second operand is not evaluated, and the result of
operation is true. When the first if statement is evaluated, x <= y evaluates to true, so the returned result will
be 10.

static int EvalIfElse()


{
bool cupFull = true;
bool sugarAdded = false;
int result = 0;

if (cupFull)
{
if(sugarAdded)
{
result = 1;
}
else
{
result = 2;
}
}
else
{
result = 3;
}

return result;
}
The answer is 2.

if(cupFull) will return true, so if(sugarAdded) will be evaluated, which will return false. The result under the
else of the if(sugarAdded) statement will be returned, which will be 2.

55 Objective 1 Study Guide


Computer decision structures Q & A

Examples of the type of questions you can expect in the international exam from this
knowledge area in Objective 1.

(a>b) and (x<y)

What is the value of this expression if a=5, b=6, x=6 and y=7?

Answer: false

Conditional Logical Operators: The key to evaluating this statement lies in the "AND" operator (&& in
C#). Both expressions are evaluated: (a>b) as well as (x<y).

The first condition evaluates to false, therefore the whole expression evaluates to false.

When you execute the following code, what would the returned result be?

static int EvalLogicalOr()


{
int x = 10, y = 20, z = 30, result = 0;
if (x <= y || z > x)
result = 10;
else if (x<=y||z<=x)
result = 20;
else
result = 30;

return result;
}
Answer: 10

Create a new C# console app and name it EvalLogicalOr.

In the Program class, just below the closing curly bracket of the Main method, add the following code:
static int EvalLogicalOr()
{
int x = 10, y = 20, z = 30, result = 0;
if (x <= y || z > x)
result = 10;
else if (x<=y||z<=x)
result = 20;
else Code
result = 30;

return result;

56 Objective 1 Study Guide


}
In the Main method, add the following code:

Console.WriteLine("EvalLogicalOr returned {0}.", EvalLogicalOr().ToString());


Console.ReadKey();

The conditional logical OR operator ||, also known as the "short-circuiting" logical OR operator,
computes the logical OR of its bool operands. The result of x || y is true if either x or y evaluates to
true. Otherwise, the result is false.

If the first operand evaluates to true, the second operand is not evaluated, and the result of the
operation is true. When the first if statement is evaluated, x <= y evaluates to true, so the returned
result will be 10.

static int EvalSwitch()


{

bool cupFull = true;


bool sugarAdded = false;
int result = 0;

switch (cupFull)
{
case true:
switch (sugarAdded)
{
case true:
result = 1;
break;
case false:
result = 2;
break;
}
break;
case false:
switch (sugarAdded)
{
case false:
result = 3;
break;
case true:
result = 4;
break;
}
break;
}

return result;
}
Answer: 2

57 Objective 1 Study Guide


static int EvalSwitch()
{

bool cupFull = true;


bool sugarAdded = false;
int result = 0;

switch (cupFull) Code


{
case true:
switch (sugarAdded)
{
case true:
result = 1;
break;
case false:
result = 2;
break;
}
break;
case false:
switch (sugarAdded)
{
case false:
result = 3;
break;
case true:
result = 4;
break;
}
break;
}

return result;
}

Add the following code to the Main method:

Console.WriteLine("EvalSwitch returned {0}.",EvalSwitch().ToString());


Console.ReadKey();

The switch (cupFull) statement will return true, so the switch (sugarAdded) will be evaluated. The
value of sugarAdded is false, so the result returned will be 2.

58 Objective 1 Study Guide


Knowledge area 3
Identify the appropriate method for handling repetition
KNOWLEDGE AREA 3: CONTENTS

While
Do-While
For
For-each
Recursion
Evaluating code loops

59 Objective 1 Study Guide


While
The while loop repeatedly executes a block of statements until a specified Boolean expression evaluates to
false.
int i = 5;
while(i<=5)
{
Console.WriteLine("the value of i is {0}", i);
i++;
}

Do-While
The do-while loop repeatedly executes a block of statements until a specified Boolean expression evaluates to
false. The condition is tested at the bottom of the loop, so the loop will always execute once before evaluating
the condition.
do
{
Console.WriteLine("the value of i is {0}", i);
i++;
}
while (i <= 5) ;

For
The for loop combines the three elements of iteration into a more readable code:
• the initialization expression
• the termination condition expression
• the counting expression
for(int i=0;i<=5;i++)
{
Console.WriteLine("the value of X = {0}", X);
}

**For an example, refer to Question 2 & 3 in the Q & A

For-each
The for-each loop is an enhanced version of the for loop for iterating through collections, such as arrays and
lists.
int[] numbers = { 1, 2, 3, 4, 5 };
foreach(int i in numbers)
{
Console.WriteLine("The value of i is: {0}", i);
}

60 Objective 1 Study Guide


Recursion
Recursion is a programming technique that causes a method to call itself to compute a result.
public static int Factorial(int n)
{
if (n == 0)
return 1;
else
return n * Factorial(n - 1);
}

**For an example, refer to Question 4 in the Q & A

Breaking out of loops and jump statements

Statement Description
break The break statement terminates the closest enclosing loop or switch statement in
which it appears.
Control is passed to the statement that follows the terminated statement, if any, for
example:
class Program
{
static void Main()
{
for (int i = 1; i <= 100; i++) Code
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
Output:
1
2
3
4
Press any key to exit
For more information: https://docs.microsoft.com/en-us/dotnet/csharp/language-
reference/keywords/break

continue The continue statement passes control to the next iteration of the
enclosing while, do, for or foreach statement in which it appears, for example:
//Add this to the Main method of a Console App
for (int i = 1; i <= 10; i++)
{
if (i < 9)//only returns values from 9 - 10
{
continue;
}
Console.WriteLine(i);
}

61 Objective 1 Study Guide


Statement Description
Console.WriteLine("continue test ended");
Console.ReadKey();
Output:
9
10
For more information: https://docs.microsoft.com/en-us/dotnet/csharp/language-
reference/keywords/continue

goto The goto statement transfers the program control directly to a labelled statement.
A common use of goto is to transfer control to a specific switch-case label or the
default label in a switch statement.
The goto statement is also useful to get out of deeply nested loops.
Example:
Console.WriteLine("Welcome to Ifs!");
EnterName://this is a label
Console.WriteLine("Please enter your name: ");
username = Console.ReadLine();
//If: if username not entered, ask again
if (username == "")
goto EnterName; //return to EnterName
Refer to the If Exercises for a coding example with goto

return Terminates execution of the method in which it appears and returns control to the
calling method.
It can also return an optional value.
If the method is a void type, the return statement can be omitted.
Example:
class Program
{
static double CalculateArea(int r)
Code
{
double area = r * r * Math.PI;
return area;
//returns a double value to the calling code
//with the result of the area calculation
}

static void Main()


{
int radius = 5;
double result = CalculateArea(radius);
Console.WriteLine("The area is {0:0.00}", result);

// Keep the console open in debug mode.


Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output: The area is 78.54

62 Objective 1 Study Guide


Evaluating code – loops: Handling repetition Q & A

Examples of the type of questions you can expect in the international exam from this
knowledge area in Objective 1.

▪ For
▪ While
▪ Do-While
▪ For-each

Answer: Do-While

In a do-while loop the test is at the end of the structure, so it will be executed at least once.

int counter = 0;
Console.WriteLine("Printing all the uneven numbers from 0 to 100:");
for (int x = 0; x <= 100; x++)
{
if(x%2!=0)
{
counter++;
Console.Write("Hi There!");
}
}
Console.WriteLine("\nPrinted 'Hi There' to the Console {0} times", counter);
Console.ReadKey();

Answer: 50

Create a new console application in Visual Studio (C#). Copy the code into the Main() method and press Start.
The results will be as follows:

Printing all the uneven numbers from 0 to 100:

Hi There! HI There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi
There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi
There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi
There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi There!Hi
There!Hi There!Hi There!

Printed 'Hi There' to the console 50 times.

The % operator is the Remainder operator. In this case, the if statement (if(x%2!=0)
is used to get all uneven numbers in the loop between 0 and 100 (for (int x = 0; x <= 100; x++)).
Each time an uneven number is found, “Hi There” is printed to the console. It is printed 50 times.
\n is the new line character for C#.

63 Objective 1 Study Guide


int counter = 0;
for (int x=0; x<=10; x+=2)
{
counter++;
Console.WriteLine("Looping through the for loop {0} time", counter);
Console.WriteLine("The value of x is: {0}", x);
}
Console.ReadKey();

Answer: 6

Create a new console application in Visual Studio and paste the question code in the Main() method. Press the
Start button. You will get the following results:
Looping through the for loop 1 times
The value of x is: 0
Looping through the for loop 2 times
The value of x is: 2
Looping through the for loop 3 times
The value of x is: 4
Looping through the for loop 4 times
The value of x is: 6
Looping through the for loop 5 times
The value of x is: 8
Looping through the for loop 6 times
The value of x is: 10
The loop executed 6 times, starting at 0 (x=0) and incrementing by multiples of 2 (x+=2), ending at 10 (x<=10).

64 Objective 1 Study Guide


private static int Printer (int j)
{
for(var i=j;i>0;i=Printer(i-1) )
{
Console.Write(i);
}
return j;
}

A. Printer(2);

Answer: 211

Create a new C# console app in Visual Studio and name it Recursive_Loop.

Add a new method to the Program class, just after the Main method:

private static int Printer (int j)


{
for(var i=j;i>0;i=Printer(i-1) )
{
Console.Write(i);
}
return j;
}

Add the following code to the Main method:

Printer(2);

Console.ReadKey();

When you run the app, the console will return the following: 211

Another question can be asked, based on the same function:

B.

Answer: 2

Change the code in the Main method to the following:


static void Main(string[] args)
{
int retvalue = Printer(2);
Console.WriteLine("Return value of Printer(2): {0}", retvalue);
Console.ReadKey();
}
When you run the app now, the Console will return the following:

- the function returns 2

65 Objective 1 Study Guide


Knowledge Area 4
Error handling
KNOWLEDGE AREA 4: CONTENTS

Debugging and using the debugger


Exceptions
Handling exceptions with try, catch and finally
Throw
Error handling Q & A

! ! ! 

66 Objective 1 Study Guide


Debugging and using the debugger
Up to this point, when you have run an application in Visual Studio by pressing the F5 key, or pressing the
green Start button on the Toolbar, or by selecting Debug->Start Debugging on the menu bar, you have
been running your app with the Visual Studio Debugger attached.

The debugger provides many ways for you to see what your code is doing while running. Here are a few of
those ways and a description of each:

Debugger Description
functionality
Set a A breakpoint indicates where Visual Studio should suspend your running code so you can examine
breakpoint – the values of variables, the behavior of memory or whether a branch of code is reached.
F9 How?
With the Coding Window open, click in the left margin next to the line of code you want to examine.
For more details, see Set a breakpoint and start the debugger in the Visual Studio 2019
documentation.
Step into - While running your app, once the debugger has reached a breakpoint, press F11 to step into the
F11 code you want to examine on statement at a time.
The yellow arrow represents the statement on which the debugger paused:

Step over – When you are on a line of code that is a function or method call, you can press F10 (Debug > Step
F9 over) instead of F11.

F10 advances the debugger without stepping into functions or methods in your app code (the code
still executes).
Step into By default, the debugger skips over properties and fields, but the Step into Specific command allows
Specific you to override this behavior.
Right-click on a property or field and choose Step into Specific, then choose one of the available
options.
Step out Sometimes, you might want to continue your debugging session but advance the debugger all the
way through the current function.
Press Shift + F11 (or Debug > Step out).
This command resumes app execution (and advances the debugger) until the current function
returns.
Stop Press Shift+F5, or the red Stop Debugging button on the toolbar.
Debugging
Restart Restart your app quickly by pressing the Restart button in the debug toolbar (Ctrl + Shift +F5)

For more information on the debugger and debugging, visit First look at the Visual
Studio Debugger on Microsoft Visual Studio docs.

67 Objective 1 Study Guide


Exceptions
An exception is an unexpected error condition that occurs during program execution.

When an exception occurs, the runtime creates an exception object and throws it.
Unless you catch the exception, the program execution will terminate.
Exceptions belong to the System.Exception class or one of its derived classes, e.g.,
DivideByZeroException, FileNotFound Exception.
With unhandled exceptions, the exception will stop execution of the program.

Common Exceptions and the conditions under which you would throw them:

**Links to Microsoft docs, .Net Framework 4.8 provided for more information.

Exception Condition

ArgumentException A non-null argument that is passed to a method is invalid.

ArgumentNullException An argument that is passed to a method is null.

ArgumentOutOfRangeException An argument is outside the range of valid values.

DirectoryNotFoundException Part of a directory path is not valid.

DivideByZeroException The denominator in an integer or Decimal division operation is


zero.

DriveNotFoundException A drive is unavailable or does not exist.

FileNotFoundException A file does not exist.

FormatException A value is not in an appropriate format to be converted from a


string by a conversion method, such as Parse.

IndexOutOfRangeException An index is outside the bounds of an array or collection.

InvalidOperationException A method call is invalid in an object's current state.

KeyNotFoundException The specified key for accessing a member in a collection cannot


be found.

NotImplementedException A method or operation is not implemented.

NotSupportedException A method or operation is not supported.

ObjectDisposedException An operation is performed on an object that has been disposed.

68 Objective 1 Study Guide


Exception Condition

OverflowException An arithmetic, casting, or conversion operation results in an


overflow.

PathTooLongException A path or file name exceeds the maximum system-defined


length.

PlatformNotSupportedException The operation is not supported on the current platform.

RankException An array with the wrong number of dimensions is passed to a


method.

TimeoutException The time interval allotted to an operation has expired.

UriFormatException An invalid Uniform Resource Identifier (URI) is used.

69 Objective 1 Study Guide


Handling exceptions with try-catch-finally
You can gracefully handle exceptions in try-catch blocks:
Place the code that throws the exceptions inside a try block.
Place the code that handles the exception inside a catch block.
You can have more than one catch block for each try block to handle different types of exceptions.
A try block must have at least one catch block or one finally block associated with it.
The finally block is used in association with the try block. The finally block is always executed
regardless of whether an exception is thrown or not. The finally block is used for clean-up code.

Create a new C# console application and name it Exceptions.

Add the following code to the Main method in the Program class:

static void Main(string[] args)


{
int x = 0;
try
{
int y = 100 / x;
}
catch (ArithmeticException e)
{
Console.WriteLine($"ArithmeticException Handler: {e.Message}");
}
catch (Exception e)
{
Console.WriteLine($"Generic Exception Handler: {e.Message}");
}
finally
{
Console.ReadKey();
}

The console will return the following when you run the app:

70 Objective 1 Study Guide


Create a new C# console application and name it Exceptions.

Add the following code to the Main method in the Program class, and remember to add the using System.IO
using statement at the top of the coding window:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Exceptions2
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = null;
try
{
sr = File.OpenText(@"C:\data.txt");
Console.WriteLine(sr.ReadToEnd());
}
catch (FileNotFoundException fe)
{
Console.WriteLine(fe.Message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.ReadKey();
sr = null;
}

}
}
}
When you run your app, the console will return the following if the data.txt file does not exist on the C: Drive:

Create your own data.txt file on the C: drive with any data. The console should read the data and return it,
e.g.:

71 Objective 1 Study Guide


Throw
The throw statement is used to raise an exception or to rethrow exceptions in a catch statement.

using System;

public class NumberGenerator


{
int[] numbers = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

public int GetNumber(int index)


{
if (index < 0 || index >= numbers.Length) {
throw new IndexOutOfRangeException();
}
return numbers[index];
}
}

Re-throwing an exception means calling the throw statement without an exception object inside
a catch block. It can only be used inside a catch block.

using System;

public class Sentence


{
public Sentence(string s)
{
Value = s;
}

public string Value { get; set; }

public char GetFirstCharacter()


{
try {
return Value[0];
}
catch (NullReferenceException e) {
throw;
}
}
}

public class Example


{
public static void Main()
{
var s = new Sentence(null);
Console.WriteLine($"The first character is {s.GetFirstCharacter()}");
}
}
// The example displays the following output:
// Unhandled Exception: System.NullReferenceException: Object reference not set to an
instance of an object.
// at Sentence.GetFirstCharacter()
// at Example.Main()

72 Objective 1 Study Guide


Error handling Q & A

Examples of the type of questions you can expect in the international exam from this
knowledge area in Objective 1.

• conclude the execution of the code.


• break out of the error handler.
• execute code only when an exception is thrown.
• execute code regardless of whether an exception is thrown.

Answer: Execute code only when an Exception is thrown.

Use a try block around the statements that might throw exceptions. A catch block catches and handles try
block exceptions.

• To execute clean-up code and release resources.


• To execute code only when an exception is thrown.
• Code in a finally block is executed even if an exception is not thrown.
• To conclude the execution of the application.
• To break out of the error handler.

Answers

To execute clean-up code and release resources AND

Code in a finally block is executed even if an exception is not thrown

Explanation:

Code in a finally block is executed whether an exception is thrown or not. Use a finally block to release
resources, for example to close any streams or files that were opened in the try block.

• To move error handling to a separate thread.


• To stop the processing of code.
• To raise exceptions.
• To rethrow exceptions as a different type.

Answer: To raise exceptions AND To rethrow exceptions as a different type

Explanation:

The throw statement is used to raise an exception or to rethrow exceptions in a catch statement.

73 Objective 1 Study Guide


74 Objective 1 Study Guide
Appendix A – Next Steps towards passing the ITS 305 international exam
Next step:
Work through the following study guides:
ITS 305 Software Development Fundamentals Objective 2 Study Guide
ITS 305 Software Development Fundamentals Objective 3 Study Guide
ITS 305 Software Development Fundamentals Objective 4 Study Guide
ITS 305 Software Development Fundamentals Objective 5 Study Guide

Final step:
For a thorough Q&A-style preparation for the ITS 305 international exam
with more questions, answers and explanations, enroll for, and complete the
following Udemy course:

IT Specialist Software Development - ITS 305 Exam Prep tests

Visit the course page on Udemy and Claim your


discount coupon now!

75 Objective 1 Study Guide


Appendix B
Objective 1 Exercises reference list

Exercise VT1 – Setting up your development environment and


creating a new project
Exercise VT2 – Comments and other stuff

Add a bool variable Knowledge Area 1: Built-in Value Types


Add a byte variable
Add float, double and decimal variables
Add a char variable
Add a GUID variable
Declare and use an enum
Full code for exercise VT3

Knowledge Area 1: Date and Time Type


fundamentals

Enumerating the time zones that are available on a


system
Converting times between different time zones.

Switch exercises Knowledge Area 2: Switches

Evaluate Logical Or
Knowledge Area 2: Q & A
Evaluate Switch

Knowledge Area 3: Recursion

76 Objective 1 Study Guide


References
Source
ITS-305 home page & Objectives
https://home.pearsonvue.com/itspecialist/pdf/OD-305.pdf

Microsoft Learn
https://docs.microsoft.com/en-us/

Microsoft Docs C# Language Reference


https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/

Acknowledgements
 A big thank you to Saskia Brits for her editing expertise and design tips.
 A big thank you to my family for their support, assistance and patience.
 A big thank you to Microsoft & Pearson for opportunities created by their technologies and
products for so many people.
 Thanks, praise and honor to God for all His blessings!

77 Objective 1 Study Guide


One step
closer!!!

78 Objective 1 Study Guide

You might also like