2. Today’s lecture
• Introduction to program control
– Conditional controls
• if, if … else, ?:, switch-case
– Loop controls
• for, while, do … while, if … break,
if … continue
• Typesetting of source code
• Use of indentation to keep track of nested conditions and loops
• Use of whitespace to group actions together
• Use of comments
• Log books
3. The need for program control
• Not all C++ programs execute from the first line, linearly to
the last,
– Most involve repetition, skipping and conditional branching
• In most programs, the program control path through the
code depends on the values of variables at different points in
the program
– The values of variables can be changed as the program proceeds
• Conditional statements can be used to selectively execute
either:
– A single line of code,
• Braces { } not required around the executable statement
– Multiple lines of related code (called a block)
• Braces { } REQUIRED around the executable statement
4. Flowchart: Hot drink example
(refer to Lecture 1) Start
Kettle water
level == 0?
Want milk?
Put teabag in mug
Tea
Drink!
NoExtract teabag
Yes
Add milk
Yes
Heat kettle
Yes
Fill kettle
Yes
Put instant coffee in mug
Coffee
Teabag in mug?
No
Want tea
or coffee?
No
Water
temp < 100?
No
If statement
A loop
Test condition for the loop
(whether or not to do an
iteration)
A switch
If statement
If statement
5. • The if keyword is used to test a given expression for a value of true or
false
– if the result is true, then a specified series of statements is executed
• the series of statements is specified within braces after the test
• the execution of these statements is conditional on the result of the test
– otherwise, those conditional statements are skipped
• The else keyword is used with an if statement to specify an alternative
path to be executed when the test expression is false
• Syntax:
if (test-expression)
{
code-to-be-executed-when-true;
}
Conditionals: if and if … else
Each
statement
ends with a
semi
colon!!
6. Conditional if statement
• Example program section:
int main(int argc, char* argv[])
{
int x=0, y=0;
cin >> x ;
cin >> y ;
if ( x > y )
cout << “true, x > yn“ ;
return 0;
}
7. Nested if statement
• if statements can be nested inside other if blocks to
express multiple tests, e.g. x < y, x == y, x != y
• Indentation applied for nested if blocks to keep track of
nested blocks
if (test1_expression)
{
if (test2_expression)
{
test2_true_action;
}
} Indentation
8. if-else statement
• This is called ‘conditional branching’ because the program
will choose a certain route depending on the test result.
• The syntax:
if (test-expression)
{
test_true_action1;
test_true_action2;
test_true_action3;
}
else
test_false_action;
9. if-else statement
• Example:
int main(int argc, char* argv[])
{
int int1;
cin >> int1;
if ( int1 > 1 )
cout << “yes, int1 is > 1n “ ;
else
cout << “ no, int1 is not > 1n “;
return 0;
}
Indentation
10. The ?: Conditional operator
• Unique to C/C++
• The ?: conditional operator provides a quick way to write a
test condition.
• Associated actions are performed depending on whether the
test_expression evaluates to true or false.
• The operator can be used to replace an equivalent if-else
statement.
• Syntax:
test_expression ? true_action : false_action ;
• Using example in previous slide:
(int1 > 1) ? cout << “yes, int1 is > 1n “ : cout << “
no, int1 is not > 1n “;
11. switch statement
• Multiple if-else statements
– conditional branching can often be more efficiently programmed by
using a switch statement
• switch uses a given integer/string/float… value then finds a
matching value among a series of case statements.
• default instructions can be specified for the case of no
match being found.
• Each case statement ends with a break instruction
– causes the remaining set of switch statements to be skipped.
12. switch statement
• Syntax
switch (integral_expression)
{
case constant1:
statements1;
break;
case constant2:
statements2;
break;
default:
statements;
}
No need for braces.
Statements execute until
break is encountered.
Never forget to
include break!
If integral_expression
is neither constant1 nor
constant2, execute the
following statements
13. switch statement
• Example:
int main(int argc, char* argv[])
{
int int1;
cout << “enter an integer: “;
cin >> int1;
switch (int1)
{ case 1 : cout << “1 foundn “ ; break;
case 2 : cout << “2 foundn “; break;
case 3 : cout << “3 foundn “; break;
default : cout << “ int1 is not 1, 2 or 3n “;
}
return 0;
}
Try choice of hot drink
example, e.g. hot drink
dispensing machine
14. Loops
• for, while and do-while loops
• The basic difference between a for loop and a while or
do-while loop has to do with the “known” number of
repetitions
– for loops are used whenever the required number of repetitions is
defined
• the required number of repetitions could be given by a constant or the
value of a variable
– while and do-while are used for an unknown number of
repetitions. (good for interrupt based codes or code that is invoked
on status changes)
15. for loops
• The loop iterates while the tested expression is true, repetitions
or iterations stop when the test-expression is found false.
• Syntax:
for(initialization_exp; test-exp; operation)
{
statements
}
• Example:
int i;
for(i=0; i < 2; i++)
{
cout << “iteration “ << i << endl;
} The operation doesn’t
need to be an increment
If i were initially 2, the cout
would never be executed
Only execute the statements inside the
braces if this condition is satisfied
Each time around the loop, perform this operation
Output:
iteration 0
iteration 1
16. Nested for-loops example
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
//note: indentation applied to keep track of nested loops
int i, j;
for(i = 1; i < 4; i++)
{
cout << “outer loop iteration” << i << endl;
for(j = 1; j < 4; j++)
{
cout << “t inner loop iteration” << j << endl;
}
}
return 0;
}
17. while loops
• The while keyword is combined with an expression to be
tested for a true or false value.
– If the tested expression is true, iteration around the loop will
continue,
– If the tested expression is false, iteration will stop.
• The while loop is a pre-test loop just like the for loop,
– the program evaluates the test_expression before entering the
statement(s) within the body of the loop.
– Pre-test loops can be executed from zero to many times.
18. while loops
• Syntax: while(test_expression) {statements}
• Example:
int i;
i = 0;
while(i < 2)
{
cout << “ iteration “ << i << endl;
i = i + 1;
}
Make sure the test_expression
comes to an end to avoid infinite looping
Equivalent to i+
+;
Output:
iteration 0
iteration 1This is equivalent to the first for example
19. do-while loops
• The do-while loop differs from the for and while loops in
that it is a post-test loop
– the loop is at least entered at least once
– the loop condition is tested at the end of the 1st
iteration.
• do-while loops are best used when there is no doubt the
statement(s) within the loop need to be executed at least
once
– e.g. presenting a menu to the user even if the user wants to exit
immediately after.
20. do-while loops
• The do keyword is followed by a statement block within
braces to be executed on each iteration.
• Then, the while keyword and an expression to be tested for
a true or false value.
– If the tested expression is true the loop will continue,
– If the tested expression is false, the loop will be exited.
– At least one execution of the statement block will occur.
• Syntax:
do {
statements
} while (test-expression);
21. do-while example
int i;
i = 0;
do
{
cout << “iteration “ << i << endl;
i = i + 1;
} while( i<2 );
As it stands, this produces the same result
as the previous while example
Output:
iteration 0
iteration 1
i is initially 0
No test on whether or not to
enter the do block
Execute the cout
First time through, i=1 so do the do block again
Second time through, i<2 is false so do not do the
do block again
22. do-while example
int i;
i = 2;
do
{
cout << “iteration “ << i << endl;
i = i + 1;
} while( i<2 );
• If i were initially 2 in the previous while example, the cout would not
have been executed
• In the do-while example above, however, the statements inside the
braces are executed at least once
• The test is applied only afterwards Output:
iteration 0
i is initially 2
23. if-break statement
• The break keyword was used to exit case statements inside a
switch. It can also be used to break out of a loop.
• A break statement can be used inside any loop statement block,
combined with a conditional test.
– When the test is found to be true the loop terminates (no more
iterations).
• Example/syntax:
int i = 0;
while( i < 4 )
{
i = i + 1;
cout << “ iteration “ << i;
if(i > 2) break;
cout << “go to the nextn“ ;
}
cout << “Go on through the programn”;
Output
iteration 1 go to the next
iteration 2 go to the next
iteration 3
Go on through the program
When i>2, the
program jumps out
of the loop
• go to the next
is not written
24. if-continue statement
• continue is used to go immediately to the start of the next iteration
• continue can be used inside any type of loop, combined with a
conditional test.
– When the test result is true
• current iteration is immediately terminated and the next iteration begins.
– Be careful to avoid infinite loops.
• It must be possible for the test result to be false
int i = 0;
while( i < 4 ) {
i = i + 1;
if(i == 2) continue;
cout << “ iteration “ << i;
cout << “go to the nextn“ ;
}
cout << “Go on through the programn”;
Output
iteration 1 go to the next
iteration 3 go to the next
Go on through the program
28. ++,-- operators
• The ++ increment operator and -- decrement operator
change the given value by 1
– commonly used to count iterations in loops.
• Postfix increment operator, e.g. a++, uses the value of the
variable in an expression first and then increments its value.
• Prefix increment operator, e.g. ++a, increments the value of
the variable first and then uses the value in an expression.
• Examples:
int i=3, j, k=0;
• k = ++i; //i=4, k=4
• k = i++; //i=4, k=3
• i = j = k--; //i=0, j=0, k=-1
• TAKE CARE!
29. Whitespace, comments, endl,
n, indentation
• Some lines left blank, called whitespace, make it easier to
read your program,
– separate sections of code into related statements (grouping actions
together)
• The double-slash // comment is a C++ style comment
– tells the compiler to ignore everything that follows the slashes until
the end of the line.
• The c-style slash-star /* comment mark
– tells the compiler to ignore everything that follows until it finds a star-
slash */ comment mark
• n indicates the newline escape sequence,
– endl is a C++ alternative to n
• Use indentation to keep track of nested loops or conditions
30. Log books
• You must keep a log book
– The log book should be handed in once each semester
– 10% of the final marks will be based on your log book
• What should go in a log book?
– print outs of working source code you have written for
each lab
– notes of results of testing of code in each lab
– evidence of your own reflection on programming, e.g.
• annotation of source code to note important points
• aide memoires to yourself