+ All Categories
Home > Documents > Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter...

Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter...

Date post: 18-Dec-2015
Category:
Upload: elfrieda-malone
View: 224 times
Download: 1 times
Share this document with a friend
40
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS 202 12-10-1429
Transcript

Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman

Chapter 4(Conditional Statements)

© CPCS 202

12-10-1429

CHAPTER 4 - Conditional Statements1. Simple Logic Expression2. Complex Logic Expression3. Evaluation Tree4. Conditional Statements

a) IF Statementb) Switch Statement

5. Common Errors in Conditions

-2-

#

column shows the topics index. column shows the programs index.

1. ATM Simulation 1

2. ATM Simulation 2

-3-

Simple Logic ExpressionA. Introduction

often need to look at data values and make choices

logical expressions are true/false statements of data relationships

B. Prototype

1

Simple Logic Expression

Operator

Less than <

Larger than >

Less than or equal <=

Simple Logic Expression

Operator

Larger than or equal >=

Equal ==

Not equal !=

variables or constants

relational or equality

variables or constants

data operator data

-4-

Simple Logic ExpressionC. Example

let a = 17 and b = 42 (a < b) is true (a > b) is false (a <= b) is true (a >= b) is false (a == b) is false (a != b) is true

1

-5-

Complex Logic ExpressionA. Introduction

can combine expressions to get complex logical expressions

useful for more realistic data comparison tasks

B. Prototype

2

Imagine 1 light with 2 switches; the operator between them is &&, ||, or !

Logic Expression

Result

TRUE && TRUE TRUE

TRUE && FALSE FALSE

FALSE && TRUE FALSE

FALSE && FALSE

FALSE

Logic Expression

Result

TRUE || TRUE TRUE

TRUE || FALSE TRUE

FALSE || TRUE TRUE

FALSE || FALSE FALSE

Logic Expression

Result

! TRUE FALSE

! FALSE TRUE

AND && OR || NOT !

expression operator expression

-6-

Complex Logic ExpressionC. Example

let x = 3.14 and y = 7.89 ((x < 4)&&(y < 8)) is true (because both halves are

true) ((x > 3)&&(y > 8)) is false (because second half is

false) ((x < 4)||(y > 8)) is true (because first half is true) ((x < 3)||(y < 8)) is true (because second half is

true) ((x > 4)||(y > 8)) is false (because both halves are

false) (x < y) is true,!(x < y) is false (x >= y)   is false, !(x >= y)  is true (a == b) is false, !(a == b) is true (a != b) is true,!(a != b) is false

2

-7-

T ! F

Evaluation Tree (Step-by-Step)A. Introduction

a way to solve a logic expression

B. Way to Do solve the simple logic expression first

C. Example

3

><

4 5 5 9

||

T

T

((x < 5)|| !( y > 9)) (x=4 ; y=5)

!

Precedence

Operator

Highest

Lowest

! + - &

* / %

+ -

< <= >= >

== !=

&&

||

=

-8-

Conditional StatementsA. Overview

control the flow of your program two types of the conditional statements available

in C: if statement Switch statement

4

-9-

IF StatementA. Overview

control the flow of your program based on True or False allow selecting an action based on condition three types of the IF statements:

1. IF(allows the flow of the program to be changed)

2. IF-ELSE(gives an alternative path to be executed if the IF statement condition is False)

3. Nested IF(you will see a group of IF statements that each checks one condition within another)

4a

-10-

IF Statement (IF)A. Introduction

can selectively execute code using if statement

when logical expression is true, selected code is executed

when logical expression is false, selected code is skipped

selected code can be either a single statement or a block of statements which is enclosed in { } characters

should indent code to aid program readability

you only need semi-colon after single statements, not after { }

4a1

1

2

3Conditio

n

5

6

7

4

T

-11-

B. Prototype If you have only one statement after an if

statement, you do not need (but you can) to put the statement in braces. For example:

To have more than one statement execute after an if statement that evaluates to true, use braces. For example:

if ( TRUE ){     All the statements in this block execute if the condition is True}

if ( TRUE ) Statement executes if condition is TrueStatement executes if condition is True/False

IF Statement (IF)

4a1

