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

C# Programming Book S2

This is a C# programming manual for students.

Uploaded by

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

C# Programming Book S2

This is a C# programming manual for students.

Uploaded by

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

C# Programming

A Basic Introduction to

Programming

Third Edition

STUDENT MANUAL – A practical approach.

Programming Principles 1B – PPC125C

Compiled by Mr AD van der Walt


C# A Basic Introduction to Programming 2

[ii]
© CUT 2023
C# A Basic Introduction to Programming 2

PREFACE

Welcome to this C# a Basic Introduction to Programming book 2. With the


introduction of the .NET framework, Microsoft included a new language called C#
(pronounced C Sharp). C# is designed to be a simple, modern, general-purpose,
object-oriented programming language. C# provides the features that are most
important to programmers, such as object-oriented programming, graphics, graphical-
user-interface (GUI) components, exception handling, multithreading, multimedia
(audio, images, animation, and video), file processing, pre-packaged data structures,
database processing. (C# Tutorial, 2007 - 2022)

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

PREFACE .................................................................................................................. iii

COPYRIGHT ..............................................................................................................iv

CONTENTS ............................................................................................................... v

LIST OF FIGURES .................................................................................................... vii

OVERVIEW .............................................................................................................. viii

LIST OF ANNEXURES .............................................................................................. x

SYMBOLS USED IN THIS BOOK ..............................................................................xi

CHAPTER 1: C# LOOPS ........................................................................................... 2

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

3.1.1. HANDLING ERRORS IN C# ................................................................. 42


ADDITIONAL PROGRAMS AND PRACTISE TESTS .............................................. 50

HOW TO ZIP & SUBMIT ON ETHUTO .................................................................... 69

[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

Figure 1.1.3: Difference between while and do while loops. ..................................... 11

Figure 1.1.4: While and do while loops Comparison Chart....................................... 12

Figure 1.1.5: Main Menu of Exercise 1.1 .................................................................. 13

Figure 1.1.6: Main Menu of Exercise 1.1 .................................................................. 13

Figure 1.2.1: Output of program in sample code 2.2 ................................................ 15

Figure 1.2.2: Output of program in sample code 2.3 ................................................ 18

Figure 2.1.1: Array Elements as declared in a computer’s memory. ........................ 24

Figure 2.1.2: Declaring Array and Elements............................................................. 30

Figure 2.2.1: Output of Sorting Array Program Part 1. ............................................. 38

Figure 2.2.2: Output of Sorting Array Program Part 2. ............................................. 38

[vii]
© CUT 2023
C# A Basic Introduction to Programming 2

OVERVIEW

To enable learners to eventually fulfil these functions it is expected from them to be


able to confidently comply with the appropriate programming or networking skills as
well as being able to communicate well orally and in the preparation of software or
network development. Their interpersonal skills – and skills to function as part of a
team – is also purposefully developed by the nature of assignments that they are
expected to complete. All the material in this book will be structured as follows:

ARRANGEMENT OF THIS BOOK:

CHAPTER 1: C# LOOPS (Academic Quarter 3)

UNIT 1: While and Do While Loops

• What are Loops


• WHILE Loops
• DO WHILE loops

UNIT 2: FOR Loops


• Using a FOR loop
• Nested Loops
• Definite vs Indefinite vs Infinite Loops

CHAPTER 2: C# ARRAYS (Academic Quarter 3)

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

UNIT 2: Searching arrays

• Searching an array for an exact match


• Sorting an array

CHAPTER 3: ERROR HANDLING (Academic Quarter 4)

UNIT 1: Error Handling

• Try Catch

Additional Exercises

• Additional Program 1: Investment


• Additional Program 2.1: Coffee Vending Machine
• Additional Program 2.2: Water Bucket size
• Additional Program 3: ITS Final Marks
• Additional Program 4: SAPS

How to zip and submit

[ix]
© CUT 2023
C# A Basic Introduction to Programming 2

LIST OF ANNEXURES

WILL BE UPDATED WHEN THE BOOK IS FINISHED AT THE END OF THE


SEMESTER.

[x]
© CUT 2023
C# A Basic Introduction to Programming 2

SYMBOLS USED IN THIS BOOK


FOUNDATION THINKING
Retrieving, recognizing, and recalling relevant knowledge from
long‐term memory

Constructing meaning from oral, written, and graphic messages


through interpreting, exemplifying, classifying, summarizing,
inferring, comparing, and explaining.
Carrying out or using a procedure for executing or implementing.

HIGH ORDER THINKING


Breaking material into constituent parts, determining how the
parts relate to one another and to an overall structure or purpose
through differentiating, organizing, and attributing.
Making judgments based on criteria and standards through
checking and critiquing

Putting elements together to form a coherent or functional whole;


reorganizing elements into a new pattern or structure through
generating, planning, or producing.
INSTRUCTION SYMBOLS
SELF STUDY

OBJECTIVE

EXERCISE

HOMEWORK

[xi]
© CUT 2023
C# A Basic Introduction to Programming 2

CHAPTER 1: C# LOOPS

Unit 1

WHILE and DO WHILE loops

OBJECTIVES:

⚫ Understand what Loops are.


⚫ Understand how to use and implement a While Loop.
⚫ Understand how to use Do While Loop and what is the difference.

Looping in a C# is a way to execute a statement or a set of statements multiple times


depending on the result of the condition to be assessed to execute statements. The
result condition should be true to execute statements within loops. This technique
comes in very handy because it means that you can repeat actions as many times as
you want without having to write the same code each time.

1.1.1. WHILE LOOP

The while statement executes a statement or a block of statements while the


conditions stays to true. Because that expression is evaluated before each execution
of the loop, a while loop executes zero or more times.

When a while loop runs, this is what happens (Sharp, 2013):

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

The basic declaration of a while loop in C# will be:

while (boolean condition)


{
// statement(s) to repeatedly execute
}

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.

1.1.2. DEFINITE COUNTER CONTROLLED LOOP

Sample code 1.1:

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.

The output of this program:

Figure 1.1.1: Output of the while loop in the quick example.

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

1.1.3. INDEFINITE SENTINEL VALUE LOOP


The previous while loop example was a Counter controlled loop, we will now look at a
sentinel value loop. A sentinel value is a value that will form part of the condition and
the user decides how many times the loop executes.

Sample code 1.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.

Figure 1.1.2: Output of the while loop with a sentinel value.

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.)

The basic declaration of a DO while loop in C# will be:

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,

Sample code 1.3:

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

1.1.5. IMPLEMENTING LOOPS

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.

The program structure:

• 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

Sample code 1.4:

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

Sample code 1.5:

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.

Sample code 1.6:

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.

Sample code 1.7:

Lastly the program tests if the user wants to enter a new registration.

CUT 2023
[10]
C# A Basic Introduction to Programming 2

Sample code 1.8:

When the user chooses menu items 2 in the main menu the program will print the
registration of the new infant entered.

1.1.6. CHAPTER 1 – UNIT 1: SUMMARY

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.

Figure 1.1.3: Difference between while and do while loops.

CUT 2023
[11]
C# A Basic Introduction to Programming 2

Figure 1.1.4: While and do while loops Comparison Chart.

1.1.7. EXERCISES & HOMEWORK – CHAPTER 1 - UNIT 1

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

Recommended Program Screens:


Main Menu:

Figure 1.1.5: Main Menu of Exercise 1.1

OUTPUTS:

Figure 1.1.6: Main Menu of Exercise 1.1

CUT 2023
[13]
C# A Basic Introduction to Programming 2

CHAPTER 1: C# LOOPS

Unit 2

FOR loops

OBJECTIVES:

⚫ Understand what FOR Loops are and how to use them.

⚫ Understand what nested loops are.

⚫ Understand Definite vs Indefinite vs Infinite Loops

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)

