Chapter 4. Making Decisions - PowerPoint PPT Presentation

1 / 122
About This Presentation
Title:

Chapter 4. Making Decisions

Description:

This program uses an if/else if statement to assign a ... This program uses an if/else if statement to //assign a letter grade ( A, B, C, D, or F ) ... – PowerPoint PPT presentation

Number of Views:46
Avg rating:3.0/5.0
Slides: 123
Provided by: cathe100
Category:

less

Transcript and Presenter's Notes

Title: Chapter 4. Making Decisions


1
Chapter 4. Making Decisions
2
4.1 Relational Operators
  • Relational operators allow you to compare numeric
    values and determine if one is greater than, less
    than, equal to, or not equal to another.

3
Table 4-1
4
Table 4-2
5
The Value of a Relationship
  • Relational expressions are also know as a Boolean
    expression
  • Warning! The equality operator is two equal
    signs together

6
Table 4-3
7
Program 4-1
  • // This program displays the values of true and
    false
  • // states.
  • include ltiostream.hgt
  • void main(void)
  • int trueValue, falseValue, x 5, y
    10 trueValue X lt Y falseValue Y
    X cout ltlt "True is " ltlt trueValue ltlt
    endl cout ltlt "False is " ltlt falseValue ltlt endl
  • Program OutputTrue is 1False is 0

8
Table 4-4 (Assume x is 10, y is 7, a and b are
ints)
9
4.2 The if Statement
  • The if statement can cause other statements to
    execute only under certain conditions.

10
Program 4-2
  • // This program averages 3 test scores
  • include ltiostream.hgt
  • void main(void)
  • int score1, score2, score3
  • float average
  • cout ltlt "Enter 3 test scores and I will average
    them "
  • cin gtgt score1 gtgt score2 gtgt score3
  • average (score1 score2 score3) / 3.0
  • cout.precision(1)
  • cout.setf(iosshowpoint iosfixed)
  • cout ltlt "Your average is " ltlt average ltlt endl
  • if (average gt 95)
  • cout ltlt "Congratulations! That's a high
    score!\n"

11
Program Output with Example Input
  • Enter 3 test scores and I will average them 80
    90 70 Enter
  • Your average is 80.0
  • Program Output with Other Example Input
  • Enter 3 test scores and I will average them 100
    100 100 Enter
  • Your average is 100.0
  • Congratulations! That's a high score!

12
Table 4-5
13
Be Careful With Semicolons
  • if (expression)
  • statement
  • Notice that the semicolon comes after the
    statement that gets executed if the expression is
    true the semicolon does NOT follow the expression

14
Program 4-3
  • // This program demonstrates how a misplaced
    semicolon
  • // prematurely terminates an if statement.
  • include ltiostream.hgt
  • void main(void)
  • int x 0, y 10
  • cout ltlt x is " ltlt x ltlt " and y is " ltlt y ltlt
    endl
  • if (x gt y) // misplaced semicolon!
  • cout ltlt x is greater than y\n" // Always
    executed
  • Program Output
  • X is 0 and Y is 10
  • X is greater than Y

15
Programming Style and the if Statement
  • The conditionally executed statement should
    appear on the line after the if statement.
  • The conditionally executed statement should be
    indented one level from the if statement.
  • Note Each time you press the tab key, you are
    indenting one level.

16
Comparing Floating Point Numbers
  • Round-off errors can cause problems when
    comparing floating point numbers with the
    equality operator ()

17
Program 4-4
// This program demonstrates how floating point
round-off // errors can make equality comparisons
unreliable.   include ltiostream.hgt   void
main(void) float result   result 6.0
0.666666 // Round-off error if (result
4.0) cout ltlt "It's true!" else cout ltlt
"It's false!" Program Output It's false!
18
And Now Back to Truth
  • 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 by the if statement.
  • An expression that has any value other than 0 is
    considered true by the if statement.

19
Not All Operators Are Equal
  • Consider the following statement
  • if (x 2) // caution here!
  • cout ltlt It is True!
  • This statement does not determine if x is equal
    to 2, it assigns x the value 2, therefore, this
    expression will always be true because the value
    of the expression is 2, a non-zero value

20
Program 4-5
  • // This program averages 3 test scores. The if
    statement uses
  • // the operator, but the operator was
    intended.
  • include ltiostream.hgt
  • void main(void)
  • int score1, score2, score3
  • float average
  • cout ltlt "Enter 3 test scores and I will average
    them "
  • cin gtgt score1 gtgt score2 gtgt score3
  • average (score1 score2 score3) / 3.0
  • cout.precision(1)
  • cout.setf(iosshowpoint iosfixed)
  • cout ltlt "Your average is " ltlt average ltlt endl
  • if (average 100) // Wrong
  • cout ltlt "Congratulations! That's a high
    score!\n"

