500 likes | 612 Views
Branching Statements. CS 141 Computer Programming 1. Teacher Assistant Hadeel Al- Ateeq. Outline. Control Structure. Control Structures in C++. Sequence Structure. Selection Statements. If- single selection statement. If else – double selection statement. Conditional Operators.
E N D
Branching Statements CS 141Computer Programming 1 Teacher Assistant Hadeel Al-Ateeq
Outline Control Structure. Control Structures in C++. Sequence Structure. Selection Statements. If- single selection statement. If else – double selection statement. Conditional Operators. Nested if-else statements. Dangling else Problem. Using Boolean Variables. Implicit Typecasting. Switch – multiple selection statement. Questions.
Control Structure (Logic Structure) Control Structures • Sequence structure: • Process one instruction after another in the order they are written. • Selection structures: • Decision structure • Make choices by using relational or logical operators. • Case structure • Enable to pick up one of a set of tasks. • Repetition structure: • Enable to repeat tasks.
Sequence Structure Activity Diagram Models the workflow (activity) of a portion of a software system Transitions order in which actions occur Initial State Beginning of the workflow Corresponding C++ statement: total=total + grade; Add grade to total Notes Describe the purpose of the symbols Corresponding C++ statement: counter=counter + 1; Add 1 to counter Final State End of the workflow Dotted line connects each note with element it describes Action states contains action expressions
Selection Statements Types Single selection statement Multiple-selection statement Selects or ignores a single group of actions. Selects among many group of actions. Double-selection statement • Selects between two groups of actions.
If - Single Selection Statement Pseudocode: If student grade is greater than or equal to 60 Print “Passed” Example: if (grade >=60) cout<<“Passed”; Use the keyword if. Begin with iffollowed by condition; then action or group of actions (compound statements or blocks) are listed. Enclose compound statements between braces {} and indent these statements. Ifcondition is true, action is performed. Otherwise, actions is ignored.
If - Single Selection Statement Activity Diagram Decision Symbol indicates that a decision to be made Grade >=60 Print “Passed” Grade<60
If - Single Selection Statement Condition can be relational or equality operators or any other expressions Zero False nonzero True Single Action Multiple Actions surrounded by braces {} if (condition) action; if (condition) { action1; action2; ….. …. …. actionN; }
if…else-Double-selection Statement Use the keyword if and else. Begin with if followed by condition; then actionor groupof actions are listed. End with else then action or group of actions are listed. If condition is true, action that followed by if is performed. Otherwise, action that followed by elseis performed.
if…else-Double-selection Statement Condition can be relational or equality operators or any other expressions Zero False nonzero True if (condition) { action1; ….. actionN; } else { action1; …. actionN; } Single Action Multiple Actions surrounded by braces {} if (condition) action1; else action2;
if…else-Double-selection Statement Activity Diagram Print “Failed” Print “Passed” Grade<60 Grade >=60
if…else-Double-selection Statement Example Pseudocode: if student's grade is greater than or equal to 60 Print “passed” Else Print ”failed” If (grade >=60) cout<<“Passed”; else cout<<“Failed”;
Conditional Operator (?:) • Provide similar result of if…else double selection statement. Ternary operator requires three operands: • Condition. • Value when condition is true. • Value when condition is false. Syntax: • (Condition? Condition’s true value: condition’s false value)
Conditional Operator (?:) Example Can be written as: cout<<(grade >=60 ? “passed”: “failed”); Example Precedence of the conditional operator is low inti=1, j=2, max; max=(i>j ?i:j); Grade >=60 ? cout<<“Passed”: cout<<“Failed”;
Nested if.. else Statements Example One inside another, test for multiple cases Once condition met, other statements skipped.
Nested if.. else Statements if(conditioin1) action1; else if (condition2) action2; else if(condition3) action3; … else actionN;
Nested if.. else Statements if (condition1) { if (condition2) action1; else { if (condtion3) action2; else action3; } } else action4;
Nested if.. else Statements Question Write a C++ program that prints A for exam grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D for grades in the range 60 to 69 and F for all other grades.
Nested if.. else Statements Another Solution
Nested if.. else Statements Another Solution
Dangling –else Problem Example x=10; y=2; if (x>5) if(y>5) cout<<“x and y are >5 “<<endl; else cout<<“x is <=5”<<endl; Each else associated with immediately preceding if There is an exceptionwhen placing braces {} Logical error !!
Dangling –else Problem Correctness Block x=10; y=2; if(x>5) { if(y>5) cout<<“x and y are >5”<endl; } else cout<<“x is <=5”;
Dangling –else Problem Example
Using Boolean variables bool flag1, flag2; if (flag1) ---- else ---- if( flag1|| flag2) ---- else -----
Implicit Typecasting intx1,x2; if(x1) … else … if(x1||x2) … else ….
Note Example This message will always be printed !! int x=0; if (x=2) cout<<"x is equal to 2"; else cout<<"x is not equal to 2"; intX=0; X==1; X’s value will remain 0 Confusing the equality operator == with the assignment operator = results in logic errors.
Switch - Multiple-selection Statement Break Keyword • Causes immediate exit from switchstatement. • Jumps out of the switch statement, and do not execute any more code. Perform actions based on possible values of variable or expression. Use keywords switch, case, defaultand break. Begin with switchfollowed by controlling expressionenclosed between parentheses (). Value of the controlling expressionis compared with each caselabel, then if a match occurs the program executes action for that case. No matching, the program executes the optional defaultstatement.
Switch - Multiple-selection Statement Activity Diagram [True] case a case a action(s) break [False] [True] case b case b action(s) break [False] [False] [True] case z action(s) break case z [False] default action(s)
Switch Multiple-selection Statement switch(expression) { casevalue1: action1; break; casevalue2: action2; break; …. casevaluen: actionN; break; default: action; }
Switch Multiple-selection Statement Example switch (number) { case 0: cout<<“too small, sorry!”; break; case 5: cout<<“good job!”<<endl; //fall through case 4: cout<<“nice pick!”<<endl; //fall through case 3: cout<<“excellent !”<<endl; //fall through case 2: cout<<“masterfull!”<<endl; //fall through case 1: cout<<“incredible!”<<endl; //fall through break; }
Question #1 • You are lucky!, if the result of comparison is less than 10. • Fine payable: 40 Dollars, if the result of comparison is in the range of 10 and20. • Fine payable: 80 Dollars, if the result of comparison is in the range of 20and30. • Hand over your driver’s license!, otherwise Write a C++ program that outputs the fine for driving too fast. It takes BOTH the speed limitandcurrent speed, compares between them and prints the appropriate fine as follows:
Question #2 Write a C++ program that calculates the minimum of two input numbers. Note: check the validity of the inputs
Question #3 Write a C++ program that calculates the maximum of two input numbers. Note: check the validity of the inputs
Question #4 Output if(x<10) if(y>10) cout<<“*****”<<endl; else cout<“#####”<<endl; cout<<“$$$$$”<<endl; ***** $$$$$ $$$$$ State the output for each of the following: • When x is 9 and y is 11. • When x is 11 and y is 9.
Question #4 State the output for each of the following: • When x is 9 and y is 11. • When x is 11 and y is 9. Output ***** ##### $$$$$ if(x<10) { if(y>10) cout<<“*****”<<endl; } else { cout<<“#####”<<endl; cout<<“$$$$$”<<endl; }
Question #5 Sample Output: Write a C++ program that compares any two integers using if statements, relational operators and equality operators.
Question #6 Write a C++ program that prints out the entered characterchoice. It accepts only three characters a, b and c (upper or lower cases). Otherwise it prints “Your choice is not defined” Note: Use Switch Statement
Question #7 Trace the following code segment and show the value of value variable. Value Cannot be determined because the value of input variable is unknown