Thread: Help With C code looping

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    5

    Help With C code looping

    Hi All,

    I have written a program that doesn't seem to work and I can't figure out why it's not working. It compiles correctly, but when I run it I get prompted by the first couple of printf statements, as it should, but then the rest of the code doesn't run. Could someone please help me?

    Thanks for your help!

    Code:
    #include <stdio.h>
    
    int main()
    {
    
        /* Declare Array Variables */
        
        float deposits[50] = {0}; 
        float withdrawals[50] = {0};
        char  first_name[20] = {0};
    
        /* Declare Variables */
    
        int   num_withdrawals, num_deposits, x;
        float current_balance = {0};
        float start_bal;
        float total_deposits;
        float total_withdrawals;
        float balance;
        
        /* Output initial greeting */
    
        printf("Welcome to the Milas Banking System.\n\n");
    
        printf("Please enter your first name: ");
        scanf("%s", first_name);
        fflush(stdin);
    
        printf("\nHello, %s.\n\n", first_name);
    
        /* Get Starting Balance */    
    
        do{
    
        printf("%s, Please enter your current balance in dollars and cents: "); /* Prompt user for current balance. */
        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*/
    
        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 || num_withdrawals > 50); /* end do-while trap loop */
    
        return num_withdrawals;
    
        /* end function number of withdrawls */
    
        /*START FUNCTION GET NUMBER OF DEPOSITS*/
    
        do{
    
        printf ("\nEnter the number of deposits: ");
        scanf ("%i",&num_deposits);
        fflush (stdin);
    
        if ( num_deposits < 0 || num_deposits > 50)
        printf ("Error: Number of deposits must be between 0 and 50, please re-enter!\n\n");
        
        } while (num_deposits < 0 || num_deposits > 50); /* end do-while trap loop */
    
        return num_deposits;
    
        /* end function number of deposits */
        
        /*START FUNCTION GET EACH DEPOSIT*/
    
        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 */
    
        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*/
    
        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*/
    
        {
        
        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*/
    
        printf ("     *** Bank Record ***\n");
        
        printf ("\nStarting Balance:$   %13.2f\n\n", current_balance);
        
        for (x = 1; x <= num_deposits; x++)
        
        {
        
        printf ("Deposit #%i:          %13.2f\n", x, deposits[x]);
        
        }
        
        for (x = 1; x <= num_withdrawals; x++)
            
        {
            
        printf ("\nWithdrawal  #%i:      %13.2f", x, withdrawals[x]);
        
        }
        printf ("\n\nEnding Balance is:$  %13.2f\n", balance);
        
        /*end function display bank record*/
        
        getchar(); /* Pause output */
    
        return (0);
    
    }

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Proper indention sometimes calls for more than a single tab character.

    Read the FAQ - don't flush stdin.
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User ch4's Avatar
    Join Date
    Jan 2007
    Posts
    154
    Your program is running in main function and after do-while loop you do this "return start_bal;
    " which terminates your program.

    Why don't you use separate functions to do you job ?

  4. #4
    Registered User
    Join Date
    Oct 2008
    Posts
    5

    fflush stdin

    Hi Dino,

    I know fflush stdin is a big no no, but it's something that's required by my C programming teacher. If I don't have it I lost points...

    Quote Originally Posted by Dino View Post
    Proper indention sometimes calls for more than a single tab character.

    Read the FAQ - don't flush stdin.

  5. #5
    Registered User
    Join Date
    Oct 2008
    Posts
    5

    Separate Functions

    Hi ch4,

    Thanks for your reply and your explanation.

    I would like to use separate functions, but I'm not exactly sure how to do this. Could you please provide an example?

    Thanks



    Quote Originally Posted by ch4 View Post
    Your program is running in main function and after do-while loop you do this "return start_bal;
    " which terminates your program.

    Why don't you use separate functions to do you job ?

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > but it's something that's required by my C programming teacher. If I don't have it I lost points...
    What about void main, or using gets() ?
    Does your teacher think they're a good idea as well?

    Or other "works for me" crap which you'll accept (because you know no better at the moment), but which will in the end prove to be competely and utterly wrong.

    IMO, your teacher is an ass collecting a paycheck.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by maker10 View Post
    I know fflush stdin is a big no no, but it's something that's required by my C programming teacher. If I don't have it I lost points...
    So if your chemistry teacher told you to gurgle with sulphuric acid, you would do that too, to not loose points?

    fflush(stdin) is not a good idea, and please be aware that it MAY cause an application to crash.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User
    Join Date
    Oct 2008
    Posts
    5

    Thanks for your help

    Hi All,

    Thanks for all your help and suggestions...I am re-posting my code, with proper formatting for your review. The code runs correctly, but the ending balance, after all the withdrawals, is incorrect and I can't find where I messed up. Any help would be most appreciated:

    Code:
    #include <stdio.h>
    
    int main()
    {
    
        /* Declare Array Variables */
        
        float deposits[50] = {0}; 
        float withdrawals[50] = {0};
        char  first_name[20] = {0};
    
        /* Declare Variables */
    
        int   num_withdrawals, num_deposits, x;
        float current_balance = 0;
        float start_bal;
        float total_deposits;
        float total_withdrawals;
        float balance;
        
        /* Output initial greeting */
    
        printf("Welcome to the Banking System.\n\n");
    
        printf("Please enter your first name: ");
         scanf("%s", first_name);
    
        printf("\nHello, %s.\n\n", first_name);
    
        /* Get Starting Balance */    
        
        do {
            
            printf("%s, Please enter your current balance in dollars and cents: "); /* Prompt user for current balance. */
            scanf("%f", &start_bal);
    
            if (start_bal < 0)
                printf("Invalid entry. Starting balance must be at least zero!\n\n");
    
        } while (start_bal < 0); /* End do-while */
        
        /* end function get starting balance */
    
        /* Get Number of Withdrawals */
    
        do {
            
            printf ("\nEnter the number of withdrawals: ");
            scanf ("%i", &num_withdrawals);
            printf ("\n");
    
            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 || num_withdrawals > 50); /* end do-while trap loop */
    
        /* end function number of withdrawls */
    
        /* Get Number of Deposits */
    
        do {
            
            printf ("Enter the number of deposits: ");
            scanf ("%i",&num_deposits);
            printf ("\n");
            
            if ( num_deposits < 0 || num_deposits > 50)
                printf ("Error: Number of deposits must be between 0 and 50, please re-enter!\n\n");
        
        } while (num_deposits < 0 || num_deposits > 50); /* end do-while trap loop */
    
        /* Get Each Deposit */
    
        for (x = 1; x <= num_deposits; x++)
        
        do {
            
            printf ("Enter the amount of deposit #%i: ", x);
            scanf ("%f",&deposits[x]);
            
            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];
        current_balance = total_deposits + start_bal;     
        
        /* end for loop */
           
        /* Get Each Withdrawal */
    
        for (x = 1; x <= num_withdrawals; x++)
        
        do {
            
            printf ("\n");
            printf ("Enter the amount of withdrawal #%i: ", x);
            scanf ("%f",&withdrawals[x]);
            
            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 get each withdrawl */
         
        /* Check 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;
             
            } 
        
          
        /* Calculate and Display 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);
        
        }   /*end-if*/
        
        /* Calculate and display balance*/
        
        printf ("     *** Bank Record ***\n");
        
        printf ("\nStarting Balance:   $%13.2f\n\n", current_balance);
        
        for (x = 1; x <= num_deposits; x++)
            
            {
            
            printf ("Deposit #%i:          %13.2f\n", x, deposits[x]);
            
            }
        
        for (x = 1; x <= num_withdrawals; x++)
            
            {
            
            printf ("\nWithdrawal  #%i:      %13.2f", x, withdrawals[x]);
            
            }
        
            printf ("\n\nEnding Balance is:  $%13.2f\n", balance);
        
        /* end function display bank record */
        
        getchar(); /* Pause output */
    
        return (0);
    
    }   /* end main */

  9. #9
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I don't see you initializing total_deposits and total_withdrawals to 0 before you start? And also, all your arrays are off by 1 (they go from 0 to 49, but you are using 1 to 50).

  10. #10
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    There's a bug in this code:
    Code:
    float withdrawals[50] = {0};
    ...
    /* Get Each Withdrawal */
    
        for (x = 1; x <= num_withdrawals; x++)
        
        do {
            
            printf ("\n");
            printf ("Enter the amount of withdrawal #&#37;i: ", x);
            scanf ("%f",&withdrawals[x]);
            
            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 */
    You allow 50 elements in the array. This means the elements are indexed from 0 to 49. However, your FOR loop uses indexes 1 through 50. This means it will leave the first one empty (index 0) and when it writes the 50th elements, you'll be corrupting the storage (or seg faulting) storing the last value.
    Mainframe assembler programmer by trade. C coder when I can.

  11. #11
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    This is posted all over net...

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Yeah, and I'm bored with it as well, so let's cut one head off the Hydra
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Enforcing Machine Code Restrictions?
    By SMurf in forum Tech Board
    Replies: 21
    Last Post: 03-30-2009, 07:34 AM
  2. Obfuscated Code Contest: The Results
    By Stack Overflow in forum Contests Board
    Replies: 29
    Last Post: 02-18-2005, 05:39 PM
  3. Obfuscated Code Contest
    By Stack Overflow in forum Contests Board
    Replies: 51
    Last Post: 01-21-2005, 04:17 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 4
    Last Post: 01-16-2002, 12:04 AM