21
Program 4-5 Output With Example Input
  • Program Output with Example Input
  • Enter your 3 test scores and I will average them
    80 90 70Enter
  • Your average is 80.0
  • Congratulations! Thats a perfect score!

22
4.3 Flags
  • A flag is a variable, usually a boolean or an
    integer, that signals when a condition exists.
  • If your compiler does not support the bool data
    type, use int instead.

23
Program 4-6
// This program averages 3 test scores. It uses
the variable highScore as a flag. include
ltiostream.hgt void main(void) int score1,
score2, score3 float average bool highScore
false   cout ltlt "Enter your 3 test scores and I
will average them " cin gtgt score1 gtgt score2 gtgt
score3 average (score1 score2 score3) /
3.0 if (average gt 95) highScore true //
Set the flag variable cout.precision(1) cout.se
tf(iosshowpoint iosfixed) cout ltlt "Your
average is " ltlt average ltlt endl if
(highScore) cout ltlt "Congratulations! That's a
high score!\n"\ Program Output with Example
Input Enter your 3 test scores and I will average
them 100 100 100 Enter Your average is
100.0 Congratulations! That's a high score!
24
4.4 Expanding the if Statement
  • The if statement can conditionally execute a
    block of statement enclosed in braces.
  • if (expression)
  • statement
  • statement
  • // Place as many statements here as
    necessary.

25
Program 4-7
  • // This program averages 3 test scores.
  • // It uses the variable highScore as a flag.
  • include ltiostream.hgt
  • void main(void)
  • int score1, score2, score3
  • float average
  • bool highScore false
  • cout ltlt "Enter 3 test scores and I will average
    them "
  • cin gtgt score1 gtgt score2 gtgt score3
  • average (score1 score2 score3) / 3.0
  • if (average gt 95)
  • highScore true // Set the flag variable

Program continues on next slide
26
Program continued from previous slide
  • cout.precision(1)
  • cout.setf(iosshowpoint iosfixed)
  • cout ltlt "Your average is " ltlt average ltlt endl
  • if (highScore)
  • cout ltlt "Congratulations!\n"
  • cout ltlt "That's a high score.\n"
  • cout ltlt "You deserve a pat on the back!\n"

27
Program Output with Example Input
  • Enter your 3 test scores and I will average them
    100 100 100 Enter
  • Your average is 100.0
  • Congratulations!
  • That's a high score.
  • You deserve a pat on the back!
  • Program Output with Different Example Input
  • Enter your 3 test scores and I will average them
    80 90 70 Enter
  • Your average is 80.0

28
Dont Forget the Braces!
  • If you intend to execute a block of statements
    with an if statement, dont forget the braces.
  • Without the braces, the if statement only
    executes the very next statement.

29
Program 4-8
  • // This program averages 3 test scores.
  • // It uses the variable highScore as a flag.
  • include ltiostream.hgt
  • void main(void)
  • int score1, score2, score3
  • float average
  • bool highScore false
  • cout ltlt "Enter 3 test scores and I will average
    them "
  • cin gtgt score1 gtgt score2 gtgt score3
  • average (score1 score2 score3) / 3.0
  • if (average gt 95)
  • highScore true // Set the flag variable

Program continues on next slide
30
Program continued from previous slide
  • cout.precision(1)
  • cout.setf(iosshowpoint iosfixed)
  • cout ltlt "Your average is " ltlt average ltlt endl
  • // The following if statement is
  • // missing its braces!
  • if (highScore)
  • cout ltlt "Congratulations!\n"
  • cout ltlt "That's a high score.\n"
  • cout ltlt "You deserve a pat on the back!\n"

31
Program Output with Example Input
Enter your 3 test scores and I will average them
100 100 100EnterYour average is
100Congratulations!Thats a high score.You
deserve a pat on the back! Program Output with
Different Example Input Enter your 3 test scores
and I will average them 80 90 70EnterYour
average is 100Congratulations!Thats a high
score.You deserve a pat on the back!

32
4.5 The if/else Statement
  • The if/else statement will execute one group of
    statements if the expression is true, or another
    group of statements if the expression is false.
  • if (expression)
  • statement or block of statements
  • else
  • statement or block of statements

33
Program 4-9
  • // This program uses the modulus operator to
    determine
  • // if a number is odd or even. If the number is
    evenly divided
  • // by 2, it is an even number. A remainder
    indicates it is odd.
  • include ltiostream.hgt
  • void main(void)
  • int number
  • cout ltlt "Enter an integer and I will tell you if
    it\n"
  • cout ltlt "is odd or even. "
  • cin gtgt number
  • if (number 2 0)
  • cout ltlt number ltlt " is even.\n"
  • else
  • cout ltlt number ltlt " is odd.\n"

