iterative/loop/repetition statements revision

32
Iterative/Loop/Repetition Statements Revision Week 02-part1 CC213:Programming A pplications

Upload: others

Post on 18-Dec-2021

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Iterative/Loop/Repetition Statements Revision

Iterative/Loop/Repetition Statements Revision

Week 02-part1

CC213:Programming Applications

Page 2: Iterative/Loop/Repetition Statements Revision

2

• Repetition in Programs –why?

• Counting Loops – Using while statement • Compoundassignment operators

– Using for statement • Increment and Decrement Operators

• Conditional Loops – – – –

sentinel-Controlled loops Nested loop Do-While loop Flag-Controlled loop

Overview

Page 3: Iterative/Loop/Repetition Statements Revision

3

• We have learned how to write code that chooses between multiple alternatives.

• It is also useful to be able to write code that repeats an action. Usually these actions either drawing or computations.

• Determine whether loops will be required in the general algorithm and if so which loop structure to choose from.

Repetition in Programs

Page 4: Iterative/Loop/Repetition Statements Revision

Flow Diagram of Loop Choice Process

4

Page 5: Iterative/Loop/Repetition Statements Revision

5

Two Types of Loops

count controlled loops

repeat a specified number of times

event-controlled loops

some condition within the loop body

changes and this causes the repetetion to

stop

Page 6: Iterative/Loop/Repetition Statements Revision

6

while Statement

SYNTAX

while ( Expression )

{ .

. /*loop body */

.

}

NOTE: Loop body can be a single

statement, a null statement, or a block.

Page 7: Iterative/Loop/Repetition Statements Revision

• This slide shows a program fragment that computes and displays the gross pay for seven employees. The loop body is the compound statements (those between { and }). • The loop repetition condition controls the while loop. count_emp = 0;

while (count_emp < 7) {

loop repetition condition

printf("Hours> "); scanf("%d",&hours);

printf("Rate> "); scanf("%lf",&rate);

pay = hours * rate;

printf("Pay is $%6.2f\n", pay);

count_emp = count_emp + 1;

}

printf("\nAll employees processed\n"); 6

while Statement Example

Page 8: Iterative/Loop/Repetition Statements Revision

8

Every while loop will always contain three main

elements:

Priming: initialize your variables.

Testing: test against some known condition.

Updating: update the variable that is tested.

Parts of a While Loop

• If any of these are skipped it may produce an infinite loop

Page 9: Iterative/Loop/Repetition Statements Revision

7

• Parts of the while Statement in previous example: – Initialization. i.e. count_emp = 0;

– Testing. i.e. count_emp < 7

– Updating i.e. count_emp = count_emp + 1;

Parts of a While Loop

• In the previous example we had count_emp < 7, but we may have more or less than 7 employees.

• To make our program fragment more general we should use a printf/scanf to get the number of employees and store it is num_emp.

• Now we can have count_emp < num_emp and our code is more general.

Page 10: Iterative/Loop/Repetition Statements Revision

10

int count ;

count = 4; /* initialize loop variable */

while (count > 0) /* test expression */

{

printf(“ %d \n ”,count ) ; /* repeated action */

count -- ; /*update loop variable */

}

printf( “Done” ) ;

Count-controlled Loop

1. Priming

2. Test Condition

3. Update

Page 11: Iterative/Loop/Repetition Statements Revision

9

• If we want to compute: we need to go 1+2+3+...+100

• We can use a while loop. /* computes the sum: 1 + 2 + 3 + ....+ 100 */

#include <stdio.h> int main(void) {

int sum =0, i = 1; while (i <= 100) {

sum = sum + i;

i = i + 1;

}

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

return 0;

}

Computing sum

100

1i

i

Page 12: Iterative/Loop/Repetition Statements Revision

12

• A loop that never ends.

•Generally, you want to avoid these!

•There are special cases, however, when you do want to create infinite loops on purpose.

Infinite loop

Page 13: Iterative/Loop/Repetition Statements Revision

13

#include <stdio.h>

#define MAX 10

main ()

{

int index =1;

while (index <= MAX)

{

printf ("Index: %d\n", index);

}

}

Infinite While Loop

1. Priming

2. Test Condition

3. Where is the update part

Index: 1

Index: 1

Index: 1

Index: 1

Index: 1

… [forever]

Page 14: Iterative/Loop/Repetition Statements Revision

14

#include <stdio.h>

/* no MAX here */

main ()

{

int index =1;

while (index > 0)

{

printf ("Index: %d\n", index);

index = index + 1;

}

}

Infinite While Loop

1. Priming

2. Test Condition

3. Update

Index: 1

Index: 2

Index: 3

Index: 4

Index: 5

… [forever]

Page 15: Iterative/Loop/Repetition Statements Revision

15

Basic for Loop Syntax

For loops are good for creating definite/counting loops.

int counter;

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

printf ("%d\n", counter);

1. Priming: Set

the start value.

2. Test Condition:

Set the stop value.

3. Update: Update the

value.

Note that each section is

separated by a semicolon.

Page 16: Iterative/Loop/Repetition Statements Revision

11

• To compute the sum of 1 to 100: int sum = 0;

int i;

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

{

sum = sum + i;

}

• Note: i++ is the same as i = i + 1

and as i += 1.

