You are on page 1of 43

Session 3

Flow Control
Operators and Meaning
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
== Equality
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
% Modulo Operator (remainder)
Flow control can be broken down into two
• Conditional Statements
• Loops

A conditional statement can be executed upon


the truth of a Boolean expression or variable

We will input data using cin>>

//prevents scientific notation output << std::fixed <<k;


C++ if Statement
• The if statement checks whether a test
condition is true or not (Boolean).
• If the test condition is true, it executes the
code/s inside the body of if statement.
• But if the test condition is false, it skips the
code/s inside the body of if statement
• This means that it could be used for all the data
types so far as the Boolean statement is true
C++ if Statement
• A single if statement Note: There can be no
is written as: else without an if
If (Boolean_expression) statement
Yes_statement;
else
No_Statement;
Example
#include <iostream> cout << "You entered a
using namespace std; positive integer: “
<<number<<endl;
int main()
{ else
int number; cout <<"You entered a
cout<< "Enter a no: "; negative number“
cin>> number; <<number;

if ( number > 0) return 0;


}
Example 2
#include <iostream>
using namespace std;

int main()
{
int num;
cout<<"Enter a whole number: ";
cin>> num;
if (num % 2 == 0)
cout<<"The number you entered is even,";
else
cout<<"The number you entered is odd";

return 0;

}
Example 3
#include <iostream> if ((age>5) && (age <=10))
using namespace std; cout<<"You are not yet a teen";
int main()
if ((age >10)&& (age <= 15))
{
cout <<"You are not matured";
int age;
cout<<"Enter a whole number: "; //else affect only the if above
cin>> age ; else
if (age <= 0) cout<<endl<<endl;
cout<<"You are not yet born"; cout<<"You need to
support Chelsea no matter
if((age>0 )&&(age<=5 ))
what is happening";
cout << "you are a todler"; return 0;
}
To modify the code such that the else affect all the if above add else to all the if’s except the first
# include<iostream> else if ((age>5)&(age<=10))
using namespace std; cout<<"you are not yet a teen ";

else if ((age >10)& (age<=15))


int main()
{ cout<<"you are now growing to
int age; maturity";
cout<<"enter a whole number: " ;
cin>>age; else
if(age<=0) cout<<"you need to support
chelsea";
cout<<"you are not yet born ";
return
0;
else if((age >0)& (age<=5)) }
cout<<"you are a todler ";
• Int main()
• { float salary;
• cout<<“enter your salary”;
• cin>>salary;
• If(salary<2500) {
• cout<<“you are a junior staff”<<endl;
• cout<<“you have to upgrade yourself”;
• }
• else
• cout<<“”you are a senior staff”;
• }
If else statement using a block
if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
Example {}
#include <iostream> else
using namespace std; {
// if condition is false then
//print the following
int main ()
cout << "a is not less than 20;"
{ // local variable declaration: << endl;
int a = 100; }
// check the boolean condition //not part of the if else statement
if( a < 20 ) //will run no matter what
{ cout << "value of a is : " << a <<
endl;
// if condition is true then
print //the following
return 0;
cout << "a is less than 20;" << }
endl;
}
• {
• {
• }
• {
• }

• }
#include <iostream> else if( a == 30 )
using namespace std; {
cout << "Value of a is 30" << endl;
int main () }
{ else
int a = 100; {
cout << "Value of a is not matching"
if( a == 10 ) << endl;
{ }
cout << "Value of a is 10" << endl; cout << "Exact value of a is : " << a
} << endl;
else if( a == 20 )
{
return 0;
cout << "Value of a is 20" << endl;
}
}
Nested if else statements
if( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is
true
}
}
example
#include <iostream> if(leaveDays>=12)
{
using namespace std; if(department ==13)
{
int main() cout<<"you are from zoology and
a senior staff";
{ }
else
cout<<"you are a senior staff but
int leaveDays, department; not from zoology";
cout<<"enter your leave days: "; }
cin>>leaveDays; else
cout<<"you are a junior staff";
cout<<"please enter your
department: "; return 0;
cin>>department; }