1.2.1. FOR LOOP

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

Sample Code 2.1:

for (init; condition; increment)


{
Statements;
}

• 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)

Sample Code 2.2:

Figure 1.2.1: Output of program in sample code 2.2

CUT 2023
[15]
C# A Basic Introduction to Programming 2

for (int counter = 0; counter < 10; counter++)


(declaring or specifying a counting variable ; boolean expression ; iterative action)

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.

1.2.2. NESTED FOR LOOPS

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.

Sample Code 2.3:

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

Figure 1.2.2: Output of program in sample code 2.3

1.2.3. UNDERSTAND DEFINITE VS INDEFINITE VS INFINITE LOOPS

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:

string userInput = “N”;


Console.WriteLine(“Do you want to print the message Y or N”);
userInput = Console.ReadLine();

while (userInput == “Y”)


{
Console.WriteLine(“Hello Indefinite Loop”);
Console.WriteLine(“Do you want to print the message again Y or N”);
userInput = Console.ReadLine();
}

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;

while (counter < 10)


{
Console.WriteLine(“Hello Definite”);
//COUNTER NOT INCREMENTED
}

The loop above will run forever and will not stop, due that the counter is not
incremented.

Scenario 2:

string userInput = “N”;

while (userInput == “N”)


{
Console.WriteLine(“Hello Indefinite”);
//User not prompted to change the control variable
}

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

