Welcome to Tech Support Forum home to more then 136,000 problems solved. Issues have included: Spyware, Malware, Virus Issues, Windows, Microsoft, Linux, Networking, Security, Hardware, and Gaming Getting your problem solved is as easy as:
1. Registering for a free account
2. Asking your question
3. Receiving an answer

Registered members:
* Get free support
* Communicate privately with other members (PM).
* Removal of this message
* See fewer ads.
* And much more..

 



Want to know how to post a question? click here Having problems with spyware and pop-ups? First Steps
Go Back   Tech Support Forum > Design Forum > Web Design & Programming
User Name
Password
Site Map Register Donate Rules Blogs Mark Forums Read


Web Design & Programming Discussion of web design, and server-side & client-side scripting

Reply
 
LinkBack Thread Tools
Old 04-23-2008, 10:48 PM   #1 (permalink)
Registered User
 
Join Date: Mar 2008
Posts: 6
OS: winxp


c program help - functions

Hello, I need some help with the program included below.


Code:
#include <stdio.h>
#include <conio.h>

int main(void)
{
              
              /* Declare Variables */
			  /* ----------------- */

	int x, number_of_deposits, number_of_withdrawals;
	float deposits[50], withdrawals[50];
	float current_balance;
	float balance;
	float total_deposits = 0, total_withdrawals = 0;
    char    first_name[20];
    
          /* Output initial greeting */
          /* ------------------------*/
        
        printf("Welcome to the Sears Banking System.\n\n");
        printf ("Please enter your first name: ");
        scanf ("%s", first_name);
        fflush(stdin);
        printf("\nHello, %s.\n\n", first_name);   
        
        /* Prompt user for current balance in dollars and cents. */
        /* ----------------------------------------------------- */

  do
  {

		printf ("Please enter your current balance in dollars and cents: ");
		scanf ("%f",&current_balance);
		fflush(stdin);


		if (current_balance < 0)
			printf ("Error: Beginning balance must be at least zero, please re-enter!\n\n");

  } while (current_balance < 0); /* end do-while loop */

        /* Prompt user for the number of withdrawals */
	    /* ----------------------------------------- */

  do
  {

		printf ("\nEnter the number of withdrawals: ");
		scanf ("%i",&number_of_withdrawals);
		fflush (stdin);


		if (number_of_withdrawals < 0 || number_of_withdrawals > 50)
			printf ("Error: Number of withdrawals must be between zero and 50, please re-enter!\n\n");

  } while (number_of_withdrawals < 0 || number_of_withdrawals > 50); /* end do-while trap loop */

        /* Prompt user to enter the number of deposits. */
	    /* -------------------------------------------- */

  do
  {

		printf ("\nEnter the number of deposits: ");
		scanf ("%i",&number_of_deposits);
		fflush (stdin);

		if ( number_of_deposits < 0 || number_of_deposits > 50)
			printf ("Error: Number of deposits must be between 0 and 50, please re-enter!\n\n");

  } while (number_of_deposits < 0 || number_of_deposits > 50); /* end do-while trap loop */
  
  printf("\n");
		
        /* Prompt user for positive deposits and withdrawals. */
	    /* -------------------------------------------------- */

  for (x = 1; x <= number_of_deposits; x++)
  {

	 do
	{

		printf ("Enter the amount of deposit #%i: ", x);
		scanf ("%f",&deposits[x]);
		fflush (stdin);

		if (deposits[x] <= 0)
			printf ("*** Deposit amount must be greater than zero. Please re-enter! ***\n");

	} while (deposits[x] <= 0);

  total_deposits = total_deposits + deposits[x];

  }// end for loop
  
  printf("\n");

  for (x = 1; x <= number_of_withdrawals; x++)
  {
	  do
	  {
		  printf ("Enter the amount of withdrawal #%i: ", x);
		  scanf ("%f",&withdrawals[x]);
		  fflush (stdin);

		  if (withdrawals[x] > current_balance)
				printf ("***Withdrawal amount exceeds current balance.***\n");
		  else
		  if (withdrawals[x] <= 0)
				printf ("*** Withdrawal amout must be greater than zero. Please re-enter! ***");

	} while (withdrawals[x] > current_balance || withdrawals[x] <= 0); /* end do-while loop */

  total_withdrawals = total_withdrawals + withdrawals[x];
  
        /* If balance goes to zero, reset the withdrawal count */
		/* -------------------------------------------------- */

  balance = current_balance - total_withdrawals + total_deposits;

	if (balance == 0)
	{
		 printf ("\n *** Balance is now zero. No more withdrawals can be made at this time. ***\n");
		 number_of_withdrawals = x;
		 break;

	} // end-if

  } //end for loop


		/* Calculate and display the closing balance */
		/* ---------------------------------------- */

	printf ("\n*** Your closing balance is $%.2f, %s*** \n", balance, first_name);


	if (balance >= 5000.00)
		printf ("*** Time to invest some money!*** \n\n");
	else if (balance >= 15000.00 && balance <= 49999.99)
		printf ("*** Maybe you should consider a CD.*** \n\n");
	else if (balance >= 1000.00 && balance <= 14999.99)
		printf ("*** Keep up the good work.*** \n\n");
	else
		printf ("*** %s, your balance is getting low!*** \n\n", first_name);

		/* Display bank record */
		/* ------------------ */
	
    printf ("     *** Bank Record ***\n");

	printf ("\nStarting Balance:$   %13.2f\n\n", current_balance);


	for (x = 1; x <= number_of_deposits; x++)
	{
	 printf ("Deposit #%i:          %13.2f\n", x, deposits[x]);
	}


	for (x = 1; x <= number_of_withdrawals; x++)
	{
	 printf ("\nWithdrawal  #%i:      %13.2f", x, withdrawals[x]);
	}


	printf ("\n\nEnding Balance is:$  %13.2f\n", balance);
	
	{
     getch();
     return 0;
    }
} /*end main*/
I need to alter this program so that it uses at least three "non-trivial" functions (non-trivial meaning that it does more than just print a line of text). My problem is that the text book I am using isn't very helpful so any help would be much appreciated.

