CS Software Development Made Easy Objective 1 Core Programming Study Guide (1) - 2
CS Software Development Made Easy Objective 1 Core Programming Study Guide (1) - 2
Sonia Cross
Sold to
[email protected]
OBJECTIVE 1 STUDY GUIDE: CONTENTS
Introduction
Appendix A: Next steps towards passing the ITS 305 international exam
References
Acknowledgements
Software Developer
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.
Review questions per knowledge area, with answers, explanations and practical application in code
where required.
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!
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.
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 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.
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 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).
STACK HEAP
A variable can be defined as a placeholder for a value of a certain type, for example:
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;
}
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.
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;
}
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
Professional and Enterprise will be trials only, but the Community edition is free.
Once the project is created, your screen should look as follows (I named my project Types1):
Expand the Main method by placing your cursor inside the curly brackets {} of the Main method and pressing
enter:
✓ 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.
✓ 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
✓ Add multiline comments by prefixing the first line you want to place in comments with /* and ending
the last line with */
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:
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!
//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);
//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:
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.
Press F5 or Start again. Your console window will display the following:
//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:
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.
//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);
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!
namespace ReferenceTypes
{
class Program
{
static void Main(string[] args)
{
string firstname = "Sonia";
string surname = "Cross";
Console.ReadKey();
}
}
}
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.
//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();
}
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!
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!
In the .Net Framework, provision for working with dates are made with the following structs:
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();
}
Press F5, or the Start button on the Standard toolbar, or Debug -> Start Debugging on the Menu bar to run the
app.
Add another method to the Program class of your previous exercise to illustrate DateTimeOffset:
Add a method call to the Main method of the Program class after the WorkWithDateTime method call:
Press F5, or the Start button on the Standard toolbar, or Debug -> Start Debugging on the Menu bar to run the
app.
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:
Add the following method call to the Main method in your WorkingWithDates app:
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:
Add the following method to the Program class in your WorkingWithDates console app:
Add the following method call to the Main method in your WorkingWithDates app:
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:
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:
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:
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:
Add the following method to the Program class in your WorkingWithDates console app:
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:
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:
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:
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.
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;
If decision structures
Multiple decision structures – Switches
Operators
Reading flowcharts
Decision tables
Evaluating expressions
Computer decision structures Q & A
int x = 1;
if (x == 0)
Console.WriteLine("x is equal to 0."); //one statement only
If (x>=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");
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)
{
}
}
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.ReadKey();
}
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();
}
return result;
}
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.
• 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;
}
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.
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();
}
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
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
int x = 1;
Console.WriteLine((x > 0) ? "x greater than 0" : "x less than or equal to 0");
Operators Exercises
Create a new C# console application and name it Operators.
Add the following method to the Program class, underneath the Main method:
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:
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
In a decision table, conditions are usually expressed as true (T) or false (F).
(From: https://reqtest.com/requirements-blog/a-guide-to-using-decision-tables/)
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.
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.
Examples of the type of questions you can expect in the international exam from this
knowledge area in Objective 1.
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?
return result;
}
Answer: 10
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;
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.
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
return result;
}
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.
While
Do-While
For
For-each
Recursion
Evaluating code loops
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-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);
}
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);
}
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
}
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:
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!
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#.
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).
A. Printer(2);
Answer: 211
Add a new method to the Program class, just after the Main method:
Printer(2);
Console.ReadKey();
When you run the app, the console will return the following: 211
B.
Answer: 2
! ! !
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.
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
Add the following code to the Main method in the Program class:
The console will return the following when you run the app:
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.:
using System;
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;
Examples of the type of questions you can expect in the international exam from this
knowledge area in Objective 1.
Use a try block around the statements that might throw exceptions. A catch block catches and handles try
block exceptions.
Answers
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.
Explanation:
The throw statement is used to raise an exception or to rethrow exceptions in a catch statement.
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:
Evaluate Logical Or
Knowledge Area 2: Q & A
Evaluate Switch
Microsoft Learn
https://docs.microsoft.com/en-us/
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!