1.1.8. CHAPTER 1 – UNIT 2: SUMMARY

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.

1.1.9. EXERCISES & HOMEWORK – CHAPTER1 - UNIT 2

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.

• Option 1 – Order Coffee Size 1 – 250ml


• Option 2 – Order Coffee Size 1 – 500ml
• Option 3 – Exit vending machine

The only options that is valid is 1, 2 and 3.

• 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;

REQUIRED OUTPUT AND PROGRAM:

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:

⚫ Understand what Arrays in C# are.

⚫ Understand how an array can replace nested decisions.

⚫ Understand how to use constants within arrays

An array stores a fixed-size sequential collection of elements of the same type. An


array is used to store a collection of data, but it is often more useful to think of an array
as a collection of variables of the same type stored at contiguous memory locations.
(ChancellorMetalIbex, n.d.)

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.

First Element Last Element

Numbers[0] Numbers[1] Numbers[2] Numbers[3] Numbers[…….]

Figure 2.1.1: Array Elements as declared in a computer’s memory.

CUT 2023
[24]
C# A Basic Introduction to Programming 2

2.1.2. DECLARING AN ARRAYS AND POPULATING


Declaring an array does not initialize the array in the memory. When the array variable
is initialized, you can assign values to the array. Array is a reference type, so you need
to use the new keyword to create an instance of the array. Here you can see three
(3) different ways to declare a marks array:

int[] marks = new int[5] {99, 88, 80, 40, 75}; OR


int[] marks = {99, 88, 80, 40, 75}; OR
int[] marks = new int[5];

The method we will use for this course will be as follows:


double[] balance = new double[10];
string[] name = new string[5];

Declare and populate after declared


Method 1:
string[] name = new string[5];
name[0] = “Bongani”;

Declare and populate after declared


Method 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:

string[] name = new string[5];

for (int counter = 0; counter < 5; counter++)


{
Console.WriteLine("Please enter name{0}:", counter+1);
name[counter] = Console.ReadLine();
}

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.

2.1.3. HOW AN ARRAY CAN REPLACE NESTED DECISIONS


In the previous sub section, we were introduced on how to create an Array and how
to populate it. The question remains, can Arrays replace nested decisions? Let’s
investigate. Let’s say we want to capture data for a business survey and one of the
data fields we want to capture is ID Number. Note in this hypothetical scenario we
want to capture 150 employee’s ID numbers. If we approach this declaration of ID
numbers before our knowledge of Arrays, the declaration will look something like this:

Normal Variables:
string idNum1, idNum2, idNum3, idNum4, idNum5, idNum6, ......idNum150;

Now let’s store data in these variables:


Console.WriteLine(“Please enter ID Number 1”);
idNum1 = Console.ReadLine();
Console.WriteLine(“Please enter ID Number 2”);
idNum2 = Console.ReadLine();
Console.WriteLine(“Please enter ID Number 3”);
idNum3 = Console.ReadLine();
UP TO:
Console.WriteLine(“Please enter ID Number 150”);
idNum150 = Console.ReadLine();

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.

Now let’s store data in this array:


for (int counter = 0; counter < 150; counter++)
{
Console.WriteLine("Please enter ID Number{0}:", counter+1);
idNum[counter] = Console.ReadLine();
}

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.

