1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem...

42
1 ELEC 206 ELEC 206 Chapter 3 Chapter 3 Control Structures Control Structures

Transcript of 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem...

Page 1: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

1

ELEC 206ELEC 206

Chapter 3Chapter 3

Control StructuresControl Structures

Page 2: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

5-Step Problem Solving 5-Step Problem Solving MethodologyMethodology

1.1. State the problem clearly.State the problem clearly.

2.2. Describe the input and output.Describe the input and output.

3.3. Work a hand example.Work a hand example.

4.4. Develop a solution.Develop a solution.

5.5. Test your solution.Test your solution.

2

Page 3: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Control structuresControl structures

Algorithm DevelopmentAlgorithm Development Conditional ExpressionsConditional Expressions Selection StatementsSelection Statements Repetition StatementsRepetition Statements Structuring Input LoopsStructuring Input Loops

3

Page 4: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Algorithm DevelopmentAlgorithm Development

An algorithm is a sequence of steps for An algorithm is a sequence of steps for solving a problem.solving a problem.

Engineering problem solutions to real Engineering problem solutions to real world problems require complex world problems require complex algorithms.algorithms.

Development of a good algorithm Development of a good algorithm increases the quality and maintainability increases the quality and maintainability of a solution, and reduces the overall time of a solution, and reduces the overall time required to implement a correct solution. required to implement a correct solution.

4

Page 5: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Top-Down DesignTop-Down Design

Top-down design begins with a "big Top-down design begins with a "big picture" description of a problem picture" description of a problem solution in sequential steps.solution in sequential steps.

The sequential steps are refined until The sequential steps are refined until the steps are detailed enough to the steps are detailed enough to translate to language statements.translate to language statements.

The refined steps, or algorithm, can The refined steps, or algorithm, can be described using pseudo code or be described using pseudo code or flowcharts.flowcharts.

5

Page 6: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Evaluation of Alternative SolutionsEvaluation of Alternative Solutions

Most problems have more than one solution. Most problems have more than one solution. There may not be a single best solution, but There may not be a single best solution, but

some solutions are better than others.some solutions are better than others. Elements that contribute to a good solution:Elements that contribute to a good solution:

– correctness correctness – reliabilityreliability– readabilityreadability– maintainabilitymaintainability– execution speedexecution speed– memory considerationsmemory considerations– user interfaceuser interface

6

Page 7: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Structured ProgrammingStructured Programming

A structured program is written using A structured program is written using simple control structures, including:simple control structures, including:– Sequence – Sequence – steps are performed one after steps are performed one after

another.another.– Selection – Selection – one set of statements is executed one set of statements is executed

if a given condition is true, a different set of if a given condition is true, a different set of statements, or no statements at all, is statements, or no statements at all, is executed if the condition is false.executed if the condition is false.

– Repetition –Repetition –A set of statements is executed A set of statements is executed repeatedly as long as a given condition is true.repeatedly as long as a given condition is true.

7

Page 8: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

8

Structured ProgrammingStructured Programming

SequenceSequence

SelectionSelection

RepetitionRepetition

?truefalse

?true

false

? => conditional expression

Page 9: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Conditional ExpressionsConditional Expressions

A conditional expression is a Boolean A conditional expression is a Boolean expression that evaluates to true or expression that evaluates to true or false.false.

Selection structures and repetition Selection structures and repetition structures rely on conditional structures rely on conditional expressions.expressions.

RelationalRelational operatorsoperators and and logicallogical operatorsoperators are used to form are used to form conditional expressions.conditional expressions.

9

Page 10: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

10

Relational OperatorsRelational Operators

==== equalityequality !=!= non equalitynon equality << less thanless than >> greater thangreater than <=<= less than equal toless than equal to >=>= greater than equal togreater than equal to

Page 11: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

11

Logical OperatorsLogical Operators

!! notnot &&&& andand |||| oror

Page 12: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Logical OperatorsLogical Operators

AA BB A&&BA&&B A||BA||B !A!A !B!B

00 00 00 00 11 11

00 11 00 11 11 00

11 00 00 11 00 11

11 11 11 11 00 00

12

Truth table for conditional expressions

0 = false 1=true

Page 13: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

