Inner Product

WARNING: This example assumes spaces are ignored for the I and F descriptors and the output is sent to a printer.

Problem Statement

The inner product of two sequences of numbers x1, x2, x3,...., xn and y1, y2, y3,...., yn is defined to be the sum of products of corresponding elements. More precisely, the inner product is

x1y1 + x2y2 + x3y3 + ... + xnyn

Write a Fortran to read in two sequences of numbers and computes their inner product.

Suppose we have an input like the following. The first line gives the number of input values. Each of the input line has two fields with 10 positions each. You should use only one format to read all data items.

         1
....5....0
5
4    7
2    -1
6    2
-3   4
-2   -3
Your program should produce the following output report.
         1    1    2    2    3
....5....0....5....0....5....0
 Input Data

    No    X    Y
     1    4    7
     2    2   -1
     3    6    2
     4   -3    4
     5   -2   -3

 Input product =      32

Solution

PROGRAM  InnerProduct
   IMPLICIT  NONE
   INTEGER, PARAMETER         :: SIZE = 50
   INTEGER                    :: Number, Sum, i
   INTEGER, DIMENSION(1:SIZE) :: x, y
   CHARACTER(LEN=80)          :: Fmt1, Fmt2, Fmt3

   Fmt1 = "(I5/(2I5))"
   Fmt2 = "(1X,A//1X,3A5/(1X,3I5))"
   Fmt3 = "(/1X, A, I7)"

   READ(*,Fmt1)   Number, (x(i), y(i), i = 1, Number)
   WRITE(*,Fmt2)  "Input Data", "No", "X", "Y", &
                  (i, x(i), y(i), i = 1, Number)
   Sum = 0
   DO i = 1, Number
      Sum = Sum + x(i)*y(i)
   END DO
   WRITE(*,Fmt3)  "Input product = ", Sum
END PROGRAM  InnerProduct
Click here to download this program.

Program Input and Output

Suppose we have the following input:
         1
....5....0
5
4    7
2    -1
6    2
-3   4
-2   -3
The output of the program is:
         1    1    2    2    3
....5....0....5....0....5....0
 Input Data

    No    X    Y
     1    4    7
     2    2   -1
     3    6    2
     4   -3    4
     5   -2   -3

 Input product =      32

Discussion