Разделы презентаций


Control Structures

Содержание

2.15 Essentials of Counter-Controlled RepetitionCounter-controlled repetition requiresName of control variable/loop counterInitial value of control variableCondition to test for final valueIncrement/decrement to modify control variable when looping

Слайды и текст этой презентации

Слайд 1Control Structures
Week 3
Akbayan Bekarystankyzy
akbayan.b@gmail.com

Control StructuresWeek 3Akbayan Bekarystankyzyakbayan.b@gmail.com

Слайд 22.15 Essentials of Counter-Controlled Repetition
Counter-controlled repetition requires
Name of control variable/loop counter
Initial

value of control variable
Condition to test for final value
Increment/decrement to

modify control variable when looping
2.15	Essentials of Counter-Controlled RepetitionCounter-controlled repetition requiresName of control variable/loop counterInitial value of control variableCondition to test for

Слайд 31 // Fig. 2.16: fig02_16.cpp
2 //

Counter-controlled repetition.
3 #include
4
5

using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 int counter = 1; // initialization
12
13 while ( counter <= 10 ) { // repetition condition
14 cout << counter << endl; // display counter
15 ++counter; // increment
16
17 } // end while
18
19 return 0; // indicate successful termination
20
21 } // end function main

1
2
3
4
5
6
7
8
9
10

1   // Fig. 2.16: fig02_16.cpp2   // Counter-controlled repetition.3   #include 4

Слайд 42.15 Essentials of Counter-Controlled Repetition
The declaration
int counter = 1;
Names counter
Declares counter

to be an integer
Reserves space for counter in memory
Sets counter

to an initial value of 1
2.15	Essentials of Counter-Controlled RepetitionThe declarationint counter = 1;Names counterDeclares counter to be an integerReserves space for counter

Слайд 62.16 for Repetition Structure
General format when using for loops
for ( initialization;

LoopContinuationTest; increment )
statement
Example
for( int counter = 1;

counter <= 10; counter++ )
cout << counter << endl;
Prints integers from one to ten
2.16	for Repetition StructureGeneral format when using for loopsfor ( initialization; LoopContinuationTest; increment )  statement Examplefor( int

Слайд 71 // Fig. 2.17: fig02_17.cpp
2 //

Counter-controlled repetition with the for structure.
3 #include
4


5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 // Initialization, repetition condition and incrementing
12 // are all included in the for structure header.
13
14 for ( int counter = 1; counter <= 10; counter++ )
15 cout << counter << endl;
16
17 return 0; // indicate successful termination
18
19 } // end function main

1
2
3
4
5
6
7
8
9
10

1   // Fig. 2.17: fig02_17.cpp2   // Counter-controlled repetition with the for structure.3

Слайд 82.16 for Repetition Structure
for loops can usually be rewritten as while

loops
initialization;
while ( loopContinuationTest){
statement
increment;
}
Initialization and increment
For multiple

variables, use comma-separated lists
for (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl;

2.16	for Repetition Structurefor loops can usually be rewritten as while loopsinitialization;while ( loopContinuationTest){  statement  increment;}Initialization

Слайд 91 // Fig. 2.20: fig02_20.cpp
2 //

Summation with for.
3 #include
4
5

using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 int sum = 0; // initialize sum
12
13 // sum even integers from 2 through 100
14 for ( int number = 2; number <= 100; number += 2 )
15 sum += number; // add number to sum
16
17 cout << "Sum is " << sum << endl; // output sum
18 return 0; // successful termination
19
20 } // end function main

Sum is 2550

1   // Fig. 2.20: fig02_20.cpp2   // Summation with for.3   #include 4

Слайд 102.17 Examples Using the for Structure
Program to calculate compound interest
A

person invests $1000.00 in a savings account yielding 5 percent

interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts:
a = p(1+r)
p is the original amount invested (i.e., the principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the n-th year

n

2.17 Examples Using the for StructureProgram to calculate compound interestA person invests $1000.00 in a savings account

Слайд 111 // Fig. 2.21: fig02_21.cpp
2 //

Calculating compound interest.
3 #include
4
5

using std::cout;
6 using std::endl;
7 using std::ios;
8 using std::fixed;
9
10 #include
11
12 using std::setw;
13 using std::setprecision;
14
15 #include // enables program to use function pow
16
17 // function main begins program execution
18 int main()
19 {
20 double amount; // amount on deposit
21 double principal = 1000.0; // starting principal
22 double rate = .05; // interest rate
23

1   // Fig. 2.21: fig02_21.cpp2   // Calculating compound interest.3   #include 4

Слайд 1224 // output table column heads
25

cout

"Amount on deposit" << endl;
26
27 // set floating-point number format
28 cout << fixed << setprecision( 2 );
29
30 // calculate amount on deposit for each of ten years
31 for ( int year = 1; year <= 10; year++ ) {
32
33 // calculate new amount for specified year
34 amount = principal * pow( 1.0 + rate, year );
35
36 // output one table row
37 cout << setw( 4 ) << year
38 << setw( 21 ) << amount << endl;
39
40 } // end for
41
42 return 0; // indicate successful termination
43
44 } // end function main

24    // output table column heads25    cout

Слайд 13Year Amount on deposit
1

1050.00
2

1102.50
3 1157.63
4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89

Year  Amount on deposit  1       1050.00  2

Слайд 142.17.1 for Repetition Structure Flowchart

2.17.1	 for Repetition Structure Flowchart

Слайд 152.19 do/while Repetition Structure
Similar to while structure
Makes loop continuation test at

end, not beginning
Loop body executes at least once
Format
do {

statement
} while ( condition );

2.19	do/while Repetition StructureSimilar to while structureMakes loop continuation test at end, not beginningLoop body executes at least

Слайд 162.19 do/while Repetition Structure

2.19	do/while Repetition Structure

Слайд 171 // Fig. 2.24: fig02_24.cpp
2 //

Using the do/while repetition structure.
3 #include
4


5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 int counter = 1; // initialize counter
12
13 do {
14 cout << counter << " "; // display counter
15 } while ( ++counter <= 10 ); // end do/while
16
17 cout << endl;
18
19 return 0; // indicate successful termination
20
21 } // end function main