13

Operator PrecedenceOperator Precedence

1.1. < <= > >=< <= > >=

2.2. == !=== !=

3.3. &&&&

4.4. ||||

Page 14: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

14

(-6<0)&&(12>=10)(-6<0)&&(12>=10)

(3.0 >= 2.0) || (3.0 >= 4.0)(3.0 >= 2.0) || (3.0 >= 4.0)

(3.0 >= 2.0) && (3.0 >= 4.0)(3.0 >= 2.0) && (3.0 >= 4.0)

true && true results in true

Practice! - evaluatePractice! - evaluate

true || false results in true

true && false results in false

Page 15: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

15

Selection StatementsSelection Statements

The C++ programming language The C++ programming language supports the implementation of selection supports the implementation of selection with:with:– if if statementsstatements– switchswitch statements statements

Page 16: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

16

The The ifif statementstatement

if(if(expressionexpression))statement; /*single statement executed statement; /*single statement executed

if expression is true */if expression is true */

// statement block is executed if expression is true. if(expression){

statement1;statement2;

…statement n;

}

Page 17: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

17

The The ifif statement - examples statement - examples

if (x>0)++k;

if(x>0) {

x=sqrt(x);++k;

}

Page 18: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

18

The The if - elseif - else statement statement

if(if(expressionexpression))statementstatement;;

elseelse statementstatement;;

if(expression) {

statement block }else {

statement block }

Page 19: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

19

The nested The nested if-elseif-else

if(x > y)if(y < z)

k++;else

m++;else

j++;

Page 20: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

20

Practice!Practice!

int x=9, y=7, z=2, k=0, m=0, j=0;if(x > y)

if(y >z && y>k)k++;

elsem++;

elsej++;

What are the values of j, k and m?

Page 21: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

21

TheThe switch switch statement statement

switch(expression){

case constant:statement(s);break;

case constant:statement(s);break;

/* default is optional*/default:

statement(s);}

Page 22: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

22

The The switchswitch statement statement

ExpressionExpression must be of type integer or must be of type integer or character.character.

The keyword The keyword casecase must be followed must be followed by a by a constant.constant.

breakbreak statement is required unless statement is required unless you want all subsequent statements you want all subsequent statements to be executed.to be executed.

Page 23: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

23

switchswitch statement example statement example

char ch;int ecount=0, vowels=0, other=0;cin.get(ch);while(!cin.eof()){ switch(ch) { case ‘e’: ecount++;

case ‘a’:case ‘i’:case ‘o’:case ‘u’: vowels++;

break;default: other++;

}//end switch cin.get(ch);}//end whilecout << ecount << ‘,’ << vowels << ‘,’ << other << endl;

Page 24: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

24

Practice!Practice!

Convert these nested if/else statements to a switch statement:if (rank==1 || rank==2) cout << "Lower division \n";else{ if (rank==3 || rank==4) cout << "Upper division \n"; else    { if (rank==5) cout << "Graduate student \n"; else cout << "Invalid rank \n"; }}

Page 25: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

REPETITION STATEMENTSREPETITION STATEMENTS

while while statementstatement

do while do while statementstatement

for for statementstatement

Structuring input loopsStructuring input loops

25

Page 26: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

26

Repetition StatementsRepetition Statements

The C++ programming language The C++ programming language supports the implementation of repetition supports the implementation of repetition with:with:– while while statementsstatements– do/whiledo/while statements statements– forfor statements statements

Page 27: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

27

The The whilewhile statement statement

while (while (expressionexpression))

statement;statement;

whilewhile ((expressionexpression))

{{

statement blockstatement block

}}

?

true

false

Page 28: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

28

The The do/whiledo/while statement statement

do do

statement;statement;

while (while (expressionexpression))

dodo

{{

statement blockstatement block

} while } while ((expressionexpression))

?true

false

Page 29: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

29

PracticePractice!!#include <iostream>using namespace std;int main(){

int n=4;while(n>0){

cout << n << endl;--n;

}cout << “value of n outside while is “ << n << endl;return 0;

}Program Trace:Output?

Page 30: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

30

The The forfor statement statement

initalize?

increment/decrement

true

statement(s)statement(s)

false

