PLD Experiment 5
PLD Experiment 5
PLD Experiment 5
5.1 Introduction
C++ if Statement
if (testExpression)
// statements
Flowchart of if Statement
PROGRAM # 5.1
#include <iostream>
int main()
int number;
if ( number > 0)
cout << "You entered a positive integer: " << number << endl;
return 0;
Output 1
Enter an integer: 5
Output 2
Enter a number: -5
C++ if...else
The if else executes the codes inside the body of if statement if the test expression is true and
skips the codes inside the body of else.
If the test expression is false, it executes the codes inside the body of else statement and skips
the codes inside the body of if.
Flowchart of if...else
PROGRAM #5.2
#include <iostream>
int main()
{
int number;
if ( number >= 0)
cout << "You entered a positive integer: " << number << endl;
else
cout << "You entered a negative integer: " << number << endl;
return 0;
Output
Enter an integer: -4
C++ if...elseif….else
The if...else statement executes two different codes depending upon whether the test expression is
true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute different
codes for more than two conditions.
Syntax of if...elseif….else
if (testExpression1)
}
else if(testExpression2)
else if (testExpression 3)
else
PROGRAM # 5.3
#include <iostream>
int main()
int number;
if ( number > 0)
cout << "You entered a positive integer: " << number << endl;
}
else
return 0;
Output
Enter an integer: 0
You entered 0.
Conditional/Ternary Operator ?:
if ( a < b ) {
a = b;
else {
a = -b;
a = (a < b) ? b : -b;
The ternary operator is more readable than a if...else statement for short conditions.
5.2 Prelab
1. Execute PROGRAM #5.1 and explain.
2. Execute PROGRAM #5.2 and explain.
3. Execute PROGRAM #5.3 and explain.
Output 2
MENU
[1]Balance Inquiry
[2]Deposit
[3]Withdraw
[4]Balance Inquiry
Transaction: 1
Current Balance: 0
………
Transaction: 2