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

Lecture 04b - Making Decisions

The document announces that a semester test is scheduled for March 19th in 3 sessions from 4-7:40 PM, provisionally as a coding exam only with no multiple choice. It provides homework on writing a guessing game program and covers content on decision making using if/else statements and switch cases. The document emphasizes planning solutions before coding and provides an example of pseudocode for a tax calculation program.

Uploaded by

kabelomokoena060
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)
51 views14 pages

Lecture 04b - Making Decisions

The document announces that a semester test is scheduled for March 19th in 3 sessions from 4-7:40 PM, provisionally as a coding exam only with no multiple choice. It provides homework on writing a guessing game program and covers content on decision making using if/else statements and switch cases. The document emphasizes planning solutions before coding and provides an example of pseudocode for a tax calculation program.

Uploaded by

kabelomokoena060
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
You are on page 1/ 14

2024/03/07

Making decisions
Lecturer:
Ms Marinda Taljaard / Mr Ighsaan Salie / Mr Ntembeko Jafta

Admin – Semester test


▪ Test is scheduled for Tuesday 19 March
• Content covered will be up to and including Week 5 (11 – 15 Mar)
▪ To have enough space, there will probably be 3 sessions – booking will be on
Moodle
• Provisional times (to be confirmed later)
- Session 1: 16:00 – 17:00
- Session 2: 17:20 – 18:20
- Session 3: 18:40 – 19:40
▪ Provisionally planned as coding only,
no multiple choice

1
2024/03/07

Any general questions

Homework
Write a program named GuessingGame that generates a random number
between 1 and 10. Ask a user to guess the random number, then display the random
number and a message indicating whether the user’s guess was too high, too
low, or correct.

You can create a random number that is at least min but less than max using the
following statements:
Random ranNumberGenerator = new Random();
int randomNumber;
randomNumber = ranNumberGenerator.Next(min,max);

2
2024/03/07

Homework – one possible solution

Making decisions (choices)


▪ if
• Statement(s) within the if statement will only be executed when the condition (expression) evaluates
to true
▪ if-else
• Statement(s) within the if statement will only be executed when the condition (expression) evaluates
to true, otherwise the statement(s) within the else statement will be executed
▪ Nested if-else
• By nesting a number of if-else statements it is possible to choose between more than 2 options
▪ switch statement (discussed in the next couple of slides)
• Test a single variable against a series of exact matches
• Can also be referred to as a case structure

3
2024/03/07

Making decision using switch


switch (year)
▪ Consider a scenario where you want to {
display a comment based on a student’s case 1:
WriteLine(“Freshman”);
year in university break;
• For a student in year 1, display Freshman case 2:
WriteLine(“Sophomore”);
• For a student in year 2, display Sophomore break;
case 3:
• For a student in year 3, display Junior WriteLine(“Junior”);
• For a student in year 4, display Senior break;
case 4:
• Any other values are seen as invalid WriteLine(“Senior”);
break;
default:
• This can be done using a nested if-else WriteLine(“Invalid year”);
statement or with a switch statement break;
}

Making decision using switch


switch (year)
▪ Begins by evaluating the year variable {
• Which must be declared earlier, and must case 1:
WriteLine(“Freshman”);
have a value break;
case 2:
▪ If year is equal to any case label value, the WriteLine(“Sophomore”);
statement(s) for that case executes break;
case 3:
▪ The break statement that follow each output WriteLine(“Junior”);
statement cause a bypass of other cases break;
case 4:
▪ If year does not contain the same value as WriteLine(“Senior”);
any of the case label values, the default break;
default:
statement(s) execute WriteLine(“Invalid year”);
break;
}

4
2024/03/07

Making decision using switch


switch (year)
▪ Another way to make decisions instead of {
using a nested if-else, case 1:
WriteLine(“Freshman”);
▪ Easy to read and understand, but break;
case 2:
▪ Note that the functionality is limited, WriteLine(“Sophomore”);
• It can only test one variable, break;
case 3:
• Can only test for equality WriteLine(“Junior”);
break;
case 4:
WriteLine(“Senior”);
break;
default:
WriteLine(“Invalid year”);
break;
}

Time to gather your thoughts


▪ Is there always just one correct solution?
▪ Are some solutions better (more efficient) than others?
▪ What should you do to master the content?
• Practice as much as possible
• Run your code, check whether it works for a variety of cases (values)
• Consider whether it can be made more efficient

5
2024/03/07

How to think about Programming


▪ What info do we have?
• Variables (e.g. types, constants, initialised, declared, user input …)
▪ What info do we need to end up with?
• What results are required, how should it be displayed?
▪ How do we get from the input info to the output info?
• Plan the solution (what formulas, what logical expressions, what loops, in what order?)
• Order of statements can be very important

▪ How do I write the code?


• Implement the solution (syntax)
▪ Does the code work?
• Test with a variety of input data

Class exercise 1
Write a program that requests from a user the number of pies (at R18.50 per pie) and
the number of hamburgers (at R35.00 per hamburger), and then calculates the total for
the order.

▪ Should use constants for price of Pies and Hamburger


