/* calculat.c  calculator to add,subtract,multiply or divide 2 numbers
   Richard Kay
   last changed: 27 Sept 2000
*/

#include <stdio.h>
#include <conio.h>

void get_two(float *f1,float *f2,char *operation); /* gets 2 numbers */
float add(float n1, float n2);      /* adds */
float subtract(float n1, float n2); /* subtracts */
float multiply(float n1, float n2); /* multiplies */
float divide(float n1, float n2);   /* divides */

int main(void){
  char continu='y',choice;
	 /* continu: whether user wants to continue
	 choice: option entered by user */
  int arithop; /* 1 (true) if result of arithmetic operation is
		     to be output 0 (false) if not */
  float n1,n2,result; /* 2 numbers to be operated upon and result */
  while(continu == 'y'){  /* loop until user wants to quit */
	fflush(stdin);
	clrscr();
	/* display menu and input user choice */
	printf("Enter    For Option\n");
	printf("  a      add \n");
	printf("  s      subtract \n");
	printf("  m      multiply \n");
	printf("  d      divide\n");
	printf("  q      quit \n");
	choice=getchar(); fflush(stdin);

	/* process user choice */
	switch(choice){
	  case 'a': case 'A':
		get_two(&n1,&n2,"add");
		result=add(n1,n2);    /* add */
		arithop=1; /* true */
		break;
	  case 's': case 'S':
		get_two(&n1,&n2,"subtract");
		result=subtract(n1,n2);    /* subtract */
		arithop=1; /* true */
		break;
	  case 'm': case 'M':
		get_two(&n1,&n2,"multiply");
		result=multiply(n1,n2);   /* multiply */
		arithop=1; /* true */
		break;
	  case 'd': case 'D':
		get_two(&n1,&n2,"divide");
		if(n2==0){ /* catch attempt to divide by 0 */
		  printf("divide by zero error caught\n");
		  arithop=0; /* false */
		  break;
		}
		result=divide(n1,n2);   /* divide */
		arithop=1; /* true */
		break;
	  case 'q': case 'Q':   /* user wants to quit */
		continu='n';
		arithop=0; /* false */
		break;
	  default:             /* trap any option not yet tested for */
		printf("invalid option please try again\n");
		arithop=0; /* false */
		break;
	} /* end of switch */

	/* output result */
	if(arithop)  /* arithmetic operation carried out, so print result */
	  printf("result of calculation is %f\n",result);
	printf("press a key to continue\n");
	getch();
  } /* end of while block */
  return 1;
}  /* end of main function */

void get_two(float *f1,float *f2,char *operation){
  /* inputs 2 numbers for arithmetic operation */
  printf("enter 2 numbers to %s\n",operation);
  scanf("%f%f",f1,f2);
  fflush(stdin);
}


float add(float n1, float n2){ /* adds */
  return n1+n2;
}

float subtract(float n1, float n2){  /* subtracts */
  return n1-n2;
}

float multiply(float n1, float n2){  /* multiplies */
  return n1*n2;
}

float divide(float n1, float n2){  /* divides */
  return n1/n2;
}