Thanks
Sleepwalker817 is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Reddit!
Reply With Quote
Important Information
Join the #1 Tech Support Forum Today - It's Totally Free!

TechSupportForum.com is a leading support website for your computer needs. We offer free, friendly and personalized computer support. Why pay to have your computer fixed when you can do it for free.

Join TechSupportforum.com Today - Click Here

Old 04-24-2008, 05:18 PM   #2 (permalink)
Design Team Member
 
jamiemac2005's Avatar
 
Join Date: Jul 2007
Location: Coventry, UK
Posts: 1,883
OS: Vista, various linux distros


Re: c program help - functions

If you want a nice tutorial on functions (and anything else C or C++ related) you can go to www.cprogramming.com I believe the information you're seeking is here:

http://www.cprogramming.com/tutorial/c/lesson4.html

Hope it helps,
Jamey

p.s. after having looked through your code there is alot which could be proceduralised (contained in a function to make the code re-useable, etc etc)... so take a look at that tutorial and it should help
jamiemac2005 is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Reddit!
Reply With Quote
Old 04-24-2008, 05:20 PM   #3 (permalink)
Design Team Member
 
jamiemac2005's Avatar
 
Join Date: Jul 2007
Location: Coventry, UK
Posts: 1,883
OS: Vista, various linux distros


Re: c program help - functions

Oh, also, when seeking help on C, etc. you should use the Programming sub-forum, this is web-design&programming (all web-based)...

The Programming forum is here:

http://www.techsupportforum.com/conv...t/programming/

Cheers,
Jamey
jamiemac2005 is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Reddit!
Reply With Quote
Old 04-27-2008, 04:35 AM   #4 (permalink)
Registered User
 
Join Date: Mar 2008
Posts: 6
OS: winxp


Re: c program help - functions

Hello, This is what I have so far.


Code:
#include <stdio.h>

float get_startingbalance(void);
float getCntOfWithdrawls();
float getCntOfDeposits();
float getEachDeposit();
float getEachWithdrawl();
float checkBalance();
float calcAndDisplayBalance();
float displayBankRecord()
void print_withdrawalnumber(int num_withdrawals);
void print_depositnumbers(int num_deposits);
void print_startingbalance(float start_balance);
void print_endbalance(float current_balance);
int main()
{
/* Declare Variables */
int num_withdrawals, num_deposits, x;
float deposits[50] = {0.0}; 
float withdrawals[50] = {0.0}; 
float current_balance = {0.0};
float start_balance = {0.0};
char first_name[20];

/* Output initial greeting */
printf("Welcome to the Sears Banking System.\n");
printf("Please enter your first name: ");
scanf("%s", first_name);
fflush(stdin);
printf("\nHello, %s\n\n", first_name);

/* Prompt user for current balance. */

start_balance = get_startingbalance();

printf("You entered %.2f ", start_balance);

getchar();



} /* end main */
/*START FUNCTION GET STARTING BALANCE*/

