Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 20

KIG2007 : Computer Programming

Control Statements
(if, if…else, while)

Semester 2, Session 2022/2023


Algorithm
• An algorithm is a procedure for solving a problem in terms of
• the actions to execute and
• the order in which the actions execute
• Specifying the order in which statements (actions) execute in a
computer program is called program control.

Example:
Algorithm to add two numbers entered by user
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
A simple flowchart representing a process for
dealing with a non-functioning lamp.
Pseudocode
• Pseudocode (or “fake” code) is an artificial and informal language
that helps you develop algorithms.
• Similar to everyday English; convenient and user friendly.
• Helps you “think out” a program before attempting to write it.
• Carefully prepared pseudocode can easily be converted to a
corresponding C++ program.
• Normally describes only executable statements – no declarations

Example: Pseudocode to add two numbers entered by user


Prompt the user to enter the first integer
Input the first integer

Prompt the user to enter the second integer


Input the second integer

Add first and second integer, store result


Display result
Flow control

Sequential flow: programming statements are executed in the order that they


are written - from top to bottom in a sequential manner.
Control statements
• Unless directed otherwise, the computer executes C++ statements
one after the other in the order in which they’re written—that is, in
sequence.
• Three types of selection statements
1. if
2. if … else
3. switch
• Three types of repetition statements (looping statements or loops)
1. while
2. do…while
3. for
Conditional flow control
Syntax Example Flowchart

You could omit the braces { }, if there is only one statement inside the block
Conditional flow control
Syntax Example Flowchart
if and if…else statements
• if selection statement
• single-selection statement
• either performs (selects) an action if a condition (predicate) is
true or skips the action if the condition is false.
• if…else selection statement
• double-selection statement
• performs an action if a condition is true or performs a different
action if the condition is false.
Nested if…else statement
• test for multiple cases by placing if…else selection statements inside other if…
else selection statements.
• In a nested if... else statement, test the conditions that are more likely to be true
at the beginning of the nested if...else statement. This will enable the nested
if...else statement to run faster and exit earlier than testing infrequently occurring
cases first.

Example:
If student’s grade is greater than or equal to 90
Print “A”
Else
If student’s grade is greater than or equal to 80
Print “B”
Else
If student’s grade is greater than or equal to 70
Print “C”
Else
If student’s grade is greater than or equal to 60
Print “D”
Else
Print “F”
Relational & logical operators
• Very often, you need to compare two values before deciding on the
action to be taken.
== Equal to expr1 == expr2
Example:
!= Not Equal to expr1 != expr2 if (x >= 2 && x < 10)
> Greater than expr1 > expr2 cout << x;
Relational operators

>= Greater than or equal to expr1 >= expr2


< Less than expr1 < expr2
<= Less than or equal to expr1 >= expr2

&& Logical AND expr1 && expr2 AND (&&) OR (||) XOR (^) NOT (!)

T && T → T T || T → T T^T→F !T→F


|| Logical OR expr1 || expr2
Logical operators

F && T → F F || T → T F^T→T !F → T
! Logical NOT !expr
T && F → F T || F → T T^F→T
^ Logical expr1 ^ expr2
XOR F && F → F F || F → F F^F→F
Conditioner operator (? :)
• is closely related to the if…else statement
• The operands, together with the conditional operator, form a
conditional expression.
• take three operands:
• first operand is a condition,
• second operand is the value for the entire conditional expression
if the condition is true
• third operand is the value for the entire conditional expression if
the condition is false.

cout << ( grade >= 60 ? "Passed" :


"Failed" );
condition if true if false

conditional expression
Dangling-else problem
if ( x > 5 )
which if if ( y > 5 )
does this cout << "x and y are > 5";
else
else
belongs to?
cout << "x is <= 5";

• The C++ compiler always associates an else with the immediately


preceding if unless told to do otherwise by the placement of
braces { }.
if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
else
cout << "x is <= 5";
Example
Write a simple C++ program to
1. request the user to input the grade
2. determine if the student passes or fails using if… else statement.
The passing grade should be greater than 50%.
3. Repeat Q2 using conditioner operator.

int main() {
int grade;
cout << “Please input a student’s grade: ”;
cin >> grade;
if (grade > 50)
cout << “Passed” << endl;
else
cout << “Failed” << endl;
}

cout << ( grade > 50 ? "Passed" : "Failed" );


while statement
Syntax Example Flowchart

• while loop repeats until condition becomes false.


• Not providing, in the body of a while statement, an action that
eventually causes the condition in the while to become false
normally results in a logic error called an infinite loop, in which the
repetition statement never terminates. This can make a program
appear to “hang” or “freeze” .
Counter-controlled repetition
• Loop repeated until counter reaches certain value
• Also known as definite repetition – number of repetitions is known
beforehand.
Example:
#include <iostream>
using namespace std;

int main() {
int grade;
int total = 0; // initialize sum of grades entered by the user
int gradeCounter = 1; //initialize the counter variable to 1

// counter-controlled iteration
while (gradeCounter <= 10) { // loop 10 times
cout << "Enter grade: "; // prompt for input
cin >> grade; // input next grade
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter by 1
}
}
while statement UML diagram

[counter <= 10] Display the Increment the


counter value control variable
[counter > 10]

cout << counter << “ ”; counter++

Determine
whether looping
should continue
Sentinel-controlled repetition
• Also known as indefinite repetition – the number of repetitions is not
known before the loop begins executing.
• Use a sentinel value (also called a signal/dummy/flag value) to
indicate “end of data entry”
• The sentinel value must be chosen so that it’s not confused with an
acceptable input value. For example, grades are normally
nonnegative integers, so –1 is an acceptable sentinel value.

Note: In a sentinel-controlled loop, the prompts requesting data entry


should explicitly remind the user what the sentinel value is.
Sentinel-controlled repetition (Example)

#include <iostream>
using namespace std;

int main() {
int grade;
int total = 0; // initialize sum of grades entered by the user
int gradeCounter = 1; //initialize the counter variable to 1

cout << "Enter grade or -1 to quit: ";


int grade;
cin >> grade;

// loop until sentinel value read from user


while (grade != -1) {
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter

// prompt for input and read next grade from user


cout << "Enter grade or -1 to quit: ";
cin >> grade;
}
}
Examination-results problem: Nested control
statements (1/2)
#include <iostream>
using namespace std;

int main()
{
// initializing variables in declarations
int passes = 0; // number of passes
int failures = 0; // number of failures
int studentCounter = 1; // student counter
int result; // one exam result (1 = pass, 2 = fail)

// process 10 students using counter-controlled loop


while (studentCounter <= 10) {
// prompt user for input and obtain value from user
cout << "Enter result (1 = pass, 2 = fail): ";
cin >> result; // input result
Examination-results problem: Nested control
statements (2/2)
// if...else nested in while
if (result == 1) // if result is 1,
passes = passes + 1; // increment passes;
else // else result is not 1, so
failures = failures + 1; // increment failures

// increment studentCounter so loop eventually terminates


studentCounter = studentCounter + 1;
} // end while

// termination phase; display number of passes and failures


cout << "Passed " << passes << "\nFailed " << failures << endl;

// determine whether more than eight students passed


if (passes > 8)
cout << "Bonus to instructor!" << endl;
} // end main

You might also like