KEMBAR78
Lecture 3 | PDF | Control Flow | Computer Science
0% found this document useful (0 votes)
18 views33 pages

Lecture 3

Computer Hardware
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)
18 views33 pages

Lecture 3

Computer Hardware
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/ 33

Programming Techniques

Lecture 3
Lecture Outline
• Control Structures
• Sequential Control Structures
• Decision Control Structures
• Loop Control Structures
• Decision/Selection Control Structures
• Single-alternative selection statements
• Dual-alternative selection statements
• Multiple-alternative selection statements
• Using Switch-Case Statements
Introduction
• Structured programming is a method used to design and code
programs in a systematic and organized manner.
• A structure is a basic unit of programming logic.
• Computer programs are made of one or more of three main
structures.
• The three basic types of control structures are:
• Sequential (or sequence) control structure
• Decision (or selection) control structure
• Loop (or repetition) control structure
The Sequential Structure
• A sequential structure consists of a series of consecutive
statements, executed in the order in which they appear.
• You perform an action or task, then you perform the next action,
in order.
• A sequence can contain any number of tasks, but there is no
option to branch off and skip any of the tasks.
• Once you start a series of actions in a sequence, you must
continue step by step until the sequence ends.
• The general form of a sequential structure is as follows:
Statement
Statement
…Statement Exit
Decision or Selection Control Structures
• Selection structure or decision structures ask
a question and, depending on the answer,
take one of two courses of action. Then, no
matter which path is followed, continues Yes No
with the next task.
• With this structure, you ask a question, and
depending on the answer, you take one of two
course of action.
• Thus, depending upon a given condition at the
branch point, a certain block of statements will
be executed while another is skipped.
Selection or Decision Control Structure
• There is a test condition together with one or
more blocks of statements.
• Every decision you make in a computer Yes No
program involves evaluating a Boolean
expression
• e.i. an expression whose value can be only true or
false
Decision Control Structures
• We can refer to the selection structure as an if-, if-else, or if-
else-if-statements because it fits the following structure:
if someCondition is true then if Condition1 is true
do Block1 do Block1
else if Condition2 is true
if someCondition is true then do Block2
do Block1 else if Condition3 is true
else do Block 3
do Block2 else
do BlockN
Examples
if it is raining then if hours_worked > 40 then
take an umbrella calculate pay
calculate overtime_pay
else
calculate pay
if traffic light == red then
cross the road
else
do not cross the road
Loop or Repetition Structures
• The loop control structure contains a branch which results in
a block of statements that can be executed many times.
• They tell us not to go on to the next instruction but, instead, to go
back and repeat the execution of a previous block of instructions.
• The loop will be repeated as long as a given condition within
the loop structure causes the branch to be taken.
• You will continue to repeat the actions while the condition
remains true.
Loop or Repetition Control Structure
• In a loop structure, you continue to
repeat actions while a condition
remains true.
• The action or actions that occur within
Yes
the loop are known as the loop body.
• E.g.:
while testCondition is true No

do someProcess
Comparison Operators
• Logical operators are used to determine the logic between
variables or values:
Operator Name Example
== Equal to 12 == 8
!= Not equal 9 != 10
< Less than 11 < 13
<= Less than or equal to 16 <= 15
> Greater than 25 > 19
>= Greater than or less than 14 >= 14
Logical Operators
• Logical operators are used to determine the logic between
variables or values:

Operator Name Example


&& Logical AND age >= 18 && age <=120
|| Logical OR score > 0 || score < 100
! Logical NOT !(x > 5 && x < 10)
Selection Control Statements
• The selection control statements are used to specify a block to be
executed if a condition is true.
• There are three basic selection control structures:
• The single-alternative (or if-statement) structure:
• The dual-alternative (or if-else-statement) structure
• The multiple alternative (or if-else-if-statement) structure
Selection Control Statements

Yes Yes No

Value 1 Value 2 Value n

No …

If-Statement If-else statement If-else-if statement


Conditional Statements: Single-alternative
• The simplest type of selection structure is the If-
Then, or single-alternative, structure.
• If the test condition is met, the statements are executed.
• If the test condition is not met, the statements are
skipped.
Yes
• The general form of this structure is:
if (test condition) then
Statement No

Statement

Statement If-Statement

End If
Examples
If age > 18 then if (age > 18){
write “eligible to vote” cout << “eligible to vote”;
End if }

If balance >= amount then if (balance >= amount){


balance = balance – amount balance -= amount;
End if }
Conditional Statements: Dual-Alternative
• The If-Else structure contains two blocks of
statements.
• If the condition is met, the first block is executed
and the program skips over the second block.
• If the test condition is not met, the first block of Yes No
statements is skipped and the second block is
executed.
• The structure has the general form:
If test condition Then
Statement …
Else
If-else statement
Statement …
End If
Conditional Statements: Dual-Alternative
• Syntax: C++

