Thread: Help with functions

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    33

    Help with functions

    hey folks..I am beyond confused when it comes to functions, I just don't seem to get how to apply them. Basically for this assignment I need to use at least a couple functions in order for it to be considered complete. Right now I'm having intense mental block because I can't even figure out what's going on with my if statements, when i try to run it, i get the error "expected if before else" but the if is there, im pretty sure its the do while that's causing the problem but if i were to move that above the if statements I get an infinite loop. I will highlight the line where i'm getting the else issue in red.

    Code:
    do{   do{
           
           printf("Would you like to order FISH (y/n)?: ");
           scanf (" %c", &fish);
           
               if (fish =='Y' || fish == 'y')
                 {
                  do{
                      printf("Choice of Fish? (K - Haddock or T- Hailbut: ");
                      scanf(" %c", &option);
                  
                       if (option =='K' || option == 'k')
                       do{{
                    
                             printf("Choose your size (L - large, M - medium, S - small: ");
                             scanf(" %c", &choice);
                               if(choice =='L' || choice =='l')
                                 {
                                   f_price= HADDOCK_L;
                                 }
                             else if (choice == 'M' || choice == 'm')
                                 {
                                  f_price= HADDOCK_M;
                                 }
                             else if (choice == 'S' || choice == 's')
                                 {
                                  f_price= HADDOCK_S;
                                 }
                             else
                                 {
                                  printf("Please select a size\n");
                                 }
                         }
                    else if  (option == 'T' || option == 't')
                         {
                           printf("Choose your size (L - large, M - medium, S - small: ");
                           scanf(" %c", &choice);
                             if(choice =='L' || choice =='l')
                               {
                                f_price= HAILBUT_L;
                               }
                           else if (choice == 'M' || choice == 'm')
                               {
                                f_price= HAILBUT_M;
                               }
                           else if (choice == 'S' || choice == 's')
                               {
                                f_price= HAILBUT_S;
                               }
                           else
                               {
                                printf("Please select a size\n");
                               }
                        }
                  }while(choice != 'L' || choice != 'l' || choice != 'M' || choice !='m' || choice != 'S' || choice != 's');
                     else
                         {
                          printf("Please select K for Haddock or T for Hailbut\n");
                         }
                                   
                 
                    
                    }while(option != 'K' || option != 'k' || option != 'T' || option != 't');
                    } 
              else if ( fish == 'N' || fish == 'n')
                 {
    
    
                   do{
                       printf("Would you like to order chips? (Y/N): ");
                       scanf(" %c", &fries);
    
    
                     }while(fries != 'Y' || fries != 'y' || fries != 'N' || fries != 'n');
                 }                    
      }while(fish != 'Y' || fish != 'y' || fish != 'N' || fish != 'n');
      
      }while(exit == 1); 
    }
    most of my variables and defines have been made...my issue is I dont know how to apply a function to this.

    if anyone want's to see the details of the assignment to get a better understanding of what I'm trying to do, this is it.
    https://scs.senecac.on.ca/~ipc144/assignments/asst2.pdf


    Any help is greatly appreciated, thank you.

  2. #2
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    There is a lot to work on here, but it's a good start. One thing before I try to answer your broad question about functions: look into toupper() to avoid all those || conditionals.

    In general any time you have several lines of code that are identical, or nearly identical, in more than 1 location you should consider a function. In this case I can see (at least) 2 blocks of code that are nearly identical. They both start with printf("choose your size.... You probably want to create a function called something like chooseSize(). Now what are you going to pass into that function? Well take a look at what is slightly different about those 2 blocks of code.

    There are many other issues with this code, but a good place to start is wrapping your head around functions. If you don't start using them, your code will become unmanagable. You definitely need to slow down and do some thinking about them -- and how you can use them, or coding will become miserable.

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    Hmm i think I get what you're saying.

    so i could functions like these?

    fishorder(char hailbut, char haddock) [ this will cover the question for 'would you like to order fish?' and the type of fish to choose ]
    chipsorder(char fries, char rings) [ represents chips and rings and which one they would like to choose ]
    drinkorder(char soft_drink, char coffee, char tea) [ covers soft drinks, coffee, and tea ] ---or should I keep those options separate?
    orderSize(char large, char medium, char small) [ what size of they would like for their order ]

    and then i would have it after the

    Code:
    main()
    {
      printf("welcome to Shadow's fish n chips") 
      printf("would you like to order fish?(y/n): ")
      scanf(" %c", &fishorder)
    }
    void fishorder(hailbut, haddock)
    {
      for (halibut == 't' || haddock =='k')
        {
           if (fishorder =='t' || fishorder=='T')
             {
                printf(''What size would you like? (L-M-S): ");
                scanf(" %c", &orderSize);
              }
        }
    and then have the void orderSize() after, something like that?

  4. #4
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    Ok, you're getting a tiny bit closer to seeing functions in the right light. Couple questions: When is this due? How much time are you willing to spend refactoring (making the code readable and usable, but not changing it's features)?

    As for functions, more often than not a function is passed in one or more parameters, it then does 'something' with them and then it returns a value. Think about what variable you are ultimately setting to a value. This will replace 'void' in your function prototype.

    The classic way to think of a function is as a black box. You pass something in, you get something out. Once the function is written, in can be reused, and you never really have to think about how it's doing what it's doing, you just use it, over and over. Code reuse is a basic tenet of programming. It's definitely worth stopping what you're doing and mulling over a while. Try to give me just the function prototype. Ask yourself: what do I NEED to pass in, and what do I WANT to get out.

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    hmmm interesting. The assignment is due tomorrow 11:59pm, im not to concerned about it being late my concern is more about utilizing functions and really understanding how to implement them, because our program is "fail the exam you fail the course...even if you have an 90" lol.

    ok if i got this right, function prototype would be something like this


    char fish_order (char halibut, char haddock)
    int quantity (int quantity)

    would those be considered prototypes?

  6. #6
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    I took a look at the actual assignment, and you're going to have your work cut out for you. Let's start this code over and see if you can't start understanding functions. We're going to write two very simple functions. 1 function will be called displayMenu() it will accept no parameters and return nothing (pretty boring, but it is reusable) The second function, getMediumPrice() will calculate and return the medium price, given the large price. Take a look at the code and see if functions are getting any clearer.
    What I want you to do is rewrite the function getMediumPrice() and make it more generic. Call it getReducedPrice() and pass in another parameter (the discount rate, e.g. .8 ) to

  7. #7
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    Oops, accidentally posted. Anyway here's the code to rewrite.
    Code:
    #include <stdio.h>
    
    #define haddock_large 5.00
    #define coffee_large 1.75
    
    //FUNCTION PROTOTYPES
    void displayMenu();
    float getMediumPrice(float largeprice);
    
    int main(void)
    {
    displayMenu();
    
    return 1;
    }
    
    void displayMenu()
    {
    printf("Welcome to Shadow's Fish 'n Chips");
    printf("Price for Large Haddock is: $%.2f" , haddock_large);
    printf("Price for Medium haddock is $%.2f" , getMediumPrice(haddock_large) );
    }
    
    float getMediumPrice(float largeprice)
    {
    float mediumprice = largeprice * .8;
    return mediumprice;
    }

  8. #8
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    ok so it looks like you made the prototypes and then your calling it after the main.

    the displayMenu() you have in the main is going to return what you have in void displayMenu right?

    and the medium price is being returned, so the value is being passed through

    if im looking at that correctly, your calculation of float getMediumPrice will apply to (haddock_large) in the third printf statement.

    so I can do the same thing for the small price as well


    Code:
    void displayMenu()
    {
    printf("Price for Small haddock is: $%.2lf", getSmallPrice(haddock_large) );
    }
    then I could apply the getMediumPrice and getSmallPrice to the drinks portion as well right?.

    so if I'm understanding this right, i can define the price for all my large items and keep them as my constant and adjust using the other two functions.

    i'm not sure what you mean by making it more generic but i think getReducedPrice() i could use it as

    Code:
    
    float getReducedPrice(int fish, float largeprice)
    
    void getReducedPrice(int fish, float largeprice)
    {
      float mediumprice = largeprice * .8;
      float smallprice = largeprice *.6;
      
      do{
            if (fish >=5)
              {
                 discount = Drink * .10
              }
          }while (fish > 0 || fish >=5)
    }
    would that work? I could have a function called getDrink(float softdrink, float tea, float coffee) for that discount to apply to.

  9. #9
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    You're getting closer, but still off a bit. Forget about the drink special for now. Keep in mind your function prototype must match your function definition. I was looking for something like:
    Code:
    float getReducedPrice(float discountrate , float largeprice)
    See if you can write the function body for this one.

    Also, within the program you are asking a lot of Y/N questions. Why not write a function askQuestion() where you pass in the text you want to ask, and return Y or N. Try to use toupper() in it.

  10. #10
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    oh okay. Let's see if I can get this right.

    Code:
    #define discountrate .10
    float getReducedPrice(float discountrate, float largeprice)
    
    void getReducedPrice(float discountrate, float largeprice)
    {
       float mediumprice = largeprice * .8;
       float smallprice = largeprice * .6;
    }
    i'm not sure what to do with the discount rate, it seems to only apply when 5 or more fish are purchased and the rate is given to the drinks :/

    as for the askQuestion() i have no idea how to implement that.

    would do it like this?
    Code:
    char getaskQuestion()
    {
     char fish
     printf(''Would you like to order fish (y/n): ");
     scanf('' %c", fish);
     return fish
    }
    is there a way to make that just a generic question ''would you like to order x (y/n)" and x would change to fish / chips / drinks ? and I dont know where I would put toupper to make it uppercase lol

  11. #11
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    Slowly you're getting closer. This is more what I had in mind for getReducedPrice():
    Code:
    #define discountrate .10  // GET RID OF THIS LINE
    
    float getReducedPrice(float discountrate, float largeprice) //CORRECT
    
     
    
    void getReducedPrice(float discountrate, float largeprice) //CHANGE void TO float, THE FUNCTION RETURNS (Sends back) A FLOAT
    
    {
    
       float mediumprice = largeprice * .8; //NOPE
    
       float smallprice = largeprice * .6;  //NOPE
       float newprice = largeprice * discountrate;  
       return newprice; // THIS IS WHAT THE FUNCTION RETURNS OR SENDS BACK
    
    
    }
    And when you call this function, you would do something like
    Code:
     float mediumhaddockprice = getReducedPrice(.8 , haddock_large); 
    and then : float smallhaddockprice = getReducedPrice(.6 , haddock_large);
    Keep in mind we're really going overboard here, and technically you don't need this function, it's just to get you thinking about a simple one.

    You're on the right track with askQuestion(), Ultimately you will call it like char wantfish = askQuestion("Would you like fish?"); askQuestion will RETURN (See last line of getReducedPrice) a char. So you will not put void in the prototype, you will put char.

    make sure within askQuestion body, do your scanf and you check to make sure they have entered a valid response, and then RETURN that response. You can reuse askQuestion later, e.g.
    Code:
    char wantchips = askQuestion("Do you want chips?");  
    char wantdrink = askQuestion("Want a drink?");  Can you you see how you will be reusing your functions, and thus reusing code?

  12. #12
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    oh wow, that's awesome. haha I wish my professor was this efficient in explaining things lol. question though, would the discountrate would be predefined? or am I going to assign a value to it in the main? like

    Main()
    float discountrate = .10 //10%

    so then when i have float newprice= largeprice * discountrate, and the value for it would already be there.

    do you recommend making a separate function for calculating user input for how many fish, chips, and drinks the user would take? Or keep it all in the same function? because I need to incorporate the amount a person saves for buying 5 or more fish to discount the drinks and apply them to the totals.

  13. #13
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    Code:
    char askQuestion(char fish, char chips, char drinks)
    {  
     char y='y';
     char n='n';
     y=toupper(y);
     n=toupper(n);
     char wantfish = askQuestion ("Do you want fish?(y/n)");
     scanf(" %c", &fish);
     char wantchips = askQuestion ("Do you want chips?(y/n)");
     scanf(" %c", &chips);
     char wantdrinks = askQuestion ("Do you want drinks?(y/n)");
     scanf(" %c", &drinks);
    
    
     return fish;
     return chips;
     return drinks;
    }
    so I ran the program using this, but the question's never came up nor did the option for me to choose.

    this is my whole code so far:

    Code:
    int main(void)
    {
    displayMenu();
    
    
    return 1;
    }
    
    
    
    
    void displayMenu()
    {
      printf("                 Welcome to Sunny FISH & CHIPS!    \n");
      printf("                            FOODS:                 \n");
      printf("                         -----------_              \n");
      printf(" Fish:     Haddock (K)   Large(L) $5.00 | Halibut (T) Large(L) $4.00\n");
      printf(" Chips:    Cut(C)        Large(L) $2.00 | Ring(R)     Large(L) $3.00\n");
      printf("                         -----------               \n");
      printf("                           DRINKS:                 \n");
      printf("                         -----------               \n");
      printf(" Drinks:   Soft Drink(S) Large(L) $2.00 | Coffee(C)   Large(L) $1.75\n");
      printf("           Tea(T)        Large(L) $1.50                             \n");
      printf("--------------------------------------------------------------------\n");
      printf(" Note: Price for Medium Sizes are 80%% of the large price\n");
      printf("       Price for Small  Sizes are 60%% of the large price\n");
      printf("--------------------------------------------------------------------\n");
    }
    
    
    char askQuestion(char fish, char chips, char drinks)
    {
     char y='y';
     char n='n';
     y=toupper(y);
     n=toupper(n);
     char wantfish = askQuestion ("Do you want fish?(y/n)");
     scanf(" %c", &fish);
     char wantchips = askQuestion ("Do you want chips?(y/n)");
     scanf(" %c", &chips);
     char wantdrinks = askQuestion ("Do you want drinks?(y/n)");
     scanf(" %c", &drinks);
    
    
     return fish;
     return chips;
     return drinks;
    }
    Last edited by ShadowBoss; 03-25-2012 at 02:03 PM.

  14. #14
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    Once again, close but no cigar. When you pass variables into a function, from main, local copies are created. You can't* actually change the original variable within the function. Also you can only return 1 variable from a function. This is more what I had in mind:
    Code:
    char askQuestion(char *question)
    {
            char answer;
            printf("%s - (y/n)",question);
            scanf(" %c", &answer);
            return answer;
    }
     AND THEN IN MAIN YOU WOULD WRITE:
    displayMenu();
    char fish = askQuestion("Would you like to buy fish");
    Now you need to make some changes in your scanf, you need to make a loop, and check whether the user has entered y or n. what if they type q?

    After you do that, try to make a function called getHowMany() which will be very similar to askQuestion(), where you can pass in the text and it will return some type of number, which type would be correct?

  15. #15
    Registered User
    Join Date
    Oct 2011
    Posts
    33
    oooooooooo damnnnnn LOL that makes a lot more sense, i can understand all of that.

    one question though. how is it that i displayed the menu to the screen?

    using


    Code:
    displayMenu(); return 1; } void displayMenu() { printf("Welcome to Shadow's Fish 'n Chips"); printf("Price for Large Haddock is: $%.2f" , haddock_large); printf("Price for Medium haddock is $%.2f" , getMediumPrice(haddock_large) ); }
    im positive its because of the printf's that i have but im just wondering why don't i keep the void displaymenu and remove the displaymenu(); return1 in the main?
    Last edited by ShadowBoss; 03-25-2012 at 05:14 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. WinAPI functions - similar functions as part of VS C++
    By jlewand in forum Windows Programming
    Replies: 2
    Last Post: 02-02-2012, 08:54 AM
  2. Creating Functions & passing information to other functions
    By RyanLeonard in forum C Programming
    Replies: 4
    Last Post: 10-28-2010, 12:17 PM
  3. Replies: 7
    Last Post: 04-19-2006, 11:17 AM
  4. Replies: 6
    Last Post: 05-06-2003, 03:08 PM
  5. Replies: 1
    Last Post: 01-20-2002, 11:50 AM