03a control structures

Post on 07-Aug-2015

112 views 5 download

Tags:

Transcript of 03a control structures

1

Control Structures

2

Flow chart Graphical representation of an algorithm or a portion of algorithm. Drawn using certain special-purpose symbols connected by arrows

called flow lines.

Special purpose symbols. Following are some symbols to draw a flow chart and there purpose.

Rectangles are action symbols to indicate any type of action, including a calculation or an input output operation.

Diamonds are conditional or decision symbols. It indicates a decision to be made.

lozenges, ovals or rounded rectangles, indicate start or end of the program usually containing the word "Start, begin” or "End“.

3

Flow chart

Parallelogram are the input/output symbols

Arrows, showing what's called "flow of control“. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to. Arrows are also called flow lines.

4

Control structures

Control structure

A control statement and the statements whose execution it controls. a control statement is any statement that alters the linear flow of

control of a program. C++ examples include: if-else, while, for, break, continue and return statement

Sequential execution Statements executed in order

Transfer of control Next statement to be executed may be other than the next one in

sequence.

5

Control structures Bohm and Jacopini’s control structures Bohm and Jacopino’s work demonstrate that all programs could be written in

terms of only three control structures. Sequence structures, selection structures and repetition

structures.

Sequence structure Built into C++. Programs executed sequentially by default.

Selection structures

C++ has three types - if, if/else, and switch

6

Control structures if selection structure

. Perform an action if condition is true.

. Skip the action if condition is false.

If/else selection structure . Perform an action if condition is true.

. Performs a different action if the condition is false.

switch selection structure . Perform one of many different actions depending on the value of an

integer expression.

7

Control structures Repetition structures

Many application require certain operations to be carried out more than once. Such situations require repetition in control flow.

C++ has three types while, do/while, for While selection structure . An action to be repeated while some conditions remains true.

Do/While selection structure . Similar to while structure.

. Tests the loop continuation after the loop body is performed.

. while structure the loop continuation condition is tested at the beginning of the loop before the body of loop is performed.

We are going to discuss if and if/else selection structures first and will explain the repetition structures and switch selection structure latter. It was just an introduction to these structures.

8

Decision making structure/ selection structure

Selection structure/decision structure allows the program to make a decision or comparison and then

select one of two paths, depending on the result of the comparison. Condition condition” is a logical expression that evaluates to true or false. It

could be a relational or Boolean expression. In other words Specifies the decision you are making Must result in either a true or false answer

IF Structure One statement or a block of statement enclosed in braces {}

i.e. (compound statement), to be processed If condition met otherwise it is skipped.

Uses equality and relational operators

9

Equality and relational operators

Conditions in if structures can be formed by using the equality and relational operators

Equality operators Same level of precedence Associated left to right.

Relational operators Same level of precedence. Associated left to right.

Equality operators precedence is lower then precedence of relational operators.

10

Equality and relational operators

Standard algebraic equality operator or relational operator

C++ equality or relational operator

Example of C++ condition

Meaning of C++ condition

Relational operators

> > x > y x is greater than y

< < x < y x is less than y

>= x >= y x is greater than or equal to y

<= x <= y x is less than or equal to y

Equality operators

= == x == y x is equal to y

!= x != y x is not equal to y

11

Boolean Expressions Boolean expressions are expressions that are

either true or false comparison operators such as '>' (greater than)

are used to compare variables and/or numbers (grade >= 60) Including the parentheses, is the

boolean expression from the grade example A few of the comparison operators that use two

symbols (No spaces allowed between the symbols!) > greater than != not equal or inequality == equal or equivalent <= less than or equal to etc

12

If selection structure

The primary C++ selection structure statement used to perform a single-alternative selection.

Choose among alternative courses of action

If the condition is true statement Print statement executed, program continues to

next If the condition is false

Print statement ignored, program continues

13

If selection structure flow chart

14

If selection structure example:

Pseudocode If student’s grade is greater than or equal to 60

Print “Passed”

C++ codeif ( grade >= 60 ) cout << "Passed";

