The if…else Selection Statement

Slides:



Advertisements
Similar presentations
Decisions If statements in C.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Chapter 3 - Structured Program Development
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Structured Program Development in C
Lecture 3 Structured Program Development in C
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved The switch Multiple-Selection Statement switch.
Control Structures I (Selection)
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 4.8The do/while Repetition Structure The do/while repetition structure –Similar to the while structure –Condition for repetition tested after the body.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (Switch, do-while, break) Outline 4.7The.
Chapter 4 C Program Control. Objectives In this chapter, you will learn: –To be able to use the for and do … while repetition statements. –To understand.
Structured Program Development Outline 2.1Introduction 2.2Algorithms 2.3Pseudo code 2.4Control Structures 2.5The If Selection Structure 2.6The If/Else.
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. –Artificial, informal language used to develop algorithms –Similar.
C Lecture Notes 1 Structured Program Development.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Selection. Flow Chart If selection If/else selection Compound statement Switch.
Spring 2005, Gülcihan Özdemir Dağ Lecture 5, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 5 Outline 5.0 Revisiting.
Dale Roberts 1 Program Control - Algorithms Department of Computer and Information Science, School of Science, IUPUI CSCI N305.
C Programming 2002 Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Structured Program Development Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
1 Programming 2 Overview of Programming 1. Write the equations in C++ notation : a) R =   a + b  24  2 a  b) W = a 12 + b 2 – 2abcos(y) 2a.
1 Programming Application Overview of Structure Programming.
Chapter 3 Structured Program Development Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
C++ Programming Lecture 5 Control Structure I (Selection) – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
C++ Programming Control Structures I (Selection).
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Dale Roberts Program Control Department of Computer and Information Science, School of Science, IUPUI Fall 2003 CSCI 230 Dale Roberts, Lecturer
 2006 Pearson Education, Inc. All rights reserved if…else Double-Selection Statement if – Performs action if condition true if…else – Performs.
Chapter 4 – C Program Control
- Standard C Statements
Chapter 4 - Program Control
Chapter 2.1 Control Structures (Selection)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Programming Fundamentals
Programming Fundamentals
Lecture 2: Logical Problems with Choices
- Additional C Statements
Structured Program
Chapter 4 - Program Control
Chapter 3 - Structured Program Development
3 Control Statements:.
Chapter 3 - Structured Program Development
Capitolo 2 - Control Structures
Chapter 4: Control Structures I (Selection)
2.6 The if/else Selection Structure
-2- Introduction to C Programming
Dale Roberts, Lecturer IUPUI
Control Statements Paritosh Srivastava.
Chapter 4 - Program Control
Dale Roberts, Lecturer IUPUI
Dale Roberts, Lecturer IUPUI
Lecture 9: Implementing Complex Logic
Structural Program Development: If, If-Else
Presentation transcript:

The if…else Selection Statement Block: Compound statements with declarations Syntax errors Caught by compiler Logic errors: Have their effect at execution time Non-fatal: program runs, but has incorrect output Fatal: program exits prematurely

The if Selection Statement Selection structure: Used to choose among alternative courses of action Pseudocode: If student’s grade is greater than or equal to 60 Print “Passed” If condition true Print statement executed and program goes on to next statement If false, print statement is ignored and the program goes onto the next statement Indenting makes programs easier to read C ignores whitespace characters

The if…else Selection Statement Compound statement: Set of statements within a pair of braces Example: if ( grade >= 60 ) printf( "Passed.\n" ); else { printf( "Failed.\n" ); printf( "You must take this course again.\n" ); } Without the braces, the statement printf( "You must take this course again.\n" ); would be executed automatically

3.6 The if…else Selection Statement Pseudocode for a nested if…else statement If student’s grade is greater than or equal to 90 Print “A” else If student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F”

Control Structures < <= > >= == != ! && || use logical expressions which may include: 6 Relational Operators < <= > >= == != 3 Logical Operators ! && ||

Equality and Relational Operators

