C# Programming Book S2
C# Programming Book S2
A Basic Introduction to
Programming
Third Edition
[ii]
© CUT 2023
C# A Basic Introduction to Programming 2
PREFACE
Programming languages have come a long way in terms of being easy to learn and
understand. C# is a versatile programming language, and after learning it, you can
apply your skills to a variety of things. With C#, .NET, and Visual Studio, you can build
an endless variety of applications, from web apps to mobile apps, REST APIs, and
more. In this book, we will cover the basics to get you started. We will look at
procedural (code that executes line for line of code in order) and selection
programming (code that can decide if a condition is true or false and follow a certain
path of code) in C#. (Angela Stringfeild, 2017)
We will continue in this book 2 with Loops, Arrays, and Introduction of Files.
[iii]
© CUT 2023
C# A Basic Introduction to Programming 2
COPYRIGHT
Copyright © 2023 - Mr AD van der Walt Author Mr AD van der Walt. All rights reserved.
This publication is protected by Copyright, and permission should be obtained from
the author prior to any prohibited reproduction, storage in a retrieval system, or
transmission in any form or by any means, electronic, mechanical, photocopying,
recording, or likewise.
[iv]
© CUT 2023
C# A Basic Introduction to Programming 2
CONTENTS
COPYRIGHT ..............................................................................................................iv
CONTENTS ............................................................................................................... v
Unit 1 ...................................................................................................................... 2
1.2.1. WHILE LOOP ......................................................................................... 2
1.2.4. DO WHILE .............................................................................................. 6
1.2.5. IMPLEMENTING LOOPS ....................................................................... 8
1.2.6. CHAPTER 1 – UNIT 1: SUMMARY ...................................................... 11
1.2.7. EXERCISES & HOMEWORK – CHAPTER 1 - UNIT 1 ........................ 12
CHAPTER 1: C# LOOPS ......................................................................................... 14
Unit 2 .................................................................................................................... 14
1.2.1. FOR LOOP ........................................................................................... 14
1.2.8. CHAPTER 1 – UNIT 2: SUMMARY ...................................................... 21
1.2.9. EXERCISES & HOMEWORK – CHAPTER1 - UNIT 2 ......................... 21
CHAPTER 2: ARRAYS ............................................................................................ 24
Unit 1 .................................................................................................................... 24
2.1.1. ARRAYS ............................................................................................... 24
2.1.2. DECLARING AN ARRAYS AND POPULATING .................................. 25
2.1.3. HOW AN ARRAY CAN REPLACE NESTED DECISIONS ................... 26
2.1.4. USING CONSTANTS IN ARRAYS ....................................................... 27
2.1.5. TYPES OF C# ARRAYS:...................................................................... 29
2.1.6. CHAPTER 2 – UNIT 1: SUMMARY ...................................................... 30
2.1.7. EXERCISES & HOMEWORK – CHAPTER 2 - UNIT 1 ........................ 31
CHAPTER 2: ARRAYS ............................................................................................ 34
[v]
© CUT 2023
C# A Basic Introduction to Programming 2
Unit 2 .................................................................................................................... 34
2.2.1. SEARCHING ARRAYS......................................................................... 34
2.2.2. SORTING ARRAYS ............................................................................. 37
2.2.3. CHAPTER 2 – UNIT 2: SUMMARY ...................................................... 39
2.1.8. EXERCISES & HOMEWORK – CHAPTER 2 - UNIT 2 ........................ 40
CHAPTER 3: ERROR HANDLING ........................................................................... 42
[vi]
© CUT 2023
C# A Basic Introduction to Programming 2
LIST OF FIGURES
Figure 1.1.1: Output of the while loop in the quick example. ...................................... 4
Figure 1.1.2: Output of the while loop with a sentinel value. ...................................... 5
[vii]
© CUT 2023
C# A Basic Introduction to Programming 2
OVERVIEW
UNIT 1: Arrays
• Arrays in C#
• How an array can replace nested decisions
• Using constants with arrays
[viii]
© CUT 2023
C# A Basic Introduction to Programming 2
• Try Catch
Additional Exercises
[ix]
© CUT 2023
C# A Basic Introduction to Programming 2
LIST OF ANNEXURES
[x]
© CUT 2023
C# A Basic Introduction to Programming 2
OBJECTIVE
EXERCISE
HOMEWORK
[xi]
© CUT 2023
C# A Basic Introduction to Programming 2
CHAPTER 1: C# LOOPS
Unit 1
OBJECTIVES:
When the loop's condition is true, C# executes the code inside the loop's body. It starts
with the first statement between braces ({ and }), and then works its way down through
all the loop's code. After all code inside the loop ran, C# arrives at the loop's closing
brace (}). It then moves back up to the while loop header and tests the condition again.
If the loop's condition still evaluates to true, code inside the loop executes again. This
process goes on until either the Boolean condition tests false or when we exit the loop.
CUT 2023
[2]
C# A Basic Introduction to Programming 2
To declare a while statement, you start with the keyword while and then in brackets
you add your condition (Remember as long as the condition is true the loop will repeat).
Then you have the start { and the stop } in this loop structure. Between the start and
stop will be the code that you want to repeat as well as the code that will change the
condition to stop the loop when required. We will now look at a program that will run
10 times and print out the 2 times table.
As can be seen in the above example code, we have a counter variable (Remember
that your counter variable can have any name). This counter variable will be used as
the value that will change and stop the loop. This counter variable we call in
programming the control variable. The above program will repeat TEN (10) times as
CUT 2023
[3]
C# A Basic Introduction to Programming 2
the counter is increased with every repetition. You will notice that the counter is
incremented with every repetition at the end of the loop. This will ensure that the
counter will stop after TEN (10) times. You will notice the answer variable that will be
used to do the calculations and then print this calculation.
READ CAREFULLY> You will notice in this calculation we made use of the counter
to do the calculation. This is a clever way to make use of the counter variable as the
value will increase with each repetition and can be used for calculations without
affecting the counter or the loop condition. Remember to never change the counter
variable when using it in calculations. The counter only needs to change as set out to
change the condition of the loop.
In the above figure the counter value was multiplied with the value of 2 and the answer
was printed to the console. When the counter variable value reached 9, the loop would
have repeated 10 times as the counter variable started at 0 when it was declared.
CUT 2023
[4]
C# A Basic Introduction to Programming 2
It can be seen in the above sample code that the user has control over the loop and
can decide how many times the loop will repeat. If the user enters yes when prompted,
the while loop will repeat. Before the loop starts the user is prompted if they would like
to continue or not by entering yes or no. The sentinel variable userInput is initialised
to no and as can be seen in the condition of the while loop, while userInput IS NOT
equal to no the loop will keep repeating. It is important to note that the user must be
prompted before the loop ends, this input will determine as the loop reaches the
condition again if the loop will repeat or not.
CUT 2023
[5]
C# A Basic Introduction to Programming 2
It can be seen in figure 1.2 that if the user input yes, the loop will continue to repeat.
Only when the user enters no the loop exits and wait for a key press. Note when the
while loop is created the programmer can decide what the condition will be and what
the user needs to enter to continue or stop. In this example we used yes and no.
Lastly and most important, a while loop will only execute if the condition is true. Thus,
if the condition is false when the program starts the loop will never executes and will
skip to the code after the loop. We will now look at a DO WHILE loop where this loop
will always execute at least once as the condition is only tested at the end of the loop.
1.1.4. DO WHILE
The do-while loop starts with the do keyword followed by a code block and a boolean
expression with the while keyword. The do while loop stops execution exits when a
boolean condition evaluates to false. Because the while(condition) specified at the end
of the block, it certainly executes the code block at least once.
The do and while keyword is used to create a do...while loop. It is like a while loop,
however there is a major difference between them. In while loop, the condition is
checked before the body is executed. It is the exact opposite in do...while loop, i.e.,
condition is checked after the body is executed. Therefore, the body of do...while loop
will execute at least once irrespective to the test-expression. (Anon., n.d.)
do
{
// body of do while loop
}
while (test-expression);
CUT 2023
[6]
C# A Basic Introduction to Programming 2
In the next sample code, we will make use of a do while loop where we will request
the user to enter their name, remember the condition will only be tested after the loop
executed at least once. We will then print the user’s name and once again ask the
question that the user enters their name OR the letters ZZZ if they want to exit,
You will note that the user cannot prevent the loop to execute, and it must run at least
once before the loop condition is tested again. Even though we have a while and do
while loop, the programmer will decide which one of the two loops will be used for a
specific part of the program’s code. It will depend if this part of code must be executed
at least once before the condition is tested (do while loop) or be tested before the loop
is executed (while loop).
In most cases the while loop is more popular than the do while, and the programmer
only needs to decide if the while loop will be a counter-controlled loop or a sentinel
value loop. Loops are used in programmes where we want specific lines of code to
repeat and the number of times will depend on what the condition was set for these
loops. Loops are most used where a functionality must repeat, or the user must input
data more than once.
CUT 2023
[7]
C# A Basic Introduction to Programming 2
We will now look at a program which will register new-born infants. This program will
repeat until the official or user chooses the exit menu option.
• Housekeeping
o MAIN MENU
• DetailLoop
o CHECK user inputs and call sub methods to capture registration information
of the new-born.
o Note to generate a Birth Number
• Finishup
o Provide an ending message and allow the user to press any key to exit the
program.
• Use Global Variables
• Recommended variables for capturing: BabyNames, BabySurname, BirthNumber,
Adress, ContactNum and Email.
• UseConstants
The variables needed for this program can be seen in the code below:
The House Keeping method code below will be used to direct the user’s options made
in the Main Menu Method code.
CUT 2023
[8]
C# A Basic Introduction to Programming 2
The Main Menu method will print the main menu and accept an input from the user.
This method will also verify if the Menu number entered is correct. Not if the user does
not enter 1, 2 or 3 the program will stay in a loop until the user do.
CUT 2023
[9]
C# A Basic Introduction to Programming 2
If the user chooses menu item number 1 the Register New Baby method will be called,
and the program will confirm if the user wants to capture a new Baby detail. The reason
for this is because much data will be requested, and this gives the user a chance to
abort the capture of details before it starts.
Lastly the program tests if the user wants to enter a new registration.
CUT 2023
[10]
C# A Basic Introduction to Programming 2
When the user chooses menu items 2 in the main menu the program will print the
registration of the new infant entered.
In this unit we learned how to implement a while or a do while loop. We have seen
code that’s inside the loop can be executed many times depending on the condition of
the loop. The figure 1.3 below summarises the differences between the two types of
while loops.
CUT 2023
[11]
C# A Basic Introduction to Programming 2
Exercise 1.1:
Write a program that will allow the user to guess a colour name and the color will
printed as background colour with a congratulation message. If the user guesses the
correct colour the program will print “You guessed the correct colour which is ___”.
There are only three colours. RED, BLUE, and GREEN. The program will repeat the
question until the user enters the words EXIT. Program Details:
• Use Methods!
o houseKeeping
▪ MAIN MENU of the program
o detailLoop
▪ While Loop that Check if the user wants to exit
▪ CHECK the users input and call a colour method or case in a switch.
o finishUp
▪ Exit the program and waits for a key press.
o Use Global Variables
o Use Constants
CUT 2023
[12]
C# A Basic Introduction to Programming 2
OUTPUTS:
CUT 2023
[13]
C# A Basic Introduction to Programming 2
CHAPTER 1: C# LOOPS
Unit 2
FOR loops
OBJECTIVES:
The FOR keyword indicates a loop in C#. The for loop executes a block of statements
repeatedly until the specified condition returns false. If an expression evaluates to true,
then it will execute the loop again; otherwise, the loop is exited. (C# for Loop, June 17
2022)
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times. The syntax of a for loop in C# is
• The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop does not execute, and flow of control jumps to the
next statement just after the for loop.
CUT 2023
[14]
C# A Basic Introduction to Programming 2
• After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after
the condition.
• The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again testing for a
condition). After the condition becomes false, the for loop terminates. (Anon., 2022)
CUT 2023
[15]
C# A Basic Introduction to Programming 2
It starts, in the first segment by either declaring or specifying a counting variable. This
is called the iterative variable and it is used for that purpose. This is the variable which
counts how many times the computer has printed to the screen. It has become practice
to name this variable counter, which stands for iterator.
The next section of the FOR loop declaration is the boolean expression. This boolean
expression acts the same as it does in the while loop, ultimately this is going to
determine whether the code inside the loop gets executed on each iteration. Most of
the time this boolean expression is going to be checking the value of the iterative
variable (counter) against some other value. Thus, this is the condition of the FOR
loop. (Anon., 2022)
Finally, the last section in the FOR loop declaration is a piece of code which gets
executed at the end of each iteration. 99% of the time this is either going to increment
(add to) or decrement (subtract from) the iterative variable.
Inner loops should not write to the iteration variables of the enclosing loop. If an inner
loop changes the iteration variable of the enclosing loop this is normally because the
programmer mistyped the iteration variable of the inner loop. If this is the intended
behaviour, then this is an example of bad practice. Loops should be designed so that
each loop controls its own iteration. Nested loops where iteration is shared between
loops are more difficult to understand and maintain. (stackOverflow, January 2020)
A nested loop is a loop within a loop, an inner loop within the body of an outer one.
How this works is that the first pass of the outer loop triggers the inner loop, which
CUT 2023
[16]
C# A Basic Introduction to Programming 2
executes to completion. Then the second pass of the outer loop triggers the inner loop
again. This repeats until the outer loop finishes. Of course, a break within either the
inner or outer loop would interrupt this process.
The above nested FOR loops is making use of the counter of the outer loop to control
the condition of the inner loop. The outer loop prints an empty line for every repetition
and the inner loop prints on a line counter2 value and a space after it.
When this program runs, the code in the inner loop will repeat the amount of the
counter1 variable as its incremented with every repeat. It worth mentioning that each
time the outer loop repeats the inner loop counter will be reset to 0. Thus, as the
counter 1 increases the more the inner loop will repeat as counter 1 is the condition of
the for loop. On the next page you can see the output of this program. Remember the
outer loop is only printing “go to next line” by using a blank Console.WriteLine(); The
inner loop is the one that is printing the numbers below.
CUT 2023
[17]
C# A Basic Introduction to Programming 2
There is different types of Loops and we will give a brief comparison of each as they
are were explained in this chapter 1.1.2 and 1.1.3.
Definite loop
A definite Loop Executes a predetermined number of times. These loops make use of
a Counter-controlled Variables. Mainly where the condition is determined by a fixed
value. For example:
CUT 2023
[18]
C# A Basic Introduction to Programming 2
int counter = 0;
while (counter < 10)
{
Console.WriteLine(“Hello Definite Loop”);
counter++;
}
In the above code the loop will run 10 times. Not less or more, there is a fixed value
10. Remember that the counter must be incremented with each repeat.
Indefinite loop
An indefinite loop repeats a different number of times each time the program executes.
The user decides how many times the loop executes. Thus, an input from the user will
determine if the loop will repeat. For example:
In the above code a control variable will determine if the loop will repeat and this control
variable can only be changed by the user. It is important to note that the control
variable is initialised before the loop starts and then before the loop reaches the end
the user gets another chance to change the control variable.
CUT 2023
[19]
C# A Basic Introduction to Programming 2
Infinite loop
An infinite loop repeats forever and has no end. In situations like these the control
variable is never changed or incremented. This is a common fault, and the result will
seem like the program has frozen, where a loop is sometimes in an infinite repeat. For
Example:
Scenario 1:
int counter = 0;
The loop above will run forever and will not stop, due that the counter is not
incremented.
Scenario 2:
The loop above will run forever and will not stop, due that the user is not prompted to
change the userInput to a Y.
CUT 2023
[20]
C# A Basic Introduction to Programming 2
In this chapter we investigated FOR loops, and learned that the declaration consists
of the counter, condition and incrementor. This type of loop is a definite loop and will
repeat for a certain amount of times depending on the condition of the counter.
We have learned about nested loops and where we can have an outer loop and inner
loops. The inner loop will always finish it’s repeats and then the outer loop will repeat
once more. This brings us to the end for loops in C# and remember loops can be
joined and used inside each other in the code. The next Chapter will look at Arrays.
Exercise 2.1:
Scenario: Nescafe Africa has contacted your programming company to assist them
to program their vending machine to have 2 choices when selecting coffee. Once size
is 250ml and the second is 500ml.
There will be a Main Menu: (The program will check that the user can only enter 1,2
or 3. Else re-prompt.
• If the user has chosen option 1 the machine will dispense 250ml coffee and
draw a small cup on the screen.
• If the user has chosen option 2 the machine will dispense 500ml coffee and
draw a large cup on the screen.
CUT 2023
[21]
C# A Basic Introduction to Programming 2
You may use While or For Loops. Nested Loops will be used.
The outside of cup is Gray and coffee inside cup is colour dark yellow.)
Console.ForegroundColor = ConsoleColor.DarkYellow;
Button1: Button2:
ONLY LOOPS AND SINGLE CONSOLE.WRITE OR WRITELINES MAY BE USED IN THIS PROGRAM.
CUT 2023
[22]
C# A Basic Introduction to Programming 2
CUT 2023
[23]
C# A Basic Introduction to Programming 2
CHAPTER 2: ARRAYS
Unit 1
ARRAYS
OBJECTIVES:
2.1.1. ARRAYS
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific element
in an array is accessed by an index. All arrays consist of contiguous memory locations.
The lowest address corresponds to the first element and the highest address to the
last element.
CUT 2023
[24]
C# A Basic Introduction to Programming 2
You can assign values to the array at the time of declaration, as shown:
string[] name = {“Bongani", ”Tlhokomelo", "Liyanda", “Karabo", "Mosele"};
Declare and populate after declared (Method we will use in this book)
Method 3:
CUT 2023
[25]
C# A Basic Introduction to Programming 2
It can be seen on the previous page how the FOR loop was used to populate the name
Array. We are making use of a FOR loop because we know how many elements
(Items) can be stored in the array. The FOR loop’s counter will be used to set the
position in the array to store a ReadLine that is been captured from the console. With
every loop the counter becomes one more and thus changing the position of the array
element to save the next input.
Normal Variables:
string idNum1, idNum2, idNum3, idNum4, idNum5, idNum6, ......idNum150;
From the above we can see to declare 150 variables and capturing the data line by
line code 150 times will be a tedious job. If the same program will be used for a census,
how will you capture 55 million people’s data. Declare 55 Million variables and request
input 55 million times. This is unpractical and there must be a better way?
CUT 2023
[26]
C# A Basic Introduction to Programming 2
Indeed, if you use arrays instead of normal variables the coding will not be much more
than a few lines and can be adjusted to any amount of number without creating more
lines of code. Let’s investigate this now and repeat the previous approach but use
arrays.
Array Variables:
string[] idNum = new string[150];
With the above declaration no matter how many id numbers there will be, you only
need to adjust the number of string arrays to create.
It can be seen from the above code, it doesn’t matter how many id numbers needs to
be captured, the programmer only needs to adjust the amount of times the FOR loop
will repeat. With the use of an array and then using a FOR loop to populate, the amount
of data that needs to be captured will not increase the lines of code.
With the same code above, we can capture millions id numbers and the code will stay
the same amount and only the array size and the number of repeats in the FOR loop.
CUT 2023
[27]
C# A Basic Introduction to Programming 2
With the information provided on the previous page, we can now declare a variable
that will accept a number as an input which will determine the number of names that
can be stored in the array. We will declare an integer variable named amount and
then request the user to enter a number on how many names they wish to capture.
int amount = 0;
Console.WriteLine("How many names would you like to enter");
amount = Convert.ToInt32(Console.ReadLine());
string[] name = new string[amount];
When the above code is executed, it can be seen the value the user will enter will
create the size of the array. Thus, after this the value of the array cannot change.
There is also another option how to make use of a constant in arrays. Let’s have a
look…
In the above code a constant integer variable amount is declared and initialized to 50.
As the program continues the value which is the size of the array cannot change and
will act as a constant. As the program continues, the user can now populate 50 names
but let’s say the number of names must be more, then it is as simple as upgrading the
program. But with this approach will the first approach not be better? Where the user
can decide how many names can be captured?
It all depends on the program specifications and ultimately what the client wants in the
program. Lastly another method of having constant arrays will be to declare an array
and populate it and the values that is initialised must not change, thus constants.
Interesting enough when creating an array that must be a constant, we do NOT use
the keyword const. We will use the keyword readonly, let’s see how this declaration
will look like.
CUT 2023
[28]
C# A Basic Introduction to Programming 2
It can be seen from the array above that all names of the months of the year has been
populated at initialization level and that the array is set as read only. Thus, nothing can
be written to this array and data can only be read from this array. This can be used
when the user subscribes or need to enter their date of birth and can then easily select
one of the array values for their birth month.
1. Single-Dimensional Array:
The single-dimension array contains only one row of data, hence the data element
stored in the array can be accessed using a numeric index like 0, 1, 2, etc. Like
covered in this chapter.
2. Multidimensional Array:
The multidimensional array contains more than one row to store the data, hence its
index will be two numbers in pair, one identifying the row and one for the column. This
type of array contains the same length of elements in each row hence, it is also known
as a rectangular array. This will be covered next year in the subject code SOD.
(Programming, 2 September 2022)
3. Jagged Array:
It is the array whose elements are also arrays and of any dimension and size. It is also
known as the array of arrays. Its elements are of reference types and are initialized to
null. Note: The elements of a jagged array must be initialized before they are used.
This will be covered next year in the subject code SOD. (Anon., 26 Oct 2021)
CUT 2023
[29]
C# A Basic Introduction to Programming 2
In C#, an array index starts at zero. That means the first item of an array starts at the
0th position. The position of the last item on an array will the total number of items - 1.
So, if an array has 3 items, the last 3rd item is in 2nd position.
Arrays are certainly not unique to C#, in fact just about every other programming and
scripting language preceding the introduction of C# provided support for arrays. An
array allows a collection of values of the same type to be stored and accessed via a
single variable. In the next unit we will look at sorting an Array and more.
CUT 2023
[30]
C# A Basic Introduction to Programming 2
Your client in the South African New-born Online Registrations Unit, requires a
registration program to capture information to register a New-born Baby. The Program
must also be able to print all Birth Certificates captured.
Program Details:
CUT 2023
[31]
C# A Basic Introduction to Programming 2
The Program will keep on capturing New-born Registration up to 500 or when the user
says No.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CUT 2023
[32]
C# A Basic Introduction to Programming 2
CUT 2023
[33]
C# A Basic Introduction to Programming 2
CHAPTER 2: ARRAYS
Unit 2
OBJECTIVES:
Linear search or sequential search is a method for finding a target value within a list.
It sequentially checks each element of the list for the target value until a match is found
or until all the elements have been searched. Sometimes called a sequential search,
it uses a loop to sequentially step through an array, starting with the first element. It
compares each element with the value being searched for and stops when either the
value is found, or the end of the array is encountered. If the value being searched for
is not in the array, the algorithm will search to the end of the array.”
In this example we will store all nine (9) province names of South Africa in an array.
The user will be allowed to enter a name and the program will search for the name in
the array. If found a message will be given that it has been found. If it has not been
found the user will be informed and return to the main menu. The complete program
will be added to the end of this book as an Appendix.
CUT 2023
[34]
C# A Basic Introduction to Programming 2
searchValue = Console.ReadLine();
nameSearch = searchValue.ToUpper();
The value of the user will be put in a local variable (searchValue) and then some
optional code is performed by taking whatever the user entered and making it upper
case. Thus, if the user entered Free State, the code .ToUpper will save the name
entered by the user in the global variable (nameSearch) as FREE STATE. This helps
to search the array where all values in the array is uppercase and then the search
value is also uppercase. No matter how the user used upper and lower case. This will
avoid a lot of failed searches where the value was correct but not all the letters where
upper or lower as it should have been.
flagFound = false;
It can be seen from the above code that the value provided from the user will be tests
against each element in the array. But it is crucial to take note that when the items (in
this case name) in the array has been found that the Boolean flag is set to true and
the counter of the FOR loop has been set to maximum (9) to ensure the loop does not
repeat anymore.
CUT 2023
[35]
C# A Basic Introduction to Programming 2
The flag that is set to true will be used in the code later and either perform feedback
to the user if the name was found or return the user to the main menu to try a new
search again.
• Using the flag to proceed to either turn to main menu or inform user of a successful
found in the search.
if(flagFound == true)
{
Console.WriteLine(" Search has been completed. Press any key for feedback");
Console.ReadKey();
Console.Clear();
Feedback();
}
else
{
Console.WriteLine("Search has been completed. Your input has not been found.");
Console.WriteLine("Press any key to return to main menu.");
Console.ReadKey();
Console.Clear();
}
With the code above if the flag was set to true as on the previous page this will happen
if the user’s search word was found in the array, the Feedback method will be called.
This method will inform the user that the search was successful and return to the Main
Menu, else the program will inform the user that search was not successful, and the
method will end and return to the main menu.
To conclude, if you need to do a search, make use of a loop and search through the
array. If you find for what you are searching for, create a flag that will indicate that the
search item was found and stop the loop. Then when the loop is stopped you can
inform the user that you found the item in the search. Make use of a selection
statement in the loop to determine if the item has been found or not. Thus, you will use
the Boolean flag to be set to true if found or false if not found.
CUT 2023
[36]
C# A Basic Introduction to Programming 2
Console.WriteLine("=========================================");
Console.WriteLine(" LIST OF UNIVERSITIES OF TECHNOLOGIES ");
Console.WriteLine();
Console.WriteLine("Abbreviation ");
Console.WriteLine("=========================================");
Console.WriteLine();
It can be seen from the above code that if you want to sort an Array in C# you will use
the code Array.Sort() and in the brackets you will enter the name of the array which
was declared to sort this array.
• Let’s see how this program looks like when its running.
CUT 2023
[37]
C# A Basic Introduction to Programming 2
In the above figure the current arrangement inside the array has been printed to the
screen. Thus element 0 to 5 has been printed and the contents is not in alphabetical
order. The program will now continue and sort the array and print again.
It can now be seen after the array has been sorted and printed again the abbreviations
has been reordered in the array and is now in an alphabetical order.
CUT 2023
[38]
C# A Basic Introduction to Programming 2
Here, <baseType> may be any variable type, including the enumeration and struct
types you’ve seen in this chapter. Arrays must be initialized before you have access
to them. You can’t just access or assign values to the array elements like this:
int[] myIntArray;
myIntArray[10] = 5;
Arrays can be initialized in two ways. You can either specify the complete contents of
the array in a literal form or specify the size of the array and use the new keyword to
initialize all array elements. Specifying an array using literal values simply involves
providing a comma-separated list of element values enclosed in curly braces:
int[] myIntArray = { 5, 9, 10, 2, 99 };
OR
Arranging the array's elements from largest to smallest is termed as sorting the array
in descending order. First, sort the array using Array. Sort() method which sorts an
array ascending order then, reverse it using Array. Reverse() method.
CUT 2023
[39]
C# A Basic Introduction to Programming 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CUT 2023
[40]
C# A Basic Introduction to Programming 2
CUT 2023
[41]
C# A Basic Introduction to Programming 2
OBJECTIVES:
• try − A try block identifies a block of code for which exceptions is activated. It
is followed by one or more catch blocks.
try
{
// Code to try goes here.
}
catch
{
// Code to handle the exception goes here.
// Only catch exceptions that you know how to handle.
}
In the code above two key words can be seen TRY and CATCH. The code you want
to protect from unexpected errors will be in the TRY { } code. Then if an error occur
during run time the CATCH { } will be executed. Here you will insert code that will alert
CUT 2023
[42]
C# A Basic Introduction to Programming 2
the user of the error and then the programmer will decide where to redirect code or
even exit the program.
Now let’s look at an example program, where the user can only enter a number as
requested by the program for their age. Let’s investigate what happens when the user
enters a text (any string).
The code:
Entering junk string to the program, where the correct input would have been a numeric
value.
CUT 2023
[43]
C# A Basic Introduction to Programming 2
You will notice the error refers to the input string (value the user entered) that is not in
the correct format. Meaning it should have been a number, but it was a string text.
It is important to remember if this was a final program and was sold, and the user has
run the program an made this error that the whole program would have crashed and
closed. This is very unprofessional and would damage the company name you work
for or even worse your name as a programmer.
It will be much better to handle the errors in the programming code and instruct the
user to correct an error they have made. Remember the TRY / CATCH will only be
used at areas in the program where the user can cause an error in the program and
not to use the TRY / CATCH to fix your programming mistakes later.
try
{
Console.WriteLine("Please enter your age");
age = Convert.ToInt16(Console.ReadLine());
}
catch
{
Console.WriteLine("You did not enter a valid age number. Press any key to try again");
Console.ReadKey();
Input1();
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CUT 2023
[44]
C# A Basic Introduction to Programming 2
APPENDIX A
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SearchArrayBook
{
class Program
{
static string[] provinceNames = {"EASTERN CAPE", "FREE STATE", "GAUTENG", "KWAZULU-NATAL", "LIMPOPO", "MPUMALANGA", "NORTHERN CAPE",
"NORTH WEST", "WESTERN CAPE"};
static string nameSearch, userContinue;
static bool flagFound = false, programRepeat = true, exitProgramNow = false;
static int menuOption;
if (exitProgramNow == false)
{
Console.WriteLine("Would you like to run the program again. YES or NO?");
userContinue = Console.ReadLine();
if (userContinue == "NO")
{
programRepeat = false;
}
}
}
EndofProgram();
CUT 2023
[45]
C# A Basic Introduction to Programming 2
}
static void UserMenu()
{
Console.WriteLine("=================================");
Console.WriteLine(" SEARCH SYSTEM MENU ");
Console.WriteLine();
Console.WriteLine(" 1.Search if province name exist ");
Console.WriteLine(" 2.Exit Program ");
Console.WriteLine();
Console.WriteLine("=================================");
Console.WriteLine();
if(menuOption == 1)
{
UserSearch();
}
else
{
programRepeat = false;
exitProgramNow = true;
}
}
static void UserSearch()
{
string searchValue;
Console.Clear();
Console.WriteLine("=========================================");
Console.WriteLine(" SEARCH PROGRAM ");
Console.WriteLine();
Console.WriteLine("Please enter the name you want to search:");
Console.WriteLine();
searchValue = Console.ReadLine();
nameSearch = searchValue.ToUpper(); //This code takes whatever is inside the variable and make it uppercase.
CUT 2023
[46]
C# A Basic Introduction to Programming 2
while(nameSearch == "")
{
Console.WriteLine("You entered an empty value and is not valid. Press any key to Try again");
Console.ReadKey();
Console.Clear();
UserSearch();
}
SearchArray();
}
static void SearchArray()
{
flagFound = false;
if(flagFound == true)
{
Console.WriteLine(" Search has been completed. Press any key for feedback");
Console.ReadKey();
Console.Clear();
Feedback();
}
else
{
Console.WriteLine("Search has been completed. Your input has not been found.");
Console.WriteLine("Press any key to return to main menu.");
Console.ReadKey();
CUT 2023
[47]
C# A Basic Introduction to Programming 2
Console.Clear();
}
}
static void Feedback()
{
Console.Clear();
Console.WriteLine("Your value {0} has been found in the array", nameSearch);
Console.WriteLine("Press any key to return to the Main Menu");
Console.ReadKey();
Console.Clear();
}
static void EndofProgram()
{
Console.Clear();
Console.WriteLine("The program will now exit. Press any key...");
Console.ReadKey();
}
}
}
CUT 2023
[48]
C# A Basic Introduction to Programming 2
CUT 2023
[49]
C# A Basic Introduction to Programming 2
Your Company needs an Investment Program. Your clients will enter an amount and the
program will print out a 12-month report how their money will grow against 11% per month.
2. houseKeeping Module
a. Will print a neat main menu with two options:
i. Make an investment
ii. Exit the Program
b. The housekeeping module will also request the Menuchoice from the user and will run
in a while loop preventing the user from entering any other numbers except 1 or 2.
3. detailLoop Module
a. A global variable InvestmentAmount will be used to request the user on how much
money they would like to invest over a period over a period
b. You can use the same InvestmentAmount variable in a For loop to calculate the total
money for each month of the 12 months indicating how their money has grown with an
interest of 11%. A Messages will be printed which will indicate each month of the 12 months
how their money has grown of their investment. REMEMBER TO ACCUMULATE THE
INTEREST FOR EACH MONTH.
4. finishUp Module
a. A local variable exitProgram will be used to test Y or N if the user wants to exit the
program. If a Y is entered the program will exit and an N will call the Main module. Make sure
your Main module has no arguments in the (). This will enable you to call the Main module
again.
© CUT 2023
[50]
C# A Basic Introduction to Programming 2
© CUT 2023
[51]
C# A Basic Introduction to Programming 2
Scenario: Nescafe Africa has contacted your programming company to assist them to program their vending
machine to have 2 choices when selecting coffee. Once size is 250ml and the second is 500ml.
There will be a Main Menu: (The program will check that the user can only enter 1,2 or 3. Else re-prompt.
• If the user has chosen option 1 the machine will dispense 250ml coffee and draw a small cup on
the screen.
• If the user has chosen option 2 the machine will dispense 500ml coffee and draw a large cup on
the screen. You may use While or For Loops. Nested Loops will be used.
The above counts 70% if cups are one colour. If the cups are printed with different colours inside the cup
a 100% will be allocated as a mark. (Outside of cup is grey and coffee inside cup is colour dark yellow.)
Console.ForegroundColor
= ConsoleColor.DarkYellow;
© CUT 2023
[52]
C# A Basic Introduction to Programming 2
Button1: Button2:
© CUT 2023
[53]
C# A Basic Introduction to Programming 2
Scenario: Valpre Africa has contacted your programming company to assist them to program their
machine to have 2 choices when dispensing water for the community. One size is 500ml and the
second is 1lt.
There will be a Main Menu: (The program will check that the user can only enter 1,2 or 3. Else re-
prompt.)
• If the user has chosen option 1 the machine will dispense 500ml water and draw a bucket on the
screen.
• If the user has chosen option 2 the machine will dispense 1lt water and draw a large bucket on the
screen.
You may use While or For Loops. Nested Loops will be used.
The above counts 70% if buckets are one colour. If the buckets are printed with different
colour inside the bucket a 100% will be allocated as a mark. (Outside of bucket is grey and
water inside bucket is colour blue.) Console.ForegroundColor = ConsoleColor.Blue;
© CUT 2023
[54]
C# A Basic Introduction to Programming 2
Button1: Button2:
© CUT 2023
[55]
C# A Basic Introduction to Programming 2
Scenario: You were asked to write an ITS program that would capture student details (Student
Number, Name, Surname, final mark) for any subject where there is up to 150 students max. This
program will be used by all the lecturers in SA.
Hints
You will make use of 4 global parallel arrays, one for each of the student’s details and 7 global
variables. There are also 6 methods.
The program will capture the marks for a subject where there could be a max of 150 students
(Student Number, Name, Surname, final mark – Parallel arrays). The user will indicate how many
students there are in the class and then capture the final marks.
This menu will create the ITS report where student data will be displayed with their marks. At the
end of the Report the following will be indicated:
• Amount Passed:
• Amount Failed:
• Average Final Mark.
• Then a * chart for the above 3.
•
Menu option: 3) Exit the program.
© CUT 2023
[56]
C# A Basic Introduction to Programming 2
Please Note!!
When the program starts there will not be any data to print when the user selects number 2:
When the user selects 1 it will show this screen and prompting the question:
You will also need to add error handling for if the user enters an incorrect number.
There will be a loop running depending on how many student details must be entered. In the
example we select 2 so the loop will run 2 times. This may change depending on the user’s input.
© CUT 2023
[57]
C# A Basic Introduction to Programming 2
Once all the data is captured you must return the user to the main menu screen
Next will be the ITS report. This will display the students details as seen below (Please note you will
be penalized if the details alignment is wrong).
You need to show how many students passed and how many failed. You also need to calculate what
the Average Final Mark is of all the student’s marks that have been entered e.g.
75 + 40 = 115
115 / 2 = 57.5
After that you need to make a small chart (*) using the passed, failed and average mark values as
seen below
© CUT 2023
[58]
C# A Basic Introduction to Programming 2
Once the user is done and want to exit the can choose 3 and then the program will close.
© CUT 2023
[59]
C# A Basic Introduction to Programming 2
Scenario: The South African Police Service (SAPS) has contacted your programming
company and requested that you develop software which will enable SAPS to capture
new cases, search for a specific captured case (future add-on) and print all cases
in the system to the screen and then the last option to exit the system. The system
must be able to capture at least 10 cases (Records), and the user must be able to choose
if they want to capture more records or not and can stop capturing cases at any time
after a case has been captured.
The system must have the recommended Main Menu and must check that the correct
Menu Number was entered to continue. If the user did not enter the correct menu number
an error message must be provided, and the user must try again. The system must
ONLY allow 3 chances to enter the correct menu number, else if all 3 chances has been
used a final error message is displayed and the system must close completely with a
keypress.
Program Specifics:
• // Add your Initials + Surname, Student Number as comments at the beginning of
your program (Just before the Namespace)
• A Main Menu that will print the 4 options:
1. Register a new Police Case
2. Search a Police Case (Note this method is in demo mode and the search does not
have to work but print a message to the screen informing the user that this function is
coming soon.)
3. Print all Police Cases to screen
4. Exit System
• 3 changes are given to enter correct menu number and if correct the
SubMenuChoice method will handle the call of all 4 menu options using a switch
statement which will be calling the methods.
• Menu Nr 1 will capture Police Cases and Menu Nr 3 will print all Cases and Menu
Nr 4 exit the program. Menu Nr 2 is in demo mode and only print a message that it is
coming soon.
• See Appendix A for Methods to be used in your program and see Appendix B for
recommended Screen Outputs.
© CUT 2023
[60]
C# A Basic Introduction to Programming 2
APPENDIX A
METHODS TO BE CODED:
//Global menu number variable:
//5 Global string Arrays for data of case to be saved:
© CUT 2023
[61]
C# A Basic Introduction to Programming 2
capture another case. The program must confirm after each case captured that all data
was captured and then request If the user wants to capture another case? If entered
Yes, then next case will be captured. If No the program will return to SubMenuChoice()
and clear the screen and call the MainMenu() method again.
//Data that will be captured is: caseNumber, officerOnDuty, complainantName,
complainantIdNum and complaintDetail array. HINT: a while loop to be used as the user
can exit any time if they do not want to capture anymore records.
}
static void CheckSecurity()
{
//This method is called from the switch when Menu nr 2 was triggered and will request a
password from the user using a local string variable and match it with a local constant
variable ADMINPASSWORD = “12345”. The user ONLY has one chance to enter the
correct password and then the Search Method will be called. Else a WARNING
MESSAGE will be given, and the program will return to the Main Menu.
}
static void SearchCase()
{
//THE BELOW CODE IS FOR DEMONSTRATION PURPOSES TO THE USER AND
DOES NOT COMPLETE THE SEARCH program. THIS METHOD COUNTS 0 MARKS.
THIS ONLY PRINTS THAT THIS FUNCTION IS COMING SOON. DO THIS METHOD
LAST if there is time!!!
Console.Clear();
//Report Header
Console.ForegroundColor = ConsoleColor.Blue; //Change colour to Blue because
this is coming soon
Console.WriteLine(" ");
Console.WriteLine(" SOUTH AFRICAN POLICE SERVICE (SAPS) ");
Console.WriteLine(" ");
Console.WriteLine(" SEARCH SYSTEM - RESTRICTED ACCESS: ");
Console.WriteLine(" ================================== ");
Console.WriteLine(" ");
Console.WriteLine(" ");
© CUT 2023
[62]
C# A Basic Introduction to Programming 2
//Return to Main Menu by exiting the method and calling Main Menu in the switch
statement. Console.WriteLine("Press any key to return to Main Menu...");
Console.ReadKey();
//(Advanced PPC Students challenge can afterwards for fun code this search function
for extra exercise at home and search by using case number and if found print to screen
or error if case is not found and return to Main Menu – No marks for this but if you can
do this you are one of the great advance students.)
}
static void PrintAllCases()
{
//A suitable header will be printed and then a FOR loop will print ALL the data in the
caseNumber, officerOnDuty, complainantName, complainantIdNum and complaintDetail
array neatly to the screen below each other with headings. Note future advance code for
the advanced students to add extra code that will only print records that contains data.
//(Advanced PPC Students challenge can afterwards for fun code that when printing
all cases, the loop will only print if there is any data in the arrays AND THEN if there are
data to only print the arrays that contains data and skip the rest. This can be for extra
exercise at home– No marks for this but if you can do this you are a great advanced
student.)
}
static void ExitSAPS()
}
//This method will only print a suitable EXIT SAPS screen and close with a message and
a keypress.
}
© CUT 2023
[63]
C# A Basic Introduction to Programming 2
© CUT 2023
[64]
C# A Basic Introduction to Programming 2
© CUT 2023
[65]
C# A Basic Introduction to Programming 2
If the user chooses No: (If the user entered Yes, then the next case would have
been captured)
© CUT 2023
[66]
C# A Basic Introduction to Programming 2
After pressing any key, the Demo screen will be printed: (Remember this
method is in “coming soon” status and does not function. The purpose is to
see if you can setup a password and call the method if the password is correct:
© CUT 2023
[67]
C# A Basic Introduction to Programming 2
Will print all records till 10: (Note Nr: printed is the counter of loop)
EXIT System
© CUT 2023
[68]
C# A Basic Introduction to Programming 2
On the computer’s desktop, click the right mouse button to create a new folder on the
desktop to easily navigate to your work. Note to name the new folder your student
number for easy access.
A new folder will appear on the desktop, make sure to Name this folder as your
student number.
© CUT 2023
[69]
C# A Basic Introduction to Programming 2
Same as in figure 1.9 Saving your project, when you create a new project make sure
that you browse for your folder (using the square block with the 3 dots inside) you
created on the computers desktop and double click on the folder and click select
folder in the bottom right to make the folder the new save location for your project.
Make sure that when you have saved your project and you wish to zip and submit
the folder on ethuto, make sure that all your work is located inside the folder and that
your programme does actually work when you run it.
Note that the lecturer is not responsible for your work not working
properly if not submitted correctly and the programme does not work
when it is run in Visual Studio.
When you are certain that your programme works you can zip the folder by hovering
over the folder and right click. Click on compress to ZIP file to zip the folder. A new
folder will appear on the desktop with a similar name to your original folder. Note that
when you try to test the programme from the zip file it will not work, you will first have
to extract the zipped folder to access the files.
© CUT 2023
[70]
C# A Basic Introduction to Programming 2
When you are ready to submit your work on ethuto go to the subject you need to
submit your work on and locate the submission link needed to submit your work.
When you want to submit your folder containing your programme, you can either
browse for the folder (Browse Local Files) or you can drag on drop the folder.
After you have uploaded the folder in the step above, make sure to click on submit in
the bottom right. Do not yet close the window, you must make sure that your work is
submitted. Wait for the window to display a screen that you can download your
submission from, then you will know that your work is submitted.
Note that it is the student’s own responsibility to ensure that their work is
correctly submitted on ethuto.
© CUT 2023
[71]
C# A Basic Introduction to Programming 2
© CUT 2023
[72]
C# A Basic Introduction to Programming 2
END OF BOOK
© CUT 2023
[73]
C# A Basic Introduction to Programming 2
References
Angela Stringfeild, 2017. DZone. [Online]
Available at: https://dzone.com/articles/learn-c-tutorials-for-beginners-intermediate-
and-a-1
[Accessed 30 11 2022].
Anon., 2022. tutorialspoint. [Online]
Available at: https://www.tutorialspoint.com/csharp/csharp_for_loop.htm#
[Accessed 30 11 2022].
Anon., 26 Oct 2021. C# | Arrays. [Online]
Available at: https://www.geeksforgeeks.org/c-sharp-arrays/
[Accessed 30 11 2022].
Anon., n.d. Programiz. [Online]
Available at: https://www.programiz.com/csharp-programming/do-while-loop
[Accessed 30 11 2022].
C# for Loop, June 17 2022. TutorialsTeacher. [Online]
Available at: https://www.programiz.com/csharp-programming/do-while-loop
[Accessed 30 11 2022].
C# Tutorial, 2007 - 2022. The complete C# Toturial. [Online]
Available at: https://csharp.net-tutorials.com/om/104/getting-started/introduction/
[Accessed 30 11 2022].
ChancellorMetalIbex, n.d. Course Hero. [Online]
Available at: https://www.coursehero.com/file/57809453/Array-OOP-VBnetdocx/
[Accessed 30 11 2022].
Programming, 2 September 2022. studyTonight. [Online]
Available at: https://www.studytonight.com/post/csharp-arrays
[Accessed 30 11 2022].
stackOverflow, January 2020. stackOverflow. [Online]
Available at: https://stackoverflow.com/questions/44481466/for-loop-explanation/
[Accessed 30 11 2022].
© CUT 2023
[74]