15

If selection structure Flow chart for the pseudocode statement.

true

false

grade >= 60

print “Passed”

A decision can be made on any expression.

16

Example

Example is using the relational and equality operators. Following example used six if statements to compare two numbers

input by the user. If the condition in any of these if statements is satisfied, the output

statement associated with if is executed. If the condition with the if statement is false the output statement

associated with that if statement is skipped. Observe the different outputs for various inputs at the end of the

program.

17

1 // example2 // Using if statements, relational3 // operators, and equality operators4 #include <iostream.h>5678910 int main()11 {12 int num1, num2; // declare variables1314 cout << "Enter two integers, and I will tell you\n"15 << "the relationships they satisfy: ";16 cin >> num1 >> num2; // read two integers1718 if ( num1 == num2 )19 cout << num1 << " is equal to " << num2 << endl;2021 if ( num1 != num2 )22 cout << num1 << " is not equal to " << num2 << endl;2324 if ( num1 < num2 )25 cout << num1 << " is less than " << num2 << endl;2627 if ( num1 > num2 )28 cout << num1 << " is greater than " << num2 << endl;2930 if ( num1 <= num2 )31 cout << num1 << " is less than or equal to "32 << num2 << endl; //continued on next slide33

if structure compares values of num1 and num2 to test for equality.

If condition is true (i.e., values are equal), execute this statement.if structure compares values

of num1 and num2 to test for inequality.

If condition is true (i.e., values are not equal), execute this statement.

If structure compare the values of num1 and num2 to test if num1 is less than num2

If condition is true (i.e., num1 is less than num2 ), execute this statement.if structure compares values

of num1 and num2 to test if num1 is greater than num2

If condition is true (i.e., num1 is greater than num2 ), execute this statement.if structure compares values

of num1 and num2 to test if num1 is less than or equal to num2

If condition is true (i.e., num1 is less than or equal to num2), execute this statement.

18

34 if ( num1 >= num2 )

35 cout << num1 << " is greater than or equal to "

36 << num2 << endl;

37

38 return 0; // indicate that program ended successfully

39 }

Input is 35 and 30

Input is 25 and 25

Input is 10 and 20

19

If/else selection structure Different actions if conditions true or false

Syntax

A single statement for each alternativeif (Boolean_expression) yes_statement;

else no_statement;

A sequence statement for each alternativeif (Boolean_expression)

{ yes_statement1; yes_statement2;

yes_statement last; }else { no_statement1;

no_statement2; no_statement last; }

20

If/else selection structure flow chart

Boolean expression

Action if false Action if true

truefalse

21

If/else selection structureExample Pseudocode

if student’s grade is greater than or equal to 60print “Passed”

elseprint “Failed”

C++ codeif ( grade >= 60 ) cout << "Passed";else cout << "Failed";

22

If/else selection structureFlow chart for the pseudocode

truefalse

print “Failed” print “Passed”

grade >= 60

23

Compound Statement Compound statement

Set of statements within a pair of braces also known as BLOCK

if ( grade >= 60 ) cout << "Passed.\n";else { cout << "Failed.\n"; cout << "You must take this course again.\n";}

Without braces,cout << "You must take this course again.\n";always executed

24

Another simple Example

1. //program to determine if user is ill

2. #include <iostream>3. using namespace std;4. int main()5. {6. const double NORM = 98.6; // degree Fahranheit;7. double temperature;8. cout<<"Enter your temperature\t";9. cin>>temperature;

10. if (temperature>NORM) //if temperature is greater than NORM print following statement11. cout<<"\n\nYou are sick\n"<<"take rest and drink lots of fluids"; 12. else //if temperature is <= NORM print following statement13. cout<<"\n\nYou are perfectly fine";

14. return 0;15. }

25

output

Input is 100

100 > NORM

Input is 98

98<NORM

26

Example of if and if/else selection structure drawn in flow chart form

If selection structure(program 1) If/else selection structure(program2)

27

c++ code for the flow chart of if selection structure (program 1).