Anything inside braces is called a compound statement, or a block

2.

3.4.

1

2Conditio

n

4

3

T

1

2Conditio

n

5

3

T

4

2.3.4.

-12-

C. Examplescanf(“%d”, &a);scanf(“%d”, &b); if (b > a)    printf ("B is larger than A\n“);printf (“Done...\n“);

scanf(“%d”, &a);scanf(“%d”, &b);if (a < b) {    printf("A is smaller than B\n“);    printf("The difference is %d\n“, b–a); }printf (“Done...\n“);

1.2.3.

4.5.

6.

1.2.3.4.5.

IF Statement (IF)

4a1

In a diagram, you can merge the sequential blocks in one block

1-2

3

5

4

T

1-2

3

6

4-5

T

-13-

IF Statement (IF-ELSE)A. Introduction

often need two alternatives in an if statement

want to execute certain code if expression is true

want to execute different code if expression is false

the if-else statement lets you do this can use single statement or block of

code for either part should indent code to aid program

readability

4a2

1

2

3Conditio

n

6

7

8

5

T

4

F

-14-

IF Statement (IF-ELSE)B. Prototype

if ( condition 1 )

{

   // A. Execute these statements

// if condition 1 is TRUE

}

else

if ( condition 2 )

{

   // B. Execute these statements

// if condition 2 is TRUE

} else if ( condition 3 ) {    // C. Execute these statements // if condition 3 is TRUE } else {    // D. Execute these statements // if condition 1, 2 and 3 are FALSE }

4a2

The compiler looks at the entire program in one line unless there is ;

The

sam

e

Cond.1

A

TF

Cond.2

B

TF

Cond.3

C

TF

D

-15-

C. Exampleprintf(“Enter the grade for the course: ”); scanf(“%d”, &grade);

if (grade >= 90) printf(“GPA = A\n”); else if (grade >= 80) printf(“GPA = B\n”); else if (grade >= 70) printf(“GPA = C\n”); else if (grade >= 60) printf(“GPA = D\n”); else{ printf(“GPA = F\n”); printf(“UNSATISFACTORY.\n”); }

1.2.

3.4.5.6.7.8.9.10.

11.12.

IF Statement (IF-ELSE)

4a2

ELSE is not an stand alone statement, so do not put a line number for it

-16-

IF Statement (Nested IF)A. Introduction

often need to check one condition within another can nest if statements to accomplish this need to take care when matching up { } brackets use indentation to reflect nesting and aid

readability

4a3

-17-

IF Statement (Nested IF)B. Prototype

if (expression 1) {

   // A. statements   if (expression 2)

{       // B. statements   }    else

  {       // C. statements      if (expression 3)

  {          // D. statements       }    } } else {    // E. statements   if (expression 4)   {       // F. statements   } }

4a3

Exp. 1

A

T

E

F

Exp. 2

B

T

C

F

Exp. 3

D

T

Exp. 4

F

T

-18-

C. Example if (a > 0) {    if (b < 0) {     a = 3 * b;    c = a + b; }} else{    a = 2 * a;    c = b / a;}

1.

2.

3.4.

5.6.

IF Statement (Nested IF)

4a3

Draw the flowchart for this program?

-19-

IF StatementB. Conclusion

4a

In a diagram, you can merge the sequential blocks in one block

1

2

3

4

5

6

7

1

2

Condition

4

5

6

3

T

1

2

Condition

5

6

7

3

T

4

F

Sequential IF IF / ELSE

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 1

P1

Write a program that simulates an ATM, where they are three main options:1.Deposit Money2.Withdraw Money3.Print Balance

Assume the balance in the account is Zero Use if to choose an option from the Main Menu

-20-

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 1

P1

Input An option from the main menu Amount of money to deposit if the user choose option 1 Amount of money to withdraw if the user choose option

2 Output

The balance if the user choose option 3 Formula

Balance = Balance + Deposit if the user choose option 1

Balance = Balance – Withdraw if the user choose option 2

Think about the input/formula/output for each option in the main menu

-21-

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 1

P1

1. Initial the balancebalance = 0

2. Ask the user to choose one of the 3 options command

Deposit Money

A. Get the amount of money that wants to deposit money

B. Calculate the balance

balance = balance + money Withdraw Money

A. Get the amount of money that wants to deposit money

B. Calculate the balance

balance = balance - money

C. Display the balance balance

-22-

1

2

Error Option

ImplementationProblem Analysis Design Outline Testing Maintenance

#include <stdio.h>

int main(void){ int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // Output: Display the balance

/* 1. Initial the balance */

/* 2. Ask the user to choose one of the 3 options */ if (command == 1) /* 2.1 Deposit Money */ { } else if (command == 2) /* 2.2 Withdraw Money */ { } else if (command == 3) /* 2.3 Print Balance */ { }

return(0);}

ATM Simulation 1

P1

-23-

1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 1#include <stdio.h>

int main(void){ int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // Output: Display the balance

/* 1. Initial the balance */ balance = 0;

/* 2. Ask the user to choose one of the 3 options */ printf(" Main Menu\n"); printf("-----------------------\n"); printf(" 1 - Deposit money\n"); printf(" 2 - Withdraw money\n"); printf(" 3 - Print balance\n"); printf("Enter command number: "); scanf("%d", &command);

if (command == 1) /* 2.1 Deposit Money */ { printf("Enter deposit amount: "); scanf("%d", &money); balance = balance + money; } else if (command == 2) /* 2.2 Withdraw Money */ { printf("Enter withdraw amount: "); scanf("%d", &money); balance = balance - money; } else if (command == 3) /* 2.3 Print Balance */ { printf("Current balance = %d\n", balance); }

return(0);}

1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.

P1

-24-

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 1

P1

Useless program because it doesn’t have a loop to see the new balance

-25-

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 1

P1

Maintain the program to validate the inputs? input has to be 1,2,3 only

-26-

Validation Check:

If a user put an invalid input, you need to display an error message

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 1#include <stdio.h>

int main(void){ int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // Output: Display the balance

/* 1. Initial the balance */ balance = 0;

/* 2. Ask the user to choose one of the 3 options */ printf(" Main Menu\n"); printf("-----------------------\n"); printf(" 1 - Deposit money\n"); printf(" 2 - Withdraw money\n"); printf(" 3 - Print balance\n"); printf("Enter command number: "); scanf("%d", &command);

if (command == 1) /* 2.1 Deposit Money */ { printf("Enter deposit amount: "); scanf("%d", &money); balance = balance + money; } else if (command == 2) /* 2.2 Withdraw Money */ { printf("Enter withdraw amount: "); scanf("%d", &money); balance = balance - money; } else if (command == 3) /* 2.3 Print Balance */ { printf("Current balance = %d\n", balance); } else /* Otherwise, display an error */ { printf("Error choice...\n"); } return(0);}

1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.

P1

-27-

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 1

P1

-28-

-29-

Switch StatementA. Introduction

switch statement convenient for handling multiple if-else cases

need to use single value as decision variable (called: controlling expression) of type: int or char, but not of type double

need to identify code to be executed for each case it is essential to end each case with break command can use default for all cases not specifically labeled

B. Prototypeswitch ( decision value ) {    case label1 : statements;       break;    case label2: statements;       break;    default: statements; }

4b

C. Examples

Switch Statement

4b

switch (command) { case 1: printf(“Light is ON.\n"); break; case 2: printf(“Light is OFF.\n"); break;   default:   printf("Error Option!\n"); }

1.2.3.4.5.6.7.8.9.10.11.

3

4

TF

6

7

TF

10

switch (command) { case 1: printf(“Light is ON.\n"); break; case 2: printf(“Light is OFF.\n"); break;   default:   printf("Error Option!\n"); }

1.2.3.4.5.6.7.8.9.10.11.

3

4

TF

6

7

TF

10

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 2

P2

Write a program that simulates an ATM, where they are three main options:1.Deposit Money2.Withdraw Money3.Print Balance

Assume the balance in the account is Zero Use if to choose an option from the Main Menu Validate the input; if a user choose a wrong option,

display an error message

As same as Program 1, but use Switch statement instead of IF -31-

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 2

P2

Input An option from the main menu Amount of money to deposit if the user choose option 1 Amount of money to withdraw if the user choose option

2 Output

The balance if the user choose option 3 An error message if the user choose a wrong option

Formula Balance = Balance + Deposit if the user choose option

1 Balance = Balance – Withdraw if the user choose option

2

Think about the input/formula/output for each option in the main menu

-32-

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 2

P2

1. Initial the balancebalance = 0

2. Ask the user to choose one of the 3 options command

Deposit Money

A. Get the amount of money that wants to deposit money

B. Calculate the balance

balance = balance + money Withdraw Money

A. Get the amount of money that wants to deposit money

B. Calculate the balance

balance = balance - money

Print Balance

C. Display the balance balance

D. Display an error message -33-

1

2

3

Error Option

ImplementationProblem Analysis Design Outline Testing Maintenance

#include <stdio.h>

int main(void){ int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // Output: Display the balance

/* 1. Initial the balance */

/* 2. Ask the user to choose one of the 3 options */ switch (command) { case 1: /* 2.1 Deposit Money */ break; case 2: /* 2.2 Withdraw Money */ break; case 3: /* 2.3 Print Balance */ break; default: /* Otherwise, Error Message */ } return(0);}

ATM Simulation 2

P2

-34-

1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 2#include <stdio.h>

int main(void){ int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // Output: Display the balance

/* 1. Initial the balance */ balance = 0;

/* 2. Ask the user to choose one of the 3 options */ printf(" Main Menu\n"); printf("-----------------------\n"); printf(" 1 - Deposit money\n"); printf(" 2 - Withdraw money\n"); printf(" 3 - Print balance\n"); printf("Enter command number: "); scanf("%d", &command);

switch (command) { case 1: /* 2.1 Deposit Money */ printf("Enter deposit amount: "); scanf("%d", &money); balance = balance + money; break; case 2: /* 2.2 Withdraw Money */ printf("Enter withdraw amount: "); scanf("%d", &money); balance = balance - money; break; case 3: /* 2.3 Print Balance */ printf("Current balance = %d\n", balance); break; default: /* Otherwise, Error Message */ printf("Error choice...\n"); }

return(0);}

1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.

P2

-35-

ImplementationProblem Analysis Design Outline Testing Maintenance

ATM Simulation 2

P2

-36-

-37-

Common Errors in ConditionsA.if (0 <= x <= 4) printf(“Condition is true.\n”);

B.if (x = 10) printf(“x is 10.\n”);

C.if (x > 0) sum = sum + x; printf(“Greater than zero.\n”);else printf(“Less than or equal to zero”);

5

Make sure to indent the block of statements to clear the readability

Evaluation Homework1. The 2nd example in IF-ELSE described transferring the

number grades to letter grades. Write a program for this problem using a Switch statement without any IF statement?

2. The result of the following logic expression is: flag || !(y + z >= x – z) where (flag=0; x=3; y=4; z=2)

A. True

B. False

3. The output of the following flow diagram if (X=1) is:A. 1

B. 2

C. 3

D. 13

E. 23

-38-

hw

X>2

printf(“2”);printf(“1”);

printf(“3”);

TF

Evaluation Homework4. Type Program 2 and display the result when case

= 2(Print a copy of the code and a snapshot of the output), and then remove the break from the second case.(Display the output only in the same page when case=2) Describe what happened when break was removed?(put the answer at the end of the same page)

5. Re-write the following program them after fixing the errors? Show the output and draw the flow diagram?

-39-

hw

double fee(int speed) { IF (speed > 160) money = 300.00; elseif (speed > 140) money = 200.00; Else money = 100.00;  return (money);}int main(void) {  printf(“What is the speed of the car:”); scanf(“%d”, &speed); printf(“Speed = %d, Ticket = %f\n”, speed, fee(speed));}

1.2.3.4.5.6.7.8.9.10.11.12.13.

CHAPTER 4 - Conditional Statements1. Simple Logic Expression2. Complex Logic Expression3. Evaluation Tree4. Conditional Statements

a) IF Statementb) Switch Statement

5. Common Errors in Conditions

-40-

#

column shows the topics index. column shows the programs index.

1. ATM Simulation 1

2. ATM Simulation 2


Recommended