You can amend the code to use && instead


Nested if
#include <iostream>
using namespace std;
int main()
{ int leaveDays, department;
cout<<"enter your leave days: ";
cin>>leaveDays;
cout<<"please enter your department: ";
cin>>department;
if((leaveDays>=12)&&(department == 13))
{
cout<<"you are from zoology and a senior staff";
}
else
cout<<"you are a junior staff";
return 0;
#include <iostream>
using namespace std; else {
if( marks >= 60) {
cout << "U are within 2nd class !!";
int main ()
}
{ else {
int marks; if( marks >= 40) {
cout<<"Enter your marks: "; cout << "U are within 3rd class !!";
cin>>marks; }
if( marks >= 80) else {
cout << "U have failled !!";
{
}
cout << "U are within 1st class !!"; }
} }
return 0;
}
Var1 ? Var2 : var3
int a;
if (x > y)
a = x;
else
a = y;
//this is equivalent to:
int a = ( x > y ) ? x : y;
Example
#include <iostream>
using namespace std;
What is displayed

int main ()
{
// Local variable declaration:
int x, y = 10;
x = (y <= 10) ? 30 : 40;

cout << "value of x: " << x << endl;

return 0;
#include <iostream>
using namespace std; T = (A<=R) ? 12 : 11;

int main () cout << "value of T is "


{ << T << endl;
// Local variable declaration:
int A,R,T; return 0;
cout<<"enter the value of A:
}
";
cin>> A;
cout<<"enter the value of R:
";
cin>>R;
#include <iostream>
using namespace std;
int main ()
{ // Local variable declaration:
int a,b = 6,x = 9;
a = (b>x)? 20: 40;
cout << "value of a: " << a << endl;
return 0;
}

?
What will be displayed and why
#include <iostream>
using namespace std;
int main ()
{ int x, y = 4, z = 2;
x = (y>z) ? y:z;
cout<< "The value of x is "<<x;
return 0;
}
?
What will be displayed and why
Many cin can be put together
#include <iostream>
int main()
{
using namespace std;
cout<<"enter two numbers: ";
int a,b;
cin>>a>>b;
cout<<"The larger of the two is "<<((a>b)?a:b)<<endl;
}
The switch statement
The switch statement
• The switch statement is similar to the if/ else,
statement.
• It evaluates the value of an integer and
compares with two or more values and
determine which code to execute.
• The following program determines your
average based on your grade.
The switch statement
• The switch statement is similar to the if/ else,
statement.
• It evaluates the value of an integer and
compares with two or more values and
determine which code to execute.
• The following program determines your
average based on your grade.
#include <iostream> case 'B':
cout<<"Your grade is between 70 - 79";
using namespace std; case 'C':
cout<<"Your grade is between 60 -
69"<<endl;
int main()
{
break;
char grade; case 'D':
cout<<"Enter your grade: "; cout<<"Your grade is between 50 - 59";
cin>>grade; break;
default:
switch (grade) cout<<"Your grade is below 50";
{ cout<<endl<<endl;
case 'A': }
cout<<"Your grade is between return 0;
80 - 100"; }
Interpretation
• The switch key word evaluates an integer
expression grade while grade is a character
variable.
• Every character has a corresponding integer
value in the American Standard Code for
Information Interchange (ASCII) between 1 to
127.
• Note that ASCII value for upper cases are
different from those of lower cases
Interpretation Cont.
• The default key word serves the same purpose
as an final else in an if / else statement.
• The integer following the switch key word is
evaluated and compared with the integer
constant following each case key word.
• If there is a match ie the two integers are
equal.
• The statement belonging to that case is
executed . Otherwise they are not
• Thus the statement belonging to a case are
conditional just as those of if / else
Differences between if /else and switch
• With an if / else statement, comparison
following the if part may be different from
comparison following the else part. Example
• If (apple == orange)
• Do this;
• else if (sales >= 500)
• Do that;
• In a switch statement, the constant integer
following a case must be compared with value
following the switch key word and nothing else.
Differences between if /else and switch
• With an if / else statement, comparison
following the if part may be different from
comparison following the else part. Example
• If (apple == orange)
• Do this;
• else if (sales >= 500)
• Do that;
• In a switch statement, the constant integer
following a case must be compared with value
following the switch key word and nothing else.
Possible
#include <iostream> case 'B':
case 'b':
using namespace std; cout<<"Your grade is between 70 - 79\n";
break;

int main()
case 'C':
{
case 'c':
char grade; cout<<"Your grade is between 60 - 69\n";
cout<<"Enter your grade: "; break;
cin>>grade;
case 'D':
case 'd':
switch (grade) cout<<"Your grade is between 50 - 59\n";
{ break;
case 'a': default:
cout<<"Your grade is below 50\n";
case 'A':
cout<<"Your grade is between 80 - 100\n";
}
break;
return 0;
}
Range of numbers
If (testScore >= 90)
Cout<< “Your grade is A”;
else if (testScore >=88)
cout<<“Your grade is B”;
else
cout<<"Your grade is blow
B\n";
#include <iostream> case 94:
using namespace std; case 93:
case 92:
case 91:
int main()
case 90:
{
int testScore; cout<<"Your grade is A\n";
cout<<"Enter your test score: "; break;
cin>>testScore; case 89:
case 88:
switch (testScore) cout<<"Your grade is B\n";
{ break;
case 100:
default:
case 99:
cout<<"Your grade is blow B\n";
case 98:
case 97: }
case 96: return 0;
case 95: }
#include <iostream> Double Arguments
using namespace std; produce Semantic
int main()
errors
{ char echo;
char bank;
cout<<"enter two variables: "; Irrelevant output
cin>>bank>>echo; would be generated
switch (echo || bank) { for both or (||) and
case '8' ||'g': (&&)
cout<<"The wish is Try it out
through"<<endl;
// case 'n'&& 'p':
default:
cout<<"Catch up"; }
Lab Exercise 2
a) Suppose savings and expenditure are
variables of type double. Write an if – else
statement that request two inputs from the user
and outputs the word “Solvent”, decreases the
value of savings by the value of expenditure, and
sets the value of expenditure to zero, provided
savings is at least greater than the expenditure.
If, however, savings is less than expenditure, the
program should output the word “Bankrupt”.
Lab Exercise 2 Cont.
Students of Amasaman Polytechnic will have to
travel to the school campus to check their results.
The authorities decided to make it possible for
them to check their results online.
On a trial basis, they asked that two persons with
the following credentials be used to test the
system.
Student’s name : Paulina Sosu
Index number PS1024
Lab Exercise 2 Cont.
Student’s name: Emmanuel Tetteh
Index number: ET1025
Write a c++ console application that would be embedded in a web application such that if a
username, PSosu and password PS1024 is inputted, the following should be displayed

Welcome Paulina Sosu


Physics B
Chemistry B+
Mathematics B
However if a username ETetteh and password EY1025 is inputted
Welcome Emmanuel Tetteh
CS103: A
CS225: B
IT: 204: B+
Any other input should produce. Sorry you are not registered to use the application. See the
registrar.
NB: your job is just to provide the c++ code not how to embed it in the web app.
Exercises
1. Write an if – else statement that outputs the
word High if the value of the variable score is
greater than 100 and Low if the value score is at
most 100. the variable score is of type int
Exercises Cont.
2. Write an if – else statement that output the
word Passed provided the value of the variable
exam is greater than 60 and also the value of
variable program_done is greater than or equal
to 10.
Otherwise the if – else statement outputs the
word Fail.
The variables exam and program_done are both
of type int.
Lab Exercise
Write an if – else statement to display the
sentence
Welcome to Chigolo Bank
Your balance is GHC 500
Provided the username = Frank and password
Frank1235 are entered correctly.
The variable username and password are of type
String.
Submission date is
midnight 18/02/2018
Good Luck

You might also like