Skip to content

Commit 540fe6c

Browse files
authored
Add Linear Search in Fortran (#5159)
1 parent 28f08a5 commit 540fe6c

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
Program linearsearch
2+
implicit none
3+
4+
character(len=256) :: input1
5+
character(len=10) :: input2
6+
integer :: key
7+
integer, dimension(5) :: array
8+
logical :: searched
9+
integer :: io_status
10+
11+
if(command_argument_count() < 2) call usage()
12+
13+
call get_command_argument(1, input1)
14+
call get_command_argument(2,input2)
15+
16+
if(input1 == "") call usage()
17+
18+
read(unit=input1, fmt=*, iostat=io_status) array
19+
read(unit=input2, fmt=*, iostat=io_status) key
20+
21+
searched = exists(array,key)
22+
23+
if (searched) then
24+
print '(a)', 'true'
25+
else
26+
print '(a)', 'false'
27+
end if
28+
29+
contains
30+
31+
pure function exists(array, key) result(answer)
32+
implicit none
33+
INTEGER :: i
34+
integer, intent(in) :: key
35+
integer, intent(in) :: array(:)
36+
logical :: answer
37+
38+
answer = .false.
39+
40+
do i = 1, size(array), 1
41+
if(array(i) == key) then
42+
answer = .true.
43+
return
44+
end if
45+
end do
46+
47+
end function exists
48+
49+
subroutine usage()
50+
write(*,'(a)') "Usage: please provide a list of integers (""1, 4, 5, 11, 12"") and the integer to find (""11"")"
51+
stop
52+
end subroutine usage
53+
54+
End Program linearsearch

0 commit comments

Comments
 (0)