Page 31: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

31

The The forfor statement statement

for(for(initializationinitialization;; expressionexpression; ; incrementincrement//decrementdecrement))

statementstatement;;

for(for(initializationinitialization;; expressionexpression; ; incrementincrement//decrementdecrement))

{{

statementstatement;;

statementstatement;;

}}

Page 32: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

32

The The forfor statement - examples statement - examples

//sum integers from //1 to 10 inclusive#include<iostream>using namespace std;int main(){ int sum=0; for(int i=1;i<11;++i) { sum = sum + i; } cout << sum << endl; return 0;}

Alternate solution://sum integers from //1 to 10#include<iostream>using namespace std;int main(){ int sum=0; for(int i=1;i<=10;i++)

sum = sum + i; cout << sum << endl; return 0;}

Page 33: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

The The forfor statement - example statement - example

//sum odd integers from //sum odd integers from //1 to n inclusive//1 to n inclusive#include<iostream>#include<iostream>using namespace std;using namespace std;int main()int main(){{ int sum=0, n;int sum=0, n; cout << "enter non-negative integer: ";cout << "enter non-negative integer: "; cin >> n;cin >> n; for(int i=1;i<=n;i+=2)for(int i=1;i<=n;i+=2)

sum = sum + isum = sum + i cout << sum << endl;cout << sum << endl; return 0;return 0;}}

33

Page 34: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

The The forfor statement - example statement - example//sum odd integers from //sum odd integers from //1 to n inclusive//1 to n inclusive//Alternate Solution//Alternate Solution#include<iostream>#include<iostream>using namespace std;using namespace std;int main()int main(){{ int sum=0, n;int sum=0, n; cout << "enter non-negative integer: ";cout << "enter non-negative integer: "; cin >> n;cin >> n; for(int i=1;i<=n;++i)for(int i=1;i<=n;++i) {{ if(i%2) sum = sum + i;if(i%2) sum = sum + i; }} cout << sum << endl;cout << sum << endl; return 0;return 0;}} 34

Page 35: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

35

Practice!Practice!

Write a program solution to print Write a program solution to print all integer values all integer values betweenbetween 1 and 1 and n that are multiples of 5 (ie evenly n that are multiples of 5 (ie evenly divisible by 5).divisible by 5).

Compare your solution with Compare your solution with another person's solution.another person's solution.

Page 36: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

36

The The breakbreak statement statement

break;break;– terminates loopterminates loop– execution continues with the first statement execution continues with the first statement

following the loopfollowing the loop

Example: What is the output?for(int i-0; i<=10; ++i){ if(i%2) break; cout << i << endl;}

Page 37: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

37

The The continuecontinue statement statement

continue;continue;– forces next iteration of the loop, forces next iteration of the loop,

skipping any remaining statements in skipping any remaining statements in the loopthe loopExample: What is the output?for(int i-0; i<=10; ++i){ if(i%2) continue; cout << i << endl;}

Page 38: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

38

PracticePractice!!//This while loop calculates n!int nfact=1, n;cout << "enter positive integer ";cin >> n;while(n > 1){

nfact = nfact*n;n--;

}cout << n << "! = " << nfact << endl;

//What is the output for n=5?

//Write an alternate solution.

Page 39: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Structuring Input LoopsStructuring Input Loops

39

Repetition is useful when inputting data from standard input or from a file.Common repetition structures:

counter-controlled sentinel-controlled end-of-data controlled

Page 40: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Counter-controlled Repetition StructureCounter-controlled Repetition Structure

i 0i 0

while i < = counterwhile i < = counterinput data value input data value

//Do something with data value//Do something with data value

increment iincrement i

end whileend while

40

Page 41: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

Sentinel-controlled Repetition StructureSentinel-controlled Repetition Structure

input data valueinput data value

while data value ! = sentinel valuewhile data value ! = sentinel value//Do something with data value//Do something with data value

input next data valueinput next data value

end whileend while

41

Page 42: 1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.

eof()-controlled Repetition Structureeof()-controlled Repetition Structure

input data valueinput data value

while end-of-file is not truewhile end-of-file is not true//Do something with input data//Do something with input data

input next data valueinput next data value

end whileend while

42