CHAPTER Four
CHAPTER Four
CHAPTER Four
Making Decisions
1
THE
if,
if/else,
if/else if
nested if
switch
STATEMENTS
2
THE if STATEMENT
If the expression inside the parentheses is true, the
statements inside the braces are executed. Otherwise, they
are skipped.
The following figure shows the general format of the if
statement.
3
… the if statement
Ifthe block of statements to be conditionally executed
contains only one statement, the braces can be
omitted.
Example of if statement:
if (x == 100)
cout << "x is 100";
the cout statement will only be executed only if x is equal
to100
If we want more than a single instruction to be
executed in case that condition is true we can specify a
block of instructions using curly braces { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}
4
… the if statement
// This program shows an if-statement
#include <iostream.h>
void main()
{
int score1, score2, score3;
double average;
cout << "Enter 3 test scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "Your average is " << average << endl;
if (average == 100)
{
cout << "Congratulations! ";
cout << "That's a perfect score!\n";
}
}
Output Enter 3 test scores and I will average them: 100 100 100[Enter]
Your average is 100.0 5
Congratulations! That's a perfect score!
Class work
1. Write an if statement that assigns 0 to x
when y is equal to 20.
2. Write an if statement that multiplies
payRate by 1.5 when hours is greater than
40
6
THE if/else STATEMENT
7
THE if/else STATEMENT
The if/else statement is an expansion of the if statement.
The if/else statement will execute one set of statements when the if
expression is true, and another set when the expression is false.
The following figure shows the general format of this statement and
a flowchart visually depicting how it works.
8
… the if/else Statement
The if/else statement causes program
execution to follow one of two exclusive
paths.
If you don’t use braces the else part
controls a single statement.
To execute more than one statements with
the else part, place these statements
inside a set of braces.
9
… the if/else Statement
//Example Program 1
/*This program uses the modulus operator to determine if a number is odd or
even. */
#include <iostream.h>
int main()
{
int number;
cout << "Enter an integer and I will tell you if it\n";
cout << "is odd or even. ";
cin >> number;
if (number % 2 == 0) // If the number is evenly divisible by 2, it
cout << number << " is even.\n";
else
cout << number << " is odd.\n";
return 0;
}
Output
Enter an integer and I will tell you if it
is odd or even. 17[Enter] 10
17 is odd.
… the if/else Statement
// Example Program 2
/*This program makes sure that the divisor is not equal to
0 before it performs a divide operation.*/
#include <iostream.h>
int main() Output
Enter a number: 10[Enter]
{
Enter another number: 0[Enter]
double num1, num2, quotient;
Division by zero is not possible.
cout << "Enter a number: ";
Please run the program again and enter a
cin >> num1;
number other than zero.
cout << "Enter another number: ";
cin >> num2;
if (num2 == 0)
{
cout << "Division by zero is not possible.\n";
cout << "Please run the program again and enter ";
cout << "a number other than zero.\n";
}
else
{
quotient = num1 / num2;
cout << "The quotient of " << num1 << " divided by ";
cout << num2 << " is " << quotient << ".\n";
}
return 0; 11
}
Class work 2
1. Write a C++ program by using if/else
statement that prints the message “The
number is not valid.” if the variable hours is
outside the range 0 through 80.
12
THE if/else if STATEMENT
13
THE if/else if STATEMENT
The if/else if statement is a chain of if statements.
They perform their tests, one after the other, until one of them is found to
be true.
The following figure shows its format and a flowchart visually depicting
how it works.
14
… the if/else if Statement
Each if statement in the structure depends on all
the if statements before it being false.
The statements following a particular else if are
executed when the conditional expression
following the else if is true and all previous
conditional expressions are false.
A trailing else, placed at the end of an if/else if
statement, provides a default set of actions
when none of the if expressions are true.
15
… the if/else if Statement
/* Example Program :This program uses an if/else if statement to assign a letter grade (A,
B, C, D, or F) to a numeric test score.*/
#include <iostream.h>
void main()
{
int testScore;
char grade;
cout << "Enter your numeric test score: ";
cin >> testScore;
if (testScore < 60)
grade = 'F';
else if (testScore < 70)
grade = 'D';
else if (testScore < 80)
grade = 'C';
else if (testScore < 90)
grade = 'B';
else if (testScore <= 100)
grade = 'A';
else
{
cout << "\nThe test score is an invalid score.\n";
cout << "Please enter a score that is between 0 and 100.\n";
}
cout << "\nYour grade is " << grade << ".\n";
} 16
Class work 3
1. Write a compiled a c++ program that tells
whether you pass or fail on an exam(note
the pass mark is >=50 out of 100 )& the
program prompt the user to insert the mark
b/n 0-100 only
17
Nested if
Statements
18
Nested if Statements
A nested if statement is an if statement in
the conditionally executed code of another
if statement.
Anytime an if statement appears inside
another if statement, it is considered
nested.
Nested if statement is good for narrowing
choices down and categorizing data.
19
… Nested if Statements
/* Example Program: This program demonstrates a nested if statement.*/
#include <iostream.h>
int main()
{
char employed, recentGrad;
cout << "Answer the following questions with either Y for Yes or N for No.\n";
cout << "Are you employed? ";
cin >> employed;
cout << "Have you graduated from college in the past two years? ";
cin >> recentGrad;
if (employed == 'Y')
{ // Nested if
if (recentGrad == 'Y') // Employed and a recent graduate
{
cout << "You qualify for the special interest rate.\n";
}
else // Employed but not a recent graduate
{
cout << "You must have graduated from college in the past two years to qualify.\
n";
}
}
else // Not employed
cout << "You must be employed to qualify.\n";
return 0; 20
}
//program checks the enrollment status
#include<iostream>
#include<string>
using namespace std;
int main()
{
string tc,l4;
cout<<"write either yes or no for the question below \n";
cout<<"are you 12 complete ? \n";
cin>>tc;
cout<<"do you have level 4 coc ? \n";
cin>>l4;
if(tc=="yes")
{
if(l4=="yes")
{
cout<<"ok congratulation \n";
cout<<" you go for enrollment \n";
}
}
else
{
cout<<"sorry \n";
cout<<"not satisfy the requirement \n";
} 21
}
Class work 4
1. Write a complied c++ program that
checks enrollment criteria & give decision
based on the rules.(the rule says:- the
student enroll on the course when they
are grade 12 complete & level 4 coc
certificate). By using nested if
statement..
22
SWITCH STATEMENT
23
switch Statement
The switch statement lets the value of a variable
or expression determine where the program will
branch to.
The if/else if statement allows your program to
branch into one of several possible paths.
Itperforms a series of tests (usually relational) and
branches when one of these tests is true.
The switch statement tests the value of an
integer expression and then uses that value to
determine which set of statements to branch to.
24
…switch Statement
Here is the format of the switch statement:
switch (integer expression)
{
case constant expression:
// Place one or more statements here.
case constant expression:
// Place one or more statements here.
// Case statements may be repeated as many times as necessary.
case constant expression:
// Place one or more statements here.
default:
// Place one or more statements here.
}
25
…switch Statement
An integer expression can be either of the
following:
A variable of any of the integer data types (including
char)
An expression whose value is of any of the integer
data types
On the next line is the beginning of a block
containing several case statements.
Each case statement is formatted in the
following manner:
case constant expression:
// Place one or more statements here.
26
…switch Statement
After the word case is a constant expression
The constant expression can be either an integer literal
or an integer named constant.
The constant expression
cannot be a variable and
it cannot be a Boolean expression such as x < 22 or n == 25.
The case statement marks the beginning of a section of
statements.
case statements are branched to if the value of the
switch expression matches that of the case expression.
The expressions of each case statement in the block
must be unique.
27
…switch Statement
Anoptional default section comes after all
the case statements.
This section is branched to if none of the case
expressions match the switch expression.
Thus it functions like a trailing else in an
if/else if statement.
28
Example(This program demonstrates the use of a
switch statement)
main()
{
char choice; Program Output
cout << "Enter A, B, or C: "; Enter A, B, or C: B [Enter]
cin >> choice; You entered B.
switch (choice) Program Output
{ Enter A, B, or C: F [Enter]
case 'A': You did not enter A, B, or C!
cout << "You entered A.\n";
break;
case 'B':
cout << "You entered B.\n";
break;
case 'C':
cout << "You entered C.\n";
break;
default:
cout << "You did not enter A, B, or C!\n";
}
} 29
…switch Statement
A break statement is needed whenever you want
to “break out of” a switch statement.
The case statements show the program where
to start executing in the block and the break
statements show the program where to stop.
Without the break statements, the program
would execute all of the lines from the matching
case statement to the end of the block.
the program “falls through” all of the statements below
the one with the matching case expression.
The default section (or the last case section, if
there is no default) does not need a break
statement. Put there anyway, for consistency. 30
Example (This program demonstrates how a switch
statement works if there are no break statements)
main()
Program Output:
{ Enter A, B, or C: A[Enter]
char choice; You entered A.
You entered B.
cout << "Enter A, B, or C: "; You entered C.
cin >> choice; You did not enter A, B, or C!
switch (choice) Program Output
{ Enter A, B, or C: C[Enter]
You entered C.
case 'A':
You did not enter A, B, or C!
cout << "You entered A.\n";
case 'B':
cout << "You entered B.\n";
case 'C':
cout << "You entered C.\n";
default :
cout << "You did not enter A, B, or C!\n";
}
31
}
Example (The switch statement in this program uses the "fall
through" feature to catch both uppercase and lowercase letters
main()
entered by the user)
{
char feedGrade;
cout << "Our dog food is available in three grades:\n";
cout << "A, B, and C. Which do you want pricing for? ";
cin >> feedGrade;
switch(feedGrade)
{
case 'a': Program Output
case 'A': Our dog food is available in three grades:
cout << "30 cents per pound.\n"; A, B, and C. Which do you want pricing for?
break; b[Enter]
case 'b': 20 cents per pound.
case 'B': Program Output
cout << "20 cents per pound.\n"; Our dog food is available in three grades:
break; A, B, and C. Which do you want pricing for?
case 'c': B[Enter]
case 'C': 20 cents per pound.
cout << "15 cents per pound.\n";
break;
default :
cout << "That is an invalid choice.\n";
}
return 0;
32
}
#include<iostream>
using namespace std;
int main()
{ //two arithmetic operation on two operands
char ch;
int i,j;
cout<<"enter any two operand";
cin>>i>>j;
cout<<"enter a for addtion & m for multiplication of two operand";
cin>>ch;
switch(ch)
{
case 'a':
cout<<"addition of the number is"<<i+j;
break;
case 'm':
cout<<"multiplication of the number is"<<i*j;
break;
default:
cout<<" select ethier a or m only"; 33
}
THE CONDITIONAL OPERATOR
34
The Conditional Operator
You can use the conditional operator to
create short expressions that work like
if/else statements.
The operator consists of the question-
mark (?) and the colon(:).
Its format is
35
… the Conditional Operator
Here is an example of a statement using the conditional
operator:
x < 0 ? y = 10 : z = 20;
This statement is called a conditional expression and
consists of three sub-expressions separated by the ? and :
symbols.
The expressions are x < 0, y = 10, and z = 20.
Note: Since it takes three operands, the conditional
operator is considered a ternary operator.
The conditional expression above performs the same
operation as the following if/else statement:
if (x < 0)
y = 10;
else
z = 20;
36
… the Conditional Operator
The part that comes before the question mark is the
expression to be tested.
It’s like the expression in the parentheses of an if statement.
If the expression is true, the part of the statement
between the ? and the : is executed.
Otherwise, the part after the : is executed.
E.g. (x < 0) ? (y = 10) : (z = 20);
37
… the Conditional Operator
If the first sub-expression is true, the value of the conditional
expression is the value of the second sub-expression. Otherwise it
is the value of the third sub-expression.
Here is an example of an assignment statement using the value of a
conditional expression:
a = x > 100 ? 0 : 1;
The value assigned to a will be either 0 or 1, depending upon
whether x is greater than 100.
This statement could be expressed as the following if/else
statement:
if (x > 100)
a = 0;
else
a = 1;
38
… the Conditional Operator
Here is the statement with the conditional
expression:
hours = hours < 5 ? 5 : hours;
If the value in hours is less than 5, then 5
is stored in hours.
Otherwise hours is assigned the value it
already has.
39
… the Conditional Operator
For instance, consider the following statement:
cout << "Your grade is: " << (score < 60 ? "Fail." : "Pass.");
If you were to use an if/else statement, this
statement would be written as follows:
if (score < 60)
cout << "Your grade is: Fail.";
else
cout << "Your grade is: Pass.";
The parentheses are placed around the conditional
expression because the << operator has higher
precedence than the ?: operator.
Without the parentheses, just the value of the
expression score < 60 would be sent to cout.
40
Class work 5
1. Convert the following conditional
expression into an if/else statement.
q = x < y ? a + b : x * 2;
2. Assume the variables x = 5, y = 6, and z =
8. Indicate if each of the following conditions
is true or false:
A) x == 5 || y > 3
B) 7 <= x && z > 4
C) 2 != y && z == 3
41
3. Write a C++ statement that prints the
message “The number is valid.” if the
variable grade is within the range 0 through
100.
43