L-11 MCS 260 Fri 14 Sep 2001

Below is the program we discussed in class.

/* L-11 MCS 260 Fri 14 Sep 2001 : management of bank account 

We used this program in L-10 to illustrate the switch.
At first, it may seem that the program below is much
more involved than the equivalent program of L-10.
However, the use of functions makes the program more
readable, extendable, and better maintainable.
For example, if we wish to change the layout of the
way we print the balance, then we only need to modify
the program at only one place, in the definition of the
print function and not everywhere the print is invoked.

Before the main program, we list the prototypes of the
function we use: */

int ask_user();
/* prints menu and returns answer :
     0. leave the program;
     1. make a deposit;
     2. withdraw cash;
     3. print the current balance. */

int withdraw ( int balance );
/* reads in an amount and subtracts it from the balance,
   the new balance is returned */

int deposit ( int balance );
/* reads in an amount and adds it to the balance,
   the new balance is returned */

void print ( int balance );
/* prints the balance on screen */

#include<stdio.h>

int main(void)
{
   int balance = 0;    /* balance of bank account */
   int choice;         /* choice of the user */

   do
   {
      choice = ask_user();

      switch (choice)
      {
	 case 0: printf("\nBye bye, have a nice day now.\n\n");
                 break;
         case 1: balance = deposit(balance);
                 print(balance);
                 break;
         case 2: balance = withdraw(balance);
         case 3: print(balance);
	         break;
         default: printf("\nInvalid option, please try again...\n");
      }       

   } while (choice != 0);

   return 0;
}

/* after the main program come the function definitions : */

int ask_user()
{
   int answer = 0;    /* provide default for invalid conversions */
 
   printf("\nWe offer the following options :\n");
   printf("  0. leave this program;\n");
   printf("  1. make a deposit;\n");
   printf("  2. withdraw cash;\n");
   printf("  3. print the balance.\n");
   printf("Type 0, 1, 2, or 3 to choose : ");
   scanf("%d", &answer);

   return answer;
}

int withdraw ( int balance )
{
   int amount;

   printf("\nGive amount you wish to withdraw : ");
   scanf("%d", &amount);

   return balance - amount;
}

int deposit ( int balance )
{
   int amount;

   printf("\nGive amount you wish to deposit : ");
   scanf("%d", &amount);

   return balance + amount;
}

void print ( int balance )
{
   printf("\nThe current balance at your account is %d.\n", balance);
}