for Statement Example

Page 17: Iterative/Loop/Repetition Statements Revision

12

for (initialize; test; update)

{

//Steps to perform each iteration }

1. First, the initialization expression is executed. 2. Then, the loop repetition condition is tested. 3. If the condition is true, the statement enclosed in { } are executed. 4. After that the update expression is evaluated. 5. Then the loop repetition condition is retested.

• The statement is repeated as long as the condition is true. • For loop can be used to count up or down by any interval.

General form of for Statement

Page 18: Iterative/Loop/Repetition Statements Revision

13

Increment and Decrement Operators

• The counting loops that we have seen have all included assignment expressions of the form counter = counter + 1 or counter++

or counter += 1

• This will add 1 to the variable counter. If we use a - instead of a +, it will subtract 1 from the variable counter.

• Be careful about using the ++ or -- options.

Page 19: Iterative/Loop/Repetition Statements Revision

Increment and Decrement Other Than 1

• Instead of adding just 1, we can use sum = sum + x or sum += x

• Both of these will take the value of sum and add x to it and then assign the new value to sum.

14

• We can also use temp = temp -x or temp -= x

• Both of these will take the value of temp and subtract x from it and then assign the new value to temp.

Page 20: Iterative/Loop/Repetition Statements Revision

15

• In many programming situations, we will not be able to determine the exact number of loop repetitions before loop execution begins.

• Next is an example where we do not know how many times our program will repeat.

Event/Conditional controlled

Loops

Page 21: Iterative/Loop/Repetition Statements Revision

21

Event controlled loop Flag-controlled Loops

• How are they used?

– Programmer picks a value that would never be encountered for normal data

– User enters normal data and then when done,

enters the unusual value – The loop would stop when seeing the unusual

value

Page 22: Iterative/Loop/Repetition Statements Revision

Example

• We need a program that prompts the user for a value and multiplies it by the value of the variable temp. It then stores the result in temp. It keeps doing this until the user enters a

0.

• The outline of the program would be as follows:

16

assign temp the value of 1

prompt the user for a value

while value does not equal 0

assign temp the value of temp times value prompt the user for a value

output the value of temp

Page 23: Iterative/Loop/Repetition Statements Revision

Program Fragment

temp = 1;

printf("Enter a value, 0 will stop the program> ");

scanf("%d",&value);

while(value != 0) {

temp = temp * value; printf("Enter a value, 0 will stop the program>");

Initialization

Testing

17

scanf("%d",&value);

}

printf("The product is %d", temp);

Update

Page 24: Iterative/Loop/Repetition Statements Revision

24

do-while Statement Is a looping control structure in which the loop

condition is tested after each iteration of the loop.

SYNTAX

do

{

Statements

} while ( Expression ) ;

Loop body statement can be a single statement or a block.

Page 25: Iterative/Loop/Repetition Statements Revision

25

Computing Sum

If we want to compute , we need to go

1+2+3+...+100

/* computes the sum: 1 + 2 + 3 + ....+ 100 */

#include <stdio.h>

int main(void)

{

…..

……

……

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

return 0; }

100

1i

i

Page 26: Iterative/Loop/Repetition Statements Revision

• 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

18

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.

The do-while Statement

Page 27: Iterative/Loop/Repetition Statements Revision

do-while Example

19

#include<stdio.h>

#define m_in_km 1.606

void main(){

float m,km;

char d;

do{

printf("Enter distance in miles> ");

scanf("%f",&m);

km=m_in_km * m;

printf("\n\n %f miles is %f kms\n",m,km);

printf("Do you want another conversion? <enter y to continiue>");

fflush(stdin); //in order for scanf( “%c”…) to work properly

scanf("%c",&d);

}while(d=='Y'||d=='y');

printf("thank you for using our software...");

}

Page 28: Iterative/Loop/Repetition Statements Revision

28

do-while Loop vs. while Loop

POST-TEST loop

(exit-condition)

The looping condition

is tested after

executing the loop

body.

Loop body is always

executed at least

once.

PRE-TEST loop

(entry-condition)

The looping condition

is tested before

executing the loop

body.

Loop body may not be

executed at all.

Page 29: Iterative/Loop/Repetition Statements Revision

20

• 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.

Nested Loops

Page 30: Iterative/Loop/Repetition Statements Revision

What is the Output? /* * Illustrates a pair of nested counting loops */ #include <stdio.h> Int main(void) {

21

int i, j; /* loop control variables */ printf(" I J\n"); for (i = 1; i < 4; i++) { printf("Outer %6d\n", i); for (j = 0; j < i; j++) { printf(" Inner%9d\n", j); } /* end of inner loop */ } /* end of outer loop */ return (0);

}

I

1 2 3

//output: Outer

Inner

Outer

Inner

Inner

Outer

Inner

Inner

Inner

J 0 0

1 0

1

2

Page 31: Iterative/Loop/Repetition Statements Revision

Compound Assignment Operators

• Several times we have seen: variable = variable <operator> expression; Example: sum = sum + i;

• where <operator> is a C operator

22

• This occurs so often, C gives us short cuts.

• Instead of writing x = x +1 we can write: x += 1.

• We can use -=, *=, /=, and %= in the same way.

Page 32: Iterative/Loop/Repetition Statements Revision

The End