0% found this document useful (0 votes)
23 views42 pages

Lec 10

Uploaded by

Mohamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views42 pages

Lec 10

Uploaded by

Mohamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Introduction to Computers

Lecture 9
Recap: What is the Output?
int x = 100;
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
equivalent
if (x == 100) if (x == 100)
cout << "x is 100"; cout << "x is 100";
cout << "x is not 100"; cout << "x is not 100";

In case x equals 100


The first block will print one message only,
while the second and third blocks will print two messages

-2-
Recap: What is the Output?

int count= 50; if (count = 100) is


if ( count = 100 ) almost ALWAYS true. T
he condition
cout << “count equals
count = 100 is actually an
100”; "assignment statement“
else
cout << “count does not Whereas,
equal 100”;
if (count == 100) is
} true ONLY if the value
stored in count is the
The output: number 100.
count equals 100
Increase/Decrease Operators

 In Example 1, B is increased before its value is


copied to A.
 In Example 2, the value of B is copied to A and
then B is increased.

-4-
Problem: Even/Odd Number

int number;
cout << "Enter a number\n";
cin >> number;

if (number % 2 == 0)
cout << number << "is Even\n";
else
cout << number << "is Odd\n";

-5-
Logical Operators

 AND (&&)
 OR (||)
 NOT (!)

-6-
Exercise: Logical Operators

 Assume weight = 140 and age = 24.

Expression Value
! (age > 18) false
! (weight == 150) true
(age > 18) || (weight >= 150) true
(age > 18) && (weight >= 140) true
(weight == 150) || (age < 45) true
(age > 34) || (weight < 140) false
(weight >=120) && (age >=30) false

-7-
Logical Operators

BEWARE:
 To check a range,
Math: 2 < x < 10 OK
Computer: if (2 < x < 10) NO!!!
Say x= 11, the computer will check the first
condition (2 < x) which evaluates to true (1). Then
the computer checks (1 < 10) which evaluates to
true!
 if ((2 < x) && (x < 10)) YES

-8-
Logical operators - De Morgan’s law

 Many programmers also make the mistake of thinking


that !(x && y) is the same thing as !x && !y.
 De Morgan’s law tells when you distribute
the logical NOT, you also need to flip logical
AND to logical OR, and vice-versa!
 !(x && y) is equivalent to !x || !y

 !(x || y) is equivalent to !x && !y

-9-
Note

 In expressions using operator &&, make the


condition most likely to be false the leftmost
condition.
 In expressions using operator ||, make the
condition most likely to be true the leftmost
condition.
 For example: ((5==5)||(3>6)), C++ evaluates first
whether 5==5 is true, and if so, it never checks
whether 3>6 is true or not.
 This is known as short-circuit evaluation.

-10-
Boolean Conditional Values

if (even == true) Equivalent if (even)


cout <<"It is even."; cout << "It is even.";

(a) (b)
This is better

if (even != true) Equivalent if (!even)


cout <<"It is odd."; cout << "It is odd.";

(a) (b)
This is better

-11-
Problem: BMI

 Body Mass Index (BMI) is a measure of health on weight.


It can be calculated by taking your weight in kilograms
and dividing by the square of your height in meters.
Program reads the person weight and height and displays
his BMI. The interpretation of BMI for people 16 years or
older is as follows:

BMI Interpretation
BMI< 18.5 underweight
18.5 < BMI < 25 normal
25 < BMI < 30 overweight
BMI >= 30 Seriously overweight

-12-
Solution
float weight, height;

// Prompt the user to enter weight


cout << "Enter weight: ";
cin >> weight;
// Prompt the user to enter height
cout << "Enter height: ";
cin >> height;
chaining
float bmi = weight /(height * height); if-else
cout << "BMI is " << bmi << endl;
if (bmi < 18.5)
cout << "Underweight" << endl;
else if (bmi < 25)
cout << "Normal" << endl;
else if (bmi < 30)
cout << "Overweight" << endl;
else
cout << "Seriously Overweight" << endl;
-13-
Grades int main()
Interpretation {
char grade;
 Program reads cout << "Enter student grade\n";
student grade cin >> grade;
if (grade =='A' || grade == 'a')
and interprets it. cout << "Excellent\n";
else if (grade =='B' || grade == 'b')
cout << "Very Good\n";
else if (grade =='C' || grade == 'c')
cout << "Good\n";
else if (grade =='D' || grade == 'd')
cout << "You can do better\n";
else if (grade =='E' || grade == 'e')
cout << "Disappointing\n";
else
cout << "Invalid Grade\n";
return 0;
}
-14-
Increase/Decrease Operators

 The increase operator (++) and the decrease


