1. Trang chủ
  2. » Công Nghệ Thông Tin

C++ lecture 6

27 7 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 27
Dung lượng 340 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

type of control structure in which part of the code is repeated number of times...  Mainly you use while , and do/while control structures for this type of looping. In this type you kn

Trang 2

Outline

Trang 3

selection control structures.

type of control structure in which part of the code is repeated number of times.

 while.

 for.

 do/while.

Trang 4

 Mainly you use while , and do/while control structures for this type of looping.

 In this type you know the number of times the body of the loop must be repeated, i.e the

number of loop iterations is defined in advance.

 Mainly you use for control structures for this type

of looping.

Trang 5

while Repetition Structure

while loop repeated until condition becomes false where

the next line of code after while loop will be executed.

int product = 2;

while ( product <= 1000 ) product = 2 * product;

contained within the braces after the while,

otherwise it is the first statement after the while

only.

Trang 6

while Repetition Structure II

Flowchart of while loop.

 Infinite loop:

Logical error in the while

structure.

 The condition of the

while is always true, i.e

the body of the while

loop does not modify the

condition value.

 Leaving the parenthesis

after the while empty

(i.e you do not specify

Trang 7

Essentials of Controlled Repetition

Counter- Counter-controlled repetition requires:

 The name of a control variable (or loop counter).

 The initial value of the control variable.

 The condition that tests for the final value of the control variable (i.e., whether looping should continue) (check counter value with the condition)

 The increment (or decrement) by which the control variable is modified each time through the loop

}

//the while body will execute 10 times

int counter =1; //initialization

while (counter <= 10){ //repetition

condition

cout << counter << endl

++counter; //increment

}

Trang 8

for Repetition Structure I

 Handles all the details of counter-controlled repetition in a concise way.

The general format when using for loops is:

for (initialization; LoopContinuationTest; increment/decrement )

statement

 Example:

for( int counter = 1; counter <= 10; counter++ )

cout << counter << endl;

 Prints the integers from one to ten

Pay attention to the off-by-one error.

Trang 9

for Repetition Structure II

After the condition of the for is violated, the first

statement after the for loop is executed.

exist) otherwise it is the first statement after for

}

for (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl; //how many time this statement will execute

Trang 10

for Repetition Structure III

Scope of the counter variable defined inside for

loop differs based on the used C++ compiler:

Known only inside for structure.

 Or known inside the whole program after the for

loop  this is what is applicable for our case.

The three parts of the for loop are optional, if the

condition is omitted this will create an infinite

loop since the compiler assumes that the for

condition is true.

 What will happen if you omit one of the parts of the for loop and you have not modified it inside its body?? (Hint: check for infinite loops).

for loop parts can contain arithmetic expressions.

Flowchart of the for loop is similar to the while

loop.

Trang 11

While and for example

 for (int z=8;z>0;z-=3)

cout<<”welcome”; // this will execute 3 times only

 for (int counter=-21;counter<3;counter*=-2)

cout<<“hi”; //this will execute ONE time

 for (int counter=-21;counter>3;counter*=-2)

cout<<“hi”; //this will never execute

Convert the following for loop into while loop

for (int loop=5; loop>=5&&loop<10;loop++)

cout<<“ok”;

 How many times this loop will repeat ??

for (int counter=30;counter>0;counter/=2)

cout<<“hi”<<endl;

int loop=5;

While (loop>=5 &&

loop<10) {

cout<<“ok”;

loop++;

}

Trang 12

do while Repetition

Structure I

The do/while repetition structure is similar to the while

structure except that

 Condition for repetition tested after the body of the loop is executed

 Format:

do { statement } while ( condition );

 Example (letting counter = 1):

do { cout << counter << " ";

} while (++counter <= 10);

This prints the integers from 1 to 10

 Pay attention to post/pre increment/decrement Does it has any effect?

All actions are performed at least once.

Trang 13

condition

Trang 14

The two for loops above will print loop 4 times There is no difference

if the increment/decrement is pre or post inside the third part of the for loop statement.

Trang 15

Examples (2)

 Always be careful with the pre or post condition when applied

to the while or do/while repetition

int count=-3;

do {

cout<<"loop“<<endl;

}while(count++); // loop will be

printed 4 times on the

screen

int count=-3;

do { cout<<"loop“<<endl;

}while(++count); // loop will be printed 3 times on the

screen

Trang 16

break Statement

break

do/while or switch structure

statement after the structure

 Escape early from a loop

Skip the remainder of a switch structure

inside if/else) statement is a syntax error.

