35
1 Repeating Repeating parts of your parts of your program program

Repeating parts of your program

  • Upload
    marnin

  • View
    30

  • Download
    1

Embed Size (px)

DESCRIPTION

Repeating parts of your program. 1. Repeating parts of your program. - PowerPoint PPT Presentation

Citation preview

Page 1: Repeating parts of  your program

1

Repeating Repeating parts of your parts of your

programprogram

Page 2: Repeating parts of  your program

2

A very large proportion of mathematical techniques rely on

some form of iterative process, while the processing of most

types of data requires the same or similar actions to be

carried out repeatedly for each set of data. One of the most

important of all programming concepts, therefore, is the ability

to repeat sequences of statements, either a predetermined

number of times or until some condition is satisfied.

F has a very powerful, simple to use, facility for controlling

the repetition of blocks of code.

The use of repetitive techniques, however, often leads to

situations in which it is requested to end the repetition earlier

than had been anticipated.

Repeating parts of your program

Page 3: Repeating parts of  your program

3

A “repetitive structure” or “loop” makes possible the repeated execution of one or more statements called “body of the loop”.

There are two basic types of repetition :

  “repetition controlled by a counter” , in which the body of the loop is executed once for each value of some control variable in a specified range of values.

 “repetition controlled by a logical expression”, in which the decision to continue or to terminate the repetition, is determined by the value of some logical expression.

Repeating parts of your program

Page 4: Repeating parts of  your program

4

Program Program repetitionrepetition

• In many cases, we have to repeat certain sections of a program

• Many numerical methods involve repetition/iteration

• We have to have construct to repeat a group of statements, to end the repetition, or to restart it when certain condition is fulfilled.

Page 5: Repeating parts of  your program

Consider this program – Average of 6 numbersreal x1, x2, x3, x4, x5, x6real sum, avgread*, x1read*, x2read*, x3read*, x4read*, x5read*, x6sum = x1 + x2 + x3 + x4 + x5 + x6avg = sum / 6.0print*, avgend

Page 6: Repeating parts of  your program

Using DO loop

real xreal sum, avgsum = 0do k = 1, 6

read*, xsum = sum + x

contınueavg = sum / 6.0prınt*, avgend

Page 7: Repeating parts of  your program

7

Repeat the following 3 steps 21 times considering 5oC intervals from 0oC till to 100oC without the need for any data to be read at all :

1.step : read the initial and last Celcius temperature

2.step : calculate the corresponding Fahrenheit temperature for 5oC intervals

3.step : print both tempratures

 A sequence of statements which are repeated is called a “loop.“

 The do – constructs provides the means for controlling the repetition of statements within a loop.

EXAMPLE for a TYPICAL CYCLE :

Page 8: Repeating parts of  your program

8

DO LOOP – TYPE 1

In this count-controlled do loop, the do variable is incremented by the unit value “1” on each pass starting from the initial_value (inclusive) till to the final_value (inclusive). 

 do count_variable = initial_value, final_value, step_size

Block of statements

end do 

count_variable : must be an integer

initial_value, final_value : are arbitrary expressions of integer type

step_size = 1 (default)

Page 9: Repeating parts of  your program

9

dodo constructconstruct

do count = initial, final, incblock of statementsend do

loop

count_variable : must be an integer

initial_value, final_value : are arbitrary expressions of integer type

selected step_size = inc : must be an integer

Page 10: Repeating parts of  your program

10

do number = 1, 10, 2

print *, number, number **2

end do

  print *, number, number **2

 OUTPUT produced will display following results :

1         1

3 9

5            25

7 49

9 81

 

Example

Page 11: Repeating parts of  your program

11

ExamplesExamplesdo statement iteration count do variable values 

do i = 1,10 10 1,2,3,4,5,6,7,8,9,10

do j = 20, 50, 5 7 20,25,30,35,40,45,50

do p = 7, 19, 4 4 7,11,15,19

do q = 4, 5, 6 1 4

do r = 6, 5, 4 0 (6)

do x = -20,20, 6 7 -20,-14,-8,-2,4,10,16

do n = 25, 0, -5 6 25,20,15,10,5,0

do m = 20, -20, -6 7 20,14,8,2,-4,-10,-16

do number = 1, 10, 2print *, number, number **2

end do

Page 12: Repeating parts of  your program

12

DO LOOP – TYPE 2

(controlled by logical expression)

The number of iterations cannot be determined in advance, and a more general repetition structure is required.

do

Block of statements_1

  if ( logical_expression) then

exit

else

block of statements_2

end do

Number=0

Do

Number=number+1

if (number>100) then

exit

else

Print *, number, number **2

endif

end do

Page 13: Repeating parts of  your program

13

