typestar

grade_report.f90 in Fortran

Quiz scores fold into averages and letter grades, then a formatted class report.

! Average quiz scores into letter grades and print the class report.
program grade_report
    implicit none
    character(len=8) :: names(4) = ["Imani   ", "Theo    ", &
                                    "Sofia   ", "Miles   "]
    integer :: quizzes(3, 4) = reshape( &
        [92, 88, 95, 78, 83, 80, 85, 91, 89, 62, 70, 68], [3, 4])
    real :: avg
    integer :: i

    print '(a)', "student    avg  grade"
    print '(a)', "---------------------"
    ! Each column of the matrix is one student's three quizzes.
    do i = 1, 4
        avg = sum(quizzes(:, i)) / 3.0
        print '(a, f6.1, 2x, a)', names(i), avg, letter(avg)
    end do
    print '(a)', "---------------------"
    print '(a, f5.1)', "class avg ", sum(quizzes) / 12.0
    print '(a, i0)', "quizzes graded: ", size(quizzes)

contains

    ! One grade band per branch, best first.
    pure function letter(avg) result(grade)
        real, intent(in) :: avg
        character(len=6) :: grade
        if (avg >= 90.0) then
            grade = "A"
        else if (avg >= 80.0) then
            grade = "B"
        else if (avg >= 70.0) then
            grade = "C"
        else
            grade = "retake"
        end if
    end function letter
end program grade_report

How it works

  1. reshape pours twelve scores into a 3-by-4 matrix, one column per student.
  2. sum(quizzes(:, i)) / 3.0 averages a column with an array section.
  3. The contained letter function maps each average to its grade band.

Keywords and builtins used here

The run, in numbers

Lines
38
Characters to type
1013
Tokens
220
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 203 seconds.

Type this snippet

Step 2 of 3 in Encore, step 26 of 27 in Language basics.

← Previous Next →