0% found this document useful (0 votes)
5 views2 pages

Q3

This Fortran program sorts an array of integers in both ascending and descending order. It reads the size of the array from standard input and populates the array from a file if the size is 5 or greater, otherwise it outputs an error message. The sorted arrays are then written to an output file.

Uploaded by

ZeReF Gamer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Q3

This Fortran program sorts an array of integers in both ascending and descending order. It reads the size of the array from standard input and populates the array from a file if the size is 5 or greater, otherwise it outputs an error message. The sorted arrays are then written to an output file.

Uploaded by

ZeReF Gamer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

program array_sort

implicit none

integer :: i, j, n, temp
integer, allocatable, dimension(:) :: ar

read(*,*) n

open(unit=2, file='ar_inp.txt')

12 format(i2)

if(n>=5) then
allocate(ar(0:n-1))
read(*, *) (ar(i), i=0, n-1)
write(2, 12) (ar(i), i=0, n-1)
else
write(*,*) "Error: n < 5"
end if

close(2)

open(unit=5, file='ar_out.txt')

write(5, *) "Ascending Order: "


call sort_Ascending(i, j, temp, n, ar)
write(5, *), (ar(i), i=0, n-1)

write(5, *) "Descending Order: "


call sort_Descending(i, j, temp, n, ar)
write(5, *), (ar(i), i=0, n-1)

close(5)

end program

subroutine sort_Ascending(i, j, temp, n, ar)


implicit none
integer :: i, j, n, temp
integer, dimension(0:n-1) :: ar

do i=0, n-2
do j=i+1, n-1
if(ar(i) > ar(j)) then
temp = ar(i)
ar(i) = ar(j)
ar(j) = temp
end if
end do
end do

end subroutine

subroutine sort_Descending(i, j, temp, n, ar)


implicit none
integer :: i, j, n, temp
integer, dimension(0:n-1) :: ar
do i=0, n-2
do j=i+1, n-1
if(ar(i) < ar(j)) then
temp = ar(i)
ar(i) = ar(j)
ar(j) = temp
end if
end do
end do

end subroutine

You might also like