• Tidak ada hasil yang ditemukan

Sequentially : In sequence

N/A
N/A
Protected

Academic year: 2024

Membagikan "Sequentially : In sequence"

Copied!
58
0
0

Teks penuh

(1)

CONTROL STRUCTURES

Program instructions can be executed:

Sequentially : In sequence

Selectively : by making a choice; also called a branch.

Repetitively (or iteratively) : performing

a statement over and over; this is called a loop.

(2)

expression

(3)

Selection:

Allow the flow of a program to be altered

In C++, there are two ways for implementing selections, or branch control structures:

if statements

switch structure.

Selectively (Decision)

(4)

Selection:

if and if...else statements can be used to create :

one-way selection. (if statement)

two-way selection. (if/else statement)

multiple selections. (nested if and if/else statements)

Selectively (Decision)

(5)

One-way Selection

The syntax of one-way selection is:

if(expression)

statement;

(6)

The expression is usually a Boolean Expression, which evaluates to true or false

The expression is sometimes called condition

Types of conditions:

Simple: a single Relational Expression

Complex: Multiple

Relational

Expressions joined with logical (and / or) operators.

if(expression) statement1;

statement2;

(7)

If the value of the expression is true, statement1 is executed then statement2

if the value is false, statement1 is not executed and the computer goes on to the next statement (statement2) in the program.

statement is any type of C++ statements.

In C++, if is a reserved word.

if(expression) statement1;

statement2;

(8)

Compound if (Block of Statements)

A compound if statement takes the form if(expression)

{

statement1;

statement2;

. . .

statement n;

}

(9)

Example # 1

if(score >= 90) grade = 'A';

If (score >= 90) is true, the assignment statement is executed; if it is false, the assignment statement is not executed.

For example, if the value of score is 95, the value assigned to the variable grade is A.

(10)

Common errors

if score >= 90 grade = 'A';

The parentheses around the logical expression are missing, which is a syntax error.

if (score >= 90);

grade = 'A';

To put a semicolon after the parentheses following the expression (that is, before the statement) in an if statement is a Logical error.

if ( score >= 90 ) grade = 'A';

(11)

Consider the following C++ statements:

if(score >= 90); //Line 1 grade = 'A'; //Line 2

This statement represents a one-way selection.

Because there is a semicolon at the end of the

expression, the if statement terminates at Line 1, the action of the if statement is null, and the

statement at Line 2 is not part of the if statement at Line 1.

The statement at Line 2 executes regardless of how

the if statement evaluates.

(12)

Example # 2

Draw a flowchart and write a C++ program that finds the absolute value of an integer number.

Flow chart:

START

Read Number

Number < 0

number= -number

Write number STOP

True False

(13)

Example#2

Program Code:

void main () {

int number;

cout<<"Please enter an integer: ";

cin>>number;

if(number < 0) number = -number;

cout<<endl<<"The absolute value is "

<<number<<endl;

getch();

}

Please enter an integer -6734 The absolute value is 6734

(14)

Two-way Selection

The syntax of two-way selection is:

if(expression)

statement1;

else

statement2;

(15)

if(expression)

statement1;

else

statement2;

statement3;

In a two-way selection if the value of the expression is true, statement1 is executed.

If the value of the expression is false, statement2 is executed.

statement1 and statement2 are any C++ statements

statement3 is executed what ever the expression is.

In C++, else is a reserved word.

(16)

Compound if/else(Block of Statements)

if (expression) {

statement 1;

.

statement n;

} else {

statement n+1;

.

statement n+m;

}

OR

if (expression) {

statement 1;

.

statement n;

} else

statementn+1;

OR

if (expression) statement 1;

else {

statement 2;

.

statement n;

}

(17)

Example#3

if(hours > 40.0) //Line 1

salary = 40.0 * rate + 100; //Line 2

else //Line 3

salary = hours * rate; //Line 4

If the value of the variable hours is greater than 40.0, then the salary include overtime payment.