1. //program 12. //program to find the part prices for the given part number.

3. #include<iostream>4. using namespace std;5. int main()6. {7. int part_number, ; 8. float price;9. cout<<"enter part number"<<endl;10. cin>>part_number;11. cout<<"enter price"<<endl;12. cin>>price;13. if(part_number==203)14. price = price*1.1;15. cout<<"price is "<<price;16. return 0;17. }

28

Output of program 1

Part_number is equal to 203

Part_number is not equal to 203

29

c++ code for the flow chart of if/else selection structure (program 2).

//program to calculate the sales commission

#include <iostream> using namespace std; int main() { float sales, commission; cout<<"enter the sales"<<endl; cin>>sales; if (sales>1500) commission = sales*0.2; else commission = sales*0.1; cout<<"commission is"<<commission; return 0; }

30

Output of program 2

Sales is 1500

Sales is greater than 1500

31

Example of if/else

Write a program to calculate the gross pay of an employee. The employee is paid at his basic hourly rate for the first 40 hours worked

during a week. Any hours worked beyond 40 is considered overtime. overtime is paid at the 1.5 times the hourly rate.

Pseudocode

If total number of hours >40 Gross pay = rate*40 + rate*1.5(hours – 40)

ElseGross pay = rate * hours

32

C++ code1. #include <iostream>2. using namespace std;3. int main()4. {5. int hour; //declaration6. double gross_pay, rate;7. cout<<"enter the hourly rate of pay\t"<<endl; //prompt8. cin>>rate; //reading data9. cout<<"enter the number of hours worked \t"<<endl; //prompt10. cin>>hour; //readin data

11. if(hour>40) //condition if working hours is greater than 40 12. gross_pay = rate*40 + 1.5*rate*(hour - 40); //gross pay including extra hour13. 14. else //if working hour is <=40 then use this formula to get gross

pay15. gross_pay = rate*hour;16. 17. cout<<" Gross pay is \t"<<gross_pay<<endl; //printing the gross pay on screen.18. return 0;19. }

33

output

Hour<40

Hour>40

34

If/else selection structure Ternary conditional operator (?:) It is only ternary operator. It takes three operands together with conditional operator to form a

conditional expression Three arguments (condition, value if true, value if false) example

cout << ( grade >= 60 ? “Passed” : “Failed” );

the value in the conditional can also be actions to execute for example

grade >= 60 ? cout << “Passed” : cout << “Failed” ;

Condition Value if true Value if false

35

Nested if/else structure

if structure that rests entirely within another if structure, within either the if or the else clause

One inside another, test for multiple cases Once condition met, other statements skipped

36

Simple example to understand the nested if/else

Consider an example of a program segment that accepts a gender code and print gender according to that code.

Pseudocode if the gender code is F

print female else

if the gender code is M print male

elseprint invalid code

37

Simple example to understand the nested if/else

Flow chart

38

Simple example to understand the nested if/else

C++ code

//F and M are correct codes//f and m are invalid codes

39

Nested if/else structure following pseudocode is example of nested if/else 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”

40

Nested if/else structureC++ code

if ( grade >= 90 ) // 90 and above cout << "A";else

if ( grade >= 80 ) // 80-89 cout << "B"; else

if ( grade >= 70 ) // 70-79 cout << "C"; else

if ( grade >= 60 ) // 60-69 cout << "D"; else // less than 60 cout << "F";

if grade>=90, first four conditions will be true. But only the cout statement after the first test will be executed. After that cout is executed, the else part of the outer if/else statement is skipped.

41

Avoiding Common Pitfalls with if Statements

Forgetting that C++ is case sensitive Assuming that indentation has a logical purpose Adding an unwanted semicolon Forgetting curly braces Using = instead of == (explained with example on next slide) Making unnecessary comparisons

42

Logical Operators

Logical operators are used to combine more than one condition forming a complex condition.

Allow you to combine two or more conditions into one compound condition Data validation

the process of verifying that the input data is within the expected range

C++ logical operators are

&& (Logical AND) || (Logical OR)