operator (--) increase or reduce by one the value
stored in a variable
x++; x--;
x=x+1; x=x-1;
x+=1; x-=1;
are all equivalent in functionality
also called increment/decrement operators
unary operators: works on one operand/variable
-15-
Increase/Decrease Operators
 This operator can be used as a prefix or as a suffix.
Case 1: When variable is not used in expression
• Pre-incrementing and post-incrementing have same effect
++x;
cout << x;
Same value as
x++;
cout << x;
Case 2: When variable is used in expression
 It is used as a prefix (++x) the value is increased before the
result of the expression is evaluated.
 It is used as a suffix (x++) the value stored in a is increased after
being evaluated.
cout << x++;
doesn’t output the same value as
cout << ++x; -16-
Increase/Decrease Operators

 If x = 5, then
cout << ++x;
x is changed to 6, then printed out

 If x = 5, then
cout << x++;
Prints out 5 (cout is executed before the
increment).
x then becomes 6

-17-
Increase/Decrease Operators

int i = 10; Same effect as


int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

newNum = 100
i = 11
int i = 10; Same effect as
int newNum = 10 * ++i; i = i + 1;
int newNum = 10 * i;

newNum = 110
i = 11
-18-
Conditional Operator

y = (x > 0) ? 1 : -1 ;

y = (BooleanExpression)? expression1 : expression2;


If BooleanExpression evaluates to true, then y= expression1.
If BooleanExpression evaluates to false, then y = expression2.

is equivalent to
if (x > 0)
y = 1;
else
y = -1;
-19-
Conditional Operator

 Both expressions in a conditional statement must


match.
 The following example won’t compile because one
of the expressions is an integer, and the other is a
string literal.

-20-
Problem

 Program reads two integers and displays the greater.

int num1, num2;


cout<<"Enter two numbers:\n";
cin >> num1 >> num2;

cout<<"Greater is: "


<< (num1 >= num2 ? num1 : num2) << endl;

-21-
Problem: Subtraction

Check result of subtraction of two input numbers.

-22-
Problem: Subtraction

Check result of subtraction of two input numbers.

int number1, number2, answer;


cout << "Enter two numbers: ";
cin >> number1 >> number2;
cout << "Enter the subtraction result: ";
cin >> answer;
if (number1 - number2 == answer)
cout << "correct!\n";
else
cout << "Wrong answer" << endl <<
number1 << "-" << number2 << "=" <<
number1 - number2 << endl;

-23-
Precedence Rules

-24-
Exercise

 Are they equivalent?


if (p||q &&r) if ((p||q) &&r)
cout <<"Valid."; cout <<"Valid.";
else else
cout <<"Invalid."; cout <<"Invalid.";
(a) (b)
Assume p=true, r = false. Remember, the
The expression in (a) will be true and AND operator is
output Valid. evaluated first and
The expression in (b) will be false and then the result of
output Invalid. the AND operation
So, the two expressions are is used for the OR
inequivalent. operation.
-25-
Problem

Perform subtractions of two randomly generated


numbers.

Note that:
 Function rand() generates random number.
 int x = rand() % n;
 Generates a random number from 0 to n-1.

-26-
Solution

Perform subtraction of two randomly generated numbers.

int number1 = rand() % 50; //generates random num from 0 to 49


int number2 = rand() % 10; //generates random num from 0 to 9

cout << "What is " << number1 << "-" << number2 << "? ";
int answer;
cin >> answer;
if (number1 - number2 == answer)
cout << "You are correct!\n";
else
cout << "Wrong answer" << endl <<
number1 << "-" << number2 << "=" <<
number1 - number2 << endl;

-27-
Note

 Remember to include necessary braces


if (radius >= 0) if (radius >= 0)
area = radius * radius * PI; {
cout << "The area " area = radius * radius * PI;
<< " is " << area; cout << "The area "
<< " is " << area;
}
(a) Wrong (b) Correct

-28-
Nested if
Write a program to find the minimum of three
numbers.
int n1,n2,n3;
cout << "Enter three integers: ";
cin >> n1 >> n2 >> n3;
if (n1 < n2)
{
if (n1 < n3) cout << "Their minimum is " << n1 << endl;
else cout << "Their minimum is " << n3 << endl;
}
else // n2 <= n1
{
if (n2 < n3) cout << "Their minimum is " << n2 << endl;
else cout << "Their minimum is " << n3 << endl;
} -29-
Another Solution

