1

I created a program to calculate Fibonacci numbers, using a subprogram that contains functions. how to call the function in my main program in visual studio

ps: i use intel compiler

the function that i make is bellow

    program function_fibonacci

    implicit none
function fibonacci (n1,n2,n)
integer, intent(in)::n1,n2,n
integer::fibonacci(1:n),i
fibonacci(1)=n1
fibonacci(2)=n2
do i=3,n
    fibonacci(i)=fibonacci(i-1)+fibonacci(i-2)
end do

    end program function_fibonacci

than how can i call that function in my main code

program fibonacci
integer ::n1,n2,n
print *, 'input the first fibonacci number'
read *, n1
print *, 'input the second fibonacci number'
read *, n2
print *, 'how many Fibonacci numbers do you want to display?'
read *, n
print *, 'Result'
print *, fibonacci(n1,n2,n)
end program fibonacci

if we use linux we can just type

gfortran -g main_program.f90 -o program.exe

2 Answers 2

2

Your syntax is invalid. You cannot write

    program function_fibonacci

    implicit none
function fibonacci (n1,n2,n)
    ...

You can either make the function internal to the program (not recommended) or put it into a module (recommended). Creating the function separate as external is not possible here because the function returns an array and is not recommended in general. How to declare the type of a function that returns an array in Fortran?

module functions
  implicit none
contains

function fibonacci (n1,n2,n)
  integer, intent(in)::n1,n2,n
  integer::fibonacci(1:n),i
  fibonacci(1)=n1
  fibonacci(2)=n2
  do i=3,n
    fibonacci(i)=fibonacci(i-1)+fibonacci(i-2)
  end do
end function

end module

program fibonacci

use functions

implicit none
integer ::n1,n2,n
print *, 'input the first fibonacci number'
read *, n1
print *, 'input the second fibonacci number'
read *, n2
print *, 'how many Fibonacci numbers do you want to display?'
read *, n
print *, 'Result'
print *, fibonacci(n1,n2,n)

end program fibonacci
Sign up to request clarification or add additional context in comments.

2 Comments

For what reason is it not possible for an external function to have an array result?
@francescalus Well, we need an explicit interface and I didn't want to even mention these details and interface blocks and stuff. Because it is above the current level of the asker.
0

Your program needs a contains section

program test_fibonacci
implicit none

print *, fibonacci(1,2, 8)

contains
function fibonacci (n1,n2,n)
integer, intent(in)::n1,n2,n
integer::fibonacci(1:n),i
fibonacci(1)=n1
fibonacci(2)=n2
do i=3,n
    fibonacci(i)=fibonacci(i-1)+fibonacci(i-2)
end do
end program 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.