L-30 MCS 260 Mon 29 Oct 2001

Below are the complete programs we discussed in class.
/* L-30 MCS 260 Mon 29 Oct 2001 : management of account with static variables

As an illustration of the use of static variables we illustrate
the management of an account.  We use the following function : */

int manage ( float *amount, int witdep );
/* if witdep = -1, then we withdraw the given amount of money;
             =  0, then *amount is the available amount;
             = +1, then we deposit the *amount
A successful transaction returns 0, if there are insufficient funds
for a withdrawal, then 1 is returned. */

#include<stdio.h>

int main ( void )
{
   int ans;
   float amount;

   do
   {
     printf("  %s\n  %s\n  %s",
            "Type -1 to withdraw,",
            "type  0 to see the balance,",
            "type  1 to deposit (anything else will terminate) : ");

     if (scanf("%d",&ans) == 0) break;

     if (ans == 0)
     {
        ans = manage(&amount,0);
        printf("balance is $%.2f\n", amount);
     }
     else
     {
        printf("Give the amount : ");
        scanf("%f",&amount);
        ans = manage(&amount,ans);
        if (ans != 0)
           printf("unsuccessful transaction\n");
     }
   } while (1);
   return 0;
}

int manage ( float *amount, int witdep )
{
   static float sum = 0.0;

   switch(witdep)
   {
      case -1: if (*amount <= sum)
               {
                  sum -= *amount;
                  return 0;
               }
               else
                  return 1;
      case  0: *amount = sum;
               return 0;
      case  1: sum += *amount;
               return 0;
   }
}
/* L-30 MCS 260 Mon 29 Oct 2001 : illustration of registers for speed

The program below evaluates the sum of 1/n for n going from 1 to MAX.
To ensure a good performance, we ask both variables to be stored in
the high-speed memory registers.  The mathematical sum diverges to 
infinity.  However, we will never see large numbers with this sum.
As a matter a fact, the sum will get "stuck" at a certain point.
Do you understand what happens as we increase MAX?                */

#define  MAX  100000

#include<stdio.h>

int main ( void )
{
   register double sum = 0.0;
   register int i;

   for (i=1; i <= MAX; i++)
      sum += 1.0l/((double) i);

   printf("The sum of 1/n, for n=1..%d : %.15lf\n", MAX, sum);

   return 0;
}