C++ Lecture 3
C++ Lecture 3
Conditional Statements
C++ if-else
In C++ programming, if statement is used to test the condition. There are various
types of if statements in C++.
1. if statement
2. if-else statement
3. nested if statement
Conditional Statements are used in C++ to run a certain piece of program only if a
specific condition is met.
1. If Statement:
The C++ if statement tests the condition. It is executed if condition is true.
Syntax:
if (Boolean_expression or Condition)
{ // statement(s) will execute if the Boolean expression(Condition) is true }
{1}
C++ Programming Dr. Hayder Kareem
Conditional Statements
{2}
C++ Programming Dr. Hayder Kareem
Conditional Statements
2. IF-else Statement
The C++ if-else statement also tests the condition. It executes if block if condition
is true otherwise else block is executed.
Syntax:
{3}
C++ Programming Dr. Hayder Kareem
Conditional Statements
{4}
C++ Programming Dr. Hayder Kareem
Conditional Statements
When using if , else if , else statements there are few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be
tested.
Syntax:
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 }
{5}
C++ Programming Dr. Hayder Kareem
Conditional Statements
{6}
C++ Programming Dr. Hayder Kareem
Conditional Statements
Example: Program to check whether an integer is positive, negative or zero
{7}