06MoreLoopsArrays1

# 06MoreLoopsArrays1 - Loops and Arrays Amir Hossein Rabbani...

This preview shows pages 1–12. Sign up to view the full content.

Loops and Arrays Amir Hossein Rabbani Winter 2009

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Review Definite loop example Checking for a premier number A prime number is a positive integer bigger than one that is divisible only by itself and 1 One way to check if a number x is prime is to try dividing x by every number less than x and seeing if any have 0 remainder
! Verify if the input is a prime number PROGRAM IsPrime IMPLICIT NONE INTEGER :: X, count, num_factors = 0 WRITE (*,*) “Enter your number please : ” READ (*,*) X DO count = 2, X-1, 1 IF (MOD(X,count) == 0)THEN ! is “count” a factor of X? num_factors = num_factors + 1 END IF END DO IF (num_factors == 0) THEN WRITE (*,*) X, “ is prime” ELSE WRITE (*,*) X, “ is not prime” END IF END PROGRAM IsPrime

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Review Indefinite loop example ! Indefinite loop PROGRAM NoTermination IMPLICIT NONE INTEGER :: I = 0 DO IF (I > 0) EXIT END DO END PROGRAM NoTermination
This session More on loops Introduction to Arrays

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
DO WHILE DO WHILE (Logical expression) statement block END DO
Example ! Simple do while loop PROGRAM PrintNumber IMPLICIT NONE INTEGER :: I = 0 DO WHILE (I < 10) WRITE(*,*) “ I = “, I I = I + 1 END DO END PROGRAM PrintNumbers

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Let’s code something serious …
Fibonacci number Chameleon Tail 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, … F n = 0 if n = 0 1 if n = 1 F n-1 + F n-2 if n > 1

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Find a pattern 1 = 1 + 0 3 rd = 2 nd + 1 st 2 = 1 + 1 4 th = 3 rd + 2 nd 3 = 2 + 1 5 th = 4 th + 3 rd 5 = 3 + 2 6 th = 5 th + 4 th …. N th = (N-1) th + (N-2) th The current integer is the sum of the previous two integers : start a = 0, b = 1 Counter = 3, input N Counter > N C = a+b Output c a = b, b = c end No Yes Increment the Counter
! Returns the first N Fibonacci numbers

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 01/15/2010 for the course COMP COMP 206 taught by Professor Vybihal during the Spring '04 term at McGill.

### Page1 / 27

06MoreLoopsArrays1 - Loops and Arrays Amir Hossein Rabbani...

This preview shows document pages 1 - 12. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online