CS102 Introduction to Computer Programming

28
CS102 Introduction to Computer Programming Chapter 4 Making Decisions

description

CS102 Introduction to Computer Programming. Chapter 4 Making Decisions. Chapter 4 Topics. Relational Operators Value of a Relationship What is Truth The if Statement Flags Expanding the if Statement The if/else Statement The if/else if Statement Using the Trailing else. - PowerPoint PPT Presentation

Transcript of CS102 Introduction to Computer Programming

Page 1: CS102 Introduction to Computer Programming

CS102Introduction to Computer

Programming

Chapter 4 Making Decisions

Page 2: CS102 Introduction to Computer Programming

Chapter 4 Topics• Relational Operators• Value of a Relationship• What is Truth• The if Statement• Flags• Expanding the if Statement• The if/else Statement• The if/else if Statement• Using the Trailing else

Page 3: CS102 Introduction to Computer Programming

Relational Operators

• Relational Operator Meaning> greater than

< Less than

>= greater than or equal to

<= less than or equal to

== equivalent to

!= not equal to

Concept - Relational operators allow you to compare numeric values

Concept - Relational operators allow you to compare numeric values

Page 4: CS102 Introduction to Computer Programming

Value of a Relationship

• All expressions have a value– The value of a relational expression is either 1 if true or

0 if false

– A relational expression is also called a Boolean expression

• Think of a relational expression as a question the computer will answer not a statement of fact

Concept - A relational expression is either true or falseConcept - A relational expression is either true or false

Page 5: CS102 Introduction to Computer Programming

Program 4-1/* This program displays the values

of true and false states.*/#include <iostream.h>void main(void){

int True, Falseint X = 5, Y = 10;True = (X < Y);False = (Y = = X);cout << "True is " << True << endl;cout << "False is " << False << endl;

}

Program OutputTrue is 1False is 0

The computer represents the abstract concept of truth as an integer value.

1 for true 0 for not true

Page 6: CS102 Introduction to Computer Programming

What is Truth

• C++ deals with the abstract states of true or false by converting them to numbers

• Because a relational expression is an expression and has a value, the value can be – assigned to a variable

– displayed with cout– used in a mathematical expression

Concept - True and false are values that can be stored in memory

Concept - True and false are values that can be stored in memory

Page 7: CS102 Introduction to Computer Programming

Check Point

• If x is 5, y is 6 and z is 8x == 5

7 <= (x+2)

z>4

(2+x)!=y

z!=4

x>=0

x<=(y*2)

• Correct or not(x<=y) == (y>x)

(x!=y) == (y>=x)

(x>=y) == (y<=x)

x>y and x<z then y<z

x>=y and x==z then y==z

x!=y and x!=z then z!=y

T

T

T

T

T

T

T

F

F

T

T

F

F

Page 8: CS102 Introduction to Computer Programming

The if Statement• The if statement allows a program to have more

than one path of execution if (expression) statement ;• If the value of the expression is:

– 0, then statement is skipped – Not 0, then statement is executed

• Note: the ; goes at the end of the if statement not at the end of the line

Concept - The if statement can cause other statements to execute only under certain conditions

Concept - The if statement can cause other statements to execute only under certain conditions

Page 9: CS102 Introduction to Computer Programming

The if Flow Chart Symbol

ifexpression

statement

end

!0

0

Page 10: CS102 Introduction to Computer Programming

Program 4-2

// This program averages 3 test scores

#include <iostream.h>void main(void){

int Score1, Score2, Score3;float Average;cout << "Enter 3 test scores and I will average them: ";cin >> Score1 >> Score2 >> Score3;Average = (Score1 + Score2 + Score3) / 3.0;cout.precision(1);cout.setf(ios::showpoint | ios::fixed);cout << "Your average is " << Average << endl;if (Average > 95)

cout << "Congratulations! That's a high score!\n";

}

Enter 3 test scores and I will average them: 80 90 70 [Enter]Your average is 80.0

This program uses a simple if statement to test the value of average