!Please calculate sum and ave of given number students grade.program sumandaveofstudentgrade real::note,notesum,noteaveinteger::number,inotesum=0print*,"How mony student grade you want calculate"read*,numberdo i=1,number print*,"Please enter grade of student",i read*,note notesum=notesum+noteend doprint*,"Sum of students grade is:",notesumnoteave=notesum/numberprint*,"Average of students grade is:",noteave

end program sumandaveofstudentgrade

Page 14: Repeating parts of  your program

14

Program temp_fahr_convreal::t,ft=0dot=t+1

if (t>100) thenexit

end iff=t*1.8+32

write(unit=*,fmt=“(f5.1,a,f7.2,a)”)t,”C=”,f,”F”end doend program temp_fahr_conv

Page 15: Repeating parts of  your program

15

Count-controlled Count-controlled dodo loops loopsdo count = initial, final, incdo count = initial, final(inc = 1)Do

Iteration count:How many times we will go through the loop?

max((final-initial+inc)/inc, 0)iterations = ( stop + step - start ) / step

Integer variable

Page 16: Repeating parts of  your program

16

NESTED DO - LOOPS The body of a do loop may contain another do loop. In this case,the second do loop is said to be “nested” within the first do loop.

EXAMPLE :

 do m = 1, 4

do n = 1, 3

product 1 = m * n

Write(unit=*,fmt=“(3i5)” )m,n,product1

end do

end do

 

OUTPUT  

m n product

1 1 1

1 2 2

1 3 3

2 1 2

2 2 4

2 3 6

3 1 3

3 2 6

3 3 9

4 1 4

4 2 8

4 3 12

Page 17: Repeating parts of  your program

17

More More flexibility...flexibility...For do – loops especially defined as Type 1, it is needed a control statement in order to control the cycles, otherwise it is possible to have an “infinite loop”.

Using the command “ exit “ all the remaining statements in the loop are omitted and thus, a transfer of control following the “ end do ” statement is obtained.

Thus, an “exit“ statement can cause termination of a current/indexed

do - construct before the do variable value goes beyond the final or limit value.

Page 18: Repeating parts of  your program

18

Some flexibility...Some flexibility...

do ...if (condition) then

exitend if

.

.

.end do.

Page 19: Repeating parts of  your program

19

As mentioned before, exit statement causes repetition of a loop to terminate by transfering control to the statement following the “end do”. 

On the other hand, sometimes it is necessary to terminate only the current repetition and then jump ahead to the next one. 

F provides the “cycle” statement for this purpose.

Some more flexibility...Some more flexibility...

Page 20: Repeating parts of  your program

20

Some more flexibility...Some more flexibility...

do ...if (condition) then

cycleend if

.

.

.end do.

Page 21: Repeating parts of  your program

21

PROBLEM : Suppose that in the temprature-conversion only temprature of 0oC or above values are wanted to convert. program convert1real::celcius,fahrcharacter(len=1)::kontroldo print"(a)","Sicaklığı Cel cinsinden giriniz : cikis icin Q giriniz" read"(f5.1)",celcius if ( celcius < 0.0 ) then print *, " given temprature must be 0.0 or above" cycle else fahr=celcius*1.8+32 print*,celcius," is ",fahr print*,"Cikis icin Q" read*,kontrol if (kontrol=="Q") then exit end if endifend doend program convert1

Page 22: Repeating parts of  your program

22

Naming your Naming your dodo constructs constructs

[name:] DO [control clause] block

END DO [name]

Especially in “nested do–loops” it’s very difficult to control the transfer of the program. As mentioned before an “exit“ statement in the example seen below, will transfer control to the first executable statement following the second “ end do ”.

On the other hand, there will be occasions when it is required to exit from all of the enclosing loops; or even from more than the immediately enclosing or current loop, but not from all of them.

For this reason it is strongly recommended to use “named do – constructs” by preceding the do statement by a name as is seen below :

Page 23: Repeating parts of  your program

23

Naming your Naming your dodo constructs constructsouter: DO i=1,10inner1: DO IF( x<0 ) EXIT ! exit loop inner1 IF( x==0 ) EXIT outer ! exit loop outer ... END DO inner1inner2: DO IF( x<0 ) CYCLE ! cycle loop inner2 IF( x==0 ) CYCLE inner1 ! illegal ... END DO inner2 ... END DO outer

Page 24: Repeating parts of  your program

24

number: DO i=1,100 WRITE(*,*) i ! write numbers 1 to 100

END DO number

dontwrite: DO j=100,1 WRITE(*,*) j ! no WRITE statement executed

END DO dontwrite

decr: DO k=100,1,-3 WRITE(*,*) k ! write numbers 100,97,94

END DO decr

Page 25: Repeating parts of  your program

25

INTEGER :: value=0, total=0 ... sum: DO

READ(*,*) value ! read in a number IF (value==0) EXIT sum ! if nothing to add, exit loop total = total + value ! calculate running total

END DO sum

