/* MatVecMult.c */
/* product of a =matrix and a vertical vector */

#include <stdio.h>

#define NN 200    /* maximum number entries = NN-1 */
#define INF 0XEFFFFF

int InputMat(int*);
void DisplayMat(int*);


void main(void)
{
 int I,J,K,M,N,Sum,Nzeros,  *P,*Q,*R,       VV2[NN], Mat[NN], VV1[NN];
/* Mat is an MxN matrix, VV1,VV2 are vertical arrays of length N;
       VV2 = MatxVV1 */

 puts("Input matrix");
 K = InputMat(Mat);
 if (!K) {puts("ERROR; program aborted"); goto FIN;}

 puts("Imagine the following arrays to be vertical");
 puts("and that the input arrays come just after the matrix to form products");
 M = K%100;  N = K%100;

LP:
 printf("\nInput an array of %d integers (all zeros to terminate program)\n",N);
 Q=VV1; Nzeros=0;
 Q++; printf("Input first number:  "); scanf("%d",Q); getchar();
                      if (!*Q) Nzeros++;
 for (K=2; K<N; K++)
  {Q++; printf("Input next number:  "); scanf("%d",Q); getchar();}
                      if (!*Q) Nzeros++;
 Q++; printf("Input last number:  "); scanf("%d",Q); getchar();
                      if (!*Q) Nzeros++;
 if(Nzeros>=N) goto FIN;

 
 puts("Compute product of Mat and input attay and store entries in output array");

 P=Mat; R=VV2;

 for (I=1; I<=M; I++)
  {
   Q=VV1; Sum=0;
   for (J=1; J<=N; J++)    /* Compute dot product of  Row I of Mat with VV1 */
    {P++; Q++; Sum = Sum + (*P * *Q);}
   R++; *R = Sum;
  }


 R=VV2;

 puts("Output array from product is");
 for (K=1; K<=M; K++) {R++; printf("%d ",*R);} puts("");
 goto LP;

FIN:
 getchar();
}

/*****************************************************************************/

void DisplayMat(int *P)
 {
  int I,J,K,M,N,Max=0,T;    char S1[] = "%1d%2d%3d%4d%5d%6d%7d%8d%9d",S2[3];

  M=*P/100;  N=*P%100;  P++;
  for (I=1; I<=M; I++)
   {
    for (J=1; J<=N; J++)
     {
      if (*P>=0) K=*P; else K=-*P;
      if (K>Max) Max=K;
    }
  }

 T=1; K=1;
 while (T<=Max) {T=T*10; K++;} 
 for (I=0; I<3; I++) S2[I] = S1[3*K+I];  S2[3]='\0';


 for (I=1; I<=M; I++)
   {
    for (J=1; J<=N; J++) {printf(S2,*P); P++;}
    puts("");
  }

 return;
}

/*************************************************************************/

int InputMat(int *P)       /* P -> linearmatrix array */
{
 int I,J,M,N;

 printf("Input sixe of matrix (ROWSxCOLUMNS) "); scanf("%dx%d",&M,&N); getchar();
 *P= 100*M + N; P++;

 puts("All numbers are INTEGERS. Hit Enter key after all input numbers\n");

 for (I=1; I<=M; I++)
  {
   printf("Input row %d\n",I);
   printf("Input first number of the row  "); scanf("%d",P); getchar(); P++;
   for (J=2; J<N; J++)
    {printf("Input next number  "); scanf("%d",P); getchar(); P++;}
   printf("Input last number of the row  "); scanf("%d",P); getchar(); P++;
   puts("");
  }
 *P=INF;
 return M*100 + N;
}


