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.

Slides:



Advertisements
Similar presentations
Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
Advertisements

Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Chapter 6 Horstmann Programs that make decisions: the IF command.
true (any other value but zero) false (zero) expression Statement 2
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
Visual C++ Programming: Concepts and Projects
Chapter 5 (Loop Statements)
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
1 Chapter 3 Flow of Control. 2 Review of Class on Sep 23.
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
IF-ELSE IF-ELSE STATEMENT SWITCH-CASE STATEMENT Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Chapter 4 Selection Structures: Making Decisions.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CONDITIONAL STATEMENTS OVERVIEW.  Many times we want programs to make decisions  What drink should we dispense from the vending machine?  Should we.
Flow of Control Part 1: Selection
A First C Program /* Print a Message */ #include main() { printf("This is a test!\n"); } The program is compiled and run as cc pg32.c  a.out  This is.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
TK 1914 : C++ Programming Control Structures I (Selection)
CCSA 221 Programming in C CHAPTER 6 MAKING DECISIONS 1.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter Making Decisions 4. Relational Operators 4.1.
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
IT CS 200: C ONDITION Lect. Napat Amphaiphan. T HE ABILITY TO CONTROL THE FLOW OF YOUR PROGRAM, LETTING IT MAKE DECISIONS ON WHAT CODE TO EXECUTE 2.
Lecture 7: Menus and getting input. switch Multiple-selection Statement switch Useful when a variable or expression is tested for all the values it can.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Control Statements: Part1  if, if…else, switch 1.
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Dr. Sajib Datta Sep 3,  A new operator used in C is modulus operator: %  % only used for integers, not floating-point  Gives the integer.
Chapter 4 – C Program Control
CNG 140 C Programming (Lecture set 3)
The if…else Selection Statement
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Decisions Chapter 4.
Chapter 4: Making Decisions.
Chapter 4 (Conditional Statements)
Flow of Control.
Chapter 4: Making Decisions.
Introduction to Programming
Chapter 13 Control Structures
Control Structures Lecture 6.
ICS103: Programming in C 4: Selection Structures
Chapter 13 Control Structures
Presentation transcript:

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

CHAPTER 4 - Conditional Statements 1. Simple Logic Expression 2. Complex Logic Expression 3. Evaluation Tree 4. Conditional Statements a) IF Statement b) 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

Simple Logic Expression A. Introduction  often need to look at data values and make choices  logical expressions are true/false statements of data relationships B. Prototype 3 1 Simple Logic ExpressionOperator Less than< Larger than> Less than or equal<= Simple Logic ExpressionOperator Larger than or equal>= Equal== Not equal!= variables or constants relational or equality variables or constants

Simple Logic Expression C. 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 4 1

Complex Logic Expression A. Introduction  can combine expressions to get complex logical expressions  useful for more realistic data comparison tasks B. Prototype 5 2 Imagine 1 light with 2 switches; the operator between them is &&, ||, or ! Logic ExpressionResult TRUE && TRUETRUE TRUE && FALSEFALSE FALSE && TRUEFALSE FALSE && FALSEFALSE Logic ExpressionResult TRUE || TRUETRUE TRUE || FALSETRUE FALSE || TRUETRUE FALSE || FALSEFALSE Logic ExpressionResult ! TRUEFALSE ! FALSETRUE AND && OR || NOT !

Complex Logic Expression C. 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 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 6 2

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 7 3 >< || T T ((x 9)) (x=4 ; y=5) ! PrecedenceOperator Highest Lowest ! + - & * / % + - = > == != && || =

Conditional Statements A. Overview  control the flow of your program  two types of the conditional statements available in C:  if statement  Switch statement 8 4

IF Statement A. 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) 9 4a

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 { } 10 4a Condition T

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 True Statement executes if condition is True/False IF Statement (IF) 11 4a1 Anything inside braces is called a compound statement, or a block Condition 4 3 T 1 2 Condition 5 3 T

C. Example scanf(“%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“); IF Statement (IF) 12 4a1 In a diagram, you can merge the sequential blocks in one block T T

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 13 4a Condition T 4 F

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 } 14 4a2 The compiler looks at the entire program in one line unless there is ; The same Cond.1 A T F Cond.2 B T F Cond.3 C T F D

C. Example printf(“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”); } IF Statement (IF-ELSE) 15 4a2 ELSE is not an stand alone statement, so do not put a line number for it

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 16 4a3

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 } } 17 4a3 Exp. 1 A T E F Exp. 2 B T C F Exp. 3 D T Exp. 4 F T

C. Example if (a > 0) { if (b < 0) { a = 3 * b; c = a + b; } } else { a = 2 * a; c = b / a; } IF Statement (Nested IF) 18 4a3 Draw the flowchart for this program?

IF Statement B. Conclusion 19 4a In a diagram, you can merge the sequential blocks in one block Condition T T 4 F SequentialIFIF / ELSE

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 P1  Write a program that simulates an ATM, where they are three main options: 1. Deposit Money 2. Withdraw Money 3. Print Balance  Assume the balance in the account is Zero  Use if to choose an option from the Main Menu -20-

Implementation Problem 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-

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 P1 1. Initial the balance balance = 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 A. Display the balance  balance Error Option

Implementation Problem Analysis Design Outline Testing Maintenance #include 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 P

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 #include 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); } P1 -24-

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 P1 Useless program because it doesn’t have a loop to see the new balance -25-

Implementation Problem 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

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 #include 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); } P1 -27-

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 P1 -28-

Switch Statement A. 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. Prototype switch ( decision value ) { case label1 : statements; break; case label2: statements; break; default: statements; } 29 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"); } T F 6 7 T F 10 switch (command) { case 1: printf(“Light is ON.\n"); break; case 2: printf(“Light is OFF.\n"); break; default: printf("Error Option!\n"); } T F 6 7 T F switch (command) { case 1: printf(“Light is ON.\n"); break; case 2: printf(“Light is OFF.\n"); break; default: printf("Error Option!\n"); } T F 6 7 T F 10

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 2 P2  Write a program that simulates an ATM, where they are three main options: 1. Deposit Money 2. Withdraw Money 3. 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-

Implementation Problem 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-

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 2 P2 1. Initial the balance balance = 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 A. Display the balance  balance A. Display an error message Error Option

Implementation Problem Analysis Design Outline Testing Maintenance #include 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 P

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 2 #include 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); } P2 -35-

Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 2 P2 -36-

Common Errors in Conditions A. 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”); 37 5 Make sure to indent the block of statements to clear the readability

Evaluation Homework 1. The 2 nd 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 hw X>2 printf(“2”);printf(“1”); printf(“3”); TF

Evaluation Homework 4. 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 = ; elseif (speed > 140) money = ; Else money = ; 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)); }

CHAPTER 4 - Conditional Statements 1. Simple Logic Expression 2. Complex Logic Expression 3. Evaluation Tree 4. Conditional Statements a) IF Statement b) 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