Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows...
Transcript of Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows...
Basic Of Computer Basic Of Computer ScienceScience
Dr. Mohamed Khafagy
Conditional StatementsConditional StatementsA 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 The Basic ifif Statement Statement
Syntaxif(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
action
true
false
Choice (Choice (ifif))
Put multiple action statements within braces
if (it's raining){<take umbrella><wear raincoat>
}
Absolute ValueAbsolute 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 OperatorsRelational 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 PrecedenceOperator Precedence
Which comes first?
* / %+ -
< <= >= >== !=
=
Answer:
The Boolean TypeThe Boolean Type
C++ contains a type named bool for 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 TypeThe Boolean Type
Truth table for "&&" (AND):
Operand1 Operand2 Operand1 && Operand2
true true true
true false false
false true false
false false false
The Boolean TypeThe Boolean Type
Truth table for “||" (OR):
Operand1 Operand2 Operand1 || Operand2
true true true
true false true
false true true
false false false
The Boolean TypeThe Boolean Type
Truth table for "!" (NOT):
Operand !Operand
true false
false true
A Boolean TypeA Boolean Type
Assignments to bool type variablesbool P = true;bool Q = false;bool R = true;bool S = P && Q;bool T = !Q || R;bool U = !(R && !Q);
Sorting Two NumbersSorting 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 The if-elseif-else Statement Statement
Syntaxif (condition) Action_Aelse Action_B
if the condition is true then execute Action_A elseexecute Action_B
Example:if(value == 0)
cout << "value is 0";else
cout << "value is not 0";
condition
Action_A Action_B
true false
Choice (Choice (ifif and and elseelse))
if <it's sunny>{
<go to beach>}
else{
<take umbrella>}
Finding the Big OneFinding 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 Area of the circleof the circle
const double PI = 3.1415926;
int radius;
double area;
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 OddEven 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-ifif-else-if Statements 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
TS
if-else-ifif-else-if Statement 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-ifif-else-if ExampleExample 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 Nested ifif Statements Statements
◦Nested means that one complete statement is inside anotherif <condition 1 exists>{
if <condition 2 exists>{if <condition 3 exists>{
<do A>}<do B>
} <do C: sleep>
}
Nested Nested ifif Statements 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 Nested ifif Statements 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 Nested ifif Statements 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 Nested ifif Statements 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” ProblemDangling 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” ProblemDangling 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 EvaluationShort-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: Multiple Selection: The The switchswitch Statement Statement
value1
action 1
value2
action 2
value3
action 3
value4
action 4
multiway
expression
Multiple Selection: Multiple Selection: The The switchswitch Statement StatementSyntax: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: Multiple Selection: The The switchswitch Statement StatementMeaning: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: Multiple Selection: The The switchswitch Statement Statement
action
action
action
action
case 1
case 2
case 3
default
switchswitch Statement: Statement: Example 1Example 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;
}
switchswitch Statement: Statement: Example 2Example 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;
}
switchswitch Statement: Statement: Example 2Example 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;
switchswitch Statement: Statement: Example 2Example 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;
}
switchswitch Statement with Multiple Labels Statement with Multiple Labels: : Example 3Example 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 RememberPoints 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.
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”.
#include <iostream.h>
int main()
{
return 0;
}
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“;
elsecout<<"Contents unknown\n";
Exercise:Exercise:
Instead of using both Instead of using both uppercase and lowercase uppercase and lowercase letters of the given character letters of the given character in every if-condition or in in every if-condition or in switch-cases, convert the switch-cases, convert the character given by the user character given by the user into uppercase or lowercase into uppercase or lowercase and use only this character in and use only this character in if-conditions and switch-cases.if-conditions and switch-cases.
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 Disasterhigher
Catastrophe
#include <iostram.h>
int main()
{
return 0;}
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”;
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”.
#include <iostream.h>
int main()
{
return 0;
}
char color;
cout<<"Please enter the first letter of the cylinder's color : “;
cin>>color ;
switch (color){case 'O':case 'o':cout<<"\nThe contents of the compressed-gas cylinder is Ammonia\n“;
break;case 'B':case 'b':cout<<"\nThe contents of the compressed-gas cylinder is Carbon monoxide\n";
break;case 'Y':case 'y':cout<<"\nThe contents of the compressed-gas cylinder is Hydrogen\n";
break;case 'G':case 'g':cout<<"\nThe contents of the compressed-gas cylinder is Oxygen\n“;
break;default: cout<<"\nContents unknown\n“;}