190 Lecture 6 Fortran Enclose character strings with single or double quotes,
PROGRAMS AND THE SCITE EDITOR
Double-click the SciTE icon. 'and', "x=", "It's a good day."
Drag the bar on the right toward the middle. Place all declarations at the beginning of a program.
Enter input and see output in the right-hand console They may optionally assign an initial value.
Enter the program below in the left-hand edit window.
Don’t type the comments which follow “!”.
real :: x,y
real :: x=2.,y=0. ! reals must have a decimal point.
program read_write ! save as read_write.f95 integer :: m ! integers must not
integer::n ! declare n an integer integer :: j=1,i=2
print *,'Enter an integer' ! print to screen
character :: s="hat"
read *,n ! get input from keyboard
print *,'The number is n=',n MULTIPLE COMMAND LINES
endprogram If you want to put two lines together on one line,
To run a program save it, compile it, execute it (go). separate them with a semicolon “;”
Save: select File/Save save to read_write.f95 real :: x,y; integer :: m,n
Fortran file names must end with the extension .f95
Compile: press <ctrl-F7> or select Tools/Compile. DO LOOPS
Exit code:0 in the console window means no errors. Clear the edit window.
Copy/paste this into the edit window.
Execute: press <F5> or select Tools/Go. Save to do_loop.f95. Compile<ctrl-F7> and Go<F5>
Enter any requested input in the right-hand console
window. program do_loop
To repeat the process, press <F5> and enter another integer::i
number. do i=1,7 ! repeats the commands in the loop for i = 1 to 7.
INPUT / OUTPUT
print *, prints to the screen. endprogram
read *, reads input from the keyboard.
Enter inputs in the right-hand console window. Given input n, this prints the multiples of three up to 3*n.
Anything after “!” is a comment which Fortran ignores. program multiples_of_3 ! homework 1, classwork 2
integer::num_primes ! number of primes <= n integer::i,n
print *,'Enter an integer.'
VARIABLES read *,n
Names of variables in Fortran may have letters (a-z or print *,'Multiples of 3 up to',3*n
A-Z, Fortran does not distinguish case) and digits (0-9) and do i=0,n
the underscore “_”. They must start with a letter. print *,3*i
ARITHMETIC Like Matlab except exponential has to be
**. ASSIGNMENTS AND LOGICAL EXRESSIONS
3+2; 3*2; 3.*2.; 3./2.; 3**2; abs(-3); ! not x=y sets x equal to y, this is an assignment.
3/2 x==y test if x equals y.
max(3 5 1 4); min(3 5 1 4)
x<y, x<=y, x>y, x>=y, x/=y ,
sum([2 3]); product([2 3])
for , , , , .
mod(13,5) ! =3, the remainder of 13 divided by 5
sqrt(4.); ! =.2. sqrt(4.) not sqrt(4) which gives an error
rand() ! a random number drawn from [0,1)
:: Variables and functions must be declared.
real (numbers with decimals, 3.5 -2. .088)
integer (numbers without decimals, 3, -2)
logical (either .TRUE. or .FALSE.)
character (strings of characters including letters & digits)
CONDITIONALS Every function must be accompanied by a testing
Suppose ??? is a test and *** , --- are commands. program.
if(???) then Clear the edit window.
Does *** if ??? is true.
*** Copy/paste this into the edit window.
endif Save to divides.f95. Compile <ctrl-F7> and Go <F5>
logical function divides(d,n) ! homework 3
! declares divides to be a function with logical output
if(???) then integer :: d,n
Does *** if ??? is true; if(mod(n,d)==0) then ! mod is modulo in Matlab
*** does --- if not. divides = .TRUE.
--- divides = .FALSE.
endif ! a function's output is the value assigned to its name
Clear the edit window. logical::divides ! to use a function we must declare it.
Copy/paste this into the edit window. integer::d
Save to negative_test.f95. Compile<ctrl-F7> and do d=1,12
Go<F5> if (divides(d,12)) then
print *,d,'divides 12'
program negative_test ! classwork 1, homework 2 else
integer::n print *,d,'does not divide 12'
print *,'Enter an integer' endif
if(n<0) then endprogram
print *,n,'is negative'
Let’s open a previously saved program.
print *,n,'is nonnegative' Select File/Open ... . Don’t see anything?
endif In the Files of type box, select Fortran in the
endprogram drop-down menu. Now you should see your old programs
if you are in the correct directory.
LONG LINES When programs fail to compile, the console window
When writing or copying/pasteing programs, make the shows a message with the line numbers of lines with
editor window wide enough that lines don’t wrap. If you errors. To see the line numbers select View/Line
have a long line which has to be continued on the next Numbers.
line, place a “&” at the end of the line to tell Fortran that To permanently make Fortran files and line numbers
the line continues on the next line. visible, select Options/Open Global Options
print *,'Here is a long line that needs &
Find #line.margin.visible=1 and delete the “#”.
& to be continued on a second line.'
Find source.files=*.asm;*.c;... and add *.f95;
FUNCTIONS to get source.files=*.f95;*.asm;*.c;...
Write a Fortran function divides(d,n) which
determines if d divides n.
The inputs are integers d and n.
The output will be a logical answer, either
.TRUE. which means “true” or “yes”
or .FALSE. which means “false” or “no”.
divides(2,4) is .TRUE. but
divides(2,5) is .FALSE.
CLASSWORK Write all programs in the SciTE editor. Do 3a or 3b but not both. If you can pass the two-step
Email only Fortran code, do not send program output on creativity test at the end of this lecture, do 3b, it has more
any lines the compiler won’t accept. points (8 points vs. 4) but requires originality. If you fail the
email to: email@example.com, creativity test, do 3a.
subject line: 190 6 c1(3) Write a program even_odd
(save to even_odd.f95) which: subject line: 190 6 h3a(4) Write a program
Asks the user to “Enter a positive integer”. divisors_of_n which asks the user to “Enter a
If the input n is even (i.e., if mod(n,2)==0 ), positive integer”.
it prints 'n is even' It reads the input n, then prints the divisors of n.
else Recall: d is a divisor of n iff mod(n,d)==0.
it prints 'n odd'. On input n = 5 it prints
On input 3, it prints: 3 is odd 5
On input 4, it prints: 4 is even On input n = 6 it prints
subject line: 190 6 c2(2) Write a program n_to_10 2
which asks the user to “Enter a digit”. 3
On input n it prints the numbers between n and 10.
On input n=6, it prints: For any n, d=1 is the smallest divisor and d=n is the
7 Hence after the program reads the user’s input n,
8 it begins a do loop with d ranging from 1 to n.
9 If d divides n, it prints d.
subject line: 190 6 h3b(8) Write a program
HOMEWORK DUE NEXT TIME num_divisors which asks the user to “Enter a positive
CLOSED-BOOK QUIZ BEGINNING OF NEXT PERIOD IS SIMILAR integer”.
Email only Fortran code, do not send program output. It reads the input n, then prints the number of divisors
email to: firstname.lastname@example.org, of n.
subject line: 190 6 h1(2) Write a program On input n = 5 it prints: 5 has 2 divisors
powers_of_2 which asks the user to “Enter a positive On input n = 6 it prints: 6 has 4 divisors
integer”. On input n, it prints the following powers of 2: Finally, instead of using mod(n,d)directly, this
2 0 , 2 1 , ... , 2 n . For n=3, it prints: program must use the function divides(d,n). Your
1, 2, 4, 8 in a vertical column. file num_divisors.f95 must also include the 8 lines of
the function divides(d,n). The file will look like this:
subject line: 190 6-h2(3) Write a program even_odds
which asks the user to “Enter a positive integer”. On logical function divides(d,n)
input n it classifies the numbers between 0 and n as being ! true if d divides n, false if not
integer :: d,n
even or odd. if(mod(n,d)==0) then
On input 3 it prints: divides = .TRUE.
0 is even else
1 is odd divides = .FALSE.
2 is even endif
3 is odd endfunction
... ! fill in the lines of your program
DON’T “REINVENT THE WHEEL” CREATIVITY TEST (LAST EXAMPLE)
Each problem directed to noncreative students, has a For some, creativity and originality are easy and fun.
similar example in the lecture. Copy/paste this similar But for the noncreative, problems requiring original
example to SciTE; then modify it appropriately. thinking are frustrating. If you have creative deficiencies
I can’t expect you to solve course problems requiring
multi-step combinations and I can’t expect you to get an
Programming is hard, don’t wait until the last minute to
A or B. But I do expect you to solve problems which
write a program, you might need to use my office hours
involve modifying a given example. Multiple
during the week.
modifications may be needed, but you should be able to
Programs are graded all (if it works) or nothing (0 if not).
solve the problem if each modification requires at most
You get multiple tries but lose 20% for each
one step and the steps can be done separately from each
You lose, in addition, 20% for each week the final
working program is late (any time between the due date One-step problems.
and the beginning of the next class counts as one week Generate a matrix whose 1st row is a and whose 2nd is b.
late). If you haven’t completed a homework assignment Solution: c=[a;b]
by the due date, you may submit it anyway. I’ll point out
Generate the vector a of even numbers up to 2n. Then
three errors, deduct 20% and return it to you for
generate the vector b of odd numbers up to 2n+1.
correction. If after correcting the errors, you still can’t get
Solution: a=[0:2:2*n]; b=[1:2:2*n+1]
it to work, resubmit it for correction of another 3 errors Requires two steps but they are independent of each other, each can
and another 20% deduction. be solved one step at a time. Multi-step creativity is not required
Generate a matrix whose 1st row is the evens up to 2n
and whose 2nd row is the odds up to 2n+1.
Noncreative students didn’t solve this midterm problem. Noncreative
students need a similar program to start with, say one which
generates a matrix with odds in the first row and evens in the second.
Replace the 1st element of a with its 2nd element. In the
resulting vector, replace the 2nd element with the 1st.
Solution: a(1)=a(2); a(2)=a(1)
Requires two steps but the steps are independent and can be done
separately one step at a time.
Two-step creativity test problem:
Swap the 1st and 2nd elements of the vector a.
Solution: See if you write a Scilab function F(a) such
This simple problem requires a multi-step combination. If you are
not creative and have not seen the solution before, you won’t be able
to solve it or any other programming problem in this course
requiring multi-step combinations.
PROBLEM FORMAT - NO TEMPLATES
No templates for Fortran problems.
Subject line: exactly as listed, e.g., 190 6-c2(4).
Message body: Fortran code only, nothing else. Do not
include program output. Any non-code lines (your name,
the problem number, ... ) will trigger a compiler error. If
you must include a comment lines, put them after a “!”.
If nothing happens when you click Compile or if it is
(1) Make sure you have saved to a file with the .f95
(2) Make sure the program isn’t working on a previous
failed program. If it is, click Tools/Stop executing
(3) Sometimes a wrong key-stroke can change the
language, select Language/Fortran to reset it to
(4) Line wraps. Don’t let a line continue on to a second
line. Widen the editor window so the line doesn’t wrap or
shorten the line (delete comments) or place Fortran’s
continuation symbol “&” to indicate that the line is
continued on the next line.