34
Program Output with Example Input
  • Enter an integer and I will tell you if it
  • is odd or even. 17 Enter
  • 17 is odd.

35
Program 4-10
  • // This program asks the user for two numbers,
    num1 and num2.
  • // num1 is divided by num2 and the result is
    displayed.
  • // Before the division operation, however, num2
    is tested
  • // for the value 0. If it contains 0, the
    division does not
  • // take place.
  • include ltiostream.hgt
  • void main(void)
  • float num1, num2, quotient
  • cout ltlt "Enter a number "
  • cin gtgt num1
  • cout ltlt "Enter another number "
  • cin gtgt num2

Program continues on next slide
36
Program continued from previous slide.
  • if (num2 0)
  • cout ltlt "Division by zero is not possible.\n"
  • cout ltlt "Please run the program again and
    enter\n"
  • cout ltlt "a number besides zero.\n"
  • else
  • quotient num1 / num2
  • cout ltlt "The quotient of " ltlt num1 ltlt " divided
    by "
  • cout ltlt num2 ltlt " is " ltlt quotient ltlt ".\n"

37
Program Output
  • (When the user enters 0 for num2)
  • Enter a number 10 Enter
  • Enter another number 0 Enter
  • Division by zero is not possible.
  • Please run the program again and enter
  • a number besides zero.

38
4.6 The if/else if Construct
  • The if/else if statement is a chain of if
    statements. The perform their tests, one after
    the other, until one of them is found to be true.
  • If (expression)
  • statement or block of statements
  • else if (expression)
  • statement or block of statements
  • // put as many else its as needed here
  • else if (expression)
  • statement or block of statements

39
Program 4-11
  • // 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 ltiostream.hgt
  • void main(void)
  • int testScore
  • char grade
  • cout ltlt "Enter your numeric test score and I
    will\n"
  • cout ltlt "tell you the letter grade you earned
    "
  • cin gtgt testScore

Program continues on next slide
40
Program continued from previous slide.
  • if (testScore lt 60)
  • grade 'F'
  • else if (testScore lt 70)
  • grade 'D'
  • else if (testScore lt 80)
  • grade 'C'
  • else if (testScore lt 90)
  • grade 'B'
  • else if (testScore lt 100)
  • grade 'A'
  • cout ltlt "Your grade is " ltlt grade ltlt ".\n"

41
Program Output with Example Input
  • Enter your test score and I will
  • tell you the letter grade you earned 88 Enter
  • Your grade is B.

42
Program 4-12
  • // This program uses independent if/else
    statements to assign a
  • // letter grade (A, B, C, D, or F) to a numeric
    test score.
  • // Do you think it will work?
  • include ltiostream.hgt
  • void main(void)
  • int testScore
  • char grade
  • cout ltlt "Enter your test score and I will tell
    you\n"
  • cout ltlt "the letter grade you earned "
  • cin gtgt testScore

Program continues on next slide
43
Program continued from previous slide.
  • if (testScore lt 60)
  • grade 'F'
  • if (testScore lt 70)
  • grade 'D'
  • if (testScore lt 80)
  • grade 'C'
  • if (testScore lt 90)
  • grade 'B'
  • if (testScore lt 100)
  • grade 'A'
  • cout ltlt "Your grade is " ltlt grade ltlt ".\n"

44
Program Output with Example Input
  • Enter your test score and I will tell you
  • the letter grade you earned 40 Enter
  • Your grade is A.

45
Program 4-13
  • //This program uses an if/else if statement to
  • //assign a letter grade ( A, B, C, D, or F )
  • //to a numeric test score.
  • includeltiostream.hgt
  • void main(void)
  • int testScore
  • cout ltlt "Enter your test score and I will tell
    you\n"
  • cout ltlt "the letter grade you earned "
  • cin gtgt testScore
  • if (testScore lt 60)
  • cout ltlt "Your grade is F.\n"
  • cout ltlt "This is a failing grade. Better see
    your "
  • cout ltlt "instructor.\n"
  • else if (testScore lt 70)

Program continues on next slide
46
Program continued from previous slide.
  • else if (testScore lt 80)
  • cout ltlt "Your grade is C.\n"
  • cout ltlt "This is average.\n"
  • else if(testScore lt 90)
  • cout ltlt "Your grade is B.\n"
  • cout ltlt "This is an above average grade.\n"
  • else if (testScore lt 100)
  • cout ltlt "Your grade is A.\n"
  • cout ltlt "This is a superior grade. Good
    work!\n"

47
Program Output with Example Input
  • Enter your test score and I will tell you
  • the letter grade you earned 94 Enter
  • Your grade is A.
  • This is a superior grade. Good work!

48
4.7 Using a Trailing else
  • A trailing else, placed at the end of an if/else
    if statement, provides default action when none
    of the ifs have true expressions

