You are on page 1of 48

IMAM ABDULRAHMAN BIN FAISAL UNIVERSITY

College of Computer Science & IT


Department of CS

Welcome to
CS 211: Introduction to Computing
Weeks (4):  Solving simple constraint satisfaction problems – Assignment and
Operators in C++ - Control Statements
Week#4 Lecture Outline
• Problem-Solving Principle:
• Problem decomposition
• Solving simple constraint satisfaction problems

• Programming and Application :


• Control Statements: Part I; (If..else, nested if statements, Logical Operators)
Problem-Solving Principle
Problem decomposition
Solving simple constraint satisfaction problems
Problem Decomposition (Modularization)
• Programmers seldom write programs as one long series of steps.
Instead, they break down their programming problems into smaller
units and tackle one cohesive task at a time. These smaller units are
modules.
• You are never required to modularize a large program to make it run
on a computer, but there are at least three reasons for doing so:
1. Modularization provides abstraction (isolation to the parts)
2. Modularization helps multiple programmers to work on a problem.
3. Modularization allows you to reuse work more easily. (you will find it more
efficient in Functions concept next term)
Problem Decomposition Method
• You will use techniques described as divide-and-conquer, decrease-
and-conquer, and transform-and-conquer, but we’re going to talk
about them here under the general banner of “simplify.”

• Simplify the problem as much as possible you can.


Problem # 1: Average Speed
Technique used: Simplify
• A child leaves his home and rides his bike to the store, averaging 15  
km/ h. When he comes out of the store, he sees that he has a flat tire
and walks the bike back home at a constant speed of 5   km/ h.
Assuming that he takes the same path, what is his average speed for
the back-and-forth trip?

15 km/hour

5 km/hour
Problem # 1: Average Speed (Discussion)
To break it down and simplify it:
1. First we need to know how to calculate the average speed, what is
the formula?
• Speed=distance / time
2. Calculate the total distance for the whole trip, what is it?
3. Calculate the total time for the whole trip, what is it?
4. Examine this for certain value.
5. Can you have a general formula or calculation for such problem?
6. Desk-check the resulting formula with different values.
Problem # 1: Average Speed (Discussion)
How to apply it?
Problem-Solving Technique e.g. of Technique Application
An experienced problem-solver will simply make up a If you don’t know the distance between the child’s
value for the missing parameter to move the problem home and the store assume your program shall work
forwards. for any distance.

Further, the experienced problem-solver will select a In this case, the distance of 15  km from the home to
value that is very convenient. the store is a good choice. Why 15 is convenient ?

Ensure that all measurement units used in the For example, all distances are measure using km , all
calculations are the same. speed km/h , time is measured using hours and so on.

We use those techniques to simplify problems and go forward in solving them.