Trang 17

continue Statement

of a while, for or do/while structure and

proceeds with the next iteration of the loop

test is evaluated immediately after the

continue statement is executed

increment/decrement expression is executed, then the loop-continuation test is evaluated

(e.g inside if/else) statement is a syntax

error.

Trang 18

A class of ten students took a quiz The

grades (integers in the range 0 to 100) for this quiz are available to you Determine the class average on the quiz

Trang 19

The Hashemite University 19

11 int total, // sum of grades

12 gradeCounter, // number of grades entered

13 grade, // one grade

14 average; // average of grades

15

16 // initialization phase

17 total = 0; // clear total

18 gradeCounter = 1; // prepare to loop

19

20 // processing phase

21 while ( gradeCounter <= 10 ) { // loop 10 times

22 cout << "Enter grade: "; // prompt for input

23 cin >> grade; // input grade

24 total = total + grade; // add grade to total

25 gradeCounter = gradeCounter + 1; // increment counter

26 }

27

28 // termination phase

29 average = total / 10; // integer division

30 cout << "Class average is " << average << endl;

31

32 return 0; // indicate program ended successfully

The counter gets incremented each time the loop executes Eventually, the

counter causes the loop to end.

Trang 21

Example II: (Sentinel-Controlled

Repetition)

Develop a class-averaging program that will process an arbitrary number of grades each time the program is run.

 Unknown number of students - how will the program know to end?

 Indicates “end of data entry”

 Loop ends when sentinel inputted

 Sentinel value chosen so it cannot be

confused with a regular input (such as -1 in this case)

Trang 22

The Hashemite University 22

17 int total, // sum of grades

18 gradeCounter, // number of grades entered

19 grade; // one grade

20 double average; // number with decimal point for average

Trang 23

31 total = total + grade;

39 average = static_cast < double >( total ) / gradeCounter;

40 cout << "Class average is " << setprecision( 2 )

41 << setiosflags( ios::fixed | ios::showpoint )

Enter grade, -1 to end: 75

Enter grade, -1 to end: 94

Enter grade, -1 to end: 97

Enter grade, -1 to end: 88

Enter grade, -1 to end: 70

Enter grade, -1 to end: 64

Enter grade, -1 to end: 83

Enter grade, -1 to end: 89

Enter grade, -1 to end: -1

| - separates multiple option.

setprecision(2) - prints only two digits

past decimal point.

Programs that use this must include <iomanip>

static_cast<double>() - treats total as a

Trang 24

Example III: Nested control structures

A college has a list of test results (1 = pass, 2 = fail)

for 10 students Write a program that analyzes the results If more than 8 students pass, print "Raise

Tuition".

 The program must process 10 test results A controlled loop will be used

counter- Two counters can be used—one to count the number

of students who passed the exam and one to count the number of students who failed the exam

 Each test result is a number—either a 1 or a 2 If the number is not a 1, we assume that it is a 2

Trang 25

The Hashemite University 25

11 // initialize variables in declarations

12 int passes = 0, // number of passes

13 failures = 0, // number of failures

14 studentCounter = 1, // student counter

15 result; // one exam result

Trang 26

The Hashemite University 26

31 cout << "Passed " << passes << endl;

32 cout << "Failed " << failures << endl;

Enter result (1=pass,2=fail): 1

Enter result (1=pass,2=fail): 1

Enter result (1=pass,2=fail): 1

Enter result (1=pass,2=fail): 1

Enter result (1=pass,2=fail): 2

Enter result (1=pass,2=fail): 1

Enter result (1=pass,2=fail): 1

Enter result (1=pass,2=fail): 1

Enter result (1=pass,2=fail): 1

Enter result (1=pass,2=fail): 1

Passed 9

Failed 1

Raise tuition

Ngày đăng: 12/10/2021, 21:08