float get_startingbalance()
{
float start_bal;
do
{
printf("Please enter your current balance in dollars and cents: ");
scanf("%f", &start_bal);
fflush(stdin);
if(start_bal < 0)
printf("Invalid entry. Starting balance must be at least zero!\n\n");
}while(start_bal < 0); /*END DO WHILE*/

return start_bal;

} /* end function get starting balance */
/*START FUNCTION GET NUMBER OF WITHDRAWLS*/

float getCntOfWithdrawls()
{
float num_withdrawls
do
{
printf ("\nEnter the number of withdrawals: ");
scanf ("%i",&num_withdrawals);
fflush (stdin);
if (num_withdrawals < 0 || num_withdrawals > 50)
printf ("Error: Number of withdrawals must be between zero and 50, please re-enter!\n\n");
} while (num_withdrawals < 0 || number_withdrawals > 50); /* end do-while trap loop */

return num_withdrawls;

}/* end function number of withdrawls */
/*START FUNCTION GET NUMBER OF DEPOSITS*/

float getCntOfDeposits()
{
float num_deposits
do
{
printf ("\nEnter the number of deposits: ");
scanf ("%i",&num_deposits);
fflush (stdin);
if ( num_deposits < 0 || number_deposits > 50)
printf ("Error: Number of deposits must be between 0 and 50, please re-enter!\n\n");
} while (number_deposits < 0 || number_deposits > 50); /* end do-while trap loop */
  
return num_deposits;

}/* end function number of deposits */
/*START FUNCTION GET EACH DEPOSIT*/

