610 likes | 794 Views
Basic Of Computer Science. Dr. Mohamed Khafagy. Conditional Statements. A conditional statement allows us to control whether a program segment is executed or not. Two constructs if statement if if-else if-else-if switch statement. The Basic if Statement. Syntax if(condition)
E N D
Basic Of Computer Science Dr. Mohamed Khafagy
Conditional Statements • A conditional statement allows us to control whether a program segment is executed or not. • Two constructs • if statement • if • if-else • if-else-if • switch statement
The Basic if Statement • Syntax if(condition) action • if the condition is true then execute the action. • action is either a single statement or a group of statements within braces. condition false true action
Choice (if) • Put multiple action statements within braces if (it's raining){ • <take umbrella> • <wear raincoat> }
Absolute Value // program to read number & print its absolute value #include <iostream> using namespace std; int main(){ int value; cout << "Enter integer: "; cin >> value; if(value < 0) value = -value; cout << "The absolute value is " << value << endl; return 0; }
Relational Operators Relational operators are used to compare two values to form a condition. Math C++ Plain English = == equals [example: if(a==b)] [ (a=b) means put the value of b into a] < < less than <= less than or equal to > > greater than >= greater than or equal to != not equal to
Operator Precedence Which comes first? * / % + - < <= >= > == != = Answer:
The Boolean Type • C++ contains a type named boolfor conditions. • A condition can have one of two values: • true(corresponds to a non-zero value) • false(corresponds to zero value) • Boolean operators can be used to form more complex conditional expressions. • The and operator is && • The or operator is || • The not operator is !
The Boolean Type • Truth table for "&&" (AND):
The Boolean Type • Truth table for “||" (OR):
The Boolean Type • Truth table for "!" (NOT):
A Boolean Type • Assignments to booltype variables bool P = true;bool Q = false;bool R = true;bool S = P && Q;bool T = !Q || R;bool U = !(R && !Q);
Sorting Two Numbers int value1; int value2; int temp; cout << "Enter two integers: "; cin >> value1 >> value2; if(value1 > value2){ temp = value1; value1 = value2; value2 = temp; } cout << "The input in sorted order: " << value1 << " " << value2 << endl;
The if-else Statement • Syntax if(condition) Action_AelseAction_B • if the condition is true then execute Action_Aelse execute Action_B • Example: if(value == 0) cout << "value is 0"; else cout << "value is not 0"; condition false true Action_A Action_B
Choice (if and else) if <it's sunny>{ <go to beach> } else{ <take umbrella> }
Finding the Big One int value1; int value2; int larger; cout << "Enter two integers: "; cin >> value1 >> value2; if(value1 > value2) larger = value1; else larger = value2; cout << "Larger of inputs is: " << larger << endl;
Area of the circle const doublePI = 3.1415926; intradius; doublearea; cout << "Enter the radius of the circle: "; cin >> radius; if(radius > 0){ area = radius * radius * PI; cout << "The area of the circle is: " << area; } else cout << "The radius has to be positive " << endl;
Even or Odd int value1; bool even; cout << "Enter a integer: "; cin >> value; if(value%2 == 0) even = true; else even = false; // even = !(value%2);
if-else-if Statements if <condition 1 exists>{ <do Q> } else if <condition 2 exists>{ <do R> } else if <condition 3 exists>{ <do S> } else{ <do T> } Q R S T
if-else-if Statement int people, apples, difference; cout << "How many people do you have?\n"; cin >> people; cout << "How many apples do you have?\n"; cin >> apples; if(apples == people) cout << "Everybody gets one apple.\n"; else if(apples > people){ difference = apples - people; cout << "Everybody gets one apple, & there are " << difference << " extra apples.\n";} else{ difference = people - apples; cout << "Buy " << difference << " more apples so that everyone gets one apple.\n";}
if-else-ifExample int score; cout << "Please enter a score: "; cin >> score; if (score >= 90) cout << "Grade = A" << endl; else if (score >= 80) cout << "Grade = B" << endl; else if (score >= 70) cout << "Grade = C" << endl; else if (score >= 60) cout << "Grade = D" << endl; else// totalscore < 59 cout << "Grade = F" << endl;
Nested if Statements • Nested means that one complete statement is inside another if <condition 1 exists>{ if <condition 2 exists>{ if <condition 3 exists>{ <do A> } <do B> } <do C: sleep> }
Nested if Statements • Example: if <it's Monday>{ <go to HKUST> if <it's time for class>{ if <it's raining>{ <bring umbrella> } <go to COMP 102> } }
Nested if Statements • Consider the following example: if the customer is a member, then { If the customer is under 18, then the entrance fee is half the full fee. If the customer is 18 or older, then the entrance fee is 80% of the full fee. } The if statements deciding whether to charge half fee to someone under 18 or whether to charge 80% to someone over 18 are only executed if the outer if statement is true, i.e. the customer is a member. Non-members, no matter what their age, are charged full fee.
Nested if Statements • Consider a variant of the previous example: if the customer is a member, then { If the customer is under 18, then the entrance fee is half the full fee. } If the customer is 18 or older, then the entrance fee is 80% of the full fee. Here, member customers under 18 will be charged half fee and all other customers over 18 will be charged 80% of the full fee.
Nested if Statements If (member) { if (age < 18) { fee = fee * 0.5; } if (age >=18) fee = fee * 0.8; } If (member) { if (age < 18) { fee = fee * 0.5; } } if (age >=18) fee = fee * 0.8;
“Dangling Else” Problem • Always pair an else with the most recent unpaired if in the current block. Use extra brackets { } to clarify the intended meaning, even if not necessary. For example, what is the value of c in the following code? int a = -1, b = 1, c = 1; if( a > 0 ) if( b > 0 ) c = 2; else c = 3;
“Dangling Else” Problem (A)int a = -1, b = 1, c = 1; if (a > 0) { if (b > 0) c = 2; else c = 3; } (B) int a = -1, b = 1, c = 1; if (a > 0) { if (b > 0) c = 2; } else c = 3; (A) is the correct interpretation. To enforce (B), braces have to be explicitly used, as above.
Short-circuit Evaluation • If the first operand of a logical and expression is false, the second operand is not evaluated because the result must be false. • If the first operand of a logical or expression is true, the second operand is not evaluated because the result must be true.
Multiple Selection: The switch Statement multiway expression value1 action 1 value2 action 2 value3 action 3 value4 action 4
Multiple Selection: The switch Statement Syntax: switch (<selector expression>) { case <label1> : <sequence of statements>; break; case <label2> : <sequence of statements>; break; case <labeln> : <sequence of statements>; break; default : <sequence of statements>; }
Multiple Selection: The switch Statement Meaning: • Evaluate selector expression. • The selector expression can only be: a bool, an integer, an enum constant, or a char. • Match case label. • Execute sequence of statements of matching label. • If break encountered, go to end of the switch statement. • Otherwise continue execution.
Multiple Selection: The switch Statement case 1 action case 2 action case 3 action default action
switch Statement: Example 1 • If you have a 95, what grade will you get? switch(int(score)/10){ case 10: case 9:cout << "Grade = A" << endl; case 8:cout << "Grade = B" << endl; case 7:cout << "Grade = C" << endl; case 6:cout << "Grade = D" << endl; default:cout << "Grade = F" << endl; }
switch Statement: Example 2 switch(int(score)/10){ case 10: case 9:cout << "Grade = A" << endl; break; case 8:cout << "Grade = B" << endl; break; case 7:cout << "Grade = C" << endl; break; case 6:cout << "Grade = D" << endl; break; default:cout << "Grade = F" << endl; }
switch Statement: Example 2 is equivalent to: if (score >= 90) cout << "Grade = A" << endl; else if (score >= 80) cout << "Grade = B" << endl; else if (score >= 70) cout << "Grade = C" << endl; else if (score >= 60) cout << "Grade = D" << endl; else// score < 59 cout << "Grade = F" << endl;
switch Statement: Example 2 #include <iostream> using namespace std; int main() { char answer; cout << "Is comp102 an easy course? (y/n): "; cin >> answer; switch (answer){ case 'Y': case 'y': cout << "I think so too!" << endl; break; case 'N': case 'n': cout << "Are you kidding?" << endl; break; default: cout << "Is that a yes or no?" << endl; } return 0; }
switch Statement with Multiple Labels: Example 3 switch (watts) { case 25 : lifespan = 2500; break; case 40 : case 60 : lifespan = 1000; break; case 75 : lifespan = 750; break; default : lifespan = 0; } // end switch
Points to Remember • The expression followed by each case label must be a constant expression. • No two case labels may have the same value. • Two case labels may be associated with the same statements. • The default label is not required. • There can be only one default label, and it is usually last.
Problem 1 Write a program that reports the contents of a compressed-gas cylinder based on the first letter of the cylinder’s color. The program input is a character representing the observed color of the cylinder: ‘Y’ or ‘y’ for yellow, ‘O’ or ‘o’ for orange, and so on. Cylinder colors and associated contents are as follows: orange -> ammonia brown -> carbon monoxide yellow -> hydrogen green -> oxygen Your program should respond to input of a letter other than the first letters of the given colors with the message “Contents unknown”.
Input(s) color char
Output(s) content
Relevant Formula orange -> ammonia brown -> carbon monoxide yellow -> hydrogen green -> oxygen
ALTERNATIVE SOLUTION #include <iostream.h> int main() { char color; cout<<"Please enter the first letter of the cylinder's color : “; cin>>color ; if (color == 'O' || color == 'o') cout<<“The contents of the compressed-gas cylinder is Ammonia”<<endl; else if (color == 'B' || color == 'b') cout<<"The contents of the compressed-gas cylinder is Carbon monoxide\n“; else if (color == 'Y' || color == 'y') cout<<"The contents of the compressed-gas cylinder is Hydrogen\n“; else if (color == 'G' || color == 'g') cout<<"The contents of the compressed-gas cylinder is Oxygen\n“; else cout<<"Contents unknown\n"; return 0; }
Exercise:Instead of using both uppercase and lowercase letters of the given character in every if-condition or in switch-cases, convert the character given by the user into uppercase or lowercase and use only this character in if-conditions and switch-cases.
Problem 2 The National Earthquake Information Center has asked you to write a program implementing the following decision table to characterize an earthquake based on its Richter scale number. Richter Scale Number (n)Characterization n < 5.0 Little or no damage 5.0 <= n < 5.5 Some damage 5.5 <= n < 6.5 Serious damage 6.5 <= n < 7.5 Disaster higher Catastrophe
Input(s) n double
Output(s) characterization
Relevant Formula Richter Scale Number (n)Characterization n < 5.0 Little or no damage 5.0 <= n < 5.5 Some damage 5.5 <= n < 6.5 Serious damage 6.5 <= n < 7.5 Disaster higher Catastrophe
#include <iostram.h> int main() { double n; cout<<"Please enter Richter Scale Number : “; cin>>n; if (n < 5.0) cout<<"\nLittle or no damage\n”; else if (5.0 <= n && n < 5.5) /* else if (n < 5.5) */ cout<<"\nSome damage\n”; else if (5.5 <= n && n < 6.5) /* else if (n < 6.5) */ cout<<"\nSerious damage\n”; else if (6.5 <= n && n < 7.5) /* else if (n < 7.5) */ cout"\nDisaster\n”; else cout<<"\nCatastrophe\n”; return 0; }