1 / 35

Repeating parts of your program

Repeating parts of your program. 1. Repeating parts of your program.

marnin
Download Presentation

Repeating parts of your program

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Repeating parts of your program 1

  2. Repeating parts of your program 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. 2

  3. Repeating parts of your program 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. 3

  4. Program repetition • 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. 4

  5. Consider this program – Average of 6 numbers real x1, x2, x3, x4, x5, x6 real sum, avg read*, x1 read*, x2 read*, x3 read*, x4 read*, x5 read*, x6 sum = x1 + x2 + x3 + x4 + x5 + x6 avg = sum / 6.0 print*, avg end

  6. Using DO loop real x real sum, avg sum = 0 do k = 1, 6 read*, x sum = sum + x contınue avg = sum / 6.0 prınt*, avg end

  7. EXAMPLEfor a TYPICAL CYCLE : 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 statementswithin a loop. 7

  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_sizeBlock of statements end do count_variable : must be an integer initial_value, final_value : are arbitrary expressions of integer type step_size = 1 (default) 8

  9. do construct do count = initial, final, inc block of statements end 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 9

  10. Example do number = 1, 10, 2 print *, number, number **2 end do print *, number, number **2  OUTPUT produced will display following results : 11 3 9 525 7 49 9 81 10

  11. Examples do 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, 2 print *, number, number **2 end do 11

  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 12

  13. !Please calculate sum and ave of given number students grade. program sumandaveofstudentgrade real::note,notesum,noteave integer::number,i notesum=0 print*,"How mony student grade you want calculate" read*,number do i=1,number print*,"Please enter grade of student",i read*,note notesum=notesum+note end do print*,"Sum of students grade is:",notesum noteave=notesum/number print*,"Average of students grade is:",noteave end program sumandaveofstudentgrade 13

  14. Program temp_fahr_convreal::t,f t=0dot=t+1 if (t>100) then exit end if f=t*1.8+32 write(unit=*,fmt=“(f5.1,a,f7.2,a)”)t,”C=”,f,”F”end doend program temp_fahr_conv 14

  15. Count-controlled do loops docount = initial, final, inc docount = 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 15

  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 : dom = 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 16

  17. More 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. 17

  18. Some flexibility... do . . . if (condition) then exit end if . . . end do . 18

  19. Some more flexibility... 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. 19

  20. Some more flexibility... do . . . if (condition) then cycle end if . . . end do . 20

  21. PROBLEM : Suppose that in the temprature-conversion only temprature of 0oC or above values are wanted to convert. program convert1 real::celcius,fahr character(len=1)::kontrol do 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 endif end do end program convert1 21

  22. Naming your do constructs 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 : [name:] DO [control clause] block END DO [name] 22

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

  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 24

  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 doloop integer::ii,istart=1,ilast=100,istep=3,isum do ii=istart,ilast,istep isum = isum + ii print*,isum End do end program doloop 25

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

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

  28. Syntax examples of control constructs: 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 do doname: do if ( value > climate_index) then exit doname end if value = new_value end do doname 28

  29. program can_pressure ! This program calculates the pressure inside the can real :: T,pressure T=15.0 control:do T=T+1 pressure=(0.00105*(T**2))+(0.0042*T)+1.352 if (pressure>3.2) then exit control end if print *,"The pressure inside the can is",& pressure," atmat",T," degree C" end do control end program can_pressure 29

  30. program examination_marks ! This program prints statistics about a set of exam results ! variable declerations integer :: i,number,mark,maximum,minimum,total real :: average ! initialize variable total = 0 ! read number of marks , and then the marks print *,"how many marks are there" read *,number print *," please type ",number," marks, one per line" ! Loop to read and process marks do i = 1 , number read *, 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 + mark if (mark > maximum)then maximum = mark else if (mark < minimum)then minimum = mark end if end do !! calculate average mark and print out results average = real(total) / number print *,"highest mark is",maximum,"lowest mark is",minimum,"average mark is",average end program examination_marks 30

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

  32. !This program written to understand do loop program loop_test1 integer :: i,j,k,l,m,n i=1 j=2 k=4 l=8 m=0 n=0 do i=j,k,l k=i do j=l,m,k n=j do k=l,n do l=i,k m=k*l end do end do end do end do print *,i,j,k,l,m,n end program loop_test1 32

  33. !Write a program to calculate the international paper sizes program paper_size integer :: n real :: cm,inch,p1,p2 do n = 0,6 p1 = 0.25 - n/2.0 p2 = -0.25 - n/2.0 cm = (2.0**p1 * 2.0**p2)*100.0 inch = cm/2.54 print *,"A",n," is",cm," cm"," and",inch," inch" end do end program paper_size 33

  34. !Write a program to calculate TAX depending on total income program 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

  35. ??? Bir kişiye 80 defa deli dersek ZIR DELİ olurmuş Bir kişi 80 program yazarsa ne olur ??? 35

More Related