Вы находитесь на странице: 1из 41

COMPUTER PROGRAMMING

CONDITIONS AND LOOPS


Conditional Constructs
• Provide
• Ability to control whether a statement list is executed

• Two constructs
• If statement
• If
• if-else
• if-else-if
• Switch statement
The Basic If Statement
Syntax
if (Expression)
Action Expression

true false
• If the Expression is true then
execute Action
• Action is either a single statement Action
or a group of statements within
braces
Simple if Statement Syntax
if (Boolean Expression)
Statement

if (Bool-Expr)
{
Statement_1

Statement_n
}
Example
if (Value < 0) {
Is our number negative?
Value = -Value;
}
If Value is less than Va lue < 0
zero then we need to
update its value to
true false
that of its additive
inverse If Value is not less
than zero then our
Va lue = -Va lue number is fine as is

Our number is
now definitely
nonnegative
Sorting Two Numbers
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
if (Value1 > Value2) {
int RememberValue1 = Value1;
Value1 = Value2;
Value2 = RememberValue1;
}
cout << "The input in sorted order: "
<< Value1 << " " << Value2 << endl;
Semantics
Are the numbers
out of order
Rearrange value1
and value2 to va lue 2 < value 1
put their values
in the proper
order true false

in t re mem ber Valu e1 = val ue1


v alu e1 = valu e2
v alu e2 = reme mbe rVal ue1

The numbers were


rearranged into the
proper order
The numbers were
initially in order
The numbers are in
order
These are NOT equivalent. Why?
if (number == 0 ) { if (number == 0 )
cout << “Hmmmm ”; cout << “Hmmmm ”;
cout << “You entered cout << “You entered
invalid number.\n”; invalid number.\n”;
}

When number has value 0,


When number has value 0, the output will be:
the output will be: Hmmmm You entered invalid number.
Hmmmm You entered invalid number.

When number has value NOT 0 When number has value is


not 0, the output will
there is NO output. be:
You entered invalid number.
These are equivalent. Why?
if (number == 0 ) if (!number )
{ {
. .
. .
} }

Read as: Read as:


If number is NOT true
If number is 0 If number is false

Each expression is only true when number has value 0.


The If-Else Statement
Syntax
if (Expression)
Action1 Expression
else
Action2
If Expression is true then execute true false
Action1 otherwise execute Action2

if (v == 0) { Action1 Action2
cout << "v is 0";
}
else {
cout << "v is not 0";
}
Finding the Max
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
int Max;
if (Value1 < Value2) {
Max = Value2;
}
else {
Max = Value1;
}
cout << "Maximum of inputs is: " << Max << endl;
Finding the Max
Is Value2 larger than Value1

Yes, it is . So Value2 is
larger than Value1. In
this case, Max is set No, its not. So Value1
to Value2 is at least as large as
Value2. In this case,
Value1 < Value2 Max is set to Value1
true false

Max = Value2 Max = Value1

Either case, Max is set


correctly
Nested if-else
cout << "Your semester grade is ";
• The if-clause and else-clause may
if (Average >= 90)
contain any valid C++ statements,
cout << "A" << endl;
including other if or if…else
statements: else if (Average >= 80)
cout << "B" << endl;
else if (Average >= 70)
cout << "C" << endl;
else if (Average >= 60)
cout << "D" << endl;
else
cout << "F" << endl;
Use of blocks
Denoted by { .. }
Recommended in controlled structures (if and loop)
Also called compound statement.

if (Bool-Expression ){
“if clause”
}
else{
“else clause”
}
Switch Statement
• A switch statement allows a variable to be tested for equality against
a list of values.
• Each value is called a case, and the variable being switched on is
checked for each case.
Syntax
switch(expression){
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);
}

14
Switch Statement
// local variable declaration:
char grade = 'D’;
switch(grade) {
case 'A’ :
cout << "Excellent!" << endl;
break;
case 'B’ :
case 'C’ :
cout << "Well done" << endl;
break;
case 'D’ :
cout << "You passed" << endl;
break;
case 'F’ :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
} cout << "Your grade is " << grade << endl;
return 0;

15
Switch Statement
• The following rules apply to a switch statement:
• The expression used in a switch statement must have an integral or
enumerated type, or be of a class type in which the class has a single
conversion function to an integral or enumerated type.
• You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.

16
Switch Statement
• When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.

17
Loops (Recursion/Repetition)
• Is a repetition control structure.
• Causes a single statement or block of statements to be
executed repeatedly until a condition is met.
• There are 3 kinds of loop in C++:
• For loop
• While loop
• Do-While loop
For Loop
SYNTAX
for ( Initialization, TestExpression, Update ){
… // loop body
}
• Initialization is used to initialize variables
• TestExpression determines loop termination
• Update executes once an iteration
• Updates values used in test expression
For Loop Mechanism
When the
expression is When the
tested and found Initialization expression is
to be false, the tested and found
loop is exited and to be true, the
control passes to loop body is
FALSE
the statement executed. Then,
which follows the TestExpression
the expression is
loop body. updated and
Update
TRUE TestExpression tested again.

body
statement
For Loop Example
int i; count Expression Output
double square; 1 true the square of 1 is 1

