1 Malar

Fortran 77 Array Assignment In Javascript

In computer science, a for-loop (or simply for loop) is a control flowstatement for specifying iteration, which allows code to be executed repeatedly. Various keywords are used to specify this statement: descendants of ALGOL use "for", while descendants of Fortran use "do." There are other possibilities, for example COBOL which uses "PERFORM VARYING".

A for-loop has two parts: a header specifying the iteration, and a body which is executed once per iteration. The header often declares an explicit loop counter or loop variable, which allows the body to know which iteration is being executed. For-loops are typically used when the number of iterations is known before entering the loop. For-loops can be thought of as shorthands for while-loops which increment and test a loop variable.

The name for-loop comes from the English word for, which is used as the keyword in many programming languages to introduce a for-loop. The term in English dates to ALGOL 58 and was popularized in the influential later ALGOL 60; it is the direct translation of the earlier German für, used in Superplan (1949–1951) by Heinz Rutishauser, who also was involved in defining ALGOL 58 and ALGOL 60. The loop body is executed "for" the given values of the loop variable, though this is more explicit in the ALGOL version of the statement, in which a list of possible values and/or increments can be specified.

In FORTRAN and PL/I, the keyword DO is used for the same thing and it is called a do-loop; this is different from a do-while loop.

for[edit]

A for-loop statement is available in most imperative programming languages. Even ignoring minor differences in syntax there are many differences in how these statements work and the level of expressiveness they support. Generally, for-loops fall into one of the following categories:

Traditional for-loops[edit]

The for-loop of languages like ALGOL, Simula, BASIC, Pascal, Modula, Oberon, Ada, Matlab, Ocaml, F#, and so on, requires a control variable with start- and end-values and looks something like this:

fori=firsttolastdostatement(* or just *)fori=first..lastdostatement

Depending on the language, an explicit assignment sign may be used in place of the equal sign (and some languages require the word even in the numerical case). An optional step-value (an increment or decrement ≠ 1) may also be included, although the exact syntaxes used for this differs a bit more between the languages. Some languages require a separate declaration of the control variable, some do not.

Another form was popularized by the C programming language. It requires 3 parts: the initialization, the condition, and the afterthought and all these three parts are optional.[1]

The initialization declares (and perhaps assigns to) any variables required. The type of a variable should be same if you are using multiple variables in initialization part. The condition checks a condition, and quits the loop if false. The afterthought is performed exactly once every time the loop ends and then repeats.

Here is an example of the traditional for-loop in Java.

// Prints the numbers 0 to 99 (and not 100), each separated by a space.for(inti=0;i<100;i++){System.out.print(i);System.out.print(' ');}System.out.println();

Iterator-based for-loops[edit]

Main article: Foreach loop

This type of for-loop is a generalisation of the numeric range type of for-loop, as it allows for the enumeration of sets of items other than number sequences. It is usually characterized by the use of an implicit or explicit iterator, in which the loop variable takes on each of the values in a sequence or other data collection. A representative example in Python is:

foriteminsome_iterable_object:do_something()do_something_else()