! (Logical NOT , logical negation)

43

Logical Operators && (Logical AND)

All of the conditions must be true for the compound condition to be true

Syntax (Condition_1) && (Condition_2) True if both expressions are true

Example if ( (2 < x) && (x < 7) )

True only if x is between 2 and 7 Inside parentheses are optional but enhance meaning

44

Logical Operators

Be careful translating inequalities to C++

if x < y < z translates as

if ( ( x < y ) && ( y < z ) )

NOT

if ( x < y < z )

45

Logical Operators || (Logical OR)

only one of the conditions must be true for the compound condition to be true True if either or both expressions are true Syntax (Condition_1) || (Condition_2)

Example if ( ( x = = 1) | | ( x = = y) )

True if x contains 1 True if x contains the same value as y True if both comparisons are true

46

Example to print hello according to user’s choice

Notice the program will print hello if inputIs upper case Y or lower case y

47

Output

Notice that program accepts bothLowe case y and upper case Y

48

Logical Operators ! (Logical NOT , logical negation)

Reverses the truth/falsity of its condition Returns true when its condition is false, & vice versa Is a unary operator, only takes one condition

Exampleif ( !( grade == sentinelValue ) ) cout << "The next grade is " << grade << endl;

Alternativeif ( grade != sentinelValue ) cout << "The next grade is " << grade << endl;

49

Logical Operators ! negates any boolean expression

!( x < y) True if x is NOT less than y

!(x = = y) True if x is NOT equal to y

! Operator can make expressions difficult to understand…use only when appropriate

Truth table for the ! (NOT, logical negation) operator

50

Confusing Equality (==) and Assignment (=) Operators

Common error Does not typically cause syntax errors

Aspects of problem Expressions that have a value can be used for decision

Zero = false, nonzero = true Assignment statements produce a value (the value to be

assigned) = Assignment operator

Used to assign values to variables X = 3

== equality operator Used to compare values

If (X == 3)

51

Confusing Equality (==) and Assignment (=) Operators

Exampleif ( payCode == 4 )

cout << "You get a bonus!" << endl; If paycode is 4, bonus given

If == was replaced with =if ( payCode = 4 ) cout << "You get a bonus!" << endl;

Paycode set to 4 (no matter what it was before) Statement is true (since 4 is non-zero) Bonus given in every case

52

Confusing Equality (==) and Assignment (=) Operators

L-values Expressions that can appear on left side of equation Can be changed (I.e., variables)

x = 4;

R-values Only appear on right side of equation Constants, such as numbers (i.e. cannot write 4 = x;)

L-values can be used as R-values, but not vice versa

53

The switch Multiple-Selection Structure Switch is typically a selection structure and an alternative to the long string

of ifs Tests variables for multiple values Consists of a series of case labels and an optional default case General format

switch ( variable ) {case value1: // taken if variable == value1statementsbreak; // necessary to exit switch

case value2:case value3: // taken if variable == value2 or == value3statementsbreak;

default: // taken if variable matches no other casesstatements break;

}

54

The switch Multiple-Selection Structure

Expression (variable in braces after switch) must be of type integer or character. It is the controlling expression of switch statement

The keyword case must be followed by a constant

break statement is required unless you want all subsequent statements to be executed.

55

Reviewing character data type As we know a computers can process character data too char

Short for character Can be any single character from the keyboard

To declare a variable of type char:

char letter;

Character constants are enclosed in single quotes

char letter = 'a';

Strings of characters, even if only one characteris enclosed in double quotes

"a" is a string of characters containing one character 'a' is a value of type character

56

char int It is possible to store char values in integer variables (an important feature of c++) Characters are represented as 1-byte integer in computers so we can treat a

character as either char or int depending on its use int value = ‘A'; //65 is ASCII for A

value will contain an integer representing 'A‘ i.e. value = 65 Similarly It is possible to store int values in char variables

char letter = 97; //97 is numerical representation of lower case a (ASCII)

Result of the above statement is letter = a

Use single quotes to get numerical representation of a character