Suppose that hours is 50. The expression in the if

statement at Line 1 evaluates to true, so the statement at Line 2 executes.

If hours is 30, or any number less than or equal to 40, the expression in the if statement at Line 1 evaluates to false. The program skips the statement at Line 2 and executes the statement at Line 4.

(18)

if(expression);

statement1;

else

statement2;

To put a semicolon after the expression before statement1, in a two-way selection, is a syntax error. In this case the if statement ends with the semicolon, statement1 is no longer part of the if statement and the else part of the statement is all by itself.

Remember there is no else statement in C++. It cannot be separated from the if statement.

Misplaced else

;

(19)

Example#4

The following statements show an example of a syntax error:

if(hours > 40.0); //Line 1

salary = 40.0 * rate + 100; //Line 2

else //Line 3

salary = hours * rate; //Line 4

Because a semicolon follows the closing parenthesis of the if statement (Line 1), the else statement stands alone.

The semicolon at the end of if statement ends the if statement, so the statement at Line 2 separates the else clause from the if statement. That is, else is all by itself.

Since there is no else statement in C++, this code generates a syntax error.

(20)

Example # 5

if(score >= 90)

grade = 'A';

cout<<"The grade is "<<grade<<endl;

These statements contain a Logical error.

The if statement acts on only one statement, which is grade

= 'A';.

The cout statement executes regardless of whether (score >= 90) is true or false.

(21)

Example # 7

if(score >= 90)

grade = 'A';

cout<<"The grade is "<<grade<<endl;

Correct the above statement?!

If two statements or more belong to the if statement, we should combine them by brackets.

if(score >= 90) {

grade = 'A';

cout<<"The grade is "<<grade<<endl;

}

(22)

Example # 6

if(score >= 60)

cout<<"Passing"<<endl;

cout<<"Failing"<<endl;

If the expression (score >= 60)evaluates to false, the output is Failing.

For example, if the value of score is 50, these statements will output the following line:

Failing

If the expression score >= 60 evaluates to true, the program will write both statements, giving a very

unsatisfactory result.

(23)

if(score >= 60)

cout<<"Passing"<<endl;

cout<<"Failing"<<endl;

If the value of score is 70, these statements will output the following lines:

Passing Failing

The correct code to print Passing or Failing, depending on the value of score, is

if(score >= 60)

cout<<"Passing"<<endl;

else

cout<<"Failing"<<endl;

(24)

Example # 8

if(age > 18)

{

cout<<" Eligible to vote."<<endl;

cout<<" No longer a minor."<<endl;

} else

{

cout<<"Not eligible to vote."<<endl;

cout<<"Still a minor."<<endl;

}

What would happen if there is no braces ?!

(25)

if(age > 18)

cout<<" Eligible to vote."<<endl; //line1 cout<<" No longer a minor."<<endl; //line2

else // line3

cout<<"Not eligible to vote."<<endl; //line4 cout<<"Still a minor."<<endl;

Line 2 is not belong to the if statement and it will be executed what ever the value of the if expression.

else in line 3 is all by itself ( syntax error)

Do not separate the else statement from its if.

(26)

Example # 9

Draw a flowchart and write a c++ program that determine whether an entered number is positive or negative.

Flowchart :

Read number

number > =0

Write “positive”

STOP False True

START

Write “negative”

(27)

Example # 9 Program Code:

#include <iostream.h>

#include <conio.h>

void main() {

int number;

cout<<"Please enter an integer number :";

cin>>number;

if(number>=0)

cout<<“Positive";

else

cout<<"Negative";

getch();

}

(28)

Example # 10

Draw a flowchart and write a c++ program that determine whether an entered number is even or odd.

Flowchart :

Read number

number %2 =0

Write “Even”

STOP False True

START

Write “Odd”

(29)

Example # 10 Program Code:

#include <iostream.h>

#include <conio.h>