int n1,n2,n3;
cout << "Enter three integers: ";
cin >> n1 >> n2 >> n3;
if (n1 <= n2 && n1 <= n3)
cout << "Their minimum is " << n1 << endl;
else if (n2 <= n1 && n2 <= n3)
cout << "Their minimum is " << n2 << endl;
else
cout << "Their minimum is " << n3 << endl;

-30-
Note
Logic Error Empty Body

if (radius >= 0); if (radius >= 0) { };


{ Equivalent {
area = radius * radius * PI; area = radius * radius * PI;
cout << "The area " cout << "The area "
<< " is " << area; << " is " << area; Null
} } statement
(a) (b)
Wrong Semicolon at the if Line

int i = 1; int i = 1;
int j = 2; int j = 2;
int k = 3; Equivalent
int k = 3; Dangling
if (i > j) if (i > j) else
if (i > k) This is better if (i > k)
cout << "A"; with correct cout << "A";
else indentation else
cout << "B"; cout << "B";

(a) (b)

Match ELSE to correct IF -31-


Note

To force the else clause to match the first (outer) if clause,


you must add a pair of braces:

int i = 1; int j = 2; int k = 3;


if (i > j)
{
if (i > k)
cout << "A";
}
else
cout << "B";
Output?
This statement prints B.
-32-
Selective Structure: Switch
switch (expression)  switch replaces if-else
{ chains on a single variable
case constant1: testing for equality.
group of statements 1;  The switch statement uses
break; break statement after the
case constant2: group of statements to be
executed for a specific
group of statements 2;
condition.
break;
 Otherwise, the remainder
. . .
cases will also be executed
default: until the end of the switch
default group of selective block.
statements;
 Default case is optional.
}
Switch vs. IF-ELSE

 Switch can only be used to compare an expression


against constants. We cannot put variables as labels or
ranges because they are not valid C++ constants.

-34-
Grade
char grade;
Interpretation
cout << "Enter student grade\n";
cin >> grade;
switch (grade) break causes switch to
{ end and the program continues
case 'A': with the first statement after the
cout << "Excellent\n"; break; switch structure.
case 'B':
cout << "Very Good\n"; break;
case 'C':
cout << "Good\n"; break;
case 'D':
cout << "You can do better\n"; break;
case 'E':
cout << "Disappointing\n"; break;
default:
cout << "Invalid Grade\n";
}

-35-
char grade;
Grade
cout << "Enter student grade\n";
cin >> grade; Interpretation
switch (grade)
{
case 'A': // Fall to through to next case
case 'a':
cout << "Excellent\n"; break;
case 'B':
case 'b':
cout << "Very Good\n"; break;
case 'C':
case 'c':
cout << "Good\n"; break;
case 'D':
case 'd':
cout << "You can do better\n"; break;
case 'E':
case 'e':
cout << "Disappointing\n"; break;
default:
cout << "Invalid Grade\n";
}

-36-
Problem

 Decide if input day is weekday or part of weekend based on its number.


int day;
cout << "Enter day\n";
cin >> day;
switch (day)
{
case 1: // Fall to through to the next case
case 2:
case 3:
case 4:
case 5:
cout << "Weekday\n"; break;
case 6:
case 7:
cout << "Weekend\n"; break;
default:
cout << "Invalid day\n";
}

-37-
Exercise: Complete

1. Every C++ program begins execution at function …


2. All variables must be given a … when they are
declared.
3. The … statement is used to make a decision.
4. The … operator can be used as a prefix or as a
suffix.
5. In switch statement, the … is optional.
6. … is the only ternary operator in C++.

-38-
Exercise: True/False

1. C++ considers the variables number and Number to be


identical.
2. An expression containing the || operator evaluates to
true if either or both of its operands are true.
3. The default case is required in the switch statement.
4. Operators *, / and % have the same evaluation
precedence.
5. The break statement jumps to the start of the following
case.
6. Any IF..ELSE statement can be represented using
switch case.

-39-
Exercises

 Are these statements equivalent?


(a) if (isBool = true) (b) if (x=7)
if (isBool) if (x==7)

 What is the output of the following statements:


int x=5, y=3;
if(1<x<y)
cout<<"valid\n";
else
cout<<"Invalid\n";
 What happens when you omit the default case?
-40-
C++ Problems

1. Write a program that reads two integers and prints


if the first is a multiple of the second.
2. Write a program that reads three integers and
prints the median of them.
3. Write a program that simulates a simple calculator.
It reads two integers and a character. If the
character is +, the sum is printed; if it is -, the
difference is printed; if it is *, the product is
printed; if it is /, the quotient is printed; and if it is
%, the remainder is printed. Use a switch
statement.
-41-
Thank You

You might also like