Trace int p, d=4, a=20; if ((d==4) && (a>24)) { p=d+a; printf(“ Low Risk \n”);} else { p=a-d; printf(“ the p is = %d”, p);

The if Selection Statement Pseudocode statement in C: if ( grade >= 60 ) printf( "Passed\n" ); C code corresponds closely to the pseudocode Diamond symbol (decision symbol) Indicates decision is to be made Contains an expression that can be true or false Test the condition, follow appropriate path

The if Selection Statement if statement is a single-entry/single-exit structure true false grade >= 60 print “Passed” A decision can be made on any expression. zero - false nonzero - true Example: 3 - 4 is true  

The if…else Selection Statement Only performs an action if the condition is true if…else Specifies an action to be performed both when the condition is true and when it is false Psuedocode: If student’s grade is greater than or equal to 60 Print “Passed” else Print “Failed” Note spacing/indentation conventions  

The if…else Selection Statement C code: if ( grade >= 60 ) printf( "Passed\n"); else printf( "Failed\n"); Ternary conditional operator (?:) Takes three arguments (condition, value if true, value if false) Our pseudocode could be written: printf( "%s\n", grade >= 60 ? "Passed" : "Failed" ); Or it could have been written: grade >= 60 ? printf( “Passed\n” ) : printf( “Failed\n” );

The if…else Selection Statement Flow chart of the if…else selection statement Nested if…else statements Test for multiple cases by placing if…else selection statements inside if…else selection statement Once condition is met, rest of statements skipped Deep indentation usually not used in practice true false print “Failed” print “Passed” grade >= 60

The value that printed is int delta = 0, x = 3; if (x / 2 = = 1) delta = delta + x; x - -; if (x / 2 = = 0) printf (“ % d “ , delta);

Enter two integers, and I will tell you the relationships they satisfy: 3 7 3 is not equal to 7 3 is less than 7 3 is less than or equal to 7 Program Output

Program Output (continued) Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12 Enter two integers, and I will tell you the relationships they satisfy: 7 7 7 is equal to 7 7 is less than or equal to 7 7 is greater than or equal to 7 Program Output (continued)

Logical Operators Useful as conditions in loops && ( logical AND ) Returns true if both conditions are true || ( logical OR ) Returns true if either of its conditions are true ! ( logical NOT, logical negation ) Reverses the truth/falsity of its condition Unary operator, has one operand Useful as conditions in loops Expression Result true && false false true || false true !false true

What is value of x when y is 15.0? if (y != (x-10.0) ) x=x-10.0; else x=x / 2.0;

Logical Operators

Logical Operators

int w = 5, x = 7, y = 9, z = 1; if (x % y > = 2 + w) { z+ +; What is the value of variable z after the following code is executed?   int w = 5, x = 7, y = 9, z = 1; if (x % y > = 2 + w) { z+ +; if (y – 3 * w > = - x) z - -; else z + +; } z = - 1;

What is the value is assigned to x when y is 15.0? if (y < 15.0) if (y>= 0.0) x=5*y; else x = 2*y; x= 3 * y;

Confusing Equality (==) and Assignment (=) Operators Dangerous error Does not ordinarily cause syntax errors Any expression that produces a value can be used in control structures Nonzero values are true, zero values are false Example using ==: if ( payCode == 4 ) printf( "You get a bonus!\n" ); Checks payCode, if it is 4 then a bonus is awarded

Confusing Equality (==) and Assignment (=) Operators Example, replacing == with =: if ( payCode = 4 ) printf( "You get a bonus!\n" ); This sets payCode to 4 4 is nonzero, so expression is true, and bonus awarded no matter what the payCode was Logic error, not a syntax error

Confusing Equality (==) and Assignment (=) Operators lvalues Expressions that can appear on the left side of an equation Their values can be changed, such as variable names x = 4; rvalues Expressions that can only appear on the right side of an equation Constants, such as numbers Cannot write 4 = x; Must write x = 4; lvalues can be used as rvalues, but not vice versa y = x;

If--Else for a mail order Write a program to calculate the total price of a certain purchase. There is a discount and shipping cost: The discount rate is 25% and the shipping is 10.00 if purchase is over 100.00. Otherwise, The discount rate is 15% and the shipping is 5.00 pounds.

Example The Air Force has asked you to write a program to label aircrafts as military or civilian. Your program input is the plane’s speed and its estimated length. For planes traveling faster than 1100 km/hr, you will label those shorter than 52 m “military”, and longer as “Civilian”. For planes traveling less than 1100, you will issue an “aircraft unknown” statement.

Find the output if (x > 10) z= z*m; if ( y< 0) p = p *5; For x=15, y=-5, z=2, p =3 and m=10, find the output of the following code if (x > 10) z= z*m; if ( y< 0) p = p *5; printf(“%d%d”, z, p); else if ( y< 0)

Write a program that reads a number in range 0-100 and print ‘F’ if the number is less than 50, ‘P’ if the number is in the range 50-59, and ‘S’ if the number is greater than 65.

Write a complete C program that asks a person for the number of hours he worked in a week and then print out his salary. Given that a person who worked 40 hours or less gets $5 per hour and a person who worked more than 40 hours gets $7 per hour for over 40 hours?

A factory has some workers and it divides its workers into three skill levels. Unskilled workers receive L.E. 8.15 per hour, semiskilled workers receive L.E. 12.55 an hour, and skilled workers L.E. 18.60 an hour. Write a program to calculate the worker’s weekly pay formatted to two decimal places. Your program input should consist of the hours worked and a skill level indicator for the worker. Then the wage should be displayed.

The switch Multiple-Selection Statement Useful when a variable or expression is tested for all the values it can assume and different actions are taken Format Series of case labels and an optional default case switch ( value ){ Case ‘1’: actions Case ‘2’: default: } break; exits from statement  

The switch Multiple-Selection Statement Flowchart of the switch statement true false . case a case a action(s) break case b case b action(s) case z case z action(s) default action(s)

(Part 1 of 3)

(Part 2 of 3)

(Part 3 of 3)

Enter the letter grades. Enter the EOF character to end input. a b c C Incorrect letter grade entered. Enter a new grade. D ^Z   Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1 Program Output

int z; z = 10 + 8 / 3 * 2 + 10 % 3; switch (z) { case 23 : printf(“ Very High”); break; case 21 : printf(“ High “); break; case 18 : printf(“ Med “); break; case 15 : printf(“ Low “); break; case 10 : printf(“ Very Low “); break; default : printf(“ None “); break; }

Find the output int x= 5, y= 2; char op = ‘*’; switch (op) { case ‘+’ : x = x+y; case ‘-‘ : x=x- y; break; case ‘*’ : x= x * y ; case ‘/’ : x = x / y; break; default : x =x + 1; break; } printf(“ %d % d”, x , y);

Write a program that reads the value of x and calculates the values of y and z using the following formulas: ,