Enter 3 test scores and I will average them:100 100 100 [Enter]Your average is 100.0

Congratulations! That's a high score!

Program Output

Page 11: CS102 Introduction to Computer Programming

The if Statement continued• Be careful with comparing floating point numbers

– Rounding errors can cause unwanted results

– stick with < or > relationships

• Any non-zero value is considered true

• = = is not the same as =x = = y is either 0 or 1 if (x = = y )

x = y is the value of y if (x = y )Unless y=0 this condition is always true

Page 12: CS102 Introduction to Computer Programming

Flags

• Flag variables are set by the programmer to trigger a specific operation if a specific condition has been met – if the flag = = 0 , then the condition is not met– if the flag != 0, then the condition has been met

• Note: Variables are not automatically set to 0– always be sure to initialize flags

Concept - A flag is a variable, usually an integer, that signals when a condition has been met

Concept - A flag is a variable, usually an integer, that signals when a condition has been met

Page 13: CS102 Introduction to Computer Programming

Program 4-6/* This program averages 3 test scores.

It uses the variable HighScore as a flag.*/

#include <iostream.h>void main(void){

int Score1, Score2, Score3;int true = 1, false = 0;float Average;int HighScore = false;

cout << "Enter your 3 test scores and I will average them: ";cin >> Score1 >> Score2 >> Score3;Average = (Score1 + Score2 + Score3) / 3.0; if (Average > 95)

HighScore = true;// Set the flag variable

cout << fixed << showpoint<<setprecision(1);

cout << "Your average is " << Average << endl;

if (HighScore)cout << "Congratulations!

That's a high score!\n";

}

Program Output with Example InputEnter your 3 test scores and I will average them: 100 100 100 [Enter]Your average is 100.0Congratulations! That's a high score!

The conditional expression in an if statement does not have to be a relational expression.

Page 14: CS102 Introduction to Computer Programming

Expanding the if Statement

• If you need to execute more than one statement when the condition is true:– start with an open bracket

{

– enter all the statements to be executed ending each one with a ;

– End with a closing bracket

}

Concept - The if statement can conditionally execute a block of statements enclosed in brackets

Concept - The if statement can conditionally execute a block of statements enclosed in brackets

Page 15: CS102 Introduction to Computer Programming

Program 4-7/* This program averages 3 test

scores. It uses the variable HighScore as a flag.*/

#include <iostream.h>void main(void){

int Score1, Score2, Score3;float Average;bool HighScore = false;cout << "Enter 3 test scores and I will average them: ";cin >> Score1 >> Score2 >> Score3;Average = (Score1 + Score2 + Score3) / 3.0;if (Average > 95)

HighScore = true; // Set the flag variable

cout << fixed << showpoint<< setprecision(1);

cout << "Your average is " << Average << endl;

if (HighScore)

{cout <<

"Congratulations!\n";cout << "That's a high score.\n";cout << "You deserve a

pat on the back!\n";}

}Program OutputEnter your 3 test scores and I will

average them: 100 100 100 [Enter]

Your average is 100.0Congratulations! That's a high score!Your deserve a pat on the back

If the condition is true everything inside the braces is executed

Page 16: CS102 Introduction to Computer Programming

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.

Page 17: CS102 Introduction to Computer Programming

The if/else Statement

• The if/else statement selects one of two statements or blocks of code to execute

if (expression)

statement or block;

else

statement or block;

Concept - The if/else statement will execute one group of statements if the expression is true and another if it is false

Concept - The if/else statement will execute one group of statements if the expression is true and another if it is false

Page 18: CS102 Introduction to Computer Programming

The if/else Flow Chart Symbol

ifexpression

Statementor block

end

TrueFalseStatementor block

Page 19: CS102 Introduction to Computer Programming

Program 4-9/* This program uses the modulus operator

to determine if a number is odd or even. If evenly divided the number is by 2, it is an even number. A remainder indicates it is odd.*/

#include <iostream.h>void main(void){

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)

cout << Number << " is even.\n";else

cout << Number << " is odd.\n";}

