Function - Help!!!
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 22

Thread: Function - Help!!!

  1. #1
    Join Date
    May 2004
    Posts
    209

    Function - Help!!!

    I have go this working program. has 0 warning and 0 errors, it also does what it is supposed to do. But if i want to seperate the entire code into proper functions, i m pretty much lost there. I would like my main to be as simple as possible

    Code:
    #include <iostream> //allow input and output
    using namespace std; //program uses cin and cout
    
    
    int availableProducts(); //function declarations
    int purchase();
    int checkStat();
    
    
    int main() //begin function main
    {
    char x=0; //variables declaration and initialization
    int a[4]={5,5,5,5};
    int b[4]={5,5,5,5};
    int row=0;
    int column=0;
    double sales=0;
    do //loop to keep making choices until you select exit
    {
    
    
    cout << "Vending machine simulator" << endl; //display menu
    cout << "-------------------------------------------------" << endl;
    cout << "1. Get munchies" << endl;
    cout << "2. Check status" << endl;
    cout << "3. Exit" << endl;
    cout << "Please choose an option" << endl;
    cin >> x;
    
    switch (x) //allow choosing functions
    {
    case '1':
    {
    
    system("cls");
    int availableProducts( int a[] , int b[] ); //display available products
    {
    cout << "Products available" << endl;
    cout << "----------------------------------------------------------------------------" << endl;
    cout << "Coke" << "\t" << "Sprite" << "\t" << "Water" << "\t" << "Mountain Dew" << endl;
    cout << a[0] << "\t" << a[1] << "\t" << a[2] << "\t" << a[3] << endl;
    cout << " " << endl;
    cout << "M&Ms" << "\t" << "Reeses" << "\t" << "Twix" << "\t" << "Snickers" << endl;
    cout << b[0] << "\t" << b[1] << "\t" << b[2] << "\t" << b[3] << endl;
    }
    
    int purchase( int a[] , int b[] , int row , int column ); //purchase products
    {
    do
    {
    cout << "Please choose a row" << endl;
    cin >> row;
    cout << "Please choose a column" << endl;
    cin >> column;
    if (column>4 || column<1)
    cout << "That is not a valid choice" << endl; //condition for column out of range
    else
    switch (row) //switches between arrays
    {
    case 1:
    {
    if (a[column-1]<1)
    cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    else
    a[column-1]=a[column-1]--; //decrements a[?] as a function of the variable column
    break;
    }
    case 2:
    {
    if (b[column-1]<1)
    cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    else
    b[column-1]=b[column-1]-1; //decrements b[?] as a function of the variable column
    break;
    }
    default :
    cout << "That is not a valid choice" << endl; //condition for row out of range
    }
    
    }
    while(row!=1 && row!=2 && column<=4);
    if (row==1 && column==4)
    cout << "DO THE DEW!" << endl; //program advises you to do the dew
    else if (row==2 && column==4)
    cout << "Snickers really satisfies" << endl;
    else
    {
    cout << "Thank you for choosing the vending machine simulator" << endl;
    cout << "Please come again" << endl; //program is being polite
    }
    cout << " " << endl;
    
    }
    break;
    }
    
    case '2':
    {
    system("cls");
    int checkStat( int a[] , int b[] , double sales); //check available products and display sales
    {
    sales=(((5-a[0]) + (5-a[1]) + (5-a[2]) + (5-a[3]))*1.25)+(((5-b[0]) + (5-b[1]) + (5-b[2]) + (5-b[3]))*0.75);
    cout << "Total number of items sold from row 1: " << ((5-a[0]) + (5-a[1]) + (5-a[2]) + (5-a[3])) << endl;
    cout << "Total number of items sold from row 2: " << ((5-b[0]) + (5-b[1]) + (5-b[2]) + (5-b[3])) << endl;
    cout << " " << endl;
    cout << "Total sales are: $" << sales << endl;
    }
    break;
    }
    
    
    case '3':
    {
    cout << "Goodbye!" << endl; //break out of loop and exit
    break;
    }
    
    default:
    
    cout << "That function is not possible" << endl;
    
    
    }
    system("pause"); //pause to see results
    system("cls");
    
    }
    while(x!='3'); //completes loop to keep choosing
    
    
    return 0; //indicate successful program execution
    }
    Please helpo

  2. #2
    Join Date
    Apr 1999
    Posts
    27,431

    Re: Function - Help!!!

    Quote Originally Posted by rockx View Post
    I have go this working program. has 0 warning and 0 errors, it also does what it is supposed to do. But if i want to seperate the entire code into proper functions, i m pretty much lost there.
    The first thing you should do is to learn how to format your code so that others can read it. Where are the indentations?

    Every line is flushed to the left, making it very difficult to understand the flow of your code. If you can't do this, then you're not ready to separate things code into functions and logical units.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    May 2004
    Posts
    209

    Re: Function - Help!!!

    how about now

    Code:
    #include <iostream> //allow input and output
    using namespace std; //program uses cin and cout
    
    
    	int availableProducts(); //function declarations
    	int purchase();
    	int checkStat();
    
    
    int main() //begin function main
    {
    	char x=0; //variables declaration and initialization
    	int a[4]={5,5,5,5};
    	int b[4]={5,5,5,5};
    	int row=0;
    	int column=0;
    	double sales=0;
    	do //loop to keep making choices until you select exit
    	{
    
    
    		cout << "Vending machine simulator" << endl; //display menu
    		cout << "-------------------------------------------------" << endl;
    		cout << "1. Get munchies" << endl;
    		cout << "2. Check status" << endl;
    		cout << "3. Exit" << endl;
    		cout << "Please choose an option" << endl;
    		cin >> x;
    
    	switch (x) //allow choosing functions
    	{
    	case '1':
    	{
    
    	system("cls");
    	int availableProducts( int a[] , int b[] ); //display available products
    	{
    		cout << "Products available" << endl;
    		cout << "----------------------------------------------------------------------------" << endl;
    		cout << "Coke" << "\t" << "Sprite" << "\t" << "Water" << "\t" << "Mountain Dew" << endl;
    		cout << a[0] << "\t" << a[1] << "\t" << a[2] << "\t" << a[3] << endl;
    		cout << " " << endl;
    		cout << "M&Ms" << "\t" << "Reeses" << "\t" << "Twix" << "\t" << "Snickers" << endl;
    		cout << b[0] << "\t" << b[1] << "\t" << b[2] << "\t" << b[3] << endl;
    	}
    
    	int purchase( int a[] , int b[] , int row , int column ); //purchase products
    	{
    		do
    		{
    			cout << "Please choose a row" << endl;
    			cin >> row;
    			cout << "Please choose a column" << endl;
    			cin >> column;
    			if (column>4 || column<1)
    				cout << "That is not a valid choice" << endl; //condition for column out of range
    			else
    		switch (row) //switches between arrays
    		{
    		case 1:
    		{
    			if (a[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				a[column-1]=a[column-1]--; //decrements a[?] as a function of the variable column
    			break;
    		}
    		case 2:
    		{
    			if (b[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				b[column-1]=b[column-1]-1; //decrements b[?] as a function of the variable column
    			break;
    		}
    		default :
    			cout << "That is not a valid choice" << endl; //condition for row out of range
    		}
    
    		}
    		while(row!=1 && row!=2 && column<=4);
    
    			if (row==1 && column==4)
    				cout << "DO THE DEW!" << endl; //program advises you to do the dew
    			else if (row==2 && column==4)
    				cout << "Snickers really satisfies" << endl;
    			else
    			{	
    				cout << "Thank you for choosing the vending machine simulator" << endl;
    				cout << "Please come again" << endl; //program is being polite
    			}
    				cout << " " << endl;
    
    			}
    			break;
    		}
    
    	case '2':
    	{
    		system("cls");
    	int checkStat( int a[] , int b[] , double sales); //check available products and display sales
    	{
    		sales=(((5-a[0]) + (5-a[1]) + (5-a[2]) + (5-a[3]))*1.25)+(((5-b[0]) + (5-b[1]) + (5-b[2]) + (5-b[3]))*0.75);
    		cout << "Total number of items sold from row 1: " << ((5-a[0]) + (5-a[1]) + (5-a[2]) + (5-a[3])) << endl;
    		cout << "Total number of items sold from row 2: " << ((5-b[0]) + (5-b[1]) + (5-b[2]) + (5-b[3])) << endl;
    		cout << " " << endl;
    		cout << "Total sales are: $" << sales << endl;
    	}
    	break;
    	}
    
    
    	case '3':
    	{
    		cout << "Goodbye!" << endl; //break out of loop and exit
    	break;
    	}
    
    	default:
    
    		cout << "That function is not possible" << endl;
    
    
    	}
    	system("pause"); //pause to see results
    	system("cls");
    
    	}
    	while(x!='3'); //completes loop to keep choosing
    
    
    	return 0; //indicate successful program execution
    }

  4. #4
    Join Date
    Apr 1999
    Posts
    27,431

    Re: Function - Help!!!

    Quote Originally Posted by rockx View Post
    how about now
    The code is still ragged and hard to read. See this:
    Code:
    #include <iostream> //allow input and output
    
    using namespace std; //program uses cin and cout
    
    int availableProducts(); //function declarations
    int purchase();
    int checkStat();
    
    int main() //begin function main
    {
        char x=0; //variables declaration and initialization
        int a[4]={5,5,5,5};
        int b[4]={5,5,5,5};
        int row=0;
        int column=0;
        double sales=0;
        do //loop to keep making choices until you select exit
        {
            cout << "Vending machine simulator" << endl; //display menu
            cout << "-------------------------------------------------" << endl;
            cout << "1. Get munchies" << endl;
            cout << "2. Check status" << endl;
            cout << "3. Exit" << endl;
            cout << "Please choose an option" << endl;
            cin >> x;
    
            switch (x) //allow choosing functions
            {
                case '1':
                {
    
                    system("cls");
                    int availableProducts( int a[] , int b[] ); //display available products
                    {
                        cout << "Products available" << endl;
                        cout << "----------------------------------------------------------------------------" << endl;
                        cout << "Coke" << "\t" << "Sprite" << "\t" << "Water" << "\t" << "Mountain Dew" << endl;
                        cout << a[0] << "\t" << a[1] << "\t" << a[2] << "\t" << a[3] << endl;
                        cout << " " << endl;
                        cout << "M&Ms" << "\t" << "Reeses" << "\t" << "Twix" << "\t" << "Snickers" << endl;
                        cout << b[0] << "\t" << b[1] << "\t" << b[2] << "\t" << b[3] << endl;
                    }
    
                    int purchase( int a[] , int b[] , int row , int column ); //purchase products
                    {
                        do
                        {
                            cout << "Please choose a row" << endl;
                            cin >> row;
                            cout << "Please choose a column" << endl;
                            cin >> column;
                            if (column>4 || column<1)
                                cout << "That is not a valid choice" << endl; //condition for column out of range
                            else
                                switch (row) //switches between arrays
                                {
                                    case 1:
                                    {
                                        if (a[column-1]<1)
                                            cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
                                        else
                                            a[column-1]=a[column-1]--; //decrements a[?] as a function of the variable column
                                        break;
                                    }
    
                                    case 2:
                                    {
                                        if (b[column-1]<1)
                                            cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
                                        else
                                            b[column-1]=b[column-1]-1; //decrements b[?] as a function of the variable column
                                        break;
                                    }
    
                                    default:
                                        cout << "That is not a valid choice" << endl; //condition for row out of range
                                }
                        }
                        while (row!=1 && row!=2 && column<=4);
    
                        if (row==1 && column==4)
                            cout << "DO THE DEW!" << endl; //program advises you to do the dew
    
                        else if (row==2 && column==4)
                            cout << "Snickers really satisfies" << endl;
                        else
                        {
                            cout << "Thank you for choosing the vending machine simulator" << endl;
                            cout << "Please come again" << endl; //program is being polite
                        }
                        cout << " " << endl;
    
                    }
                    break;
                }
        
                case '2':
                {
                    system("cls");
                    int checkStat( int a[] , int b[] , double sales); //check available products and display sales
                    {
                        sales=(((5-a[0]) + (5-a[1]) + (5-a[2]) + (5-a[3]))*1.25)+(((5-b[0]) + (5-b[1]) + (5-b[2]) + (5-b[3]))*0.75);
                        cout << "Total number of items sold from row 1: " << ((5-a[0]) + (5-a[1]) + (5-a[2]) + (5-a[3])) << endl;
                        cout << "Total number of items sold from row 2: " << ((5-b[0]) + (5-b[1]) + (5-b[2]) + (5-b[3])) << endl;
                        cout << " " << endl;
                        cout << "Total sales are: $" << sales << endl;
                    }
                    break;
                }
       
                case '3':
                {
                    cout << "Goodbye!" << endl; //break out of loop and exit
                    break;
                }
    
                default:
                cout << "That function is not possible" << endl;
    
    
            }
            system("pause"); //pause to see results
            system("cls");
    
        }
        while (x!='3'); //completes loop to keep choosing
        return 0; //indicate successful program execution
    }
    Now that the code is much easier to understand, here are the things that I see right away:

    1) The break keyword should be matched up with the casekeyword on the same level. In your code, the break keyword is within a code block, and is not matched with the case keyword. By doing this, you're risking bugs to be introduced, where the break keyword could be skipped.
    Code:
    case 2:
    {   
       // code for case 2
    }
    break;
    That is the general outline of what the code should look like.

    2)
    Code:
    int purchase( int a[] , int b[] , int row , int column ); //purchase products
    This function definition should occur outside of the main function. Yes, it is legal to declare a function within function, but why do something that is hardly ever, if ever, done in practice?

    3)
    Code:
       sales=(((5-a[0]) + (5-a[1]) + (5-a[2]) + (5-a[3]))*1.25)+(((5-b[0]) + (5-b[1]) + (5-b[2]) + (5-b[3]))*0.75);
    What if you had 10 items for sale, or 20, or 100, or 1000 items? What will this statement look like? You would wear out your keyboard and probably quit writing C++ programs if this is the way to do totals on a set of items. You should write a loop to do this.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; August 12th, 2013 at 10:05 PM.

  5. #5
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,460

    Re: Function - Help!!!

    But if i want to seperate the entire code into proper functions, i m pretty much lost there. I would like my main to be as simple as possible
    One way would be to have a function displaying the choices and getting input and only returning a valid value. Then have functions for availableproducts, purchase etc. You have the function declarations there (although these are usually at the start of code as per Pauls post). What you need is to now write the function definitions and where you have the declarations replace these with function calls. I guess you may not be too familiar with writing/using functions so these may be of use

    http://www.learncpp.com/cpp-tutorial...-at-functions/
    http://www.cplusplus.com/doc/tutorial/functions/
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  6. #6
    Join Date
    May 2004
    Posts
    209

    Re: Function - Help!!!

    I have done it this far. but i think there is something wrong with my lines of code.

    Code:
    #include <iostream> //allow input and output 
    #include <cmath>
    #include <stdlib.h>
    
    using namespace std; //program uses cin and cout
    
    //Function Declaration
     void ShowMenu();
     void ShowItem(int [], int [], int [] );
     void MakeSelection(int [], int [], int [], int, int);
     int checkStat(int [], int [], int [], double);
     int ReturnChange();
     int DisplayErrorMessage();
     
     
    //Introduction of the main which returns a value/ 
     int main ()
     {
       int choice = 0;
       int a[3] = {10,10,10};
       int b[3] = {10,10,10};
       int c[3] = {10,10,10};
       int row = 0, column = 0;
       double price = 0;
       do
       {
      //   system("cls");     
         cout << "Vending machine simulator" << endl; //display menu
         cout << "-------------------------------------------------" << endl;
         ShowMenu();
         cin >> choice;
         
    //	 if(choice == 1 || (choice == 2))
    	 switch (choice)
    	 {
    	  case 1:
    	  {
             ShowItem(a, b, c);
    		 MakeSelection(a, b, c, row, column);
    	  break; 
    	  }   
    	  case 2:
    	  {
    	checkStat(a,  b,  c, price);
    		 break; 
    	  }
    	   case 3:
    	  {
    		cout << "testing testing ";
    		 break; 
    	  }
          }	
    	 }while(choice != 4);              
         
     system("PAUSE");
     return 0;    
     }
     
    void ShowMenu()
    {
         
         cout << "1. Get item" << endl;
         cout << "2. Check status" << endl;
         cout << "3. Payment" << endl;
         cout << "4. Exit" << endl;
         cout << "Please choose an option:  ";
         
    } 
    
    void ShowItem(int a[] , int b[], int c[])
    {
         cout << "Products available" << endl;
         cout << "----------------------------------------------------------------------------" << endl;
         cout << "Water" << "\t" << "Coke" << "\t" << "Diet Coke" << "\t" << endl;
         cout << a[0] << "\t" << a[1] << "\t" << a[2] << endl;
         cout << " " << endl;
         cout << "Iced Tea" <<"\tSwiss Chocolate" << "\t\t" << "Candy" << "\t" <<  endl;
         cout << b[0] << "\t\t" << b[1] << "\t\t\t" << b[2] << endl;
         cout << " " << endl;
         cout << "Chips" << "\t" << "Bubble Gum" << "\t" << "Turkish Delight" << endl;
         cout << c[0] << "\t" << c[1] << "\t\t" << c[2] << endl;
         cout << " " << endl;
     } 
    void MakeSelection(int a[], int b[], int c[], int row , int column) //purchase products
    	{
    		do
    		{
    			cout << "\nPlease choose a row: ";
    			cin >> row;
    			cout << "\n\nPlease choose a column: ";
    			cin >> column;
    			if ((column>=4 || column<1) || (row>=4 || row<1))
    				cout << "That is not a valid choice" << endl; //condition for column out of range
    			else
    		switch (row) //switches between arrays
    		{
    		case 1:
    		{
    			if (a[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				a[column-1]=a[column-1]-1; //decrements a[?] as a function of the variable column
    			break;
    		}
    		case 2:
    		{
    			if (b[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				b[column-1]=b[column-1]-1; //decrements b[?] as a function of the variable column
    			break;
    		}
    		case 3:
    		{
    			if (c[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				c[column-1]=c[column-1]-1; //decrements c[?] as a function of the variable column
    			break;
    		}
    		default :
    			cout << "That is not a valid choice" << endl; //condition for row out of range
    		}
    
    		}
    		while(row!=1 && row!=2 && row!=3 && column<=3);
    
    			if (row==1 && column==3)
    				cout << "DO THE DEW!" << endl; //program advises you to do the dew
    			else if (row==2 && column==3)
    				cout << "Chocolates are really nice" << endl;
    			else
    			{	
    				cout << "Thank you for choosing the vending machine simulator" << endl;
    				cout << "Please come again" << endl; //program is being polite
    			
    				cout << " " << endl;
    
    			}
    		
    		}
    
    int checkStat( int a[], int b[], int c[], double sales) //check available products and display sales
        {
                   sales = (((10-a[0]) * 0.75) + ((10-a[1]) * 1.2) + ((10-a[2]) * 1.2) + ((10-b[0]) * 1)  + ((10-b[1]) * 1.5) + ((10-b[2])* 0.95) + ((10-c[0]) * 1.1) + ((10-c[1]) * 0.5) + ((10-c[2]) * 1.2));
                   cout << "Total number of items sold from row 1: " << ((10-a[0]) + (10-a[1]) + (10-a[2])) << endl;
                   cout << "Total number of items sold from row 2: " << ((10-b[0]) + (10-b[1]) + (10-b[2])) << endl;
                   cout << "Total number of items sold from row 3: " << ((10-c[0]) + (10-c[1]) + (10-c[2])) << endl;
                   cout << " " << endl;
                   cout << "Total sales are: $" << sales << endl;
    }
    Also if i would like to write a function taht will actually do the following using Arrays: Once the customer has finished his/her selections, your vending machine calculates the denominations of coins that are to be returned to the customer as change. Assume that only $1, 50 cents, 20 cents, 10 cents and 5 cents coins are available for making change.

    So will it be possible.

  7. #7
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,460

    Re: Function - Help!!!

    Also if i would like to write a function taht will actually do the following using Arrays: Once the customer has finished his/her selections, your vending machine calculates the denominations of coins that are to be returned to the customer as change. Assume that only $1, 50 cents, 20 cents, 10 cents and 5 cents coins are available for making change.
    Again, how would you do this manually? What would be the algorithm to use? I'll give you a big hint here. This question has already been asked and answered on these forums a few months ago!
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  8. #8
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,460

    Re: Function - Help!!!

    I have done it this far. but i think there is something wrong with my lines of code.
    checkstat() is defined to return an int but the function does not return a value.
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  9. #9
    Join Date
    May 2004
    Posts
    209

    Re: Function - Help!!!

    i have done the function as such

    Code:
    void ReturnChange(double cents, int a[])
    {
         
         int money = (int)cents;
         double coins[4];
         string as[] = {" $1", "50c", "20c", "10c", " 5c"};
         cout << "The change is  respectively: \n";
         for(int i=0; i<5; i++)
                 {
                 double remainder = money%a[i];
                 coins[i]=(money-remainder)/a[i];
                 money = (int)remainder;
                 cout << as[i] << "'s  :" << coins[i] << " \n";             
                 }
             
                 
    }
    what if i want each of the coins to be 10 per container. I mean at the start of the day, there will only be 10 of each coins and as transactions occur, the coins reduce. so for eg. if the 50c run out, then "2 x 20c" and "1 x 10c" is given out as change. would that be possible?

  10. #10
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,460

    Re: Function - Help!!!

    what if i want each of the coins to be 10 per container. I mean at the start of the day, there will only be 10 of each coins and as transactions occur, the coins reduce. so for eg. if the 50c run out, then "2 x 20c" and "1 x 10c" is given out as change. would that be possible?
    yes. Just have an array of total of each coin that reduces when used. If a particular entry for a coin is 0 then just ignor and continue round the loop.

    What happens if change of 1c is required or you run out of 5c?
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  11. #11
    Join Date
    May 2004
    Posts
    209

    Re: Function - Help!!!

    So for the above do i need to have a double array implemented or a simple single array would be sufficient?

  12. #12
    Join Date
    May 2004
    Posts
    209

    Re: Function - Help!!!

    I have nested two do...while loops in my main. So whenever the first loop is executed, I would like initialize the row and column variable in my main.

    how could i go about doing that.

    Code:
    void MakeSelection(int a[], int b[], int c[], int row , int column) //purchase products
    	{
    		do
    		{
    			cout << "\nPlease choose a row: ";
    			cin >> row;
    			cout << "\n\nPlease choose a column: ";
    			cin >> column;
    			if ((column>=4 || column<1) || (row>=4 || row<1))
    				cout << "That is not a valid choice" << endl; //condition for column out of range
    			else
    		switch (row) //switches between arrays
    		{
    		case 1:
    		{
    			if (a[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				a[column-1]=a[column-1]-1; //decrements a[?] as a function of the variable column
    			break;
    		}
    		case 2:
    		{
    			if (b[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				b[column-1]=b[column-1]-1; //decrements b[?] as a function of the variable column
    			break;
    		}
    		case 3:
    		{
    			if (c[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				c[column-1]=c[column-1]-1; //decrements c[?] as a function of the variable column
    			break;
    		}
    		default :
                    {
    			DisplayErrorMessage();
    			break;
    		        }
               
    		}
        }while(row!=1 && row!=2 && row!=3 && column<=3);
    	
    		}

  13. #13
    Join Date
    Apr 1999
    Posts
    27,431

    Re: Function - Help!!!

    Quote Originally Posted by rockx View Post
    I have nested two do...while loops in my main.
    I only see one do loop in main. If you're talking about the do loop in main() and the do loop in the MakeSelection() function, they occur in separate functions. What one function does is that function's business, and should have no bearing on what the calling function is doing. That is called encapsulation, where MakeSelection() does whatever it needs to do to get the job done, and the caller (in this case main()) doesn't care how MakeSelection does its job, so long as the job is done.

    But to your overall program, I think it's time to take a step back and see the repetition in your code. A good programmer always detects repetition and tries to see if there is a way to not repeat code.

    Look at this:
    Code:
    	case 1:
    	{
    		if (a[column-1]<1)
    			cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    		else
    			a[column-1]=a[column-1]-1; //decrements a[?] as a function of the variable column
    		break;
    	}
    	case 2:
    	{
    		if (b[column-1]<1)
    			cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    		else
    			b[column-1]=b[column-1]-1; //decrements b[?] as a function of the variable column
    		break;
    	}
    	case 3:
    	{
    		if (c[column-1]<1)
    			cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    		else
    			c[column-1]=c[column-1]-1; //decrements c[?] as a function of the variable column
    		break;
    	}
    What is the only difference in these cases? I'll ask the same question I asked you before, what if there were 10 items for sale, or 20 items for sale? Are you going to write 20 case statements?

    Work on getting rid of the duplication. You know that the only difference is the array being used, so become a little curious and see if there is a way to group the arrays in a way so that the row "points to" the array you want, and then you write the code only once with the correct array.

    Second, you are not passing arrays, you're passing pointers. So regardless of what this looks like, you are passing pointers:
    Code:
    void MakeSelection(int a[], int b[], int c[], int row , int column)
    That is no different than doing this:
    Code:
    void MakeSelection(int* a, int* b, int* c, int row , int column)
    Arrays decay to pointers, so the [] syntax isn't passing arrays, even though it looks like it does.

    Given that, then it may become obvious as to how to accomplish making the function shorter:
    Code:
    void MakeSelection(int* a, int* b, int* c, int row , int column)
    {
        int* myArrays[] = {a, b, c};
        bool bGood;
        do
        {
            cout << "\nPlease choose a row: ";
        	cin >> row;
        	cout << "\n\nPlease choose a column: ";
        	cin >> column;
            bGood = (column >= 1 && column <= 4 && row >= 1 && row <= 4);
            if ( bGood )
            {
                --row;
                --column;     
                if ( myArrays[row][column] < 1)
    		  cout << "Sorry, none left" << endl; 
                else
        	          myArrays[row][column] = myArrays[row][column] - 1; 
            }
            else
                  DisplayErrorMessage();
        } while( !bGood );
    }
    The pointers to the start of each array is placed in an array. Then I used that array to access the appropriate array using "row" as a pointer to the one I want. The code now becomes shorter and less repetitive. I also made the test for row and column limits assigned to a single boolean. This makes the while() statement super simple.

    The bottom line is that if you're writing the same code over and over again, and the only difference is a few variables, or a data type, etc. then it's time to look at the code and see how to write it in general terms.

    Even with this, I didn't mention how to make this work for 3, 4, or 100 items. To do that, you need to use two-dimensional arrays instead of separate 1 dimensional arrays.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; August 16th, 2013 at 11:03 PM.

  14. #14
    Join Date
    May 2004
    Posts
    209

    Re: Function - Help!!!

    This is wht i have done so far. below is the full set of code.



    Code:
    #include <iostream> //allow input and output 
    #include <stdlib.h>
    
    using namespace std; //program uses cin and cout
    
    //Function Declaration
     void ShowMenu();
     void ShowExitMenu();
     double DepositMoney(double);
     void ShowItem(int [], int [], int [] );
     void MakeSelection(int [], int [], int [], int, int);
     double checkStat(int [], int [], int [], double);
     int TopUp();
     void ReturnChange(double, int []);
     void InitialiseArray(int [], int [], int [], int []);
     void InitialiseArray2(int , int );
     void DisplayErrorMessage();
     
     
    //Introduction of the main which returns a value/ 
     int main ()
     {
       int choice = 0;
       int counter = 0;
       int pin = 1234;
       int a[3] = {10,10,10};
       int b[3] = {10,10,10};
       int c[3] = {10,10,10};
       int coins[5]={100, 50, 20, 10, 5}; 
       int row = 0, column = 0;
       double price = 0;
       double money = 0;
       double stat = 0;
       double cashDep = 0;
       double changeRet = 0;
       
       do
       {
          cout << "Welcome to the vending machine simulator" << endl; //display menu
          cout << "----------------------------------------" << endl;
          
    
          cashDep = DepositMoney(money);
          
              do
              {
              ShowMenu();
              cin >> choice;
              
         
         	 switch (choice)
    	     {
             case 999:
                  {
                  cout << "\nPlease enter your pin for maintenance: ";
                  cin >> pin;
                  
                  while(pin != 1234)
                  {
                              
                  cout << "Invalid Pin"; 
                  cout << "\nPlease enter your pin for maintenance: ";
                  cin >> pin;
                  
                  }
                  InitialiseArray(a, b, c, coins);
        	      break;
                  }       
    	     case 1:
    	          {
                  
                  ShowItem(a, b, c);
    		      MakeSelection(a, b, c, row, column);
    	          break; 
    	          }   
    	     case 2:
    	          {
    
                  stat = checkStat(a,  b,  c, price);
    		      break; 
    	          }
    	     case 3:
    	          {
                  
               
                  changeRet = cashDep - (checkStat(a,  b,  c, price));
                  cout << "\n\n";       
                  changeRet = 100 * changeRet;
                  ReturnChange(changeRet, coins);
             //   counter = counter + 20;
    
    		      break; 
    	          }
    	     
              
              default :
                      DisplayErrorMessage();
               }
       /*    counter++;
              if(counter > 20)
              {
                     InitialiseArray2( row, column);
              } */
                         
    	    }while((choice != 4));  
    	 
    	       ShowExitMenu();
               cin >> choice;
    	       switch (choice)
    	       {
    	       case 1:
    	            {
                     break;
                    
                    }
               case 2:
                   {
                     break;                
                   }
                default :
                        DisplayErrorMessage();
               }
               }while(choice != 2);           
                    
         
     system("PAUSE");
     return 0;    
     }
     
     void ShowMenu()
     {
         cout << "\n\nThis is the main menu of the Vending Machine\n";
         cout << "1. Get item" << endl;
         cout << "2. Check status" << endl;
         cout << "3. Payment" << endl;
         cout << "4. Exit" << endl;
         cout << "Please choose an option:  ";
         
     } 
     
     double DepositMoney(double cash)
     {
         cout << "Please deposit some money to make a purchase: ";
         cin >> cash;
         
         return cash;
      }
    
     void ShowExitMenu()
     {
         cout << "\n\nDo you wish to End your Day? \n" ;
    	 cout << "1. Make Another Purchase \n";
    	 cout << "2. Yes \n";	 
         cout << "Please choose an option:  ";
     }
    
     void ShowItem(int a[] , int b[], int c[])
     {
         cout << "\n\nProducts available" << endl;
         cout << "----------------------------------------------------------------------------" << endl;
         cout << "Water" << "\t\t" << "Coke" << "\t\t" << "Diet Coke" << "\t" << endl;
         cout << a[0] << "\t\t" << a[1] << "\t\t" << a[2] << endl;
         cout << " " << endl;
         cout << "Iced Tea" <<"\tSwiss Chocolate" << "\t\t" << "Candy" << "\t" <<  endl;
         cout << b[0] << "\t\t" << b[1] << "\t\t\t" << b[2] << endl;
         cout << " " << endl;
         cout << "Chips" << "\t\t" << "Bubble Gum" << "\t" << "Turkish Delight" << endl;
         cout << c[0] << "\t\t" << c[1] << "\t\t" << c[2] << endl;
         cout << " " << endl;
     } 
     void MakeSelection(int a[], int b[], int c[], int row , int column) //purchase products
    	{
          int qty =0;
    		do
    		{
    			cout << "\nPlease choose a row: ";
    			cin >> row;
    			cout << "\n\nPlease choose a column: ";
    			cin >> column;
    			cout << "\n\nPlease enter quantity: ";
    			cin >> qty;
    			if ((column>=4 || column<1) || (row>=4 || row<1))
    			{
                    DisplayErrorMessage(); //condition for column out of range
                }
    			else
    		switch (row) //switches between arrays
    		{
    		case 1:
    		{
    			if (a[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				a[column-1]=a[column-1]-qty; //decrements a[?] as a function of the variable column
    			break;
    		}
    		case 2:
    		{
    			if (b[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				b[column-1]=b[column-1]-qty; //decrements b[?] as a function of the variable column
    			break;
    		}
    		case 3:
    		{
    			if (c[column-1]<1)
    				cout << "Sorry, none left" << endl; //informs user item is out of stock, skips decrement of array
    			else
    				c[column-1]=c[column-1]-qty; //decrements c[?] as a function of the variable column
    			break;
    		}
    		default :
                    {
    			DisplayErrorMessage();
    			break;
    		        }
               
    		}
        }while(row!=1 && row!=2 && row!=3 && column <=3);
    
    		
    		}
    
    double checkStat(int a[], int b[], int c[], double sales) //check available products and display sales
        {
                   sales = 0;
                   sales = (((10-a[0]) * 0.75) + ((10-a[1]) * 1.2) + ((10-a[2]) * 1.2) + ((10-b[0]) * 1)  + ((10-b[1]) * 1.5) + ((10-b[2])* 0.95) + ((10-c[0]) * 1.1) + ((10-c[1]) * 0.5) + ((10-c[2]) * 1.2));
                   cout << "Total number of items sold from row 1: " << ((10-a[0]) + (10-a[1]) + (10-a[2])) << endl;
                   cout << "Total number of items sold from row 2: " << ((10-b[0]) + (10-b[1]) + (10-b[2])) << endl;
                   cout << "Total number of items sold from row 3: " << ((10-c[0]) + (10-c[1]) + (10-c[2])) << endl;
                   cout << " " << endl;
                   cout << "Total sales are: $" << sales << endl;
                   return sales;
         }
    int Payment()
         {
         
         }
    void ReturnChange(double cents, int a[])
    {
         
         int money = (int)cents;
         double coins[4];
         string as[] = {" $1", "50c", "20c", "10c", " 5c"};
         cout << "The change is  respectively: \n";
         for(int i=0; i<5; i++)
                 {
                 double remainder = money%a[i];
                 coins[i]=(money-remainder)/a[i];
                 money = (int)remainder;
                 cout << as[i] << "'s  :" << coins[i] << " \n";             
                 }
             
                 
    }
    
    void DisplayErrorMessage()
    {
        cout << "That is not a valid choice" << endl; //condition for row out of range
    }
    
    void InitialiseArray(int a[], int b[], int c[], int coins[])
    {
         for( int i = 0; i <= 3; ++i)
         {
         a[i] = 10; 
         }
         for( int i = 0; i <= 3; ++i)
         {
         b[i] = 10; 
         }
         for( int i = 0; i <= 3; ++i)
         {
         c[i] = 10; 
         }
         for( int i = 0; i <= 3; ++i)
         {
         coins[i] = 10; 
         }
         
    }
    void InitialiseArray2(int c, int d)
    {
         c = 0;
         d = 0;
        
    }
    I am still not happy with the fact that if one person has paid for his/her item and has gotten the change, then 2nd person should purchase from the items available in the machine. WHat really happens here is that if 1 person has done his/her transaction, the 2nd or 3rd person would also be held accountable for all the previous transactions. THis is only avoided when the machine is reloaded (999 wtih pin 1234)

    ALso assuming that the vending machine starts every morning with a fixed number of coins of each denomination. If the vending machine has run out of a particular coin, then alternate means for giving change must be found.

    SO what could be done now?

  15. #15
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,460

    Re: Function - Help!!!

    SO what could be done now?
    I would suggest that you take a step back from trying to code 'on the hoof' and produce a program design that provides for what you are trying to accomplish. Once you have the program design right, then code the progam from the design.
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center