float getEachDeposit()
{
float num_deposits
for (x = 1; x <= num_deposits; x++)
{
do
{
printf ("Enter the amount of deposit #%i: ", x);
scanf ("%f",&deposits[x]);
fflush (stdin);
if (deposits[x] <= 0)
printf ("*** Deposit amount must be greater than zero. Please re-enter! ***\n");
} while (deposits[x] <= 0);
total_deposits = total_deposits + deposits[x];
}/*end for loop*/
/*end function get each deposit*/
/*START FUNCTION GET EACH WITHDRAWL*/

float getEachWithdrawl()
{
float num_withdrawls
for (x = 1; x <= num_withdrawals; x++)
{
do
{
printf ("Enter the amount of withdrawal #%i: ", x);
scanf ("%f",&withdrawals[x]);
fflush (stdin);
if (withdrawals[x] > current_balance)
printf ("***Withdrawal amount exceeds current balance.***\n");
else
if (withdrawals[x] <= 0)
printf ("*** Withdrawal amout must be greater than zero. Please re-enter! ***");
} while (withdrawals[x] > current_balance || withdrawals[x] <= 0); /* end do-while loop */
total_withdrawals = total_withdrawals + withdrawals[x];
/*end function get each withdrawl*/
/*START FUNCTION CHECK BALANCE*/

float checkBalance()
{
float current_balance
balance = current_balance - total_withdrawals + total_deposits;
if (balance == 0)
{
printf ("\n *** Balance is now zero. No more withdrawals can be made at this time. ***\n");
num_withdrawals = x;
break;
} /*end-if*/
} /*end for loop*/
/*end function check balance*/
/*START FUNCTION CALC AND DISPLAY BALANCE*/

float calcAndDisplayBalance()
{
printf ("\n*** Your closing balance is $%.2f, %s*** \n", balance, first_name);
if (balance >= 5000.00)
printf ("*** Time to invest some money!*** \n\n");
else if (balance >= 15000.00 && balance <= 49999.99)
printf ("*** Maybe you should consider a CD.*** \n\n");
else if (balance >= 1000.00 && balance <= 14999.99)
printf ("*** Keep up the good work.*** \n\n");
else
printf ("*** %s, your balance is getting low!*** \n\n", first_name);
}/*end-if*/
/*end function calc and display balance*/
/*START FUNCTION DISPLAY BANK RECORD*/

float displayBankRecord()
printf ("     *** Bank Record ***\n");
printf ("\nStarting Balance:$   %13.2f\n\n", current_balance);
for (x = 1; x <= number_of_deposits; x++)
{
printf ("Deposit #%i:          %13.2f\n", x, deposits[x]);
}
for (x = 1; x <= number_of_withdrawals; x++)
{
printf ("\nWithdrawal  #%i:      %13.2f", x, withdrawals[x]);
}
printf ("\n\nEnding Balance is:$  %13.2f\n", balance);
/*end function display bank record*/
Can someone tell me if I am on the right track? I have to admit that using function is really confusing me for some reason.
Sleepwalker817 is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Reddit!
Reply With Quote
Old 04-27-2008, 05:32 AM   #5 (permalink)
Design Team Member
 
jamiemac2005's Avatar
 
Join Date: Jul 2007
Location: Coventry, UK
Posts: 1,883
OS: Vista, various linux distros


Re: c program help - functions

What you have so far looks fine, you've done everything as you have to. Well done =]... As long as you understand why functions are used and how to use them right now the more practice you get the easier it will seem.

Glad you sorted it out,
Jamey
jamiemac2005 is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Reddit!
Reply With Quote
Old 04-27-2008, 10:49 PM   #6 (permalink)
Registered User
 
Join Date: Apr 2008
Location: Oklahoma City
Posts: 26
OS: xp(sp2), OSX(10.5)


Re: c program help - functions

Quote:
Originally Posted by Sleepwalker817 View Post
Can someone tell me if I am on the right track? I have to admit that using function is really confusing me for some reason.
Try not to think about functions as normal code where you know what information you start with and end with. Some argue you should not access global variables with function, that all the data they need to work should be passed to them.

ex:
int sum( int x, int y ); // you know want you start with and will always get x + y as result.


// assuming included time.h of c standard library
time_t now;
time( now ); // system will fill the structure with the current time.






I am a little curious why you seem to be interested in learning c and avoiding c++. In c++ it expands the concepts of functions so they protect your data, without global variables. In classes the functions (also called methods) have access to the data passed to them as parameters and the variables declared in the class. You declared classes like the default c types;

class account{

int AccountNumber;
double Balance;
vector<transaction> History;
name CustomerName;

double loadHistory(); // I am assuming that the bank would store their history in database, so lets say it gets history for this AccountNumber

public:

account( int account_number ): AccountNumber(account_number){
loadHistory();
}

double getBalance();
vector<double>& getDeposits(); // returns an array of all transactions that change is positive
vector<double>& getWithdrawls(); // returns an array of all transactions that are negative
double displayBankRecord(); // I was not sure what you were going for here, floats are not usually used for status codes

bool makeDeposit( double amount );
bool makeWithdrawl( double amount );
void payInterest( double percent );

friend ostream& operator<<( ostream &os, const account &a );

};

ostream& operator<<( ostream &os, const account &a ){
os << "Current Account Balance of " << CustomerName << " $" << Balance << ". Thank you for banking with us.";
return os;
}

This organizations simplifies handling multiple accounts at once, and reuse of code. It also limits the number of ways that data can be changed to those that if needed will verify that the data will not be corrupted. It also reduces conflict when multiple files are included, even more so if namespaces are used.


A function here would screen the data to change then do it and return true, if problem occurs return false.
Note: this is an example you would probably use either an exception or at least a return code in real life, and more validation.

bool makeDeposit( double amount ){
if( amount < 0 ) return false;

Balance += amount;

time_t now;
time( now );

transaction NewTransaction( amount, now );

History.push_back( NewTransaction );
History.storeChangesToDatabase(); // not a actual method of vector class but imagine it is for this example
}




Using a class:

int MyAccountNumber = 555555555;
account MySavingsAccount( MyAccountNumber );

cout << MySavingsAccount << endl;

MySavingsAccount.makeDeposit( 500.00 );
MySavingsAccount.makeWithdrawl( 100.00 );

cout << MySavingsAccount << endl;


Would print out:

Current Account Balance of Snowman $10000. Thank you for banking with us.
Current Account Balance of Snowman $10400. Thank you for banking with us.
snowman7000 is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Reddit!
Reply With Quote
Reply


Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off




All times are GMT -7. The time now is 02:56 AM.



Copyright 2001 - 2009, Tech Support Forum
Home Tips Plus | Outdoor Basecamp | Automotive Support Forum

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85