void main() {

int number;

cout<<"Please enter an integer number :";

cin>>number;

if(number%2 == 0) cout<<“Even";

else

cout<<“Odd";

getch();

}

(30)

Example # 11

Draw a flowchart and write a c++ program that reads an integer number of two digits, then display each digit in a separate line after checking that the number consists of only two digits, otherwise display an appropriate message.

Flowchart :

Read number

10<=number <100

d1=num%10 d2=num/10

STOP False True

START

Write “Wrong Entry”

Write d1,d2

(31)

Example # 11 Program Code:

#include <iostream.h>

#include <conio.h>

void main() {

int number;

cout<<"Please enter an integer number of two digits :";

cin>>number;

if((number>=10) && (number<100)) {

d1=num%10;

d2=num/10;

cout<<d1<<endl<<d2;

} else

cout<<“Wrong Entry";

getch();

}

(32)

Example# 12

Write a c++ program that reads two integer numbers then displays the largest

#include <iostream.h>

#include <conio.h>

void main() {

int num1, num2, larger;

cout<<"Enter any two integers:":

cin>>num1>>num2;

if(num1 > num2) larger = num1;

else

larger = num2;

cout<<"The larger number is "<<larger<<endl;

getch();

}

Enter any two integers: 78 90 The larger number is 90

(33)

Example # 13

Draw a flowchart and write a c++ program that reads an employee weekly working hours and pay rate, then determine the weekly salary for that employee using time and half for working hours over 40.

Flowchart :

Read hours, rate

hours > 40

salary = 40*rate+(hours-40)*1.5*rate

Write salary STOP False True

START

salary = hours*rate

(34)

Example# 13

Program code:

#include <iostream.h>

#include <conio.h>

void main () {

float salary, rate, hours;

cout<<"Enter working hours and rate: ";

cin>>hours>>rate;

if(hours > 40.0)

salary = 40.0*rate + (hours-40)*1.5*rate;

else

salary = hours * rate;

cout<<"The salary are "<< salary;

getch();

}

Enter working hours and rate: 56 12 The salary are 768

(35)

Exercise # 1

Draw a flowchart and write a c++ program that divides two integer numbers entered by the user after checking that the

dividend is not equal to zero.

(36)

Multiple Selections:

Nested if

exp

True False

exp

True False

statement

if ( expression ) if (expression)

statement;

if ( expression ) if (expression)

{

statement 1;

.

statement n;

} exp

True False

exp True

False

Statement 1 Statement n

(37)

Multiple Selections:

Nested if

if ( expression ) {

statement 1;

if (expression) statement 2;

statement 3;

} exp

True False

exp

False True

Statement 1

Statement 2

Statement 3

(38)

Multiple Selections:

Nested if/else

exp True

False

exp

True False

statement1 statement2

if ( expression ) if (expression)

statement1;

else

statment2;

else

if (expression) statement3;

else

statment4;

exp

True False

statement3 statement4

 Not every if must have an else

 It could be multiple nested if

(39)

Multiple Selections:

Nested if/else

exp

True False

exp

True False

statement1

statement2 statement3

if ( expression ) if (expression)

statement 2;

else

statement 3;

else

statement 1;

exp

True False

exp

True

False statement1

statement2 statement3

if ( expression ) statment1;

else

if (expression) statement2;

else

statment3;

(40)

Multiple Selections:

Nested if and if/else

exp

True False

exp

True False

statement1 statement2

if ( expression ) if (expression)

statement 1;

else

statement 2;

if ( expression ) {

if (expression) statement 1;

} else

statement 2;

exp

True False

exp

True False

statement 1 statement 2

(41)

Example# 14

Write a c++ program that reads a student mark

then determine his grade (A,B,C,D, or F).

(42)

Example# 14