49
Program 4-14
  • // This program uses an if/else if statement to
    assign a
  • // letter grade (A, B, C, D, or F) to a numeric
    test score.
  • // A trailing else has been added to catch test
    scores gt 100.
  • include ltiostream.hgt
  • void main(void)
  • int testScore
  • cout ltlt "Enter your test score and I will tell
    you\n"
  • cout ltlt "the letter grade you earned "
  • cin gtgt testScore

Program continues on next slide
50
Program continued from previous slide.
  • if (testScore lt 60)
  • cout ltlt "Your grade is F.\n"
  • cout ltlt "This is a failing grade. Better see
    your "
  • cout ltlt "instructor.\n"
  • else if (testScore lt 70)
  • cout ltlt "Your grade is D.\n"
  • cout ltlt "This is below average. You should get
    "
  • cout ltlt "tutoring.\n"

51
Program continued from previous slide.
  • else if (testScore lt 80)
  • cout ltlt "Your grade is C.\n"
  • cout ltlt "This is average.\n"
  • else if (testScore lt 90)
  • cout ltlt "Your grade is B.\n"
  • cout ltlt "This is an above average grade.\n"

52
Program continued from previous slide.
  • else if (testScore lt 100)
  • cout ltlt "Your grade is A.\n"
  • cout ltlt "This is a superior grade. Good
    work!\n"
  • else // Default action
  • cout ltlt testScore ltlt " is an invalid score.\n"
  • cout ltlt "Please enter scores no greater than
    100.\n"

53
Program Output with Example Input
  • Enter your test score and I will tell you
  • the letter grade you earned 104 Enter
  • 104 is an invalid score.
  • Please enter scores no greater than 100.

54
4.8 Focus on Software Engineering Menus
  • You can use the if/else if statement to create
    menu-driven programs. A menu-driven program
    allows the user to determine the course of action
    by selecting it from a list of actions.

55
Program 4-15
  • // This program displays a menu and asks the user
    to make a
  • // selection. An if/else if statement determines
    which item
  • // the user has chosen.
  • include ltiostream.hgt
  • void main(void)
  • int choice, months
  • float charges
  • cout ltlt "\t\tHealth Club Membership Menu\n\n"
  • cout ltlt "1. Standard Adult Membership\n"
  • cout ltlt "2. Child Membership\n"
  • cout ltlt "3. Senior Citizen Membership\n"
  • cout ltlt "4. Quit the Program\n\n"

Program continues on next slide
56
Program continued from previous slide.
  • cout ltlt "Enter your choice "
  • cin gtgt choice
  • cout.setf(iosfixed iosshowpoint)
  • cout.precision(2)
  • if (choice 1)
  • cout ltlt "\nFor how many months? "
  • cin gtgt months
  • charges months 40.00
  • cout ltlt "The total charges are " ltlt charges ltlt
    endl

57
Program continued from previous slide.
  • else if (choice 2)
  • cout ltlt "\nFor how many months? "
  • cin gtgt months
  • charges months 20.00
  • cout ltlt "The total charges are " ltlt charges ltlt
    endl
  • else if (choice 3)
  • cout ltlt "\nFor how many months? "
  • cin gtgt months
  • charges months 30.00
  • cout ltlt "The total charges are " ltlt charges ltlt
    endl

58
Program continued from previous slide.
  • else if (choice ! 4)
  • cout ltlt "The valid choices are 1 through 4. Run
    the\n"
  • cout ltlt "program again and select one of
    those.\n"

59
Program Output with Example Input
  • Health Club Membership Menu
  • 1. Standard Adult Membership
  • 2. Child Membership
  • 3. Senior Citizen Membership
  • 4. Quit the Program
  • Enter your choice 3 Enter
  • For how many months? 6 Enter
  • The total charges are 180.00

60
4.9 Focus on Software Engineering Nested if
Statements
  • A nested if statement is an if statement in the
    conditionally-executed code of another if
    statement.

61
Program 4-16
  • // This program demonstrates the nested if
    statement.
  • include ltiostream.hgt
  • void main(void)
  • char employed, recentGrad
  • cout ltlt "Answer the following questions\n"
  • cout ltlt "with either Y for Yes or "
  • cout ltlt "N for No.\n"
  • cout ltlt "Are you employed? "
  • cin gtgt employed
  • cout ltlt "Have you graduated from college "
  • cout ltlt "in the past two years? "
  • cin gtgt recentGrad

Program continues on next slide
62
Program continued from previous slide.
  • if (employed 'Y')
  • if (recentGrad 'Y') // Nested if
  • cout ltlt "You qualify for the special "
  • cout ltlt "interest rate.\n"

