Professional Documents
Culture Documents
Introduction to Programming
Chapter 6
Learning outcomes:
Decision Making Statement
If statement
If-else statement
Nested if else statement
If else ladder statement
Switch statement
Decision Making Statement
Decision making statement are the statements that requires the
programmer to specify a conditions to be tested by the program, along
with a statement to be executed if the condition is true, and another
statements to be executed if the condition is false.
Some Decision-making statements available in C++ are:
if statement
If else statements
nested if statements
if-else-if ladder
switch statements
if Statement
• if statement is the most simple decision-
making statement.
• It is used to decide whether a certain
statement will be executed or not, that is,
if a certain condition is true then a block
of statement is executed otherwise not.
if Statement
Syntax:
If ( condition )
{
// Statements to execute if condition is true
}
if Statement example
// C++ program to display if a number is even
#include <iostream>
using namespace std;
int main () {
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
If-else Statement
• The if statement will execute a block of
statements if a condition is true and if the
condition is false it won’t.
• But what if we want to do something else,
if the condition is false, here comes
the else statement.
• We can use the else statement
with if statement to execute a block of
code when the condition is false.
If-else Statement
Syntax:
if (condition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}
If-else Statement example
// C++ program to display if a number is even or odd
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a Number: ";
cin>>num;
if (num % 2 == 0) {
cout<<"It is even number"<<endl;
}
else {
cout<<"It is odd number"<<endl;
} }
Nested-if Statement
Following are some of the rules while using the switch statement:
3. Each statement of the case can have a break statement and It is optional.
Switch Statement
Syntax
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
//code to be executed if all cases are not matched;
break;
}
Switch Statement
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num)
{
case 10: cout<<"It is 10"; break;
case 20: cout<<"It is 20"; break;
case 30: cout<<"It is 30"; break;
default: cout<<"Not 10, 20 or 30"; break;
}
}