▪ Declare variables for QtyPies, QtyHamb
▪ Prompt the user for the values
▪ Do calculation for total due
▪ Display result (display value with currency formatting)
▪ Request amount paid by user
▪ Calculate and display the change amount

6
2024/03/07

Class exercise 1 – possible solution


▪ Any line numbers you would
like to discuss?

Should use constants for price of Pies and


Hamburger
Declare variables for QtyPies, QtyHamb
Prompt the user for the values
Do calculation for total due
Display result (display value with currency
formatting)
Request amount paid by user
Calculate and display the change amount

Class exercise 2
People who earn less than R6 000.00 do not pay tax. People older than 70 years
do not pay tax. Write a program that reads in a person’s salary and age. If the
person should pay tax, your program should request the tax percentage. The
program must finally display an appropriate message.
▪ Declare variables, constants
▪ Prompt the user for the values
▪ Choice to be made - determine the condition(s) to check
▪ Display result
(ideally use appropriate formatting)

7
2024/03/07

Planning your solutions


▪ With you learning more and more coding structures and statements, it is important
to realise that planning should happen before coding
• Pseudo code
- Text based algorithmic design tool
• Flow diagrams

1. Ask user for age


2. Ask user for salary
3. If salary is 6000 or more
1. Ask for tax %
2. Calculate tax amount
3. Calculate final payout
4. Display message with tax amount
else
1. Display message

Class exercise 2 – possible solution


▪ Any line numbers
you would like to
discuss?

8
2024/03/07

Concepts covered up to now


▪ Variables, different data types, variable declaration, constants
▪ Syntax, comments, operators
▪ WriteLine() – displaying text and contents of variables, formatting
▪ ReadLine() – get data from user, convert to int/double when required
▪ Shortcuts and unary operators
▪ Numeric type conversion
▪ Making selections (decisions): if, if-else, nested if, switch
▪ Compound expressions (&&, ||), conditional operator, not operator
▪ Using build-in methods
▪ Planning the process
▪ Testing your solution

Time for discussion


▪ How do you decide about when to use WriteLine() or Write()?
• It influences how your text is displayed on the console screen

▪ How do you decide about which datatypes to use?


• double
• int
• String
• char
• bool

9
2024/03/07

Start thinking about efficient code


▪ Consider the practice exercise about IQ
•Write a program that prompts the user for an
IQ score (this can be an integer). If the score
is a number less than 0 or greater than 200,
display an error message. Otherwise display
a message according to the values provided…
▪ If you know that each section of the if-else Solution partially hidden,
needs a similar output message as you should be
completing it yourself
• Assign values to variables inside the if-else
sections
• But have only one output message after the
if-else

Initialising variables
▪ When a variable gets a
value inside an if / if-else
• Declare the variable before
the if
• Instead of when you want to
assign a value Solution partially hidden,
as you should be
• As message was declared completing it yourself
inside the if, it is not
recognised outside the if

10
2024/03/07

Initialising variables – compare these

Solution partially hidden,


as you should be Solution partially hidden,
completing it yourself as you should be
completing it yourself

Formatting output
▪ Formatting
• If no specific instructions are given – make appropriate choices
- Monetary amounts should be formatted to show the currency sign
• Output should look good

11
2024/03/07

Example – working with int and double


Write a program that declares four integers. The user is requested to enter the values of
the 4 variables (one by one) and then the sum and average of these values must be
calculated and displayed.
▪ Declare 4 integers, as well as variables for sum and avg (avg must be a double)
▪ Use Write() or WriteLine() to prompt the user, use ReadLine() to get value
▪ Do calculations for sum and avg
• How do you make sure you do not lose the decimal places when calculating avg
• If sum is an int , consider: avg = sum / 4 vs avg = sum / 4.0
• If sum is a double, you can have: avg = sum / 4
▪ Display result

Home work
▪ Write a program that can be used to teach a user the word for the numbers 1 –
10 in a different language (e.g. Spanish)
▪ The Spanish words are:
• Uno, dos, tres, cuatro, cinco, seis, siete, ocho, nueve,
diez

▪ Your program should request an integer from the user, and the display the
corresponding word in Spanish, if the user enters a number that is not in the range
of 1 – 10, display an appropriate message
▪ Make use of a switch statement in your solution

12
2024/03/07

Looking ahead into next week…


Write a program that allows the user to enter five integers and displays their sum
▪ Process
• What info do we have? 5 number (double/int?)
- Which variables do we need – and which types? User input
Display the sum of the numbers
- Where does the values for the variables come from?
- What info do we need to end up with?
• What do we need to determine/calculate? Calculate the sum
• How do we write this code?
No
- Is there a choice to be made?
- Do we need to repeat the same instructions a number of times?
Yes
▪ Which instructions needs to be repeated?

Any questions

13
2024/03/07

On the module to-do list


▪ Practical 3 to be completed this week
• Show completion/progress of completion before the end of the session
• But also save your projects to your S drive
• Remember to keep your S drives organised
▪ Quiz 3 is due on Monday 11 March (14:00)

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

14

You might also like