63
Program Output with Example Input
  • Answer the following questionswith either Y
    for Yes or N for No.Are you employed?
    YEnterHave you graduated from college in the
    past two years? YEnterYou qualify for the
    special interest rate.

64
Program Output with Other Example Input
  • Answer the following questionswith either Y
    for Yes or N for No.Are you employed?
    YEnterHave you graduated from college in the
    past two years? NEnter

65
4.10 Logical Operators
  • Logical operators connect two or more relational
    expressions into one, or reverse the logic of an
    expression.

66
Table 4-6
67
Table 4-7
68
Program 4-18
  • // This program demonstrates the logical
    operator.
  • include ltiostream.hgt
  • void main(void)
  • char employed, recentGrad
  • cout ltlt "Answer the following questions\n"
  • cout ltlt "with either Y for Yes or "
  • cout ltlt "N for No.\n"
  • cout ltlt "Are you employed? "
  • cin gtgt employed

Program continues on next slide
69
Program continued from previous slide.
  • cout ltlt "Have you graduated from college "
  • cout ltlt "in the past two years? "
  • cin gtgt recentGrad
  • if (employed 'Y recentGrad 'Y') //
    Operator
  • cout ltlt "You qualify for the special "
  • cout ltlt "interest rate.\n"
  • else
  • cout ltlt "You must be employed and have \n"
  • cout ltlt "graduated from college in the\n"
  • cout ltlt "past two years to qualify.\n"

70
Program Output with Example Input
  • Answer the following questionswith either Y
    for Yes orN for No.Are you employed?
    YEnterHave you graduated from college in the
    past two years? NEnterYou must be employed and
    havegraduated from college in thepast two years
    to qualify.

71
Table 4-8
72
Program 4-19
  • // This program asks the user for their annual
    income and
  • // the number of years they have been employed at
    their current
  • // job. The operator is used in a if statement
    that
  • // determines if the income is at least 35,000
    or their time
  • // on the job is more than 5 years.
  • include ltiostream.hgt
  • void main(void)
  • float income
  • int years

Program continues on next slide
73
Program continues
  • cout ltlt "What is your annual income? "
  • cin gtgt income
  • cout ltlt "How many years have you worked at "
  • ltlt "your current job? "
  • cin gtgt years
  • if (income gt 35000 years gt 5) // Use
    logical operator
  • cout ltlt "You qualify.\n"
  • else
  • cout ltlt "You must earn at least 35,000 or
    have\n"
  • cout ltlt "been employed for more than 5
    years.\n"

74
Program Output with Example Input
  • What is your annual income? 40000 Enter
  • How many years have you worked at your current
    job? 2 Enter
  • You qualify.
  • Program Output with Example Input
  • What is your annual income? 20000 Enter
  • How many years have you worked at your current
    job? 7 Enter
  • You qualify.

75
Table 4-9
76
Program 4-20
  • //This program asks the user for his annual
    income and
  • //the number of years he has been employed at his
    current job.
  • //The ! operator reverses the logic of the
    expression in the if/else statement.
  • include ltiostream.hgt
  • void main(void)
  • float income
  • int years
  • cout ltlt "What is your annual income? "
  • cin gtgt income
  • cout ltlt "How many years have you worked at "
  • ltlt "your current job? "
  • cin gtgt years
  • if (!(income gt 35000 years gt 5)) // Uses
    the ! Logical operator
  • cout ltlt "You must earn at least 35,000 or
    have\n"
  • cout ltlt "been employed for more than 5
    years.\n"

77
Precedence of Logical Operators
  • !

78
4.11 Checking Numeric Ranges With Logical
Operators
  • Logical operators are effective for determining
    if a number is in or out of a range.

79
4.12 Focus on Software Engineering Validating
User Input
  • As long as the user of a program enters bad
    input, the program will produce bad output.
    Program should be written to filter out bad input.

80
Examples of validation
  • Numbers are check to ensure they are within a
    range of possible values.
  • Values are check for their reasonableness.
  • Items selected from a menu or other set of
    choices are check to ensure they are available
    options.
  • Variables are check for values that might cause
    problems, such as division by zero.

81
4.13 More About Variable Declarations and Scope
  • The scope of a variable is limited to the block
    in which is is declared.
  • Variables declared inside a set of braces have
    local scope or block scope.

82
Program 4-22A
  • //This program demonstrates late variable
    declaration
  • include ltiostream.hgt
  • void main(void)
  • cout ltlt "What is your annual income? "
  • float income // variable declaration
  • cin gtgt income
  • cout ltlt "How many years have you worked at "
  • ltlt "your current job? "
  • int years // variable declaration
  • cin gtgt years
  • if (income gt 35000 years gt 5)
  • cout ltlt "You qualify.\n"
  • else
  • cout ltlt "You must earn at least 35,000 or
    have\n"
  • cout ltlt "been employed for more than 5
    years.\n"

83
Program 4-22B
  • //This program demonstrates late variable
    declaration
  • include ltiostream.hgt
  • void main(void)
  • cout ltlt "What is your annual income? "
  • float income // variable declaration
  • cin gtgt income
  • cout ltlt "How many years have you worked at "
  • ltlt "your current job? "
  • int years // variable declaration
  • cin gtgt years
  • if (income gt 35000 years gt 5)
  • cout ltlt "You qualify.\n"
  • else
  • cout ltlt "You must earn at least 35,000 or
    have\n"
  • cout ltlt "been employed for more than 5
    years.\n"

84
Program 4-22C
  • //This program demonstrates late variable
    declaration
  • include ltiostream.hgt
  • void main(void)
  • cout ltlt "What is your annual income? "
  • float income
  • cin gtgt income
  • int years
  • cout ltlt "How many years have you worked at "
  • ltlt "your current job? "
  • cin gtgt years
  • if (income gt 35000 years gt 5)
  • cout ltlt "You qualify.\n"
  • else
  • cout ltlt "You must earn at least 35,000 or
    have\n"
  • cout ltlt "been employed for more than 5
    years.\n"

85
Program 4-23
  • // This program demonstrates a variable declared
    in an inner block.
  •  
  • include ltiostream.hgt
  •  
  • void main(void)
  • cout ltlt "What is your annual income? "
  • float income // variable declaration
  • cin gtgt income
  • if (income gt 35000)
  • int years // variable declaration
  • cout ltlt "How many years have you worked at "
  • ltlt "your current job? "
  • cin gtgt years
  • if (years gt 5)
  • cout ltlt "You qualify.\n"

Program continues on next slide
86
Program continued from previous slide.
  • else
  • cout ltlt "You must have been employed for\n"
  • cout ltlt "more than 5 years to qualify.\n"
  • else
  • cout ltlt "You must earn at least 35,000 to\n"
  • cout ltlt "qualify.\n"

87
Variables With the Same Name
  • When a block is nested inside another block, a
    variable declared in the inner block may have the
    same name as a variable declared in the outer
    block. The variable in the inner block takes
    precedence over the variable in the outer block.

88
Program 4-24
  • // This program uses two variables with the name
    Number.
  •  
  • include ltiostream.hgt
  • void main(void)
  • int number
  •  
  • cout ltlt "Enter a number greater than 0 "
  • cin gtgt number
  • if (number gt 0)
  • int number

Program continues on next slide
89
Program continued from previous slide.
  • cout ltlt "Now enter another number "
  • cin gtgt number
  • cout ltlt "The second number you entered was "
  • cout ltlt number ltlt endl
  • cout ltlt "Your first number was " ltlt number ltlt
    endl

90
Program Output with Example Input
  • Enter a number greater than 0 2 Enter
  • Now enter another number 7Enter
  • The second number you entered was 7
  • Your first number was 2

91
4.14 Comparing Strings
  • Use the strcmp library function to compare
    C-strings.

92
Program 4-25
  • // This program illustrates that you cannot
    compare strings
  • // with relational operators. Although it appears
    to test the
  • // strings for equality, that is NOT what
    happens.
  • include ltiostream.hgt
  • void main(void)
  • char firstString40, secondString40
  •   cout ltlt "Enter a string "
  • cin.getline(firstString, 40)
  • cout ltlt "Enter another string "
  • cin.getline(secondString, 40)
  • if (firstString secondString)
  • cout ltlt "You entered the same string twice.\n"
  • else
  • cout ltlt "The strings are not the same.\n"

93
Program Output with Example Input
  • Enter a string Alfonso Enter
  • Enter another string Alfonso Enter
  • The strings are not the same.

94
The strcmp Function
  • strcmp(string1, string2) // include cstring to
    use
  • // this function
  • If the two strings are identical, strcmp returns
    0.
  • If string1 lt string 2, strcmp returns a negative
    number.
  • If string1 gt string 2, strcmp returns a positive
    number.

95
Program 4-26
  • // This program correctly tests two strings for
    equality, with
  • // the strcmp function
  • include ltiostream.hgt
  • include ltstring.hgt
  • void main(void)
  • char firstString40, secondString40
  •   cout ltlt "Enter a string "
  • cin.getline(firstString, 40)
  • cout ltlt "Enter another string "
  • cin.getline(secondString, 40)
  • if (strcmp(firstString, secondString) 0)
  • cout ltlt "You entered the same string twice.\n"
  • else
  • cout ltlt "The strings are not the same.\n"

96
Program 4-27
  • // This program uses strcmp to compare the sting
    entered
  • // by the user with the valid stereo part
    numbers.
  •  
  • include ltiostream.hgt
  • include ltstring.hgt
  • void main(void)
  • const float aprice 249.0, Bprice 299.0
  • char partNum8
  •  
  • cout ltlt "The stereo part numbers are\n"
  • cout ltlt "\tBoom Box, part number S147-29A\n"

Program continues on next slide
97
Program continued from previous slide
  • cout ltlt "\tShelf Model, part number S147-29B\n"
  • cout ltlt "Enter the part number of the stereo
    you\n"
  • cout ltlt "wish to purchase "
  • cin.width(9) // So they won't enter more than 8
    char's
  • cin gtgt partNum
  • cout.setf(iosfixed iosshowpoint)
  • cout.precision(2)
  • if (strcmp(partNum, "S147-29A") 0) // use of
    strcmp
  • cout ltlt "The price is " ltlt aprice ltlt endl
  • else if (strcmp(partNum, "S147-29B") 0)
  • cout ltlt "The price is " ltlt Bprice ltlt endl
  • else
  • cout ltlt partNum ltlt " is not a valid part
    number.\n"

98
Program Output with Example Input
  • The stereo part numbers are
  • Boom Box, part number S14729A
  • Shelf Model, part number S147-29B
  • Enter the part number of the stereo you
  • wish to purchase S147-29B Enter
  • The price is 299.00

99
Program 4-28
  • // This program uses the return value of strcmp
    to
  • // alphabetically sort two strings entered by the
    user.
  • include ltiostream.hgt
  • include ltstring.hgt
  • void main(void)
  • char name130, name230
  •  
  • cout ltlt "Enter a name (last name first) "
  • cin.getline(name1, 30)
  • cout ltlt "Enter another name "
  • cin.getline(name2, 30)

Program continues on next slide
100
Program continued from previous slide.
  • cout ltlt "Here are the names sorted
    alphabetically\n"
  • if (strcmp(name1, name2) lt 0)
  • cout ltlt name1 ltlt endl ltlt name2 ltlt endl
  • else if (strcmp(name1, name2) gt 0)
  • cout ltlt name2 ltlt endl ltlt name1 ltlt endl
  • else
  • cout ltlt "You entered the same name twice!\n"

101
Program Output with Example Input
  • Enter a name (last name first) Smith, Richard
    Enter
  • Enter another name Jones, John Enter
  • Here are the names sorted alphabetically
  • Jones, John
  • Smith, Richard

102
Program 4-29
  • //This program uses strcmp to compare the string
    entered
  • //by the user with the valid stereo part numbers.
  • includeltiostream.hgt
  • includeltstringgt
  • using namespace std
  • void main(void)
  • const float aprice 249.0, bprice 299.0
  • string partNum
  • cout ltlt "The stereo part numbers are\n"
  • cout ltlt "Boom box, part number S147-29A\n"
  • cout ltlt "Shelf model, part number S147-29B\n"
  • cout ltlt "Enter the part number of the stereo
    you\n"
  • cout ltlt "wish to purchase "
  • cin gtgt partNum

Program continues on next slide
103
Program continued from previous slide
  • cout.setf(iosfixed iosshowpoint)
  • cout.precision(2)
  • if (partNum "S147-29A")
  • cout ltlt "The price is " ltlt aprice ltlt endl
  • else if (partNum "S147-29B")
  • cout ltlt "The price is " ltlt bprice ltlt endl
  • else
  • cout ltlt partNum ltlt " is not a valid part
    number."

104
Program Output with Example Input
  • The stereo part numbers are
  • Boom box, part number S147-29A
  • Shelf model, part number S147-29B
  • Enter the part number of the stereo you
  • wish to purchase S147-29A
  • The price is 249.00

105
4.15 The Conditional Operator
  • You can use the conditional operator to create
    short expressions that work like if/else
    statements
  • expression ? result if true result if false

106
Program 4-30
  • // This program calculates a consultant's charges
    at 50 per hour,
  • // for a minimum of 5 hours. The ? operator
    adjusts hours to 5 if less
  • // than 5 hours were worked.
  • include ltiostream.hgt
  • void main(void)
  • const float payRate 50.0
  • float hours, charges
  •   cout ltlt "How many hours were worked? "
  • cin gtgt hours
  • hours hours lt 5 ? 5 hours
  • charges payRate hours
  • cout.precision(2)
  • cout.setf(iosfixed iosshowpoint)
  • cout ltlt "The charges are " ltlt charges ltlt endl

107
Program Output with Example Input
  • How many hours were worked? 10 Enter
  • The charges are 500.00
  • Program Output with Example Input
  • How many hours were worked? 2 Enter
  • The charges are 250.00

108
Program 4-31
  • // This program uses the return value of strcmp
    to alphabetically
  • // sort two strings entered by the user.
  •  
  • include ltiostream.hgt
  • include ltstring.hgt
  • void main(void)
  • char name130, name230
  •  
  • cout ltlt "Enter a name (last name first) "
  • cin.getline(name1, 30)

Program continues on next slide
109
Program continued from previous slide.
  • cout ltlt "Enter another name "
  • cin.getline(name2, 30)
  • cout ltlt "Here are the names sorted
    alphabetically\n"
  • cout ltlt (strcmp(name1, name2) lt 0 ? name1
    name2) ltlt endl
  • cout ltlt (strcmp(name1, name2) gt 0 ? name1
    name2) ltlt endl

110
Program Output with Example Input
  • Enter a name (last name first) Smith, Richard
    Enter
  • Enter another name Jones, John Enter
  • Here are the names sorted alphabetically
  • Jones, John
  • Smith, Richard

111
4.16 The switch Statement
  • The switch statement lets the value of a variable
    or expression determine where the program will
    branch to.

112
Program 4-32
  • // The switch statement in this program tells the
    user
  • // something he or she already knows what they
    just entered!
  •  
  • include ltiostream.hgt
  • void main(void)
  • char choice
  •  
  • cout ltlt "Enter A, B, or C "
  • cin gtgt choice

Program continues on next slide
113
Program continues
  • switch (choice)
  • case 'A' cout ltlt "You entered A.\n"
  • break
  • case 'B' cout ltlt "You entered B.\n"
  • break
  • case 'C' cout ltlt "You entered C.\n"
  • break
  • default cout ltlt "You did not enter A, B, or
    C!\n"

114
Program Output with Example Input
  • Enter A, B, or C B Enter
  • You entered B.
  • Program Output with Different Example Input
  • Enter a A, B, or C F Enter
  • You did not enter A, B, or C!

115
Program 4-33
  • // The switch statement in this program tells the
    user
  • // something he or she already knows what they
    just
  • // entered!
  •  
  • include ltiostream.hgt
  • void main(void)
  • char choice
  •  
  • cout ltlt "Enter A, B, or C "
  • cin gtgt choice

Program continues on next slide
116
Program continued from previous slide.
  • switch (choice)
  • case 'A' cout ltlt "You entered A.\n"
  • case 'B' cout ltlt "You entered B.\n"
  • case 'C' cout ltlt "You entered C.\n"
  • default cout ltlt "You did not enter A, B, or
    C!\n"

117
Program Output with Example Input
  • Enter a A, B, or C A Enter
  • You entered A.
  • You entered B.
  • You entered C.
  • You did not enter A, B, or C!
  • Program Output with Example Input
  • Enter a A, B, or C C Enter
  • You entered C.
  • You did not enter A, B, or C!

118
Program 4-34
  • // This program is carefully constructed to use
    the
  • // "fallthrough" feature of the switch statement.
  •  
  • include ltiostream.hgt
  • void main(void)
  •  
  • int modelNum
  • cout ltlt "Our TVs come in three models\n"
  • cout ltlt "The 100, 200, and 300. Which do you
    want? "
  • cin gtgt modelNum
  • cout ltlt "That model has the following
    features\n"

Program continues on next slide
119
Program continues
  • switch (modelNum)
  • case 300 cout ltlt "\tPicture-in-a-picture.\n"
  • case 200 cout ltlt "\tStereo sound.\n"
  • case 100 cout ltlt "\tRemote control.\n"
  • break
  • default cout ltlt "You can only choose the
    100,"
  • cout ltlt "200, or 300.\n"

120
Program Output with Example Input
  • Our TVs come in three models
  • The 100, 200, and 300. Which do you want? 100
    Enter
  • That model has the following features Remote
    control.
  • Program Output with Example Input
  • Our TVs come in three models
  • The 100, 200, and 300. Which do you want? 200
    Enter
  • That model has the following features Stereo
    sound. Remote control.

121
Program 4-35
  • // The switch statement in this program uses the
    "fallthrough"
  • // feature to catch both upper and lowercase
    letters entered
  • // by the user.
  •  
  • include ltiostream.hgt
  • void main(void)
  • char feedGrade
  •  
  • cout ltlt "Our dog food is available in three
    grades\n"
  • cout ltlt "A, B, and C. Which do you want pricing
    for? "
  • cin gtgt feedGrade

Program continues on next slide
122
Program continued from previous slide.
  • switch(feedGrade)
  • case 'a'
  • case 'A' cout ltlt "30 cents per pound.\n"
  • break
  • case 'b'
  • case 'B' cout ltlt "20 cents per pound.\n"
  • break
  • case 'c'
  • case 'C' cout ltlt "15 cents per pound.\n"
  • break
  • default cout ltlt "That is an invalid
    choice.\n"
Write a Comment
User Comments (0)
About PowerShow.com