Chapter 3
Chapter 3
Making Decisions
THE
if,
if/else,
if/else if
STATEMENTS
THE if STATEMENT
The if statement can cause other statements to execute only
under certain conditions.
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.
… the if statement
If the 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";
if (average == 100)
cout << "Congratulations! "; // There are no braces.
cout << "That's a perfect score!\n"; // This is outside the if.
If the condition (average == 100) is false, the Congratulations!
message will be skipped. That's a perfect score! was executed, as it
would be every time, regardless of whether average equals 100 or
not.
… the if statement
Do not confuse the equality operator (==) with the assignment operator
(=), as in the following statement:
if (x = 2) // Caution here!
cout << "It is True!";
This statement does not determine if x is equal to 2; it assigns x the
value 2!
Furthermore, the cout statement will always be executed because the
expression x = 2 evaluates to 2, which C++ considers true.
C++ stores the value true as 1. But it actually considers all nonzero
values, not just 1, to be true. Thus 2 represents a true condition.
… the if statement
A relational expression has the value 1 when it is true and 0 when false.
While 0 is considered false, all values other than 0 are considered true.
Here is a summary of the rules you have seen so far:
When a relational expression is true it has the value 1.
When a relational expression is false it has the value 0.
An expression that has the value 0 is considered false.
An expression that has any value other than 0 is considered true.
statements.
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";
}
}
…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.
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.
cout << "Enter A, B, or C: "; You entered B.
cin >> choice; You entered C.
You did not enter A, B, or C!
switch (choice)
Program Output
{ Enter A, B, or C: C[Enter]
case 'A': You entered C.
cout << "You entered A.\n"; You did not enter A, B, or C!
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";
}
}
Example (The switch statement in this program uses the "fall through" feature
to catch both uppercase and lowercase letters entered by the user)
main()
{
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) Program Output
{ Our dog food is available in three grades:
case 'a': A, B, and C. Which do you want pricing for?
case 'A': b[Enter]
cout << "30 cents per pound.\n"; 20 cents per pound.
break; Program Output
case 'b': Our dog food is available in three grades:
case 'B': A, B, and C. Which do you want pricing for?
cout << "20 cents per pound.\n"; B[Enter]
break; 20 cents per pound.
case 'c':
case 'C':
cout << "15 cents per pound.\n";
break;
default :
cout << "That is an invalid choice.\n";
}
return 0;
}
THE CONDITIONAL OPERATOR
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
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;
… 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.
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;
… the Conditional Operator
for (count = 1, total = 0; count <= 10 && total < 500; count++)
{
double amount;
cout << "Enter the amount of purchase #" << count << ": ";
cin >> amount;
total += amount;
}
Nested Loops
A loop that is inside another loop is called a nested loop.
The first loop is called the outer loop.
The one nested inside it is called the inner loop.
Here is the format:
while (some condition) // Beginning of the outer loop
{
// ---
while (some condition) // Beginning of the inner loop
{
//------
} // End of the inner loop
} // End of the outer loop
Nested loops are used when, for each iteration of the outer loop,
something must be repeated a number of times.
Whatever the task, the inner loop will go through all its iterations
each time the outer loop is done.
Any kind of loop can be nested within any other kind of loop.
… Nested Loops
An inner loop goes through all of its iterations for
each iteration of an outer loop.
Inner loops complete their iterations faster than
outer loops.
To get the total number of iterations of an inner
loop, multiply the number of iterations of the
outer loop by the number of iterations done by
the inner loop each time the outer loop is done.
For example, if the outer loop is done twice, and the
inner loop is done three times for each iteration of the
outer loop, the inner loop would be done a total of six
times in all.
Breaking Out of a Loop
The break statement causes a loop to terminate early.
When it is encountered, the loop stops and the program jumps to
the statement immediately following the loop.
It can be used to end an infinite loop, or to force it to end before its
natural end.
The following program segment appears to execute 10 times, but
the break statement causes it to stop after the fifth iteration.
int count = 0;
while (count++ < 10)
{
cout << count << endl;
if (count == 5)
break;
}
Example -1
//Stop the count down before it naturally finishes using break statement:
#include <iostream.h>
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
Output:
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
Using break in a Nested Loop
In a nested loop, the break statement only interrupts the loop it is
placed in.
For example:
for (int row = 0; row < 2; row++)
{
for (int star = 0; star < 6; star++)
{ The output of this program segment is
cout << '*';
if (int star == 3)
break;
****
****
}
cout << endl;
}
The continue Statement
The continue statement causes a loop to stop its
current iteration and begin the next one.
The continue statement causes the current
iteration of a loop to end immediately.
When continue is encountered, all the
statements in the body of the loop that appear
after it are ignored, and the loop prepares for the
next iteration.
In a while loop, this means the program jumps to the
test expression at the top of the loop.
In a do-while loop, the program jumps to the test
expression at the bottom of the loop
In a for loop, continue causes the update expression
to be executed.
Example(…the continue statement)
The following program segment demonstrates the use of continue in
a while loop:
int testVal = 0;
while (testVal++ < 10)
{
if (testVal == 4)
continue;
cout << testVal << " ";
}
This loop looks like it displays the integers 1 through 10. When
testVal is equal to 4, however, the continue statement causes the
loop to skip the cout statement and begin the next iteration.
The output of the loop is
1 2 3 5 6 7 8 9 10
… the continue Statement
The continue instruction causes the program to skip the rest of the
loop in the present iteration, causing it to jump to the following
iteration.
For example, we are going to skip the number 5 in our countdown:
#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--)
{
if (n==5) Output:
continue; 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}
The goto statement
It allows making an absolute jump to
another point in the program.
The destination point is identified by a
label, which is then used as an argument
for the goto statement.
A label is made of a valid identifier
followed by a colon (:).
… the goto statement
// goto loop example
#include <iostream.h>
int main ()
{
int n=10;
loop: Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
cout << n << ", ";
n--;
if (n>0)
goto loop;
cout << "FIRE!";
return 0;
}
Using Loops for Data Validation
Loops can be used to create input routines that repeat until
acceptable data is entered.
Loops are especially useful for validating input.
They can test whether an invalid value has been entered and, if so,
require the user to continue entering inputs until a valid one is received.
Using if statements to validate user inputs cannot provide an ideal
solution.
Using while loop to validate input data, Every input will be checked.
cout << "Enter a number in the range 1 - 100: ";
cin >> number;
while (number < 1 || number > 100)
{
cout << "ERROR: The value must be in the range 1 - 100: ";
cin >> number;
}
………………………………………
………………………………………
………………………………..END
………………………………….OF
………………………...CHPTER 4
-*-*-*-*-*-*-*-*-*-*-*-*-*-*- THANK U!
THANK U!
*-*-*
END OF CHAPTER-3
*-*-*