38
Chapter 5: Repetition and Loop Statements - for - while - do while Maltepe University Computer Engineering Department Algorithms and Programming

Algorithms and Programming Chapter 5: Repetition and … 5: Repetition and Loop Statements ... • There are three C loop control statements: –for, while, and do-while. 3 Writing

Embed Size (px)

Citation preview

Chapter 5: Repetition and Loop Statements

- for

- while

- do while

Maltepe University

Computer Engineering Department

Algorithms and Programming

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-2

Repetition in Programs

• In most software, the statements in the

program may need to repeat for many times.

– e.g., calculate the value of n!.

– If n = 10000, it’s not elegant to write the code as

1*2*3*…*10000.

• Loop is a control structure that repeats a

group of steps in a program.

– Loop body stands for the repeated

statements.

• There are three C loop control statements:

– for, while, and do-while.

3

Writing Pseudocode – Loop

• In computer programming, a loop is a sequence of instructions that

is continually repeated until a certain condition is reached.

• Typically, a certain process is done, such as getting an item of data

and changing it, and then some condition is checked such as

whether a counter has reached a prescribed number.

• If it hasn't, the next instruction in the sequence is an instruction to

return to the first instruction in the sequence and repeat the

sequence.

• If the condition has been reached, the next instruction "falls

through" to the next sequential instruction or branches outside the

loop.

• A loop is a fundamental programming idea that is commonly used

in writing programs.

http://whatis.techtarget.com/definition/0,,sid9_gci212500,00.html

Example: Write an algorithm adding integers from 1-10 and display

the result on the screen.

input: None.

output: Sum of the integers from 1-10.

1. Start

2. sayi=1

3. toplam=0

4. toplam=toplam+sayi

5. sayi=sayi+1

6. If (sayi<=10), go to step 4

7. Write toplam on the screen

8. Finish 4

Writing Pseudocode – Loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-5

Comparison of Loop Choices

Kind When to Use C

Structure

Counting loop We know how many

loop repetitions will be

needed in advance.

for, while

Sentinel-

controlled loop

Input of a list of data

ended by a special value

while, for

Endfile-

controlled loop

Input of a list of data

from a data file

while, for

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-6

Comparison of Loop Choices

(cont.)

Kind When to Use C

Structure

Input

validation loop

Repeated interactive

input of a value until a

desired value is

entered.

do-while

General

conditional

loop

Repeated processing of

data until a desired

condition is met.

while, for

• The syntax of for statement in C:

for (initialization expression;

loop repetition condition;

update expression)

statement;

• The initialization expression set the initial value

of the loop control variable.

• The loop repetition condition test the value of

the loop control variable.

• The update expression update the loop control

variable. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-7

The for Statement in C

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

4-8

Flowchart of a for loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

4-9

Flowchart2 of a for loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-10

An Example of a for loop

Loop repetition

condition

Initialization Expression

Update Expression

count_emp is set to 0 initially.

count_emp should not exceed the value of

number_emp.

count_emp is increased by one after each iteration.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-11

Increment and Decrement Operators

• The statements of increment and decrement

are commonly used in the for loop.

• The increment (i.e., ++) or decrement (i.e., --

) operators are the frequently used

operators which take only one operand.

• The increment/decrement operators

increase or decrease the value of the single

operand.

– e.g., for (int i = 0; i < 100; i++){ … }

– The variable i increase one after each iteration.

• The syntax of while statement in C:

while (loop repetition condition)

statement;

• Loop repetition condition is the condition

which controls the loop.

• The statement is repeated as long as the

loop repetition condition is true.

• A loop is called an infinite loop if the loop

repetition condition is always true.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-12

The while Statement in C

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

4-13

Flowchart for a while Loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-14

Flowchart for a while Loop - example

Loop repetition

condition

Statement

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-15

An Example of a while Loop

Statement

Loop repetition condition for 7 employees

Loop control variable is the variable whose value

controls loop repetition.

In this example, count_emp is the loop control variable.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-16

Multiplying a list of numbers read from the

keyboard until product is less than 1000, and

display result on the screen.

1. Start

2. product=1

3. Read number

4. product=product*number

5. If (product<1000), go to step 3

4. Write product

5. Finish

Example:

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-17

Sentinel-Controlled Loops

• Sometimes we may not know how many

times the loop will repeat.

• One way to do this is to choose a sentinel

value as an end marker.

– The loop exits when the sentinel value is read.

• If the user wish to exit the loop, he or she

has to input the sentinel value.

– It is similar to the “logout” function in many

applications.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

4-18

Sentinel Loop

1. Initialize sum to zero.

2. Get first score.

3. while (score is not the sentinel)

Add score to sum

Get next score

Incorrect Sentinel Loop

1. Initialize sum to zero.

2. while (score is not the sentinel)

Get next score

Add score to sum

You can use do-while loop for this kind of cases.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-19

An Example of Sentinel-Controlled

while Loops

If the user wish to exit the loop,

he or she has to input -99.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-20

Flag Controlled Loops

