NAG Library Manual, Mark 28.5
Interfaces:  FL   CL   CPP   AD 

NAG CL Interface Introduction
Example description
/* nag_contab_chisq (g11aac) Example Program.
 *
 * Copyright 2022 Numerical Algorithms Group.
 *
 * Mark 28.5, 2022.
 *
 */

#include <nag.h>
#include <stdio.h>

#define NOBST(I, J) nobst[(I)*tdnobs + J]
int main(void) {

  Integer exit_status = 0, i, j, ncol, *nobst = 0, nrow, tdnobs;
  NagError fail;
  double chi, *chist = 0, df, *expt = 0, g, prob;

  INIT_FAIL(fail);

  printf("nag_contab_chisq (g11aac) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT " %" NAG_IFMT " %*[^\n] ", &nrow, &ncol);
  if (nrow >= 2 && ncol >= 2) {
    if (!(expt = NAG_ALLOC((nrow) * (ncol), double)) ||
        !(chist = NAG_ALLOC((nrow) * (ncol), double)) ||
        !(nobst = NAG_ALLOC((nrow) * (ncol), Integer))) {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
    tdnobs = ncol;
  } else {
    printf("Invalid nrow or ncol.\n");
    exit_status = 1;
    return exit_status;
  }
  for (i = 0; i < nrow; ++i) {
    for (j = 0; j < ncol; ++j)
      scanf("%" NAG_IFMT "", &NOBST(i, j));
    scanf("%*[^\n]");
  }

  /* nag_contab_chisq (g11aac).
   * chi^2 statistics for two-way contingency table
   */
  nag_contab_chisq(nrow, ncol, nobst, tdnobs, expt, chist, &prob, &chi, &g, &df,
                   &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_contab_chisq (g11aac).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf("Probability = %6.4f\n", prob);
  printf("Pearson Chi-square statistic = %8.3f\n", chi);
  printf("Likelihood ratio test statistic = %8.3f\n", g);
  printf("Degrees of freedom = %4.0f\n", df);
END:
  NAG_FREE(expt);
  NAG_FREE(chist);
  NAG_FREE(nobst);
  return exit_status;
}