1 2 3 4 5 6 7 8 9 10

1   // Fig. 2.24: fig02_24.cpp2   // Using the do/while repetition structure.3

Слайд 182.20 break and continue Statements
break statement
Immediate exit from while, for, do/while,

switch
Program continues with first statement after structure
Common uses
Escape early from

a loop
Skip the remainder of switch

2.20	break and continue Statementsbreak statementImmediate exit from while, for, do/while, switchProgram continues with first statement after structureCommon

Слайд 191 // Fig. 2.26: fig02_26.cpp
2 //

Using the break statement in a for structure.
3

#include
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11
12 int x; // x declared here so it can be used after the loop
13
14 // loop 10 times
15 for ( x = 1; x <= 10; x++ ) {
16
17 // if x is 5, terminate loop
18 if ( x == 5 )
19 break; // break loop only if x is 5
20
21 cout << x << " "; // display value of x
22
23 } // end for
24
25 cout << "\nBroke out of loop when x became " << x << endl;

1   // Fig. 2.26: fig02_26.cpp2   // Using the break statement in a for

Слайд 2026
27 return 0; //

indicate successful termination
28
29 } // end function

main

1 2 3 4
Broke out of loop when x became 5

26  27    return 0;  // indicate successful termination28  29  }

Слайд 212.20 break and continue Statements
continue statement
Used in while, for, do/while
Skips remainder

of loop body
Proceeds with next iteration of loop
while and do/while

structure
Loop-continuation test evaluated immediately after the continue statement
for structure
Increment expression executed
Next, loop-continuation test evaluated
2.20	break and continue Statementscontinue statementUsed in while, for, do/whileSkips remainder of loop bodyProceeds with next iteration of

Слайд 221 // Fig. 2.27: fig02_27.cpp
2 //

Using the continue statement in a for structure.
3

#include
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 // loop 10 times
12 for ( int x = 1; x <= 10; x++ ) {
13
14 // if x is 5, continue with next iteration of loop
15 if ( x == 5 )
16 continue; // skip remaining code in loop body
17
18 cout << x << " "; // display value of x
19
20 } // end for structure
21
22 cout << "\nUsed continue to skip printing the value 5"
23 << endl;
24
25 return 0; // indicate successful termination

1   // Fig. 2.27: fig02_27.cpp2   // Using the continue statement in a for

Слайд 2326
27 } // end function main

1 2

3 4 6 7 8 9 10
Used continue to skip

printing the value 5

26  27  } // end function main1 2 3 4 6 7 8 9 10Used

Слайд 242.21 Structured-Programming Summary
Structured programming
Programs easier to understand, test, debug and modify
Rules

for structured programming
Only use single-entry/single-exit control structures
Rules
1) Begin with the

“simplest flowchart”
2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence
3) Any rectangle (action) can be replaced by any control structure (sequence, if, if/else, switch, while, do/while or for)
4) Rules 2 and 3 can be applied in any order and multiple times


 


 

2.21	Structured-Programming SummaryStructured programmingPrograms easier to understand, test, debug and modifyRules for structured programmingOnly use single-entry/single-exit control structuresRules1)

Слайд 252.21 Structured-Programming Summary
Representation of Rule 3 (replacing any rectangle with a

control structure)

2.21	Structured-Programming SummaryRepresentation of Rule 3 (replacing any rectangle with a control structure)

Слайд 262.21 Structured-Programming Summary
All programs broken down into
Sequence
Selection
if, if/else, or switch
Any

selection can be rewritten as an if statement
Repetition
while, do/while or

for
Any repetition structure can be rewritten as a while statement
2.21	Structured-Programming SummaryAll programs broken down intoSequenceSelectionif, if/else, or switch Any selection can be rewritten as an if

Слайд 27Readings:
C++ How to Program, By H. M. Deitel

Chapter 5. Control Statements: Part

Readings:C++ How to Program, By H. M. DeitelChapter 5. Control Statements: Part 2

Слайд 28Thanks for your attention!

Thanks for your attention!

Обратная связь

Если не удалось найти и скачать доклад-презентацию, Вы можете заказать его на нашем сайте. Мы постараемся найти нужный Вам материал и отправим по электронной почте. Не стесняйтесь обращаться к нам, если у вас возникли вопросы или пожелания:

Email: Нажмите что бы посмотреть 

Что такое TheSlide.ru?

Это сайт презентации, докладов, проектов в PowerPoint. Здесь удобно  хранить и делиться своими презентациями с другими пользователями.


Для правообладателей

Яндекс.Метрика