The if/else allows the control of two paths with one statement

Program Output Enter an integer and I will tellyou if it is odd or even. 17 [Enter]17 is odd.

Page 20: CS102 Introduction to Computer Programming

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 <iostream.h>void main(void){

float Num1, Num2, Quotient;

cout << "Enter a number: ";cin >> Num1;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\n";

cout << "a number besides zero.\n";}else{

Quotient = Num1 / Num2;cout << "The quotient of

" << Num1 << " divided by ";cout << Num2 << " is "

<< Quotient << ".\n";}

}

This program uses the if statement to avoid an undesirable operation

Page 21: CS102 Introduction to Computer Programming

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.

Page 22: CS102 Introduction to Computer Programming

The if/else if Statement

• The tests are performed one after another until one is found to be true.

• The if/else statement selects one of two statements or blocks of code to execute

if (expression)

statement or block;

else if (expression)

statement or block;

Concept - The if/else if statement is a chain of if statements

Concept - The if/else if statement is a chain of if statements

Page 23: CS102 Introduction to Computer Programming

Flow Chart for the if/else if

ifexpression

Statementor block

end

TrueFalse

Statementor block

Elseif

expression

True

False

Page 24: CS102 Introduction to Computer Programming

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 <iostream.h>void main(void){

int TestScore;char Grade;

cout << "Enter your numeric test score and I will\n";cout << "tell you the letter grade you earned: ";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';

cout << "Your grade is " << Grade << ".\n";

}

Program Output Enter your test score and I will tell you the letter grade you earned: 88 [Enter]Your grade is B.

As soon as a true condition is met the if/else if statement terminates

Page 25: CS102 Introduction to Computer Programming

Program 4-12

// This program uses independent if statements to assign a letter grade (A, B, C, D, or F) to a numeric test score.

#include <iostream.h>

void main(void){

int TestScore;char Grade;

cout << "Enter your test score and I will tell you\n";cout << "the letter grade you earned: ";cin >> TestScore;

if (TestScore < 60)Grade = 'F';

if (TestScore < 70)Grade = 'D';

if (TestScore < 80)Grade = 'C';

if (TestScore < 90)Grade = 'B';

if (TestScore <= 100)Grade = 'A';

cout << "Your grade is " << Grade << ".\n";

}

Program Output Enter your test score and I will tell youthe letter grade you earned: 40 [Enter]Your grade is A.Do you think it will work?

Page 26: CS102 Introduction to Computer Programming

Using the Trailing else

Can be used to to take care of any case not considered by the if expressions

if (expression)

statement or block;

else if (expression)

statement or block;

else

statement or block;

Concept - The trailing else placed at the end of an if/else if statement provides default action when none of the ifs are true

Concept - The trailing else placed at the end of an if/else if statement provides default action when none of the ifs are true

Page 27: CS102 Introduction to Computer Programming

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. A trailing else has been added to catch test scores > 100.*/

#include <iostream.h>

void main(void){

int TestScore;

cout << "Enter your test score and I will tell you\n";cout << "the letter grade you earned: ";cin >> TestScore;

if (TestScore < 60){

cout << "Your grade is F.\n";

cout << "This is a failing grade. Better see your ";

cout << "instructor.\n";}else if (TestScore < 70){

cout << "Your grade is D.\n";

cout << "This is below average. You should get ";

cout << "tutoring.\n";}

Page 28: CS102 Introduction to Computer Programming

Program continueselse if (TestScore < 80)

{cout << "Your grade is C.\n";cout << "This is average.\n";}else if (TestScore < 90){cout << "Your grade is B.\n";cout << "This is an above average grade.\n";}else if (TestScore <= 100){cout << "Your grade is A.\n";cout << "This is a superior grade. Good work!\n";}else

Program Output Enter your test score and I will tell youthe letter grade you earned: 104 [Enter]104 is an invalid score.Please enter scores no greater than 100.

else{cout << TestScore << " is an invalid score.\n";

cout << "Please enter scores no greatr than 100.\n";}

}