2.1.4. USING CONSTANTS IN ARRAYS


When we talk about constants in an array, we refer to making use of a variable to
determine the size of the array. Let say we want to capture many names in a program,
and it will be stored in an array. We can first ask the user how many names they want
to capture and according to this declare the size of the array.

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…

const int amount = 50;


string[] name = new string[amount];

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.

static readonly string[] months = { "January", "February", "March", "April", "May",


"June", "July", "August", "September", "October", "November", "December" };

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.

2.1.5. TYPES OF C# ARRAYS:


There are three types of arrays in C# programming:

1. Single-Dimensional Array (We cover this array in this course PPC125C)


2. Multidimensional Array (This will be covered in your course SOD115C next year)
3. Jagged Array (This will be covered in your course SOD115C next year)

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

2.1.6. CHAPTER 2 – UNIT 1: SUMMARY


An array is a group of like-typed variables that are referred to by a common name.
And each data item is called an element of the array. The data types of the elements
may be any valid data type like double, int, string, etc. and the elements are stored in
a contiguous location. Length of the array specifies the number of elements present in
the array. In C# the allocation of memory for the arrays is done dynamically. And arrays
are kind of objects, therefore it is easy to find their size using the predefined functions.
The variables in the array are ordered and each has an index beginning from 0. (Anon.,
26 Oct 2021)

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.

Figure 2.1.2: Declaring Array and Elements

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

2.1.7. EXERCISES & HOMEWORK – CHAPTER 2 - UNIT 1


Exercise 2.1.1:

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:

• Make use of Structured Programming!!!


o Use Modules!
▪ Housekeeping
• Sub Modules – MAIN MENU
▪ DetailLoop
• Sub Modules – CHECK INPUT and call sub module to capture
registration information of the new-born to the arrays of length
500.
• Note to generate a Birth Number
o Multiply the counter to 215958 that will generate a birth
number. We will later discuss random numbers.
▪ Finishup
• Provide an ending message and allow the user to press any key
to exit the program.
o Use Global Variables
▪ Recommended Parallel Arrays for capturing: BabyNames,
BabySurname, BirthNumber, Adress, ContactNum and Email.
o Use Constants

Recommended Program Screens:

MAIN MENU: (Text Colour Gray – Default)

CUT 2023
[31]
C# A Basic Introduction to Programming 2

MENU OPTION 1: (Text Colour Green)

The Program will keep on capturing New-born Registration up to 500 or when the user
says No.

MENU OPTION 2: (Text Colour Yellow)

Menu Option 3: (Text colour Red)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

SEARCHING AND SORTING ARRAYS

OBJECTIVES:

⚫ Understand how to search an Array for an exact match.

⚫ Understand how to sort an Array.

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.”

2.2.1. SEARCHING ARRAYS


Finding a specific member (item in the array) of an array means searching the array
until the member is found. It’s possible that the member does not exist, and the
programmer must handle that possibility within the logic of his or her algorithm. Let’s
look at an example. We will look at a program which have an array of 9 items
(Members). The user must enter the item or value to be searched for and receive
feedback if the search was successful or not.

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

• Let’s look at the declaration of this array:

