Basic Logic – Chapter 3

9
Basic Logic – Chapter 3 IPC144 Week 3

description

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. - PowerPoint PPT Presentation

Transcript of Basic Logic – Chapter 3

Page 1: Basic Logic – Chapter 3

Basic Logic – Chapter 3

IPC144 Week 3

Page 2: Basic Logic – Chapter 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

Page 3: Basic Logic – Chapter 3

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!

Page 4: Basic Logic – Chapter 3

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;

Page 5: Basic Logic – Chapter 3

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!

Page 6: Basic Logic – Chapter 3

If Statement ExampleWrite C program for this problem!

Page 7: Basic Logic – Chapter 3

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

Page 8: Basic Logic – Chapter 3

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;

Page 9: Basic Logic – Chapter 3

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

}