0% found this document useful (0 votes)
8 views14 pages

C# Methods and Practical Exercises Guide

Uploaded by

neyenic863
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views14 pages

C# Methods and Practical Exercises Guide

Uploaded by

neyenic863
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2025/04/14

More on Methods
Lecturer:
Ms Marinda Taljaard / Mr Ighsaan Salie / Mr Ntembeko Jafta

Admin – test 2 details


▪ Test 2 is scheduled for Friday 25 April – book for a session on the module site
• Session 1: 12:00 – 13:30
• Session 2: 14:00 – 15:30
• Session 3: 16:00 – 17:30
• Booking to be available from Wednesday 16 April – Wednesday 23 April (14:00)

▪ Content
• All work covered this semester, including user defined methods
• Only coding questions

1
2025/04/14

Practical 7 Discussion
▪ A discussion of the tasks will follow on the next couple of slides
▪ A number of different scenarios were used in the pracs, but yours should be similar
to the ones being discussed

▪ It is possible that your solution could be slightly different, but also working correctly

Practical 7 Task 1
Create a user defined method called GetMark()
that takes no input (as an argument), obtains a
valid integer from the user and returns the valid
mark (between 0 and 60, 0 and 60 included).
If the user enters an invalid mark, the method
should repeatedly prompt the user for a value until
a valid value is entered. When the method has a
valid mark, it should return that mark to the calling
program. In your Main() method call the newly
created GetMark() method to obtain a valid
mark from the user. When the valid mark is
received back from the method, calculate the
equivalent percentage, and display the entered
mark as a mark out of 60, as a percentage with 1
decimal places, and whether this is a pass mark
(pass mark is greater or equal to 50%) or a fail.

2
2025/04/14

Practical 7 Task 2
Create a user defined method named CalcCost() that
accepts two double values as arguments (length and width
of a room), and then computes the estimated cost of
painting a room (walls only, not ceiling), assuming the room
is rectangular and has four full walls and the walls are
2.6 meter high. The rate for the painting job is R20 per
square meter. Your method should return the estimated
cost to the calling method.
Create a program whose Main() method prompts a user
for the length and the width of a room in meter, then calls
CalcCost to calculate the estimated cost. Once
calculated, the Main() method should display the
estimated cost.
Remember to format monetary amounts to display the
currency sign.

Good programming habits


▪ By using Methods you should write efficient code
▪ WET code (Write Everything Twice) – bad
• Copy and pasting of code
• Need to keep track of any changes (updates or fixes) that might be required – and
then updated everywhere
• Easy to make mistakes, difficult to read, looks untidy
▪ DRY code (Don’t REPEAT Yourself) – good
• Duplicated code put into methods – only the parameters changes
• Do any required fixes or updates in only 1 place

3
2025/04/14

General C# aspects
▪ namespace
• a construct that acts as a container to group
similar classes
• Use existing and create your own
• the system namespace holds commonly used
classes
▪ [Link]
([Link])
▪ When creating a new console application, it
gets the name of your application

General C# aspects
▪ class Program
• class describes potential objects
• determine what data and methods will be
part of the class
• use default at this stage
▪ Main() method
• Every executable C# application should
have this – the starting point for every
program
▪ Any other methods
• Method header and body

4
2025/04/14

Debugging in
Visual Studio
▪ It could happen that you have a
running program that gives an
incorrect result, or a runtime error
▪ VS has a debugger that can help you
to identify the problem(s)
• Start debugging and enter break mode
• Navigate code while in break mode
• Debugging and break mode
• Code stepping
• Run to a specific location or function

Debugging in Visual Studio


▪ Some Resources (you will also be able to find other resources online):
• [Link]
- (watch at least the first 12 minutes of this video)
• [Link]
2022&tabs=csharp
• [Link]
• [Link]
debugger?view=vs-2022&tabs=csharp

5
2025/04/14

Reading coding questions


▪ Always check for specifics – do not rush into the coding, e.g.
• If you need to have a while loop with a sentinel value – does the question specify what
this should be, or can you decide?
• When creating a method – do you have freedom to decide about arguments and return
type, or does the question specify the requirements

Homework example
▪ Consider the following scenario:
A program is required to process and display payroll information for an employee. For
each employee the program should request the user to enter the name, hours worked and
base pay rate. An employee’s gross wage is computed at the regular rate for the first 40
hours worked, and 1.5 times the regular rate for each hour over 40. Tax is calculated at
10% of the gross wage. Your program should display the following values: Name, hours
worked, base rate, gross wage, tax, nett wage.
▪ Create user defined methods for each of the following functionality aspects:
• User input,
• Calculation of the gross wage,
• Calculation of the tax amount and nett wage,
• Display of the values

6
2025/04/14

Homework example (continued)


▪ Note that no specific requirements were provided for the methods – only that you have to
make use of at least the specified 4 methods
▪ That means that you have some freedom in deciding on the type of parameters and
return/void types of the methods

