Basic Logic – Chapter 3
-
Upload
sean-morrow -
Category
Documents
-
view
43 -
download
3
description
Transcript of Basic Logic – Chapter 3
Basic Logic – Chapter 3
IPC144 Week 3
Sequential Logic
• Statements executed sequentially – one after another
• Limited usefulness
• All programs shown so far have been sequential
• Often need to perform logic based on conditions conditional logic
Conditional example : movie tickets
• Movie tickets are to be sold using the following prices:
Adult: $10
Child under 6 years: $4
Student(6-19 years): $7
Senior citizen(65 yrs and over): $7
• Express this using conditional logic!
Conditional Logic• Condition tested and one action or another will be
performed• A condition in C can include variables, literal values
(eg 3, "a", "$", …), relational operators (> < == >= <= !=), arithmetic operators (= - * / …), …
• Example of condition: age > 19• One method of implementing conditional logic in C: if
statement• Simple if statement syntax
if (condition)statement;
Simple Conditional Logic Example
• Calculate the cost of doughnuts bought at $0.60 per doughnut
• GST of 7% is charged if fewer than 6 doughnuts bought
• Display the amount of GST charged and the total amount owed
• Write a C program to do this!
If Statement ExampleWrite C program for this problem!
Code blocks
• Groups of C statements can be treated as one logical statement by enclosing within brace {} brackets
• Group of statements within main are treated as a big block of code
• Can use additional {} within main to group statements, eg within an if statement
Code blocks example• Assume PST of 8% is also to be charged if fewer
than 6 doughnuts bought…
if (qty < 6) {
GSTamt = subtotal * 0.07;PSTamt = subtotal * 0.08;
}total = subtotal + GSTamt + PSTamt;
…
main(){
int qty;double subtotal, total, PSTamt, GSTamt =0;printf("Enter number of dougnuts: ")scanf("%d", &qty);subtotal = qty * 0.60;if (qty < 6) {
GSTamt = subtotal * 0.07;PSTamt = subtotal * 0.08;
}total = subtotal + GSTamt + PSTamt;printf("Total owed: $%.2lf , GST:$%.2lf, PST:$.2lf\n", total, GSTamt, PSTamt);
}