static string[] provinceNames = {"EASTERN CAPE", "FREE STATE", "GAUTENG", "KWAZULU-


NATAL", "LIMPOPO", "MPUMALANGA", "NORTHERN CAPE", "NORTH WEST", "WESTERN CAPE"};

• Getting the input from the user to search for:

Console.WriteLine("Please enter the name you want to search:");

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.

• Searching the Array for a match.

flagFound = false;

for (int counter = 0; counter < 9; counter++)


{
if(provinceNames[counter] == nameSearch)
{
Console.WriteLine("The value: {0} has been found", provinceNames[counter]);
flagFound = true;
counter = 9;
}
}

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

2.2.2. SORTING ARRAYS


An array is a group of like-typed variables that are referred to by a common name.
And each data item is called an element of the array. Arranging the array’s elements
from largest to smallest is termed as sorting the array in descending order. In the next
example we will look at how to sort an array, which contains the abbreviation names
of all the Universities of Technology. We will see that these abbreviations are not in
order and is mixed in the array. The following program will first print the unsorted array
and then sort the array and print it again to the user.

• The array declaration:

static string[] UniTechs = {"TUT", "CUT", "CPUT","DUT", "VUT","MUT"};

• Printing the array:

Console.WriteLine("=========================================");
Console.WriteLine(" LIST OF UNIVERSITIES OF TECHNOLOGIES ");
Console.WriteLine();
Console.WriteLine("Abbreviation ");

for (int counter = 0; counter < 6; counter++)


{
Console.WriteLine("{0} ", UniTechs[counter]);
}

Console.WriteLine("=========================================");
Console.WriteLine();

• SORTING THE ARRAY:

static void SortArray()


{
Array.Sort(UniTechs);
}

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

Figure 2.2.1: Output of Sorting Array Program Part 1.

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.

Figure 2.2.2: Output of Sorting Array Program Part 2.

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

2.2.3. CHAPTER 2 – UNIT 2: SUMMARY


All the types you’ve seen so far have one thing in common: Each of them stores a
single value (or a single set of values in the case of structs). Sometimes, in situations
where you want to store a lot of data, this isn’t very convenient. You may want to store
several values of the same type at the same time, without having to use a different
variable for each value.

Arrays are declared in the following way:


<baseType>[] <name>;

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

int[] myIntArray = new int[arraySize];


In addition, you can combine these two methods of initialization if you want:
int[] myIntArray = new int[5] { 5, 9, 10, 2, 99 };
With this method, the sizes must match. You can’t, for example, write the following:
int[] myIntArray = new int[10] { 5, 9, 10, 2, 99 };

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

2.1.8. EXERCISES & HOMEWORK – CHAPTER 2 - UNIT 2


Design a program that computes pay for employees. Allow a user to continuously input
employees' names until an appropriate sentinel value is entered. Also input each
employee's hourly wage and hours worked. Compute each employee's gross pay
(hours times rate), withholding tax percentage (based on the table below), withholding
tax amount, and net pay (gross pay minus withholding tax). Display all the results for
each employee. After the last employee has been entered, display the sum of all the
hours worked, the total gross payroll, the total withholding for all employees, and the
total net payroll.

Weekly Gross Withholding


Pay (R) Percentage (%)
0.00-3000.00 10
3000.01-5500.00 13
5500.01-8000.00 16
8000.01 and up 20

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CUT 2023
[40]
C# A Basic Introduction to Programming 2

CUT 2023
[41]
C# A Basic Introduction to Programming 2

CHAPTER 3: ERROR HANDLING

HANDLING ERROR IN YOUR PROGRAMS

OBJECTIVES:

⚫ How to use the Try Catch C# code in program code.

An exception is a problem that arises during the execution of a program. A C#


exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.

3.1.1. HANDLING ERRORS IN C#


Exceptions provide a way to transfer control from one part of a program to another.
C# exception handling is built upon four keywords: try, catch.

• try − A try block identifies a block of code for which exceptions is activated. It
is followed by one or more catch blocks.

• catch − A program catches an exception with an exception handler at the place


in a program where you want to handle the problem. The catch keyword
indicates the catching of an exception.

Let’s investigate how the C# code look like:

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:

static int age;

Console.WriteLine(" MAIN PROGRAM - Capture Age");


Console.WriteLine();

Console.WriteLine("Please enter your age");


age = Convert.ToInt16(Console.ReadLine());

Entering junk string to the program, where the correct input would have been a numeric
value.

The compiler stops the program and give an error as follows:

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.

The code with the TRY / CATCH protection:

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;

static void Main()


{
while(programRepeat == true)
{
UserMenu();

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();

Console.WriteLine("Please enter menu number 1 or 2");


menuOption = Convert.ToInt16(Console.ReadLine());

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;

Console.WriteLine(" Search is in progress..."); //animation can be added here


Console.WriteLine();

for (int counter = 0; counter < 9; counter++)


{
if(provinceNames[counter] == nameSearch)
{
Console.WriteLine("The value: {0} has been found",provinceNames[counter]);
flagFound = true;
counter = 9;
}
}

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

ADDITIONAL PROGRAMS AND PRACTISE TESTS

Additional Program 1: Investment

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.

The Program Requirements will be as follows: (YOU HAVE 60MINS!!!!!)


The Following Global Variables will be used.
• MenuChoice
• InvestmentAmount

The following Modules will be used in the Program:


1. Main Module
a. Will call houseKeeping, detailLoop and finishUp.

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

Screen Capture of the program:

© CUT 2023
[51]
C# A Basic Introduction to Programming 2

Additional Program 2.1: Coffee Vending Machine

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.

• Option 1 – Order Coffee Size 1 – 250ml


• Option 2 – Order Coffee Size 1 – 500ml
• Option 3 – Exit vending machine
The only options that is valid is 1, 2 and 3.

• 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;

REQUIRED OUTPUT AND PROGRAM:

© CUT 2023
[52]
C# A Basic Introduction to Programming 2

Button1: Button2:

ONLY LOOPS AND SINGLE CONSOLE.WRITE OR WRITELINES MAY BE USED IN THIS


PRGOGRAM.

© CUT 2023
[53]
C# A Basic Introduction to Programming 2

Additional Program 2.2: Water Bucket size

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.)

• Option 1 – Order Water Bucket Size 1 – 500ml


• Option 2 – Order Water Bucket Size 2 – 1lt
• Option 3 – Exit Water Machine

The only options that is valid is 1, 2 and 3.

• 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;

REQUIRED OUTPUT AND PROGRAM:

© CUT 2023
[54]
C# A Basic Introduction to Programming 2

Button1: Button2:

ONLY LOOPS AND SINGLE CONSOLE.WRITE OR WRITELINES MAY BE USED IN THIS


PROGRAM.

© CUT 2023
[55]
C# A Basic Introduction to Programming 2

Additional Program 3: ITS Final Marks

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.

Menu option: 1) Capture marks.

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.

Menu option: 2) ITS Report

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.