cout << "The character (" << 'a' << ") has the value " << ( int ) ( 'a' ) << endl;

PrintsThe character (a) has the value 97

ASCII (American Standard Code For Information Interchange)

57

Comparing if/else with switch with the help of an example

•When you want to create different outcomes depending on specific values, you can use a series of ifs.

58

Comparing if/else with switch with the help of an example

However, as an alternative to the long string of ifs, you can use the switch statement

Department is the control variable and is integer Compare the department to cases and prints the department it matches.

Removing break changes behavior of statement.It causes switch statement to end.

59

Example problem Problem statement Write a c++ program that enters the students grades

represented by letters A, B, C, D and F (program should not be case sensitive)

Use switch to count the number of each different letter grades that the student earned on an exam

Observe the flow chart on the next slide

60

Flow chart

true

false

.

.

.

case a case a action(s) break

case b case b action(s) break

false

false

case z case z action(s) break

true

true

default action(s)

61

C++ code1 // grades are represented by letters 2 // Counting letter grades.3 #include <iostream>4 5 9 // function main begins program execution10 int main()11 {

int grade; // one grade//initializing and declaring counters

13 int aCount = 0; // number of As14 int bCount = 0; // number of Bs15 int cCount = 0; // number of Cs16 int dCount = 0; // number of Ds17 int fCount = 0; // number of Fs18 19 cout << "Enter the letter grades." << endl20 << "Enter the EOF character to end input." << endl;21

62

C++ code22 // loop until user types end-of-file key sequence23 while ( ( grade = cin.get() ) != EOF ) {24 25 // determine which grade was input26 switch ( grade ) { // switch structure nested in while27 28 case 'A': // grade was uppercase A29 case 'a': // or lowercase a30 ++aCount; // increment aCount31 break; // necessary to exit switch32 33 case 'B': // grade was uppercase B34 case 'b': // or lowercase b35 ++bCount; // increment bCount 36 break; // exit switch37 38 case 'C': // grade was uppercase C39 case 'c': // or lowercase c40 ++cCount; // increment cCount 41 break; // exit switch42

cin.get() This function gets 1 character from the keyboard (after Enter pressed), and it is assigned to grade. Variable grade is the controlling expression of switch. Value of grade is compared with each of the case label

break causes switch to end and the program continues with the first statement after the switch structure.If break is not used in switch structure each time the match occur, statement for all remaining cases will be executed.

Compares grade (an int) to the numerical representations of A and a.

cin.get() returns EOF (end-of-file) after the EOF character is input, to indicate the end of data.If the value assigned to grade is EOF the program terminates.EOF is symbolic integer constant defined in <iostream> header file EOF may be ctrl-d (UNIX) or ctrl-z (DOS, MS) depending on your OS.

63

C++ code43 case 'D': // grade was uppercase D44 case 'd': // or lowercase d45 ++dCount; // increment dCount 46 break; // exit switch47 48 case 'F': // grade was uppercase F49 case 'f': // or lowercase f50 ++fCount; // increment fCount 51 break; // exit switch52 53 case '\n': // ignore newlines, 54 case '\t': // tabs, 55 case ' ': // and spaces in input56 break; // exit switch57 58 default: // catch all other characters59 cout << "Incorrect letter grade entered."60 << " Enter a new grade." << endl;61 break; // optional; will exit switch anyway62 63 } // end switch64 65 } // end while66

This test is necessary because Enter is pressed after each letter grade is input. This adds a newline character that must be removed. Likewise, we want to ignore any whitespace.

Notice the default statement, which catches all other cases.If no match occurs, the default case is executed and an error message is printed

64

C++ code67 // output summary of results68 cout << "\n\nTotals for each letter grade are:" 69 << "\nA: " << aCount // display number of A grades70 << "\nB: " << bCount // display number of B grades71 << "\nC: " << cCount // display number of C grades 72 << "\nD: " << dCount // display number of D grades73 << "\nF: " << fCount // display number of F grades74 << endl;75 76 return 0; // indicate successful termination77 78 } // end function main

65

Output