BSD 4_3_Tahoe release
[unix-history] / usr / lib / learn / C / L42.1a
CommitLineData
d6c1f319
C
1#print
2Write a function
3 inprod(a,b,n)
4that computes the inner product of two integer vectors
5a and b which are n items long. Name the file "inprod.c"
6and compile and test it; then type ready.
7You may assume that the result and all intermediate
8values fit in a 16-bit integer, not usually a safe assumption.
9#once #create tzaqc.c
10main()
11{
12 int x[100], y[100];
13 int k;
14 for(k=0; k<100; k++)
15 {
16 x[k] = k%10;
17 y[k] = (k*k)%3;
18 }
19 if (inprod(x,y,100) != xprod(x,y,100)) return(1);
20 return(0);
21}
22xprod(x,y,n)
23 int *x, *y;
24{
25 int k, sum;
26 for(sum=k=0; k<n; k++)
27 sum=+ *x++ * *y++;
28 return(sum);
29}
30#user
31cc tzaqc.c inprod.o
32a.out
33#succeed
34/* one way */
35inprod(a, b, n)
36int *a, *b;
37{
38 int s;
39
40 s = 0;
41 while (n--)
42 s += *a++ * *b++;
43
44/* none of the spaces in the line above are necessary but
45 would you really want to read
46 s+=*a++**b++;
47 and try to parse it? Even clearer than what I have,
48 but slower, would be
49 for(i=0; i<n; i++)
50 s += a[i]*b[i];
51*/
52
53 return(s);
54}
55#log
56#next
5743.1a 10