▪ You may write the program to only calculate and display the information for 1 employee

High level planning –


one possible solution
▪ Main method to do all the
method calls
• Get the data from the user
• Calculate the gross amount
• Calculate the tax amount
and nett amount
• Display all values

7
2025/04/14

One possible solution – create the following methods


▪ GetData
Prompt the user for required

values, return the values
▪ CalcGross
Accept hours and rate values

from the calling method,
calculate, return gross amount
▪ CalcNett
Accept gross amount from calling

method, return tax amount and
nett amount
▪ DisplayAll
• Accept all values from the calling
method, display values

Homework example (continued)


▪ Consider how you would change the code for the following scenarios:
• Enter and display the values for 5 employees
• Enter and display the values for an unknown number of employees

8
2025/04/14

Class exercise
Write a program that prompts the user for the three coefficients a, b and c of a
quadratic equation: ax2 + bx +c = 0, calculates and displays its real-number
roots (if they exist). Quadratic equations may have 0, 1 or 2 real roots.
When planning and implementing your answer, decide how you can make use of
user defined methods to ensure that you are not duplicating any code that should
rather be inside a method, and to ensure that the Main method is not too long and
complicated to read.
Display the roots with 2 decimal places.

Class exercise
No specific requirements about methods – so what route would you follow?
▪ Any ideas from the class?

▪ My solution has two additional methods


• GetNum and CalcRoots

static int GetNum()


static void CalcRoots(int a, int b, int c)

9
2025/04/14

Class exercise

Homework exercise
Access full exercise from the module site: Week 9 Homework exercise
You are required to write a program that will calculate and display the total balance on your bank accounts and the
name of the account with the highest balance.

Write a method GetAccountInfo that asks a user for an account’s identifying name (as a single character) and the balance
on that account. The method must return these values.
Write a method ProcessAccount that takes as input the following:
▪ The account name and value of its balance for the account that has the maximum balance of all the accounts processed
so far
▪ The total balance of all the accounts processed so far
▪ The account name and value of its balance for the account that is currently being processed

10
2025/04/14

Plan your solution


▪ What info do we have? (Data)
• Variables (e.g. types, constants, initialised, declared, user input …)
▪ What info do we need to end up with? (Output)
• What results are required, how should it be displayed?
▪ How do we get from the input info to the output info? (How)
• Plan the solution (what formulas, what logical expressions, what loops, in what order?)
▪ How do I write the code?
• Implement the solution (syntax)
▪ Does the code work?
• Test with a variety of input data

Homework exercise - planning


Write a method GetAccountInfo that asks a user for an account’s
identifying name (as a single character) and the balance on that account. The
method must return these values.
Items Types From? Process
Data Account name char User input
Account balance double User input
Output Return account name
Return account balance
How Make use of out variables, since two values needs to be returned

11
2025/04/14

Homework exercise – planning


Write a method ProcessAccount that takes as input the following:
▪ The account name and value of its balance for the account that has the maximum balance
of all the accounts processed so far
▪ The total balance of all the accounts processed so far
▪ The account name and value of its balance for the account that is currently being
processed
The method must update the account name and value of its balance so that they reflect the
account that has the maximum balance of all the accounts processed so far, as well as the
total balance of all the accounts processed so far.

Homework exercise – planning


Write a method ProcessAccount that takes as input the following:
▪ The account name and value of its balance for the account that has the maximum balance of all the accounts processed so far
▪ The total balance of all the accounts processed so far
▪ The account name and value of its balance for the account that is currently being processed
The method must update the account name and value of its balance so that they reflect the account that has the maximum balance of all
the accounts processed so far, as well as the total balance of all the accounts processed so far.
Items Types From? Process
Data Account name (highest) char Calling method
Balance amount (highest) double Calling method
Total balance double Calling method
Account name (current) char Calling method
Balance amount (current) double Calling method
Output Updated values for account name (highest), balance (highest), total balance
How Use 3 reference parameters because values needs to come into and out of the method
Check the balance of the current account again the balance of the highest account, If statement
update the account balance (highest), account name (highest) and total balance if
relevant

12
2025/04/14

On the module to-do list


▪ Attempt the homework exercise before your next session
• You are required to write a program that will calculate and display the total balance on your bank accounts
and the name of the account with the highest balance…
• Available on the module site as Week 9 homework exercise
▪ Read through the exercise that will be discussed in the next session
• An animal adoption agency….
• Available on the module site as Week 9 classwork exercise

▪ Quiz 6 due on Monday 14 April


▪ Prac 8 Complete and show completion of tasks in your session
▪ Quiz 7 due on Tuesday 22 April (Monday 21 April is a public holiday)

Any questions

13
2025/04/14

Last slide
▪ Time to pack up and go
▪ See you another time
▪ ☺

14

You might also like