for (i = 1; i <= 10; i++) { 2 true the square of 2 is 4


3 true the square of 3 is 9
square = i*i;
4 true the square of 4 is 16
cout << "the square of 5 true the square of 5 is 25
"+i+" is " + square;
6 true the square of 6 is 36
}
7 true the square of 7 is 49
Cout << "That's All!"; 8 true the square of 8 is 64
9 true the square of 9 is 81
10 true the square of 10 is 100
11 false That’s All!
While Loop
SYNTAX
while ( Expression )
{
… // loop body
}
• No semicolon after the boolean expression
• Loop body can be a single statement, a null statement, or a block.
While Loop Mechanism
When the When the
expression is expression is
tested and found tested and found
to be false, the FALSE
to be true, the
loop is exited and Expression
control passes to loop body is
the statement executed. Then,
TRUE
which follows the the expression is
loop body. tested again.
body
statement
While Loop Example
int count ;
count = 0; // initialize LCV
while (count < 5) // test expression
{
cout << count << “ ”; // repeated action
count = count + 1; // update LCV
}
cout << “Done” << endl ;
Loop Tracing
int count ;
count = 0; count Expression Output
while (count < 5) 0 true 0
{ 1 true 01
2 true 012
cout << count << “ ”;
3 true 0123
count = count + 1;
4 true 01234
} 5 false 0 1 2 3 4 Done
cout << “Done” << endl
;
Increment and Decrement Operators
• Denoted as ++ or --
• Mean increase or decrease by 1
• Pre increment/decrement: ++a, --a
• Increase/decrease by 1 before use.
• Post increment/decrement: a++, a--
• Increase/decrease by 1 after use.
• Pre and Post increment/decrement yield different
results when combining with another operation.
Pre and Post Increment and Decrement
int count ; count Expression Output
count = 0; 0 true 0
while (count < 5)
1 true 01
{
cout << count++ << “ “ ; 2 true 012
} 3 true 0123
cout << “Done” << endl ; 4 true 01234
5 false 0 1 2 3 4 Done
Pre and Post Increment and Decrement
int count ; count Expression Output
count = 0; 0 true 1
while (count < 5)
1 true 12
{
2 true 123
cout << ++count << “ “
; 3 true 1234
} 4 true 12345
cout << “Done” << endl ; 5 false 1 2 3 4 5 Done
Do-While Loop
SYNTAX
do
{
… // loop body
} while ( Expression );
• Insured that the loop is executed at least once
• The LCV is initialized/updated before the end of the loop.
• Boolean expression is tested at the end of the loop.
• There is a semicolon after the boolean expression.
Do-While Loop Mechanism
The loop body is executed first

When the expression When the


is tested and found to expression is
be false, the loop is tested and found
exited and control body
to be true, the
passes to the statement
statement which loop body is
follows the loop executed. Then,
body. the expression is
FALSE TRUE
tested again.
Expression
Do-While Loop Example
int ans;
do
{
Output Input ans Expression
cout << “Choose a number from
1 to 4: “;// repeated action Choose a number from 1 to 4: 2 2 true
cin >> ans; Choose a number from 1 to 4: 3 3 true
// LCV is initialized or
updated Choose a number from 1 to 4: 1 1 true
} while (ans >= 1 && ans <= 4); Choose a number from 1 to 4: 5 5 false
// test expression Done
cout << “Done”;
Loop-Controlled Types
• Count-controlled: repeat a specified number of times.
• Event-driven: some condition within the loop body changes and
this causes the repeating to stop.
• Sentinel-controlled: using a specific value to end.
• Sentinel: a value that cannot occur as valid data.

• Ask-before-Continuing: ask users if they want to continue.


• Flag-Controlled Loops: use a variable whose value is changed when
an event occurs (usually from false to true).
Count-Controlled Loop
• Has a loop control variable (LCV) as a counter.
• LCV must be
• Initialized before start of the loop
• Tested (boolean expression)
• Updated
Event-driven loop
double salary;
cout << "Enter you salary: ";
cin >> salary;
int years = 0;
while (salary < 50000) {
salary = salary * 1.02;
years++;
}
cout << “You need “ << years << “years to get to
50K";
Sentinel-Controlled
do
{
cout << ”Enter salary, type -1 to exit”; // no one earns
negative salary
cin >> salary;
// process income
} while (salary > 0);
Ask-before-Continuing
char ans = ‘y’; // LCV is initialized
while (ans == ‘Y’ || ans == ‘y’) // test expression
{
doSomething; // repeated action
cout << “Do you want to continue? ”;
cin >> ans; // LCV is updated
};
BREAK statement
• Allows to exit from any loop.

do{
cin>>x;
if (x % 2 ==0)
break;
} while (x > 0); // exits when an even number
is entered
CONTINUE Statement
• Allows you to skip the rest of the loop body and go back to the
beginning of the loop.

do{
cin>>x;
if (x % 2 == 0)
continue;
cout<<x<<endl;
} while (x <100);
//prints out all odd numbers entered less than
100
Program Style
• Indenting:
• Separate processes with blank lines
• Blank lines are also ignored and are used to increase readability.
• Indent statements within statements (loop body)
• Comments:
• // tells the computer to ignore this line.
• for internal documentation. This is done for program clarity and
to facilitate program maintenance.
General rules for Comments
• Place a comment at the beginning of every file with the file
name, version number, a brief program description,
programmer’s name.
• Place a descriptive comment after each variable declared.
• Use a blank line before and after variable declarations

• Place a descriptive comment and a blank line before each


subtask.