Exit the program.

Below is an example of the output:


When the program runs you will have a menu where you can choose 1,2 or 3
You will also need to add error handling for if the user enters an incorrect number.

© 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.

Next, the below details will be captured in the correct arrays:

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

Additional Program 4: SAPS

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:

static void Main()


{
//Calls MainMenu:
}
static void MainMenu()
{
//Prints Main Menu interface and validate menu option and only provide the user 3
chances to enter the correct Menu number. If the menu number is entered correctly then
the SubMenuChoice() will be called else the program will close after 3 wrong menu
numbers was entered with a warning and keypress.
}
static void SubMenuChoice()
{
//This method use a switch statement to call the appropriate method for the menu number
that was entered in the MainMenu() from the user. The switch will call either
RegisterCase(), SearchCase(), PrintAllCases() or ExitSAPS(). This
SubMenuChoice() method will also call the clear screen and MainMenu() after menu nr
1 to 3 methods has finished executed and will return to the main menu. If the user choses
4 then ExitSAPS() method will be called.
//Note if the user chooses menu number 2 the Method CheckSecurity() will be called
first to check for an Admin Password before the user can access the SearchCase(). A
local constant variable inside of CheckSecurity() method will be used to store the default
admin password of “12345”
}
static void RegisterCase()
{
//This Method will be called from SubMenuChoice() switch statement when the user
has entered 1 in the main menu. This Method will use the 5 Global string Arrays declared
on top of your code above the Main Method(as shown on top of this page) and will
capture all info needed to record a new case in this RegisterCase() method. At least 10
cases can be recorded but after each case captured the user can choose if they want to

© 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

Console.WriteLine("This system is coming soon...");


Console.WriteLine();

//Switch back to default colour: Console.ForegroundColor = ConsoleColor.Gray;

//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

APPENDIX B - Recommended outputs


MAIN MENU:

Wrong number entered in menu:

When menu number has been entered incorrectly 3 times:

© CUT 2023
[64]
C# A Basic Introduction to Programming 2

All data been captured for 1st Case:

© 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)

Search a Police Case:


Before the SearchCase() is called a Password check is done CheckSecurity():

If the password was entered correctly:

© 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:

Print all Police Cases to screen:

© 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

HOW TO ZIP & SUBMIT ON ETHUTO


Note that the below steps were done on Windows 11, but the similar steps
can be used on any computer.

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]

You might also like