0% found this document useful (0 votes)
11 views63 pages

Chapter 4

Chapter 4 discusses logical operators and decision-making in C++, emphasizing structured programming which includes sequence, control structures, and iteration. It explains control structures for making decisions based on conditions using various operators and statements like if, if/else, and switch. The chapter also covers validating user input, comparing characters and strings, and includes exercises for practical application.

Uploaded by

nedmacuacua88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views63 pages

Chapter 4

Chapter 4 discusses logical operators and decision-making in C++, emphasizing structured programming which includes sequence, control structures, and iteration. It explains control structures for making decisions based on conditions using various operators and statements like if, if/else, and switch. The chapter also covers validating user input, comparing characters and strings, and includes exercises for practical application.

Uploaded by

nedmacuacua88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Chapter 4

Logical Operators and Decision making C++


Structured programming
Structured Programming is a programming paradigm aimed at
developing and improving computer programs by making extensive
use of functions, block structures, loops—in contrast to using tests
and jumps such as the go to statement, which could lead to a very
messy code that is difficult to follow and maintain.
Structured programming has 3 main components:
• Sequence
• Control Structures
• Iteration
4:1

Control Structures
Control Structures: Decisions
Control Structures are also called Selection or Decision making

The purpose of control structures is to allow selection for a choice


between two alternatives of action.

A condition is the comparison of variable values or constants with


using one or more conditional (>, <=, >=) and/or logical operator (&&
,||, !).

The comparison determines whether the expression is true or false.


Selection /Decision Structure
A selection often requires a conditional operator to make a
comparison. You will need to use at least one of these when forming
your conditional statements.
Revision
Conditional Description
operator
== Equals to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
4:2

Logical Operators
Logical Operators
The logical operators are used to combine two or more conditional
operators.
Conditional Meaning Description
AND :
operator T && T =T
&& AND Result is true only if the condition T && F =F
on both sides of the operator are F && T =F
F && F =F
true
OR :
|| OR Result is false only if the condition T || T = T
T || F = T
on both sides of the operator are
F || T = T
false F || F = F
! NOT Reverses logic of a
condition
Logical Operators
int x = 12, y = 5, z = -4;
The logical && operator in Program 4-15
The logical && operator in Program 4-16
The logical && operator in Program 4-17
Logical Operators
! has highest precedence, followed by &&, then ||

If the value of an expression can be determined by evaluating just the


sub-expression on left side of a logical operator, then the sub-
expression on the right side will not be evaluated (short circuit
evaluation)
Checking Numeric Ranges with Logical Operators
• Used to test to see if a value falls inside a range:
if (grade >= 0 && grade <= 100)
cout << "Valid grade";
• Can also test to see if value falls outside of range:
if (grade <= 0 || grade >= 100)
cout << "Invalid grade";
• Cannot use mathematical notation:
if (0 <= grade <= 100) //doesn’t work!
4:3

The if Statement
The If Statement
Allows statements to be conditionally executed or skipped over
Models the way we mentally evaluate situations:
"If it is raining, take an umbrella."
"If it is cold outside, wear a coat."
The general form of an if-statement is as follows;
if (conditional expression)
statement; // instruction to be executed if condition is true
If expression is true, then the statement is executed; otherwise,
statement is skipped and control passes to the next statements.
if Statement in Program 4-2
if Statement in Program 4-2
If Statement
Note:
Do not place ; after (expression)
The expression part must be always in parenthesis.
Place statement; on a separate line after (expression),
indented:
if (score > 90)
grade = 'A';
Be careful testing floats and doubles for equality
0 is false; any other value is true
Expanding the if Statement
To execute more than one statement as part of an if
statement, enclose them in { }:
if (score > 90)
{
grade = 'A';
cout << "Good Job!\n";
}
{ } creates a block of code
4 :4

The if/else Statement


The if/else Statement
Provides two possible paths of execution
Performs one statement or block if the expression is true,
otherwise performs another statement or block.

General Format:
if (expression) Executed if
statement1; // or block.expression is true
else
Executed if
statement2; // or block
expression is
false
The if/else statement and Modulus Operator in Program 4-8
Program 4-9
Program 4-9
4:5

Nested if Statements
Nested if Statements
An if statement that is nested inside another if statement
Nested if statements can be used to test more than one condition
The general form of an nested if-statement is as follows;
if (expresion1)
if (expresion2)
statement;
If the expression1 of the first if is true, control passes to the next if. If
the expression2 of the second if is also true, statement will be
executed.
If one of the if-statements fail, execution continues from the
statements after the statement and statement is not executed.
Program 4-10
Use Proper Indentation!
4:6

The if/else if Statement


The if/else if Statement
Tests a series of conditions until one is found to be true
Often simpler than using nested if/else statements
Can be used to model thought processes such as:

if (expression)
statement1; // or block
else if (expression)
statement2; // or block
.
. // other else ifs .
else if (expression)
statementn; // or block
The if/else if Statement in Program 4-13
Using a Trailing else to Catch Errors in Program 4-14
• The trailing else clause is optional, but it is best used to catch
errors.
4:7

Flags
Flags
Variable that signals a condition
Usually implemented as a bool variable
Can also be an integer
The value 0 is considered false
Any nonzero value is considered true
As with other variables in functions, must be assigned an initial value
before it is used
4:8

