# Balancing Accounts

## Difficulty: Medium

Your bank receives two deposits or credits and three bills or debits. The credits cover the debits, meaning that your balance should never go below zero, but the bank has clever software: The bills are calculated first, which thrusts your account into negative territory complete with fees — even though the deposits cover the bills. Is this obnoxious behavior the result of greedy bankers or clever programming?

It’s both!

Bankers have long been accused of rushing through debits before credits to rake in the fines for low or zero balances. I view this approach as evil, though as a programmer I know ways exist to avoid the problem. Do you?

The following code simulates deposits and withdrawals to a bank account. Each amount in the `deposit[]` array is added or subtracted from the current balance.

### 2021_04_01-Lesson.c

```#include <stdio.h>

int main()
{
float deposit[20] = {
10.0, -5.0, -10.0, 5.0, 15.0, -10.0, 5.0, -10.0, 5.0, -15.0,
-5.0, 10.0, 15.0, -15.0, 5.0, 15.0, -5.0, 10.0, -10.0, -5.0
};
float a;

a = 0.0;
for(int x=0; x<20; x++)
{
printf("Bal: \$%4.2f\t",a);
if( deposit[x] > 0 )
printf("credit %.2f",deposit[x]);
else
printf("debit %.2f",deposit[x]);
a += deposit[x];
/* output new balance */
printf("\t= \$%4.2f",a);
/* flag overdrafts */
if( a < 0 )
printf("\t** Overdraft\n");
else
putchar('\n');
}

return(0);
}```

The program outputs a running total, where you can see how the balance occasionally dips below zero:

```Bal: \$0.00	credit 10.00	= \$10.00
Bal: \$10.00	debit -5.00	= \$5.00
Bal: \$5.00	debit -10.00	= \$-5.00	** Overdraft
Bal: \$-5.00	credit 5.00	= \$0.00
Bal: \$0.00	credit 15.00	= \$15.00
Bal: \$15.00	debit -10.00	= \$5.00
Bal: \$5.00	credit 5.00	= \$10.00
Bal: \$10.00	debit -10.00	= \$0.00
Bal: \$0.00	credit 5.00	= \$5.00
Bal: \$5.00	debit -15.00	= \$-10.00	** Overdraft
Bal: \$-10.00	debit -5.00	= \$-15.00	** Overdraft
Bal: \$-15.00	credit 10.00	= \$-5.00	** Overdraft
Bal: \$-5.00	credit 15.00	= \$10.00
Bal: \$10.00	debit -15.00	= \$-5.00	** Overdraft
Bal: \$-5.00	credit 5.00	= \$0.00
Bal: \$0.00	credit 15.00	= \$15.00
Bal: \$15.00	debit -5.00	= \$10.00
Bal: \$10.00	credit 10.00	= \$20.00
Bal: \$20.00	debit -10.00	= \$10.00
Bal: \$10.00	debit -5.00	= \$5.00```

Your challenge for this month’s Exercise is to modify the code so that the balance never goes below zero. All values in the `deposit[]` array are still be processed, but you must devise a way to ensure that the debits aren’t subtracted until sufficient funds are available in the account to cover them.

Multiple solutions are possible for this puzzle. Frankly, anything goes, though all the values must be processed.

Please try this Exercise on your own before you check my my solution.