Problem # 1: Average Speed (Discussion)
So, to break it down and simplify it using Specific Value :
• As a case to start with: we will consider 15 km as the distance between the
house and the store.
• We need to calculate the distance from and to the house (round trip) = 15 * 2 =
30 km
• Time = distance / speed
• Time from house to the shop = 15 km ÷ 15 km/h = 1 hour
• Time from the shop back to the house = 15 km ÷ 5 km/h = 3 hour
• Thus, total time for the whole round trip = 1 + 3 = 4 hours.
• So, Average Speed for the round trip = total distance / total time = 30/4= 7.5
km/h
Problem # 1: Average Speed (Discussion)
So, to break it down and simplify it using General Formula for any distance:
• Assume distance is declared as the variable (d)
• We need to calculate the distance from and to the house (round trip) = d *
2 = 2d km
• Time = distance / speed
• Time from house to the shop = d km ÷ 15 km/h = d/15 hour
• Time from the shop back to the house = d km ÷ 5 km/h = d/5 hours
• Thus, total time for the whole round trip = d/15 + d/5 = 4d/15 hours.
• So, Average Speed for the round trip = total distance / total time
= 2d ÷ 4d/15
Problem # 1: Average Speed (Discussion)
So, to break it down and simplify it using General Formula for any
distance:
• So, Average Speed for the round trip = total distance / total time
= 2d ÷ 4d/15
• Now, let us test the formula with the distance we have used (15 km).
Average Speed = 2*15÷ 4 * 15 /15 = 2*15÷ 4 = 7.5 km/hour.
• This is the same result we have got earlier. Great job!
• Now, let us examine it with different distances. Try it for distances of
45 km , 70, and 100 km. (desk-check)
Problem # 1: Average Speed (Discussion)
So, to break it down and simplify it using General Formula for any
distance (desk-check):
• Average Speed (round trip) = total distance / total time
= 2d ÷ 4d/15
• Now, let us examine it with different distances. Try it for distances of
45 km , 70, and 100 km.
Distance Calculations of Average Speed Result
45 km Average Speed = 2*45 ÷ 4 * 45 /15 = 90 ÷
180 /15 = ? 7.5 km/hour.
70 km Average Speed = 2*70 ÷ 4 * 70 /15 = 140 ÷
280 /15 = ? 7.5 km/hour.
100 km Average Speed = 2*100 ÷ 4 * 100 /15 =
200 ÷ 400 /15 = ? 7.5 km/hour.
Problem # 2: Hats Colors
Technique used: Enumerate and Eliminate
• Mr. Brown, Mr. White, and Mr. Green went to a hat shop where they
all picked out hats of different colors. When they left the store, the
man with a green hat said: “Have you noticed that although our hat
colors match our names, none of us has the same hat color as our
name?” Mr. Brown replied: “Indeed, you are right! This is
remarkable!” What hat color did each man have?
Problem # 2: Hats Colors
Technique used: Enumerate and Eliminate
• So, as a start we will assume that each gentleman has the
three choices of colors (Enumerate):
• Mr Brown: B or G or W
• Mr White: B or G or W
• Mr Green: B or G or W
• This is a good example of a problem that illustrates nicely the
process of elimination – after all possibilities were
enumerated.
Problem # 2: Hats Colors
Technique used: Enumerate and Eliminate
• But based on the fact stated : ““Have you noticed that although
our hat colors match our names, none of us has the same hat
color as our name?”
• As none of the men’s hat colors matched their name (this is the
first fact, hence the first constraint), it is possible to eliminate a
few potential assignments, and now the remaining possible
arrangements are:
• Then will (Eliminate)
• Mr Brown: B or G or W
• Mr White: B or G or W
• Mr Green: B or G or W
Problem # 2: Hats Colors
Technique used: Enumerate and Eliminate
• Now (as usual) we are ready for considering the other
constraints. The man with the green hat made a remark that
was answered by a different man, Mr. Brown.  Therefore,
the immediate inference is that Mr. Brown does not have a
green hat!
• And this is all we need to solve this puzzle, as (Eliminate):
• Mr Brown: G or W
• Mr White: B or G
• Mr Green: B or W
Problem # 2: Hats Colors
Technique used: Enumerate and Eliminate
• So, this implies also (Eliminate):
• Mr Brown: W
• Mr White: B or G
• Mr Green: B or W (WHY?)
• Then, this implies also (Eliminate):
• Mr Brown: G or W
• Mr White: B or G (WHY?)
• Mr Green: B
Problem # 2: Hats Colors
Technique used: Enumerate and Eliminate
• So:
• Mr Brown: W

• Mr White: G

• Mr Green: B
Programming and Application
Characters
• Characters are enclosed in single quotes

char letter = 'a';

• Strings of characters, even if only one character


is enclosed in double quotes
• "a" is a string of characters containing one character
• 'a' is a value of type character
char   int
• The following actions are possible but generally not
recommended!
• It is possible to store char values in integer
variables
int value = 'A';
value will contain an integer representing 'A'

• It is possible to store int values in char Why 65 is equivalent for A?


variables
char letter = 65;
Reading Character Data
• cin skips blanks and line breaks looking for data
• The following reads two characters but skips
any space that might be between

char symbol1, symbol2;


cin >> symbol1 >> symbol2;

• User normally separate data items by spaces


J D
• Results are the same if the data is not separated
by spaces
JD
Display 2.4
Type string
• string is a class, different from the primitive data types discussed so far
• Use double quotes around the text to store into the string variable
• Requires the following be added to the top of your program:
#include <string>

• To declare a variable of type string:

string name = "Apu Nahasapeemapetilon";

Slide 2- 25
Display 2.5
Mini Quiz
1. Which of the following is a character literal?
a. ‘56’
b. ‘%’
c. “a”
d. both a and b
2. Which of the following is a string literal?
a. “$”
b. “Good Morning!”
c. “ ”
d. all of the above

3. If you assign the number 10.25 to an int variable, what will the computer
store in the variable?
Commonly Used Escape Sequences

Write the C++ statement to print the text (He said: “The \ is called a backslash”)
The endl Manipulator
• You do NOT put quotation marks around endl