void main( ) {

int mark;

cout<<“Please enter a student mark”;

cin>>mark;

if(score >= 90)

cout<<"The grade is A"<<endl;

else

if(score >= 80)

cout<<"The grade is B"<<endl;

else

if(score >= 70)

cout<<"The grade is C"<<endl;

else

if(score >= 60)

cout<<"The grade is D"<<endl;

else

cout<<"The grade is F"<<endl;

getch();

}

(43)

the previous code can be rewritten as follows:

void main() {

int mark;

cout<<“Please enter a student mark”;

cin>>mark;

if(score >= 90)

cout<<"The grade is A"<<endl;

else if(score >= 80)

cout<<"The grade is B"<<endl;

else if(score >= 70)

cout<<"The grade is C"<<endl;

else if(score >= 60)

cout<<"The grade is D"<<endl;

else

cout<<"The grade is F"<<endl;

getch();

}

(44)

Example # 15

if(temperature >= 50) //Line 1

if(temperature >= 80) //Line 2 cout<<"Good day for swimming."<<endl; //Line 3

else //Line 4

cout<<"Good day for golfing."<<endl; //Line 5

else //Line 6

cout<<"Good day to play tennis."<<endl; //Line 7

In this C++ code, the else at Line 4 is paired with the if at Line 2, and the else at Line 6 is paired with the if at Line 1.

The statements on Lines 2 though 5 form the statement part of the if at Line 1.

(45)

Example #16

if(temperature >= 70) //Line 1

if(temperature >= 80) //Line 2

cout<<"Good day for swimming."<<endl;//Line 3

else //Line 4

cout<<"Good day for golfing."<<endl; //Line 5

For the else at Line 4, it is paired with the nearest incomplete if at Line 2.

In this code, the if at Line 1 has no else and is a one-way selection.

(46)

Example # 17

if(GPA >= 2.0) //Line 1

if(GPA >= 3.9) //Line 2

cout<<" graduated with honor."<<endl; //Line 3

else //Line 4

cout<<"Current GPA below graduation requirement. "

<<"\nSee your academic advisor."<<endl;//Line 5

Following the rule of pairing an else with an if, the else at Line 4 is paired with the if at Line 2.

This pairing produces a very unsatisfactory result.

Suppose that GPA is 3.8. The expression in the if at Line 1 evaluates to true, and the statement part of the if, which is an if...else structure, executes.

(47)

Because GPA is 3.8, the expression in the if at Line 2 evaluates to false, and the else associated with this if executes, producing the following output:

Current GPA below graduation requirement.

See your academic advisor.

A student with a GPA of 3.8 would graduate

In fact, the code intended to print the message

Current GPA below graduation requirement.

See your academic advisor.

only if the GPA is less than 2.0, and the message

graduated with honor.

if the GPA is greater than or equal to 3.9. To achieve that result, the else at Line 4 needs to be paired with the if at Line 1.

(48)

To pair the else at Line 4 with the if at Line 1, you need to use a compound statement as follows:

if(GPA >= 2.0) //Line 1

