basic of computer science dr. mohamed khafagy conditional statements a conditional statement allows...

55
Basic Of Computer Basic Of Computer Science Science Dr. Mohamed Khafagy

Upload: neil-pope

Post on 02-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

Basic Of Computer Basic Of Computer ScienceScience

Dr. Mohamed Khafagy

Page 2: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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

Page 3: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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

Page 4: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

Choice (Choice (ifif))

Put multiple action statements within braces

if (it's raining){<take umbrella><wear raincoat>

}

Page 5: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

}

Page 6: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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

Page 7: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

Operator PrecedenceOperator Precedence

Which comes first?

* / %+ -

< <= >= >== !=

=

Answer:

Page 8: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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 !

Page 9: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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

Page 10: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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

Page 11: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

The Boolean TypeThe Boolean Type

Truth table for "!" (NOT):

Operand !Operand

true false

false true

Page 12: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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);

Page 13: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

Page 14: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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

Page 15: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

Choice (Choice (ifif and and elseelse))

if <it's sunny>{

<go to beach>}

else{

<take umbrella>}

Page 16: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

Page 17: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

Page 18: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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);

Page 19: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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

Page 20: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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";}

Page 21: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

Page 22: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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>

}

Page 23: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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>

}

}

Page 24: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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.

Page 25: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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.

Page 26: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

Page 27: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

““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;

Page 28: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

““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.

Page 29: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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.

Page 30: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

Multiple Selection: Multiple Selection: The The switchswitch Statement Statement

value1

action 1

value2

action 2

value3

action 3

value4

action 4

multiway

expression

Page 31: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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>; }

Page 32: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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.

Page 33: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

Multiple Selection: Multiple Selection: The The switchswitch Statement Statement

action

action

action

action

case 1

case 2

case 3

default

Page 34: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

}

Page 35: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

}

Page 36: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

Page 37: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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;

}

Page 38: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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

Page 39: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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.

Page 40: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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”.

Page 41: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed
Page 42: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed
Page 43: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed
Page 44: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

#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";

Page 45: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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.

Page 46: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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

Page 47: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed
Page 48: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed
Page 49: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed
Page 50: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

#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”;

Page 51: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

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”.

Page 52: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed
Page 53: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed
Page 54: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed
Page 55: Basic Of Computer Science Dr. Mohamed Khafagy Conditional Statements A conditional statement allows us to control whether a program segment is executed

#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“;}