Where is either a data collection that supports implicit iteration (like a list of employee's names), or may in fact be an iterator itself. Some languages have this in addition to another for-loop syntax; notably, PHP has this type of loop under the name , as well as a three-expression for-loop (see below) under the name .

Vectorised for-loops[edit]

Some languages offer a for-loop that acts as if processing all iterations in parallel, such as the keyword in FORTRAN 95 which has the interpretation that allright-hand-side expressions are evaluated before any assignments are made, as distinct from the explicit iteration form. For example, in the statement in the following pseudocode fragment, when calculating the new value for , except for the first (with ) the reference to will obtain the new value that had been placed there in the previous step. In the version, however, each calculation refers only to the original, unaltered .

for i := 2 : N - 1 do A(i) := [A(i - 1) + A(i) + A(i + 1)] / 3; next i; for all i := 2 : N - 1 do A(i) := [A(i - 1) + A(i) + A(i + 1)] / 3;

The difference may be significant.

Some languages (such as FORTRAN 95, PL/I) also offer array assignment statements, that enable many for-loops to be omitted. Thus pseudocode such as would set all elements of array A to zero, no matter its size or dimensionality. The example loop could be rendered as

A(2:N-1):=[A(1:N-2)+A(2:N-1)+A(3:N)]/3;

But whether that would be rendered in the style of the for-loop or the for all-loop or something else may not be clearly described in the compiler manual.

Compound for-loops[edit]

Introduced with ALGOL 68 and followed by PL/I, this allows the iteration of a loop to be compounded with a test, as in

for i := 1 : N while A(i) > 0 do etc.

That is, a value is assigned to the loop variable i and only if the while expression is true will the loop body be executed. If the result were false the for-loop's execution stops short. Granted that the loop variable's value is defined after the termination of the loop, then the above statement will find the first non-positive element in array A (and if no such, its value will be N + 1), or, with suitable variations, the first non-blank character in a string, and so on.

Loop counters[edit]

In computer programming a loop counter is the variable that controls the iterations of a loop (a computer programming language construct). It is so named because most uses of this construct result in the variable taking on a range of integer values in some orderly sequences (example., starting at 0 and end at 10 in increments of 1)

Loop counters change with each iteration of a loop, providing a unique value for each individual iteration. The loop counter is used to decide when the loop should terminate and for the program flow to continue to the next instruction after the loop.

A common identifier naming convention is for the loop counter to use the variable names i, j, and k (and so on if needed), where i would be the most outer loop, j the next inner loop, etc. The reverse order is also used by some programmers. This style is generally agreed to have originated from the early programming of FORTRAN[citation needed], where these variable names beginning with these letters were implicitly declared as having an integer type, and so were obvious choices for loop counters that were only temporarily required. The practice dates back further to mathematical notation where indices for sums and multiplications are often i, j, etc. A variant convention is the use of reduplicated letters for the index, ii, jj, and kk, as this allows easier searching and search-replacing than using a single letter.[2]

Example[edit]

An example of C code involving nested for loops, where the loop counter variables are i and j:

for(i=0;i<100;i++){for(j=i;j<10;j++){some_function(i,j);}}

Additional semantics and constructs[edit]

Use as infinite loops[edit]

This C-style for-loop is commonly the source of an infinite loop since the fundamental steps of iteration are completely in the control of the programmer. In fact, when infinite loops are intended, this type of for-loop can be used (with empty expressions), such as:

This style is used instead of infinite loops to avoid a type conversion warning in some C/C++ compilers.[3] Some programmers prefer the more succinct form over the semantically equivalent but more verbose form.

Early exit and continuation[edit]

Some languages may also provide other supporting statements, which when present can alter how the for-loop iteration proceeds. Common among these are the break and continue statements found in C and its derivatives. The break statement causes the inner-most loop to be terminated immediately when executed. The continue statement will move at once to the next iteration without further progress through the loop body for the current iteration. A for statement also terminates when a break, goto, or return statement within the statement body is executed. [Wells] Other languages may have similar statements or otherwise provide means to alter the for-loop progress; for example in FORTRAN 95:

DO I=1,Nstatements!Executed for all values of "I", up to a disaster if any.IF(nogood)CYCLE!Skip this value of "I", continue with the next.statements!Executed only where goodness prevails.IF(disaster)EXIT!Abandon the loop.statements!While good and, no disaster.END DO!Should align with the "DO".

Some languages offer further facilities such as naming the various loop statements so that with multiple nested loops there is no doubt as to which loop is involved. Fortran 95, for example:

X1:DO I=1,NstatementsX2:DO J=1,MstatementsIF(trouble)CYCLE X1statementsEND DO X2statementsEND DO X1

Thus, when "trouble" is detected in the inner loop, the CYCLE X1 (not X2) means that the skip will be to the next iteration for I, not J. The compiler will also be checking that each END DO has the appropriate label for its position: this is not just a documentation aid. The programmer must still code the problem correctly, but some possible blunders will be blocked.

Loop variable scope and semantics[edit]

Different languages specify different rules for what value the loop variable will hold on termination of its loop, and indeed some hold that it "becomes undefined". This permits a compiler to generate code that leaves any value in the loop variable, or perhaps even leaves it unchanged because the loop value was held in a register and never stored to memory. Actual behaviour may even vary according to the compiler's optimization settings, as with the Honywell Fortran66 compiler.

In some languages (not C or C++) the loop variable is immutable within the scope of the loop body, with any attempt to modify its value being regarded as a semantic error. Such modifications are sometimes a consequence of a programmer error, which can be very difficult to identify once made. However, only overt changes are likely to be detected by the compiler. Situations where the address of the loop variable is passed as an argument to a subroutine make it very difficult to check, because the routine's behavior is in general unknowable to the compiler. Some examples in the style of Fortran:

DO I=1,NI=7!Overt adjustment of the loop variable. Compiler complaint likely.Z=ADJUST(I)!Function "ADJUST" might alter "I", to uncertain effect.normalstatements!Memory might fade that "I" is the loop variable.PRINT(A(I),B(I),I=1,N,2)!Implicit for-loop to print odd elements of arrays A and B, reusing "I"…PRINT I!What value will be presented?END DO!How many times will the loop be executed?

A common approach is to calculate the iteration count at the start of a loop (with careful attention to overflow as in in sixteen-bit integer arithmetic) and with each iteration decrement this count while also adjusting the value of : double counting results. However, adjustments to the value of within the loop will not change the number of iterations executed.

Still another possibility is that the code generated may employ an auxiliary variable as the loop variable, possibly held in a machine register, whose value may or may not be copied to on each iteration. Again, modifications of would not affect the control of the loop, but now a disjunction is possible: within the loop, references to the value of might be to the (possibly altered) current value of or to the auxiliary variable (held safe from improper modification) and confusing results are guaranteed. For instance, within the loop a reference to element of an array would likely employ the auxiliary variable (especially if it were held in a machine register), but if is a parameter to some routine (for instance, a print-statement to reveal its value), it would likely be a reference to the proper variable instead. It is best to avoid such possibilities.

Adjustment of bounds[edit]

Just as the index variable might be modified within a for-loop, so also may its bounds and direction. But to uncertain effect. A compiler may prevent such attempts, they may have no effect, or they might even work properly - though many would declare that to do so would be wrong. Consider a statement such as

for i := first : last : step do A(i) := A(i) / A(last);

If the approach to compiling such a loop was to be the evaluation of first, last and step and the calculation of an iteration count via something like (last - first)/step once only at the start, then if those items were simple variables and their values were somehow adjusted during the iterations, this would have no effect on the iteration count even if the element selected for division by A(last) changed.

List of value ranges[edit]

PL/I and Algol 68, allows loops in which the loop variable is iterated over a list of ranges of values instead of a single range. The following PL/I example will execute the loop with six values of i: 1, 7, 12, 13, 14, 15:

do i = 1, 7, 12 to 15; /*statements*/ end;

Equivalence with while-loops[edit]

A for-loop can be converted into an equivalent while-loop by incrementing a counter variable directly. The following pseudocode illustrates this technique:

factorial := 1 for counter from 1 to 5 factorial := factorial * counter

is easily translated into the following while-loop:

factorial := 1 counter := 1 while counter <= 5 factorial := factorial * counter counter := counter + 1

This translation is slightly complicated by languages which allow a statement to jump to the next iteration of the loop (such as the "continue" statement in C). These statements will typically implicitly increment the counter of a for-loop, but not the equivalent while-loop (since in the latter case the counter is not an integral part of the loop construct). Any translation will have to place all such statements within a block that increments the explicit counter before running the statement.

In practice[edit]

The formal equivalence applies only in so far as computer arithmetic also follows the axia of mathematics, in particular that x + 1 > x. Actual computer arithmetic suffers from the overflow of limited representations so that for example in sixteen-bit unsigned arithmetic, 65535 + 1 comes out as zero, because 65536 cannot be represented in unsigned sixteen-bit. Similar problems arise for other sizes, signed or unsigned. Compiler writers will handle the likes of , possibly by producing code that inspects the state of an "overflow" indicator, but unless there is some provision for the equivalent checking when calculating the while-loop equivalence will fail because the counter will never exceed 65535 and so the loop will never end - unless some other mishap occurs.

Timeline of the for-loop syntax in various programming languages[edit]

Given an action that must be repeated, for instance, five times, different languages' for-loops will be written differently. The syntax for a three-expression for-loop is nearly identical in all languages that have it, after accounting for different styles of block termination and so on.

1957: FORTRAN[edit]

Fortran's equivalent of the loop is the loop, using the keyword do instead of for, The syntax of Fortran's loop is:

DO labelcounter=first,last,stepstatementslabelstatement

The following two examples behave equivalently to the three argument for-loop in other languages, initializing the counter variable to 1, incrementing by 1 each iteration of the loop and stopping at five (inclusive).

DO 9,COUNTER=1,5,1WRITE(6,8)COUNTER8FORMAT(I2)9CONTINUE

In Fortran 77 (or later), this may also be written as:

do counter=1,5write(*,'(i2)')counterend do

The step part may be omitted if the step is one. Example:

* DO loop example.PROGRAM MAINSUM SQ=0DO 199I=1,9999999IF(SUM SQ.GT.1000)GOTO200199 SUM SQ=SUM SQ+I**2200 PRINT 206,SUMSQ206 FORMAT(I2)END

Spaces are irrelevant in fixed-form Fortran statements, thus is the same as . In the modern free-form Fortran style, blanks are significant.

In Fortran 90, the may be avoided by using an statement.

*DO loopexample.program mainimplicit noneinteger::sumsqinteger::isumsq=0do i=1,9999999if(sumsq>1000.0)exitsumsq=sumsq+i**2end do print*,sumsqend program

1958: Algol[edit]

Algol was first formalised in the Algol58 report.

1960: COBOL[edit]

COBOL was formalized in late 1959 and has had many elaborations. It uses the PERFORM verb which has many options, with the later addition of "structured" statements such as END-PERFORM. Ignoring the need for declaring and initialising variables, the equivalent of a for-loop would be

PERFORMVARYINGIFROM1 BY1 UNTILI>1000ADDI**2 TOSUM-SQ.END-PERFORM

If the PERFORM verb has the optional clause TEST AFTER, the resulting loop is slightly different: the loop body is executed at least once, before any test.

1964: BASIC[edit]

Loops in BASIC are sometimes called for-next loops.

10REM THIS FOR LOOP PRINTS ODD NUMBERS FROM 1 TO 1520FORI=1TO15STEP230PRINTI40NEXTI

Notice that the end-loop marker specifies the name of the index variable, which must correspond to the name of the index variable in the start of the for-loop. Some languages (PL/I, FORTRAN 95 and later) allow a statement label on the start of a for-loop that can be matched by the compiler against the same text on the corresponding end-loop statement. Fortran also allows the EXIT and CYCLE statements to name this text; in a nest of loops this makes clear which loop is intended. However, in these languages the labels must be unique, so successive loops involving the same index variable cannot use the same text nor can a label be the same as the name of a variable, such as the index variable for the loop.

1964: PL/I[edit]

do counter = 1 to 5 by 1; /* "by 1" is the default if not specified */ /*statements*/; end;

The LEAVE statement may be used to exit the loop. Loops can be labeled, and leave may leave a specific labeled loop in a group of nested loops. Some PL/I dialects include the ITERATE statement to terminate the current loop iteration and begin the next.

1968: Algol 68[edit]

Algol68 has what was considered the universal loop, the full syntax is:

FOR i FROM 1 BY 2 TO 3 WHILE i≠4 DO ~ OD

Further, the single iteration range could be replaced by a list of such ranges. There are several unusual aspects of the construct

  • only the portion was compulsory, in which case the loop will iterate indefinitely.
  • thus the clause , will iterate exactly 100 times.
  • the syntactic element allowed a programmer to break from a loop early, as in:
INT sum sq := 0; FOR i WHILE print(("So far:", i, new line)); # Interposed for tracing purposes. # sum sq ≠ 70↑2 # This is the test for the WHILE # DO sum sq +:= i↑2 OD

Subsequent extensions to the standard Algol68 allowed the syntactic element to be replaced with and to achieve a small optimization. The same compilers also incorporated:

for late loop termination.
for working on arrays in parallel.

1970: Pascal[edit]

forCounter:=1to5do(*statement*);

Decrementing (counting backwards) is using keyword instead of , as in:

forCounter:=5downto1do(*statement*);

The numeric-range for-loop varies somewhat more.

1972: C/C++[edit]

Further information: C syntax § Iteration statements

for(initialization;condition;increment/decrement)statement

The is often a block statement; an example of this would be:

//Using for-loops to add numbers 1 - 5intsum=0;for(inti=1;i<6;++i){sum+=i;}

The ISO/IEC 9899:1999 publication (commonly known as C99) also allows initial declarations in loops. All the three sections in the for loop are optional.

1972: Smalltalk[edit]

1to:5do: [ :counter|"statements" ]

Contrary to other languages, in Smalltalk a for-loop is not a language construct but defined in the class Number as a method with two parameters, the end value and a closure, using self as start value.

1980: Ada[edit]

forCounterin1..5loop-- statementsendloop;

The exit statement may be used to exit the loop. Loops can be labeled, and exit may leave a specifically labeled loop in a group of nested loops:

Counting:forCounterin1..5loopTriangle:forSecondary_Indexin2..Counterloop-- statementsexitCounting;-- statementsendloopTriangle;endloopCounting;

1980: Maple[edit]

Maple has two forms of for-loop, one for iterating of a range of values, and the other for iterating over the contents of a container. The value range form is as follows:

forifromfbybtotwhilewdo# loop bodyod;

All parts except and are optional. The part, if present, must come first. The remaining parts (, , , ) can appear in any order.

Iterating over a container is done using this form of loop:

foreincwhilewdo# loop bodyod;

The clause specifies the container, which may be a list, set, sum, product, unevaluated function, array, or an object implementing an iterator.

A for-loop may be terminated by , , or .

1982: Maxima CAS[edit]

In Maxima CAS one can use also non integer values :

forx:0.5step0.1thru0.9do/*"Do something with x"*/

1982: PostScript[edit]

The for-loop, written as initialises an internal variable, executes the body as long as the internal variable is not more than limit (or not less, if increment is negative) and, at the end of each iteration, increments the internal variable. Before each iteration, the value of the internal variable is pushed onto the stack.[4]

There is also a simple repeat-loop. The repeat-loop, written as , repeats the body exactly X times.[5]

1983: Ada 83 and above[edit]

procedureMainisSum_Sq:Integer:=0;beginforIin1..9999999loopifSum_Sq<=1000thenSum_Sq:=Sum_Sq+I**2endif;endloop;end;

1984: MATLAB[edit]

forn=1:5--statementsend

As is used for the Imaginary unit, its use as a loop variable is discouraged.

1987: Perl[edit]

for($counter=1;$counter<=5;$counter++){# implicitly or predefined variable# statements;}for(my$counter=1;$counter<=5;$counter++){# variable private to the loop# statements;}for(1..5){# variable implicitly called $_; 1..5 creates a list of these 5 elements# statements;}statementfor1..5;# almost same (only 1 statement) with natural language orderformy$counter(1..5){# variable private to the loop# statements;}

(Note that "there's more than one way to do it" is a Perl programming motto.)

1988: Mathematica[edit]

The construct corresponding to most other languages' for-loop is called Do in Mathematica

Mathematica also has a For construct that mimics the for-loop of C-like languages

For[x=0,x<=1,x+=0.1,f[x]]

1989: Bash[edit]

# first formfor i in 12345do# must have at least one command in loopecho$i# just print value of idone
# second formfor((i=1; i <=5; i++ ))do# must have at least one command in loopecho$i# just print value of idone

Note that an empty loop (i.e., one with no commands between and ) is a syntax error. If the above loops contained only comments, execution would result in the message "".

1990: Haskell[edit]

The built-in imperative forM_ maps a monadic expression into a list, as

forM_[1..5]$\indx->dostatements

or get each iteration result as a list in

statements_result_list<-forM[1..5]$\indx->dostatements

But, if you want to save the space of the [1..5] list, a more authentic monadicforLoop_ construction can be defined as

importControl.MonadasMforLoopM_::Monadm=>a->(a->Bool)->(a->a)->(a->m())->m()forLoopM_indxpropincrf=dofindxM.when(propnext)$forLoopM_nextpropincrfwherenext=incrindx

and used as:

forLoopM_(0::Int)(<len)(+1)$\indx->do-- whatever with the index

1991: Oberon-2, Oberon-07, or Component Pascal[edit]

FORCounter:=1TO5DO(* statement sequence *)END

Note that in the original Oberon language the for-loop was omitted in favor of the more general Oberon loop construct. The for-loop was reintroduced in Oberon-2.

1991: Python[edit]

forcounterinrange(1,6):# range(1, 6) gives values from 1 to 5 inclusive (but not 6)# statements

1993: AppleScript[edit]

repeatwithifrom1to5-- statementslogiendrepeat

You can also iterate through a list of items, similar to what you can do with arrays in other languages:

setxto{1,"waffles","bacon",5.1,false}repeatwithiinxlogiendrepeat

You may also use to exit a loop at any time. Unlike other languages, AppleScript does not currently have any command to continue to the next iteration of a loop.

1993: Lua[edit]

fori=start,stop,intervaldo-- statementsend

So, this code

fori=1,5,2doprint(i)end

will print:

For-loops can also loop through a table using

to iterate numerically through arrays and

to iterate randomly through dictionaries.

Generic for-loop making use of closures:

forname,phone,addressincontacts()do-- contacts() must be an iterator functionend

1995: CFML[edit]

Script syntax[edit]

Simple index loop:

for(i=1;i<=5;i++){// statements}

Using an array:

for(iin[1,2,3,4,5]){// statements}

Using a list of string values:

loopindex="i"list="1;2,3;4,5"delimiters=",;"{// statements}

The above example is only available in the dialect of CFML used by Lucee and Railo.

Tag syntax[edit]

Simple index loop:

<cfloopindex="i"from="1"to="5"><!--- statements ---></cfloop>

Using an array:

<cfloopindex="i"array="#[1,2,3,4,5]#"><!--- statements ---></cfloop>

Using a "list" of string values:

<cfloopindex="i"list="1;2,3;4,5"delimiters=",;"><!--- statements ---></cfloop>

1995: Java[edit]

for(inti=0;i<5;i++){//perform functions within the loop;//can use the statement 'break;' to exit early;//can use the statement 'continue;' to skip the current iteration}

For the extended for-loop, see Foreach loop

1995: JavaScript[edit]

JavaScript supports C-style "three-expression" loops. The and statements are supported inside loops.

for(vari=0;i<5;i++){// ...}

Alternatively, it is possible to iterate over all keys of an array.

for(varkeyinarray){// also works for assoc. arrays// use array[key]...}

1995: PHP[edit]

This prints out a triangle of *

for($i=0;$i<=5;$i++){for($j=0;$j<=$i;$j++){echo"*";}echo"<br>";}

1995: Ruby[edit]

forcounterin1..5# statementsend5.timesdo|counter|# counter iterates from 0 to 4# statementsend1.upto(5)do|counter|# statementsend

Ruby has several possible syntaxes, including the above samples.

1996: OCaml[edit]

See expression syntax.[6]

(* for_statement := "for" ident '=' expr ( "to" ∣ "downto" ) expr "do" expr "done" *)fori=1to5do(* statements *)done;;forj=5downto0do(* statements *)done;;

1998: ActionScript 3[edit]

for(varcounter:uint=1;counter<=5;counter++){//statement;}

2008: Small Basic[edit]

Fori=1To10' StatementsEndFor

Implementation in interpreted programming languages[edit]

In interpreted programming languages, for-loops can be implemented in many ways. Oftentimes, the for-loops are directly translated to assembly-like compare instructions and conditional jump instructions. However, this is not always so. In some interpreted programming languages, for-loops are simply translated to while-loops.[7] For instance, take the following Mint/Horchata code:

for i = 0; i < 100; i++ print i end for each item of sequence print item end /* 'Translated traditional for-loop' */ i = 0 while i < 100 print i i++ end /* 'Translated for each loop' */ SYSTEM_VAR_0000 = 0 while SYSTEM_VAR_0000 < sequence.length() item = sequence[SYSTEM_VAR_0000] print item SYSTEM_VAR_0000++ end

See also[edit]

References[edit]

For loop illustration, from i=0 to i=2, resulting in data1=200

Apparently FORTRAN 77 does not support dynamic memory allocation . You could try allocating memory in a c program and passing the result back to the FORTRAN routine.

from fortran.

The Unix portable Fortran-77 compiler ('f77') is written almost entirely in C. The second pass of the compiler is the same one used by the C compiler, and most 'f77' library routines are simply interfaces to corresponding C library routines. However, since Fortran does not support data structures like those used in C, you may not be able to take advantage of all the functionality that the 'curses' library offers. Manipulating windows with 'curses' is especially difficult. If you are interested in using routines involving data structures, you should probably use C instead of Fortran.

To call C routines from a Fortran program, you will have to write some C code. Fortran passes arguments by reference or address, so the C function has to be prepared to accept the variable as an address. This means that you will have to write functions in C that are called from Fortran that set up the arguments properly before calling the library function. Schematically, this might be something like:

Note underscore ( _ ) in name of routine.

In the C source file:

foo_(bar) /* Note underscore */ int bar; / Note variables are passed by address */

{ : }

In the Fortran source file:

call foo(baz) /* Assuming that "baz" is an integer. */ { : }

The underscore is important because Fortran uses the character to keep its symbols straight. If you are compiling on an RS6000 this is not default behavior, but compiling with the -qextname option on the RS6000 will cause it to perform identical to the other platforms.

Calling C From Fortran

Note the Fortran example below and how it calls C routines:

call initscr() call clear() . . . call move(x, y) . . . call refresh() call endwin() end

...where x and y are integers specifying the new coordinates.

Calling Curses from Fortran

If you were calling the 'curses' routine 'move()', you might do something like this:

The C source file contains the interface routine to the 'curses' library function 'move()', along with the other C functions that provide an interface to the some other 'curses' functions:

#include

initscr_() { initscr(); }

clear_() { clear(); }

move_(x, y) int *x, y; / These are pointers */ { move(*x, *y); }

refresh_() { refresh(); }

endwin_() { endwin(); }

The routines are compiled by using these commands:

cc -c curses.c f77 test.f curses.o -lcurses -ltermcap

If you are using macros defined in /usr/include/curses.h in your Fortran file, be warned that they assume conventions of the C language. Be aware that this may affect the results you obtain when using them in Fortran.

Leave a Comment

(0 Comments)

Your email address will not be published. Required fields are marked *