Thread: Functions?

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    33

    Functions?

    Still trying to learn functions and I am not sure if I am doing it right. Can someone take a look at my code (Please) I added two functions into it. Did I do them right?

    Code:
    #include <stdio.h>
    void Print_Intro_Heading();
    void print_comment (float amount);
    int	main ()
    {
    
    	/* Variable Declarations */
    	/* --------------------- */
    	char     first_name[20];
    	int		num_of_deposits, num_of_withdrawals, i;
    	float		amount_to_deposit[50], amount_to_withdraw[50];
    	float   	start_balance, current_balance;
    
    
    	 /*Prompt user to input their name*/
    	 /*-------------------------------*/
    
    		 printf ("\nWhat is your name? ");
    		 scanf ("%s", first_name);
           fflush(stdin);
    
    
    	/* This function prints the users name and a title for the program */
    	/*-----------------------------------------------------------------*/  
    	{
    	void Print_Intro_Heading();
    	
    	printf ("\n***********************************************\n"
    
    					 "Hi %s. Welcome to Colleen's Banking program!\n"
    	
    					 "***********************************************\n\n", first_name);
    	}// end funtion
    
    	/* Prompt user for starting balance */
    	/* -------------------------------- */
    
    	do
    	{
    		printf ("Enter current balance in dollars and cents: ");
    		scanf	("%f", &start_balance);
    		
    		if (start_balance < 0)
    			printf("Error: Starting Balance must be at least zero! Please re-enter!\n\n");
    	} while (start_balance < 0);
    
    		  /* Prompt for the number of withdrawals                     */
    		  /* -------------------------------------------------------- */
    
    	do
    	{
    		printf ("\nEnter the number of withdrawals (0-50): ");
    		scanf	("%i", &num_of_withdrawals);
    		
    
          /* Emsure that user did not enter less than 0 withdrawals   */
    		/* Ensure that user did not enter more than 50 withdrawals. */
          /*----------------------------------------------------------*/
    
    		if (num_of_withdrawals > 50)
    			  printf ("*** Maximum amount of withdrawals is 50. Please re-enter!***\n");
    		if (num_of_withdrawals < 0)
    			  printf ("*** Negative number of withdrawals not allowed. ***\n");
    
    	} while (num_of_withdrawals > 50 || num_of_withdrawals < 0);
    
    
    		  /* Prompt for the number of deposits.                    */
    		  /* ----------------------------------------------------- */
    
    	do
    	{
    		printf ("\n\nEnter the number of deposits (0-50): ");
    		scanf	("%i", &num_of_deposits);
    		
    
          /* Ensure that user did not enter less than 0 deposits.  */
    		/* Ensure that user did not enter more than 50 deposits. */
    		/*-------------------------------------------------------*/
    
    		if (num_of_deposits > 50)
    			  printf ("*** Maximum amount of deposits is 50. Please re-enter! ***\n");
    		if (num_of_deposits < 0)
    			  printf ("*** Negative number of deposits not allowed. ***\n");
    
    	} while ( num_of_deposits > 50 || num_of_deposits < 0);
    
    
    
    		  /* Retain starting balance for bank record. */
    		  /* ---------------------------------------- */
    
    	current_balance = start_balance;
    
    		  /* Prompt for all deposit amounts, keeping track of current balance. */
    		  /* ----------------------------------------------------------------  */
    
    	printf ("\n");     // spacing
    	for (i = 0; i < num_of_deposits; i++ )
    	{
    		do
    		{
    			printf ("Enter the amount of deposit #%i: ", i+1 );
    			scanf	("%f", &amount_to_deposit[i]);
    			
    
    			if (amount_to_deposit[i] <= 0)
    			  printf ("*** Deposit amount must be positive! Please re-enter ***\n");
    
    		} while (amount_to_deposit[i] <= 0);
    
    		current_balance = current_balance + amount_to_deposit[i];
    
    	} // end for loop
    
    
    		  /* Prompt for all withdrawal amounts, keeping track of current balance. */
    		  /* -------------------------------------------------------------------  */
    
    
    	printf ("\n");     // spacing
    	for (i = 0; i < num_of_withdrawals; i++ )
    	{
    		/* Enter amounts, and be sure amount does not exceed current balance. */
    		/* ------------------------------------------------------------------ */
    
    		do
    		{
    			printf ("Enter the amount of withdrawal #%i: ", i+1 );
    			scanf	("%f", &amount_to_withdraw[i]);
    			
    
    			if (amount_to_withdraw[i] > current_balance)
    				  printf ("*** Withdrawal amount exceeds current balance. ***\n");
    			else
    			if (amount_to_withdraw[i] <= 0)
    				  printf ("*** Withdrawal amount must be  greater than zero! ***\n");
    
    		} while (amount_to_withdraw[i] > current_balance || amount_to_withdraw[i] <= 0);
    
    		current_balance = current_balance - amount_to_withdraw[i];
    
    		/* If Balance goes to zero,  no more withdrawals allowed */
    
    
    		if(current_balance == 0)
    		{
    			printf ("\n*** Balance is now zero.  No more withdrawals allowed! ***\n");
    			num_of_withdrawals = i + 1;
    			break;
    		}  // end-if
    
    	} // end for loop.
    
    	printf ("\n");       // spacing
    
    	{
    	void print_comment (float amount);
    	/* Output an appropriate closing message based on users balance. */
    	/* ------------------------------------------------------------- */
    
    	printf ("*** The closing balance is $%.2f ***\n", current_balance);
    
    	if (current_balance >= 50000.00 )
    		printf ("***%s, Time to invest some money! ***", first_name);
    	else
    	if (current_balance >= 15000.00 )
    		printf ("***%s, Maybe you should consider a CD. ***", first_name);
    	else
    	if (current_balance >= 1000.00 )
    		printf ("***%s, Keep up the good work. ***", first_name);
    	else
    		printf ("***%s, Your balance is very low. ***", first_name);
       } // end function
    
    
    
    	/* Output bank record: Starting balance, deposits, withdrawals and end balance. */
    	/* --------------------------------------------------------------------------   */
    
    
    	printf ("\n\n");
    	printf ("*** Bank Record ***\n");
    	printf ("Starting Balance: $%13.2f\n\n", start_balance);
    
    	for (i = 0; i < num_of_deposits; i++ )
    		printf ("Deposit #%2i:     %15.2f\n", i+1, amount_to_deposit[i]);
    
    	if (num_of_deposits > 0)
    		printf ("\n");            // spacing
    
    	for (i = 0; i < num_of_withdrawals; ++i )
    		printf ("Withdrawal #%2i:  %15.2f\n", i+1, amount_to_withdraw[i]);
    
    	printf ("\nEnding Balance: $%15.2f\n\n", current_balance);
    
    } // end main.

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    No.

    Functions do not nest inside of other functions. In your case, you've tried to put them in main. And the syntax you've used is incorrect. And you also don't appear to have tried to call them anywhere.

    You should be able to find details of function definitions and declarations and calls in the early chapters of any C book.

    Also, don't use fflush(stdin), it's undefined.

    The typical function layout is like this:

    Code:
    #include <stdio.h>
    
    /* function declarations */
    void Print_Intro_Heading(void); /* note the void to indicate no arguments */
    void print_comment (float amount); /* the name of the float (amount) is optional here */
    
    int main(void)
    {
        /* some code here */
        Print_Intro_Heading(); /* call the function */
        /* some more code */
        print_comment(123.456); /* call the other function */
        /* some more code */
        return 0;
    }
    
    /* the function definitions - outside main */
    void Print_Intro_Heading(void) /* no semi-colon here */
    {
        /* some code here */
    }
    
    void print_comment (float amount) /* the name of the float is not optional here */
    {
        /* some more code here */
    }
    Last edited by cwr; 04-24-2006 at 06:57 PM.

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    33
    Newest update to code

    Code:
    #include <stdio.h>
    void print_comment ( current_balance, first_name) //to print comment based on amount
    
    {
    printf ("*** The closing balance is $%.2f ***\n", current_balance);
    
    	if (current_balance >= 50000.00 )
    		printf ("***%s, Time to invest some money! ***", first_name);
    	else
    	if (current_balance >= 15000.00 )
    		printf ("***%s, Maybe you should consider a CD. ***", first_name);
    	else
    	if (current_balance >= 1000.00 )
    		printf ("***%s, Keep up the good work. ***", first_name);
    	else
    		printf ("***%s, Your balance is very low. ***", first_name);
    }// end function
    void main (void)
    
    {
    	/* Variable Declarations */
    	/* --------------------- */
    	char     first_name[20];
    	int		num_of_deposits, num_of_withdrawals, i;
    	float		deposit_amount[50], withdraw_amount[50];
    	float   	start_balance, current_balance;
    
    
    	 /*Prompt user to input their name*/
    	 /*-------------------------------*/
    
    		 printf ("What is your name? ");
    		 scanf ("%s", first_name);
    		 fflush(stdin);
    
    
    	/* Greet user with his/her name and title of program */
    	/*---------------------------------------------------*/
    		printf ("\nHi %s. Welcome to Colleen's Banking program!\n", first_name);
    
          printf ("\n");     // spacing
    
    	/* Prompt user for starting balance */
    	/* -------------------------------- */
    
    	do
    	{
    		printf ("Enter current balance in dollars and cents: ");
    		scanf	("%f", &start_balance);
    		fflush(stdin);
    		if (start_balance < 0)
    			printf("Error: Starting Balance must be at least zero! Please re-enter!\n\n");
    	} while (start_balance < 0);
    
    		  /* Prompt for the number of withdrawals                     */
    		  /* -------------------------------------------------------- */
    
    	do
    	{
    		printf ("\nEnter the number of withdrawals (0-50): ");
    		scanf	("%i", &num_of_withdrawals);
    		fflush(stdin);
    
    		/* Emsure that user did not enter less than 0 withdrawals   */
    		/* Ensure that user did not enter more than 50 withdrawals. */
    		/*----------------------------------------------------------*/
    
    		if (num_of_withdrawals > 50)
    			  printf ("*** Maximum amount of withdrawals is 50. Please re-enter!***\n");
    		if (num_of_withdrawals < 0)
    			  printf ("*** Negative number of withdrawals not allowed. ***\n");
    
    	} while (num_of_withdrawals > 50 || num_of_withdrawals < 0);
    
    
    		  /* Prompt for the number of deposits.                    */
    		  /* ----------------------------------------------------- */
    
    	do
    	{
    		printf ("\n\nEnter the number of deposits (0-50): ");
    		scanf	("%i", &num_of_deposits);
    		fflush(stdin);
    
    		/* Ensure that user did not enter less than 0 deposits.  */
    		/* Ensure that user did not enter more than 50 deposits. */
    		/*-------------------------------------------------------*/
    
    		if (num_of_deposits > 50)
    			  printf ("*** Maximum amount of deposits is 50. Please re-enter! ***\n");
    		if (num_of_deposits < 0)
    			  printf ("*** Negative number of deposits not allowed. ***\n");
    
    	} while ( num_of_deposits > 50 || num_of_deposits < 0);
    
    
    
    		  /* Retain starting balance for bank record. */
    		  /* ---------------------------------------- */
    
    	current_balance = start_balance;
    
    		  /* Prompt for all deposit amounts, keeping track of current balance. */
    		  /* ----------------------------------------------------------------  */
    
    	printf ("\n");     // spacing
    	for (i = 0; i < num_of_deposits; i++ )
    	{
    		do
    		{
    			printf ("Enter the amount of deposit #%i: ", i+1 );
    			scanf	("%f", &deposit_amount[i]);
    			fflush(stdin);
    
    			if (deposit_amount[i] <= 0)
    			  printf ("*** Deposit amount must be positive! Please re-enter ***\n");
    
    		} while (deposit_amount[i] <= 0);
    
    		current_balance = current_balance + deposit_amount[i];
    
    	} // end for loop
    
    
    		  /* Prompt for all withdrawal amounts, keeping track of current balance. */
    		  /* -------------------------------------------------------------------  */
    
    
    	printf ("\n");     // spacing
    	for (i = 0; i < num_of_withdrawals; i++ )
    	{
    		/* Enter amounts, and be sure amount does not exceed current balance. */
    		/* ------------------------------------------------------------------ */
    
    		do
    		{
    			printf ("Enter the amount of withdrawal #%i: ", i+1 );
    			scanf	("%f", &withdraw_amount[i]);
    			fflush(stdin);
    
    			if (withdraw_amount[i] > current_balance)
    				  printf ("*** Withdrawal amount exceeds current balance. ***\n");
    			else
    			if (withdraw_amount[i] <= 0)
    				  printf ("*** Withdrawal amount must be  greater than zero! ***\n");
    
    		} while (withdraw_amount[i] > current_balance || withdraw_amount[i] <= 0);
    
    		current_balance = current_balance - withdraw_amount[i];
    
    		/* If Balance goes to zero,  no more withdrawals allowed */
    
    
    		if(current_balance == 0)
    		{
    			printf ("\n*** Balance is now zero.  No more withdrawals allowed! ***\n");
    			num_of_withdrawals = i + 1;
    			break;
    		}  // end-if
    
    	} // end for loop.
    
    	{
    	print_comment(current_balance, first_name);
    	}
    
    
    
    	/* Output bank record: Starting balance, deposits, withdrawals and end balance. */
    	/* --------------------------------------------------------------------------   */
    
    
    	printf ("\n\n");
    	printf ("*** Bank Record ***\n");
    	printf ("Starting Balance: $%13.2f\n\n", start_balance);
    
    	for (i = 0; i < num_of_deposits; i++ )
    		printf ("Deposit #%2i:     %15.2f\n", i+1, deposit_amount[i]);
    
    	if (num_of_deposits > 0)
    		printf ("\n");            // spacing
    
    	for (i = 0; i < num_of_withdrawals; ++i )
    		printf ("Withdrawal #%2i:  %15.2f\n", i+1, withdraw_amount[i]);
    
    	printf ("\nEnding Balance: $%15.2f\n\n", current_balance);
    
    
    } // end main.
    Last edited by paulntysmom; 04-25-2006 at 06:50 PM.

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Uhm, yes you are on the right track... did the compiler give you a line number to go with your error?

    Posting Code? READ THIS FIRST! It is impolite to post your entire program unless totally necessary.

    Code:
    int	main (void);
    {
    The semicolon here is the culprit. You proceeded to define the main function but typed the prototype by mistake.

    Looking at your code you have some trouble defining functions. It works like this:
    Code:
    return_value function_name ( parameter, parameter ... )
    {
       // code...
    }
    Now that you know that, happy debugging.

  5. #5
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    You need to re-read my post and apply everything in it to your code.

  6. #6
    Registered User
    Join Date
    Feb 2006
    Posts
    33
    I re-read your post many times the problem is I don't understand what I am doing wrong??? I am so lost. Will I ever get this?

  7. #7
    Registered User wintellect's Avatar
    Join Date
    Mar 2006
    Posts
    24
    functions need to be independantly created - outside of other functions. main() is a function itself and is the default function started by running the program.

    To create a function called "foo" that returns an int, you do this:
    Code:
    int foo(void)
    {
        /* a function that returns an int */
        return(5);
    }
    now, to have your program use the function, you call it as follows:
    Code:
        foo();
    So... to put this all together into a tiny program, you end up with this:
    Code:
    #include <stdio.h>
    
    int foo(void)
    {
        /* a function that returns an int */
        return(5);
    }
    
    int main(void)
    {
        int a;
        a = foo();
    
        printf("Function foo replied with: %d\n", a);
        return(0);
    }
    Notice how the creation of the function is made OUTSIDE of the function main()

  8. #8
    Registered User
    Join Date
    Feb 2006
    Posts
    33
    Still confused and I have no clue why?? Can you maybe give me an example where I used the void print_comment (float amount); and show me how it suppose to be set up in my code? Then I might be able to understand it better and realize what I am doing wrong. This is not homework I am teaching myself or at least trying to

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    #include<stdio.h>
    
    /*
        Function name: 'print_comment'
        Returns: 'void'
        Arguments: 'float amount'
        Comments: This function prints out the passed number.
    */
    void print_comment( float amount )
    {
        printf( "The amount is %f.\n", amount );
    }
    
    int main( void )
    {
        float a = 1.1, b = 2.2, c = 3.3;
    
        print_comment( a );
        print_comment( b );
        print_comment( c );
        print_comment( 4.4 );
    
        return 0;
    }
    A function is a collection of statements executed when you call the function. This function just simply displays the number we pass it.


    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Registered User
    Join Date
    Feb 2006
    Posts
    33
    Ok I updated the my code which is above in my previous post (the second code I posted, sorry didn't know I wasn't suppose to that) with my most recent change to the code. I only have one function in there now. Did I finally get it right?

    I get no errors when compiling but when I get down to where it tells you the closing balance and is suppose to display the persons name and a brief suggestion. The name does not output?
    Last edited by paulntysmom; 04-25-2006 at 07:08 PM.

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    void print_comment ( current_balance, first_name) //to print comment based on amount
    
    {
    printf ("*** The closing balance is $%.2f ***\n", current_balance);
    
    	if (current_balance >= 50000.00 )
    		printf ("***%s, Time to invest some money! ***", first_name);
    	else
    	if (current_balance >= 15000.00 )
    		printf ("***%s, Maybe you should consider a CD. ***", first_name);
    	else
    	if (current_balance >= 1000.00 )
    		printf ("***%s, Keep up the good work. ***", first_name);
    	else
    		printf ("***%s, Your balance is very low. ***", first_name);
    }// end function
    You're close here. You're missing a few things. You need to specify what type each argument to the function is. You do this in the function definition. Consider the following:
    Code:
    #include<stdio.h>
    
    int foo( int ); /* A function prototype... */
    
    /* The main function defined... */
    int main( void )
    {
        foo( 1 ); /* The foo function called with an argument... */
    
        return 0;
    }
    
    /* The 'foo' function defined... */
    int foo( int bar )
    {
        return printf("bar is %d\n", bar );
    }
    We have chosen to prototype the function up top. This is a way of telling the functions that follow what arguments and return type the function 'foo' is composed of, so if they want to use it, they'll know what it requires to be used.

    Note that the actual variable names in the prototype are optional. For that matter, they can even be called something different than what they appear as in the actual definition. This would still be a legal prototype for our above code:
    Code:
    int foo( int baz );
    The functions that might call 'foo', don't care what the variables are called inside the function itself. It's irrelevant.

    Next, we call the function. Calling a function is done similar to prototyping, except you don't put the return type, and you provide variables / values as arguments, instead of types. Such as:
    Code:
    x = foo( 5 );
    foo( x );
    Here we have a few different function calls. One we assign the return value to a variable 'x', and the second, we don't assign the return value, we instead pass it a variable 'x', rather than a value directly.

    Finally, we define the function. Functions have four parts:
    1 - A name.
    2 - A return type; 'void' if the function doesn't return a value.
    3 - Arguments; 'void' if the function takes no arguments.
    4 - A body, which is wrapped in a pair of braces. We'll ignore the obvious jokes about bodies and embracing.

    This gives us our function.
    Code:
    int foo( int bar )
    {
        return printf( "bar is %d\n", bar );
    }

    Quzah.
    Hope is the first step on the road to disappointment.

  12. #12
    Registered User
    Join Date
    Feb 2006
    Posts
    33
    This is what I have fixed now, everything seems to work (name and correct message gets displayed) so I am assuming I finally did it right?

    Code:
    #include <stdio.h>
    void print_comment (float amount, char first_name[20])  // to print name and comment based on amount
    
    
     /*Function to print name and comment based on amount*/
     /*--------------------------------------------------*/
    {
    printf ("*** The closing balance is $%.2f ***\n", amount);
    
    	if (amount >= 50000.00 )
    		printf ("***%s, Time to invest some money! ***", first_name);
    	else
    	if (amount >= 15000.00 )
    		printf ("***%s, Maybe you should consider a CD. ***", first_name);
    	else
    	if (amount >= 1000.00 )
    		printf ("***%s, Keep up the good work. ***", first_name);
    	else
    		printf ("***%s, Your balance is very low. ***", first_name);
    
    
    }// end function

  13. #13
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    If it ain't broke, don't fix it.

  14. #14
    Registered User
    Join Date
    Feb 2006
    Posts
    33
    Thanks everyone for all your help. I finally understand functions

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Void Functions Help
    By bethanne41 in forum C++ Programming
    Replies: 1
    Last Post: 05-09-2005, 05:30 PM
  2. Functions and Classes - What did I do wrong?
    By redmage in forum C++ Programming
    Replies: 5
    Last Post: 04-11-2005, 11:50 AM
  3. calling functions within functions
    By edd1986 in forum C Programming
    Replies: 3
    Last Post: 03-29-2005, 03:35 AM
  4. Factory Functions HOWTO
    By GuardianDevil in forum Windows Programming
    Replies: 1
    Last Post: 05-01-2004, 01:41 PM
  5. Shell functions on Win XP
    By geek@02 in forum Windows Programming
    Replies: 6
    Last Post: 04-19-2004, 05:39 AM