{

if(GPA >= 3.9) //Line 2

cout<<" graduated with honor."<<endl; //Line 3 }

else //Line 4

cout<<"Current GPA below graduation requirement. "

<<"\nSee your academic advisor."<<endl;//Line 5

(49)

Example # 18

What is the output of the following code segment:

int age;

cin>>age;

if (age>=5) if (age<=11)

cout<<“child”;

else

cout<<“teenager”;

Input:6

Output: child

Input:15

Output: teenager

Input:4

Output: Nothing

(50)

Example # 19

What is the output of the following code segment:

int age;

cin>>age;

if (age>=5) {

if (age<=11)

cout<<“”child”;

}

else

cout<<“not child”;

Input:6

Output: child

Input:12

Output: Nothing

Input:4

Output: Not child

(51)

Comparing nested if ... else Statements with a Series of if Statements

Consider the following C++ program segments.

(a) Using nested if/else statement

if(month == 1) //Line 1

cout<<"January"<<endl; //Line 2

else if(month == 2) //Line 3

cout<<"February"<<endl; //Line 4

else if(month == 3) //Line 5

cout<<"March"<<endl; //Line 6

else if(month == 4) //Line 7

cout<<"April"<<endl; //Line 8

else if(month == 5) //Line 9

cout<<"May"<<endl; //Line 10

else if(month == 6) //Line 11

cout<<"June"<<endl; //Line 12

(52)

(b) Using series of if statement

if(month == 1)

cout<<"January"<<endl;

if(month == 2)

cout<<"February"<<endl;

if(month == 3)

cout<<"March"<<endl;

if(month == 4)

cout<<"April"<<endl;

if(month == 5)

cout<<"May"<<endl;

if(month == 6)

cout<<"June"<<endl;

(53)

Both programs accomplish the same thing.

If month is 3, then both programs output March.

If month is 1, then in program (a), the expression in the if statement at Line 1 evaluates to true. The statement (at

Line 2) associated with this if then executes; the rest of the structure, which is the else of this if statement, is skipped;

and the remaining if statements are not evaluated.

In program (b), the computer has to evaluate the expression in each if statement because there is no else statement.

Program (b) executes more slowly than does program (a)

(54)

Example # 20

Write a c++ program that reads two integer numbers then finds the largest, or display an appropriate message if they are equal.

void main() {

int num1, num2;

cout<<"Enter any two integers:”;

cin>>num1>>num2;

cout<<endl;

if(num1 > num2)

cout<<"The larger number is"<<num1<<endl;

else if(num2 > num1)

cout<<"The larger number is "<<num2<<endl;

else

cout<<"Both numbers are equal."<<endl;

getch();

}

(55)

Exercise # 2

Draw a flowchart and write a c++ program that

reads an integer number from the user then

determine whether it is positive or negative or

zero

(56)

Example # 21

Write a c++ program that reads a character from the user then displays its ASCII code and finds whether the entered character is an alpabetic,

numeric, or a symbol.

#include <iostream.h>

#include <conio.h>

#include <ctype.h>

void main ( ) {

char input;

cout <<"Enter any character:";

cin>>input;

int code=toascii(input);

cout<<input<<"has ASCII code="<<code<<'\n';

if( isalpha ( input ) )

cout << "Alphabetic character\n";

else if ( isdigit ( input ) )

cout << "Numeric digit\n";

else

cout<<“A symbol\n”

getch();

}

(57)

Exercise # 3

Draw a flowchart and write a C++ program that reads the water temperature in centigrade then determine the water state (ice, steam, or liquid according to its temperature.

when temp ≤0 Ice

water state = Water when 0 < temp <100 when temp ≥100

Steam

(58)

Exercise # 4

Write a C++ program that reads three integer

numbers from the user then finds the largest, or

display an appropriate message if they are equal

Referensi

Dokumen terkait

This type of statement is useful when you want the code block to be executed at least once, even if the while expression evaluates to false. Listing 5.7 creates a

If this statement is later proven false, the researcher willingly takes any responsibility from English Department, Faculty of Letters &amp; Fine Arts of Sebelas

MATLAB evaluates the expression and, if the evaluation yields a logical true or nonzero result, executes one or more MATLAB commands denoted here as statements.. if - else

Pada bentuk ini, hanya jika kondisi bernilai true (ya) maka proses atau statement didalam blok if tersebut yang akan dilaksanakan1. Evaluate an expression and directs

If isDefect is false then the last statement if( ! isDefect) returns true, and the program writes also P to the standard output2. If x is equal to 1, the statement if(x &lt;

Awareness of facts about pregnancy-related issues in women with epilepsy Statement True % False % Don’t know % “The best AED during pregnancy is the one that is most appropriate

Write ‘true’ if the statement is correct and ‘false’ if the statement is incorrect: 1x6=6 a A man went to the river bank for a drink.. b The ant fell into the water and almost

In your cover letter, please indicate whether the following statements are true or false, and provide an explanation if necessary: 2a All authors had access to relevant aggregated