if (condition) {
Yes No
// block of code to be executed if the
condition is true
} else {
// block of code to be executed if the
condition is false
} If-else statement
Examples
If amount > 0 then if (amount > 0){
set profit = revenue - cost profit = revenue – cost;
write “Profit: $”+profit cout << “Profit: $”<<profit;
Else }else{
set loss = revenue – cost loss = revenue – cost;
write “Loss: $”+(-loss) cout<<“Loss: $”<<(-loss);
End if }
Examples
Start #include <iostream>
using namespace std;
Declare num as integer int main(){
Write "Enter a number.” int num;
cout<<“Enter a number”;
Input num
cin>>num;
If num != 0 Then if (num != 0){
Set Reciprocal = 1/Number reciprocal = 1/num;
cout<< “The reciprocal of ” <<num
Write "The reciprocal of " + << “ is ” << reciprocal;
Number + " is " + Reciprocal }else{
Else cout<<“The reciprocal of 0 is not
defined.”<<endl;
Write "The reciprocal of 0 is not }
defined.” return 0;
}
End if
Conditional Statements: Multiple Alternative
• A multiple-alternative structure contains
more than two blocks of statements.
• The program is written so that when the
test condition is met, the block of
statements that goes with that condition is Value 1 Value 2 Value n
executed and all the other blocks are
skipped. …

If-else-if statement
Conditional Statements: Multiple Alternative
• Syntax

if (condition1) {
// block of code to be executed if condition1 is
true
Value 1 Value 2 Value n
} else if (condition2) {

// block of code to be executed if the
condition1 is false and condition2 is true
} else {
If-else-if statement
// block of code to be executed if the
condition1 is false and condition2 is false
}
Example
If Score == 10 then char rating;
Set Rating = “A” If (score == 10){
Else if Score == 8 or Score == 9 then rating = “A”;
Set Rating = “B” }else if (score == 8 || score == 9){
rating = “B”;
Else if Score == 6 or Score == 7 then
}else if (score == 6 || score == 7){
Set Rating = “C”
rating = “C”;
Else if Score >= 1 or Score <= 5 then }else if (score >= 1 || score <= 5){
Set Rating = “D” rating = “D”;
End if }
Example
int time = 22;

if (time < 10) {


cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}

// Outputs "Good evening."


Short-hand If-statement
• There is a short-hand if-else-statement known as the ternary operator
because it consists of three operands.
• It can be used to replace multiple lines of code with a single line.
• It is often used to replace simple if else statements

• Syntax:
variable = (condition) ? expressionTrue : expressionFalse;
Tenary Operator
• Instead of writing • We simply write

int time = 20; int time = 20;


if (time < 18) { String result;
cout << "Good day."; result = (time < 18) ? "Good day." :
} else { "Good evening.";
cout << "Good evening."; cout << result;
}
Conditional Statements: Switch Statements
• The switch statement contains a single test
expression that determines which block of
code is to be executed.
• The test expression is evaluated once and its
value is compared with each case value. Value 1 Value 2 Value n

• If there is a match, the block of statements in …


that case is executed and the structure is exited.
• If there is no match, the value of the test
expression is compared with the next case
Switch statement
value.
Conditional Statements: Switch Statements
• The programmer can either write a Default
statement
• A default statement is code that will run if the
test expression does not match with any of the
Cases.
Value 1 Value 2 Value n
• After either the Default or the end of all the

Cases, the structure is exited.
• The Case statement works only when the test
expression is an integer or a single character.
Switch statement
Conditional Statements: Switch Statement
• Syntax: • The switch expression is evaluated
switch(expression) { once
• The value of the expression is compared
case x: with the values of each case.
// code block • If there is a match, the associated block
of code is executed
break;
• The break and default keywords are
case y: optional.
// code block • When the program reaches a break
keyword, it breaks out of the switch
break; block.
default: • This will stop the execution of more
code and case testing inside the block.
// code block • The default keyword specifies some
} code to run if there is no case match:
Example
int day = 4; case 4:
switch (day) { cout << "Thursday";
break;
case 1:
case 5:
cout << "Monday"; cout << "Friday";
break; break;
case 2: case 6:
cout << "Tuesday"; cout << "Saturday";
break; break;
case 3: case 7:
cout << "Sunday";
cout << "Wednesday";
break;
break; }
Example
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"
Math
• There are many predefined math Function Description

functions to help you perform abs(x) Returns the absolute value of x


mathematical tasks on numbers.
pow(x, y) Returns the value of x to the power of y
• Math functions can be found in the
<cmath> header file: max(x, y) Returns the largest value of x and y
#include <cmath>
min(x, y) Returns the lowest value of x and y

tan(x) Returns the tangent of an angle


cout << max(17, 28);
cout << min(34, 19); sin(x) Returns the sine of x (x is in radians)

floor(x) Returns the value of x rounded down to


its nearest integer
Try
The Accra Soccer Academy Park maintains five soccer teams, as
shown in the table below. Design a program that accepts a
player’s team number and displays the player’s team name.

Team Number Team Name

1 Cape Coast Venomous Vipers

2 Elmina Sharks
3 Accra Lions
4 WAFA
5 Accra Great Olympics

You might also like