program doloopinteger::ii,istart=1,ilast=100,istep=3,isumdo ii=istart,ilast,istep isum = isum + ii

print*,isumEnd doend program doloop

Page 26: Repeating parts of  your program

26

Dealing with exceptional situations: Dealing with exceptional situations: There are occasionally situations in which the statements used before are inconvenient or make programming very difficult. Thus, two additional statements exist to help us in these exceptional situations. These are, 

STOP : this statement terminates the execution without to need to find a way of reaching the “end” statement of the main program unit. This word “stop” causes execution of the program to be terminated immediately. 

RETURN : this statement causes a return from a procedure without the need to find a way of reaching the “end” statement of the procedure. This word “return” causes execution of the procedure to be terminated immediately and control transferred back to the program unit which called or referenced the procedure.

Page 27: Repeating parts of  your program

27

Dealing with exceptional situations: Dealing with exceptional situations:

• stop statement– simply terminates execution

• return statement– causes execution of the procedure to be

terminated immediately and control transferred back to the program unit which called or referenced the procedure

Page 28: Repeating parts of  your program

Syntax examples of control constructs: Syntax examples of control constructs:

28

if (number > maximum) then number = maximum else if (number < minimum) then number = minimum

end if select case (n+no)

case (3) x = 34.3

case default x = 1.0 / x

end select do j = 1,100

if ( j <= 50) then k = j - 4 print *, k cycle end if print *, j

end dodoname: do

if ( value > climate_index) then exit doname

end if value = new_value end do doname

Page 29: Repeating parts of  your program

29

program can_pressure! This program calculates the pressure inside the can

real :: T,pressureT=15.0control:do

T=T+1pressure=(0.00105*(T**2))+(0.0042*T)+1.352

if (pressure>3.2) thenexit control

end ifprint *,"The pressure inside the can is",&

pressure," atm at",T," degree C"end do controlend program can_pressure

Page 30: Repeating parts of  your program

30

program examination_marks! This program prints statistics about a set of exam results! variable declerations

integer :: i,number,mark,maximum,minimum,totalreal :: average

! initialize variabletotal = 0

! read number of marks , and then the marksprint *,"how many marks are there" read *,numberprint *," please type ",number," marks, one per line"

! Loop to read and process marksdo i = 1 , numberread *, mark

! initialize max. and min. marks for only the first loop. if (i==1) then! this if construct is executed for the case only i=1. maximum = mark minimum = mark end if! on each pass ,update sum,maximum and minimum

total = total + markif (mark > maximum)then maximum = markelse if (mark < minimum)then minimum = mark end if end do

!! calculate average mark and print out resultsaverage = real(total) / numberprint *,"highest mark is",maximum,"lowest mark is",minimum,"average mark

is",averageend program examination_marks

Page 31: Repeating parts of  your program

31

program lever! This program calculates the effort required for levers of lengths! differing in steps 2 metresinteger ,parameter :: load=2000,d2=2integer :: d1,n,mreal :: effortprint *,"please type the min limit of distance n and max limit c m"read *,n,mdo d1 = n , m , 2effort = real(load)*real(d2)/real(d1)print *,"The required effort when d1=",d1," m."," is",effort," kg"end doend program lever

Page 32: Repeating parts of  your program

32

program loop_test1integer :: i,j,k,l,m,ni=1j=2k=4l=8m=0n=0do i=j,k,l

k=ido j=l,m,k

n=jdo k=l,n

do l=i,km=k*l

end doend do

end doend doprint *,i,j,k,l,m,nend program loop_test1

!This program written to understand do loop

Page 33: Repeating parts of  your program

33

!Write a program to calculate the international paper sizes

program paper_sizeinteger :: nreal :: cm,inch,p1,p2do n = 0,6

p1 = 0.25 - n/2.0p2 = -0.25 - n/2.0cm = (2.0**p1 * 2.0**p2)*100.0inch = cm/2.54print *,"A",n," is",cm," cm"," and",inch," inch"

end doend program paper_size

Page 34: Repeating parts of  your program

!Write a program to calculate TAX depending on total incomeprogram exercise_2!taxation parameter declarationsinteger, parameter ::first=5000,second=15000 real,parameter::first_per=0.10,second_per=0.25,next_per=0.30!variable declarationinteger :: income, total_tax!read the incomeprint *," Type total income in US dollars"read *, income!do if blocksif (income <= first) then!first slicetotal_tax = first_per*incomeelse if (income > first .and. income < second) thentotal_tax = second_per*incomeelsetotal_tax = next_per*incomeend if!print the resultprint *," total income = ",incomeprint *," total tax charged = ",total_taxend program exercise_2

Page 35: Repeating parts of  your program

35

??????Bir kişiye 80 defa deli dersek

ZIR DELİ olurmuş

Bir kişi 80 program yazarsa ne olur

???