• Sometimes a loop repetition condition becomes so

complex that placing the full expression in its usual spot

is awkward.

• In many cases, the condition may be simplified by using

a flag.

while (flag)

{

….

}

• A flag is a type int variable used to represent whether or

not a certain event has occurred.

• A flag has one of two values: 1 (true) and 0 (false).

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-21

Do While statement

• Both the for statement and the while statement evaluate the loop condition before the first execution of the loop body.

• In most cases, this pretest is desirable and prevents the loop from executing when there may be no data items to process

• There are some situations, generally involving interactive input, when we know that a loop must execute at least one time.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-22

The do-while Statement in C

• The syntax of do-while statement in C:

do

statement

while (loop repetition condition);

• The statement is first executed.

• If the loop repetition condition is true, the

statement is repeated.

• Otherwise, the loop is exited.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-23

An Example of the do-while Loop

/* Find even number input */

do {

printf(“Enter an even value: ”);

scanf(“%d”, &num);

} while (num % 2 !=0)

This loop will repeat if the

user inputs odd number.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-24

Do-While Example

do

{

printf("Enter a letter from A through E> ");

scanf("%c", &letter_choice);

} while (letter_choice < ’A’ || letter_choice > ’E’);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-25

Compound Assignment Operators

• The loop body usually consists of

statements of the form: variable = variable

op expression.

– e.g., count_emp = count_emp + 1;

• C provides compound assignment

operators which enable a more concise

notation for this kind of statements.

– “variable op = expression” is the same to

“variable = variable op expression.”

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-26

Compound Assignment Operators

Simple Assignment

Operators

Compound

Assignment Operators

count_emp = count_emp+1; count_emp += 1;

time = time -1; time -= 1;

product = product * item; product *= item;

total = total / number; total /= number;

n = n % (x+1); n %= x+1;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-27

Comparison of Prefix and Postfix

Increments

The value of the expression (that uses the ++/--

operators) depends on the position of the operator.

The value

of j is

increased

The value

of j is not

increased

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-28

Nested Loops

• Usually used to work with two dimensional arrays

(later).

• Nested loops consist of an outer loop with one or

more inner loops.

• Each time the outer loop is repeated, the inner

loops are reentered

– Their loop control expressions are reevaluated

– All required iterations are performed again.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-29

Nested Loops

• Nested loops consist of an outer loop with

one or more inner loops.

• e.g.,

for (i=1;i<=100;i++){

for(j=1;j<=50;j++){

}

}

• The above loop will run for 100*50

iterations.

Inner loop

Outer

loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 4-30

Flowchart for a nested for loop

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-31

What is the Output?

x = 1;

sum = 0;

while (x <= 100)

{

y = 1;

while (y <= 100)

{

sum = sum + 1;

y++;

}

x++;

}

printf(“Sum is %d\n”, sum);

/* Output = */

Sum is 10000

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-32

What is the Output?

int a=0, b=0, sum=0;

for(a=0; a<6; a+=2)

for(b=0; b>4; b--)

sum=sum+1;

printf(“%d”,sum);

/* Output = */

Sum is 0

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-33

In class work

• Write a program that prompts the user to

input an integer n.

• Draw a triangle with n levels by star

symbols. For example,

n = 3,

*

**

***

• After drawing the triangle, repeat the above

process until the user input a negative

integer.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-34

In class work #4

• An usage scenario:

Please input: 2

*

**

Please input: 3

*

**

***

Please input: -9

Thank you for using this program.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5-35

#include <stdio.h>

int main(void) {

FILE *inp;

int sum = 0, score, input_status;

inp = fopen("scores.dat", "r");

input_status = fscanf(inp, "%d", &score);

while (input_status != EOF)

{

printf("%d ", score);

sum += score;

input_status = fscanf(inp, "%d", &score);

}

printf("\nSum of exam scores is %d\n", sum);

fclose(inp);

return 0;

} /* Output */

55 33 77

Sum of exam scores is 165

Not included

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-36

What is the Output?

int i, sum=0,status=0;

status = scanf(“%d”,&i);

while(status!=EOF)

{

sum+=i;

status = scanf(“%d”,&i);

}

printf(“%d\n”, sum);

/* Input = */

2

4

6

ctl-d

/* Output = */

12

Not included

Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-37

Endfile-controlled loops

• Many library functions return helpful data as the value of

the function.

• For example, scanf returns the number of data items it

actually obtained.

num = scanf(“%d%d%d”, &n1, &n2, &n3);

• A data file is always terminated by an endfile character

(EOF) that can be detected by the scanf and fscanf

functions.

• You can write a program that processes a list of data of

any length from a file without requiring a special sentinel

value at the end of the data file.

Not included

Copyright ©2004 Pearson

Addison-Wesley. All rights

reserved. 5-38

An Example of Endfile-Controlled Loops

• fscanf is a

function

used to

read file.

• EOF stands

for the

special

value of

end-file

returned by

fscanf.

• This loop

repeats

until

reading the

end of the

file.

Not included