Menus
Menu
Menu-driven program: program execution controlled by user selecting
from a list of actions
Menu: list of choices on the screen
Menus can be implemented using if/else if statements
Display list of numbered or lettered choices for actions
Prompt user to make selection
Test user selection in expression
if a match, then execute code for action
if not, then go on to next expression
4:9

Validating User Input


Validating User Input
Input validation: inspecting input data to determine whether it is
acceptable
Bad output will be produced from bad input
Can perform various tests:
Range
Reasonableness
Valid menu choice
Divide by zero
Input Validation in Program 4-19
4 : 10

Comparing Characters and


Strings
Comparing Characters and Strings
Characters are compared using their ASCII values
'A' < 'B'
The ASCII value of 'A' (65) is less than the ASCII value of 'B'(66)
'1' < '2'
The ASCII value of '1' (49) is less than the ASCI value of '2' (50)
Lowercase letters have higher ASCII codes than uppercase letters,
so 'a' > 'Z'
Relational Operators Compare Characters in Program 4-20
Comparing string Objects
• Like characters, strings are compared using their ASCII values

string name1 = "Mary";


string name2 = "Mark";
The characters in each string
name1 > name2 // true must match before they are
name1 <= name2 // false equal
name1 != name2 // true

name1 < "Mary Jane" // true


Relational Operators Compare Strings in Program 4-21
Exercises
1. Write a program to ask the user to enter a number from keyboard.
i. If the number is equal to zero, it will prompt “it is zero“ .
ii. If the number is less than 0, it will prompt “it is a negative
number”.
iii. Finally if the number is larger than zero, it will prompt “it is a
positive number”

2. Write a program to find the largest and smallest among three


entered numbers and also display whether the identified
largest/smallest number is even or odd.

3. Write a program to check whether the entered year is leap year or


not (a year is leap if it is divisible by 4 and divisible by 100 or
400.)
Exercises
4. Write a program to ask the user to enter his/her own lab result.
Then, validate the entered lab result.
i. If user entered result which is greater than 100 or less than 0,
display message " you have entered an invalid value" .
ii. Otherwise, decide whether the user has passed the exam or
not.
iii. If user enters a mark more than 49, the program will prompt
that he/she has passed the course. If the user has entered a
lower mark than 50, then the program will prompt he/she has
failed the course.
Exercises
5. What is the output? Notice that && is stronger than ||
#include <iostream>
using namespace std;
int main(void) {
int i=7, result;
if ( (i != 0) && (i <= 10) || (i ==17) )
result = 1;
else
result = 0;
cout << “\n result = ” << result;
return 0;
}
Exercises
6. What is the output?
#include<iostream>
using namespace std;
int main(void) {
int i = 3, j = 5;
if ( ( i ==3) || (++j > 0 )&& (i++ + 2 <= j ++))
cout << “\n i = ” << i << “\n j = ” << j;
else if (++j +i > 8)
cout << “\n i = ”<<I;
else
cout << “\n j = ”<<j;
return 0;
}
4 : 11

The switch Statement


The switch Statement
It is used to select among statements from several alternatives
In some cases, can be used instead of if/else if statements
General format:
First the switch expression
switch (expression) //integer is evaluated. Then, the case
{ label having a constant
value that matches the value
case label1: statement1; of the expression is found
and corresponding statements
case label2: statement2; are executed.
...
If it is not found, default
case labeln: statementn; statement is executed.
default: statementn+1; Switch statement terminates
when a break or end symbol (
} }) is reached.
The switch Statement in Program 4-23
switch Statement Requirements
1. expression must be an integer variable or an expression that
evaluates to an integer valu
2. label1 through labeln must be constant integer expressions
or literals, and must be unique in the switch statement
3. default is optional but recommended
break Statement
Used to exit a switch statement
If it is left out, the program "falls through" the remaining statements in
the switch statement
break and default statements in Program 4-25
Using switch in Menu Systems
switch statement is a natural choice for menu-driven program:
display the menu
then, get the user's menu selection
use user input as expression in switch statement
use menu choices as expr in case statements
4 : 12

More About Blocks and


Scope
More About Blocks and Scope
Scope of a variable is the block in which it is defined, from the point of
definition to the end of the block
Usually defined at beginning of function
May be defined close to first use
Inner Block Variable Definition in Program 4-29
Variables with the Same Name
Variables defined inside { } have local or block scope
When inside a block within another block, can define variables with
the same name as in the outer block.
When in inner block, outer definition is not available
Not a good idea
Two Variables with the Same Name in Program 4-30
Exercises
7. Write a complete C++ program that would first get a choice of a
meal type(1 for Hamburger, 2 for Chicken Wrap, and 3 for Cheese
Burger) from the user. Having done so, the program would ask the
user to enter how many they want to order of that specific meal
type. As the output, the program calculates and displays the total
price of the chosen meal according to the prices given below:

1 Hamburger (40tl)
2 Chicken Wrap (35tl)
3 Cheese Burger (45tl)

8. Write a complete C++ program to find whether a character is


consonant or vowel using the switch statement
Exercises
7. Write a complete C++ program to find whether a character is
consonant or vowel using the switch statement
Questions??
Thank you!

You might also like