• The last character in endl is a lowercase L, not the number 1.

endl This is a lowercase L


Control Statements: Part 1
Simple Flow of Control
• Flow of control
• The order in which statements are executed.

• Branch
• Let the program choose between two alternatives.
• A selection structure is needed when a decision must be made
(based on some condition) before selecting an instruction to execute
• A selection structure’s condition must be phrased as a Boolean
expression (evaluates to true or false)
Assignment 1

• You need to calculate the weekly wages such that


• If number of hours worked less than or equal to 40 then regular per hour pay
• If number of hours more than 40 then for the hours that are more than 40,
the per hour pay should be doubled
• Need to have employee name, employee id, per hour pay and
number of hours worked in the week
• What do we need ( inputs, processing, outputs) ?
• Can you make an algorithm ?
• Then write the equivalent C++ code for this algorithm
Branch Example
• To calculate hourly wages there are two choices:
• Regular time ( up to 40 hours)
• totalPay = rate * hours;

• Overtime ( over 40 hours)


• totalPay = rate * 40 + 2 * rate * (hours - 40);

• Let us think, how we can design the branch?


• The program must choose which of the two expressions to use.
• Decide if (hours >40) is true, or not.
Implementing the Branch
• if-else statement is used in C++ to perform a branch.

if (hours > 40)


totalPay = rate * 40 + 2 * rate * (hours - 40);
else
totalPay = rate * hours;

Display 2.8
One-Way Selection

• The syntax of one-way selection is:

• The statement is executed if the value of the expression is true


• The statement is bypassed if the value is false, program goes to the next
statement
• if is a reserved word
Two-Way Selection

• The syntax of two-way selection is:

• If expression is true, statement1 is executed, otherwise,


statement2 is executed
• statement1 and statement2 are any C++ statements
• else is a reserved word
Compound Statement
• If you want to execute more than one statement for a condition then you need to add

parenthesis { }

if (age > 18)


{
cout << "Eligible to vote." << endl;
cout << "No longer a minor." << endl;
}
else
{
cout << "Not eligible to vote." << endl;
cout << "Still a minor." << endl;
}
Comparison Operators
• A condition is represented by a logical (Boolean) expression that can be true or
false
• Comparison operators (Relational operators):
• Require two operands.
• Evaluate to true or false.

Slide 2- 38
Comparison Operators and Numeric Data Types

• You can use the comparison operators with all numeric data types:
• 8 < 15 evaluates to true

• 6 != 6 evaluates to false

• 2.5 > 5.8 evaluates to false

• int x = 3.9, y =7.5;


x <= y evaluates to true

Slide 2- 39
Comparison Operators and Char Data Types
• You can use the comparison operators with char data type (using the
ASCII collating sequence):

Slide 2- 40
Logical Operators
• Used to evaluate more than one expression at the same time.
• Logical operators such as:
• AND
• OR
• NOT

Slide 2- 41
Logical Operators (AND)
• The AND operator: &&
• True if both expressions are true.
• Syntax: (Expression 1) && (Expression 2)
• Example:

Slide 2- 42
Logical Operators (OR)
• The OR operator: ||
• True if either or both expressions are true.
• Syntax: (Expression 1) || (Expression 2)
• Example:

Slide 2- 43
Logical Operators (NOT)
• The NOT operator: !
• Negates any Boolean expression.
• ! Operator can make expressions difficult to understand. Use only when appropriate

• Example:

Slide 2- 44
Common errors to avoid in if condition
• Confusion Between == and =
• ' = ' is the assignment operator, used to assign values to variables:
o Example: x = 3;
• ’ = = ' is the equality operator, used to compare values:
o Example: if ( x == 3)
• The compiler will accept this error: if (x = 3)
but stores 3 in x instead of comparing x and 3
o Since the result is 3 (non-zero), the expression is always true!

What will be the output of the


following program?

Slide 2- 45
Common errors to avoid in if condition
• Be careful translating inequalities to C++
• if x < y < z translates in C++ as: if ( ( x < y ) && ( y < z ) )
NOT as: if ( x < y < z )
Assignment 2
• Write an if-else statement that outputs the word High if the value of
the variable score is greater than 80 and Low if the value of score is at
most 80? The variables are of type int.

• Write an if-else statement that outputs the word Warning provided


that either the value of the variable temperature is greater than or
equal to 45, or the of the variable pressure is greater than or equal to
70, or both. Otherwise, the if_else statement outputs the word OK.
The variables are of type double.
Questions?

You might also like