Lecture 4 Boolean and Conditions in C++
Lecture 4 Boolean and Conditions in C++
Computer Programming
CHAPTER 2
BOOLEANS AND CONDITIONS
2
Booleans
In programming, you will need a data type that can only have one of two
values, like:
Yes/No
On/Off
True/False
C++ has bool data type, which can take a value Yes(1) or No(0)
3
Boolean Values
Boolean variable is declared as bool and can only take two values True/False:
#include <iostream>
using namespace std;
int main() {
bool T = true;
bool F = false;
cout << T << endl; // Outputs 1 (true)
cout << F << endl; // Outputs 0 (false)
}
4
Boolean expression
#include <iostream>
using namespace std;
int main() {
int x = 10;
int y = 9;
cout << (x > y) << endl;
}
5
Boolean expression (cont.)
#include <iostream>
using namespace std;
int main() {
int x = 10;
int y = 9;
cout << (x == 9) << endl;
}
6
Conditions
#include <iostream>
using namespace std;
int main() {
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y“<< endl;
}
}
9
The if Statement (cont.)
int main() {
int x;
cin >> x;
if (x >= 60) {
cout << “Passed“<< endl;
}
}
11
The if Statement activity diagram
12
The else Statement
if (condition) {
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is false
}
13
The else Statement (cont.)
#include <iostream>
using namespace std;
int main() {
int time = 20;
if (time < 18) {
cout << "Good day.";
}
else {
cout << "Good evening.";
}
}
14
The if Statement (cont.)
#include <iostream>
using namespace std; If the user enters value
Less than or equal 60
int main() {
int x;
cin >> x;
if (x >= 60) {
cout << “Passed“<< endl;
}
else {
cout << “Failed“<< endl; }
}
15
The if else Statement activity diagram
16
The else if Statement
Use the else if statement to specify a new condition if the first condition is false
if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
}
else {
// block of code to be executed if the condition1 is false and condition2 is false
}
17
The else if Statement (cont.)
if (x >= 90)
{cout << "A"<< endl;}
else if (x >= 80)
{cout<<"B"<<endl;}
else if (x >= 70)
{cout<<"C"<<endl;}
else if (x >= 60)
{ cout<<"D"<<endl;}
else cout<<"Failed"<<endl;
18
The else if Statement (cont.)
if (x >= 90)
{cout << "A"<< endl;}
else if (x >= 80)
{cout<<"B"<<endl;}
else if (x >= 70)
{cout<<"C"<<endl;}
else if (x >= 60)
{ cout<<"D"<<endl;}
else cout<<"Failed"<<endl;
19
Nested if