• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 629
  • Last Modified:

functions and c++

As part of an assignment for C++ programming as part of my Engineering course I have to create a programme to mimic a vending machine. Which I have done and it is below and it works. The trobule is that the specification sheet says I have to use the function command and makes reference to void myvariable (int x, int n, int w).
I know a fair bit of programming language from basic to vba and the C++ doesn't seem to be that different.
What I can't do though is see how I can change my code to make use of this void myvariable (int x, int n, int w).

The comments are bit haphazard as I'm normally do the comments at the end, if at all, and the tutor want's eveything commented.
Any suggestions would be much appreciated. Ed.

/* Assignment 2 - Question 1
   Ed Macey - PT EEE - Student No.
   Mob. Email edmacey@gmail.com
   
   This programme mimics the behaviour of chocolate vending machine. For full details of the question please see Assignment 2(C++) document on blackboard*/
 
 
#include <iostream> // This is a directive for the preprocessor, it tells the compiler to include the iostream standard file which means we can use the basic declarations of C++
#include <string>
#include <stdlib.h>
#include <iomanip>
using namespace std; // This tells the compiler that the commands we will be using are from the namespace std
int main() // This is the start of the programme
{
	double BANK=0;  // Define all the variables we will be using in the programme
	double COINSLOT;
	double COST;
	double REFUND;
	char KEYSTROKE;
	int NUMPAD;
	string CHOCCHOICE;
	cout << "ACME Chocolate Vending Machine\n"; // cout outputs whatever text is contained by the quotation marks onto the screen
	cout << "______________________________\n";
	cout << "\n";
	cout << "Plain Bar               "<<(char)156<<" 0.30\n";
	cout << "Brazil Nut Bar          "<<(char)156<<" 0.35\n";
	cout << "Luxury Bar              "<<(char)156<<" 0.50\n";
	choice:
	cout << "\n";
	cout << "Which bar would you like?\n";
	cout << "P, B or L? ";
	cin >> KEYSTROKE;
	switch (KEYSTROKE) {
    case 'P':
	case 'p':
    CHOCCHOICE="Plain Bar";
	COST=0.30;
	break;
    case 'B':
	case 'b':
    CHOCCHOICE="Brazil Nut Bar";
	COST=0.35;
	break;  
    case 'L':
	case 'l':
    CHOCCHOICE="Luxury Bar";
	COST=0.50;
	break;
	default:
    cout << "\n";
	puts("You must choose either P, B or L!");
	goto choice;
    break;
	}
check:
	cout << "You chose "<<CHOCCHOICE<<"\n";
	cout << "just checking that's correct?\n";
	cout << "Y or N\n";
	cin >> KEYSTROKE;
	switch (KEYSTROKE) {
    case 'Y':
	case 'y':
    goto costs;
	break;
    case 'N':
	case 'n':
    goto choice;
	break;  
    default:
    cout << "\n";
	puts("Y or N please");
	goto check;
    break;
}
costs:
    system("cls");
    cout << "ACME Chocolate Vending Machine\n";
	cout << "______________________________\n";
	cout << "\n";
	cout << CHOCCHOICE<<" is "<<(char)156<< setprecision(2)<< fixed << COST<<"\n";
	cout << "\n";
	cout << "               Balance:" << BANK <<"\n";
	cout << "\n";
	cout << "Please insert money below,\n";
	cout << "One coin at a time\n";
	cout << "\n";
	cout << "1 for one pence\n";
	cout << "2 for two pence\n";
	cout << "3 for five pence\n";
	cout << "4 for ten pence\n";
	cout << "5 for twenty pence\n";
	cout << "6 for fifty pence\n";
	cout << "7 for one pound\n";
	cout << "8 for two pounds\n";
	cout << "\n";
	cin >> NUMPAD;
	switch (NUMPAD) {
    case 1:
	COINSLOT=0.01;
	BANK=BANK+COINSLOT;
	goto bankcheck;
	case 2:
	COINSLOT=0.02;
	BANK=BANK+COINSLOT;
	goto bankcheck;
	case 3:
	COINSLOT=0.05;
	BANK=BANK+COINSLOT;
	goto bankcheck;	
	case 4:
	COINSLOT=0.10;
	BANK=BANK+COINSLOT;
	goto bankcheck;
	case 5:
	COINSLOT=0.20;
	BANK=BANK+COINSLOT;
	goto bankcheck;
	case 6:
	COINSLOT=0.50;
	BANK=BANK+COINSLOT;
	goto bankcheck;
	case 7:
	COINSLOT=1.00;
	BANK=BANK+COINSLOT;
	goto bankcheck;
	case 8:
	COINSLOT=2.00;
	BANK=BANK+COINSLOT;
	goto bankcheck;
	goto exit;
	break;
    default:
    cout << "\n";
	puts("It's not free, you need to add some money!");
	goto costs;
    break;
}
bankcheck:
	system("cls");
    cout << "ACME Chocolate Vending Machine\n";
	cout << "______________________________\n";
	cout << "\n";
	if (BANK==COST) goto bought; 
	else if (BANK>COST) goto refund;
	else goto costs;
 
bought:
	cout << "Your "<<CHOCCHOICE<<" is at \n";
	cout << "the bottom of the machine.\n";
	cout << "Thanks for buying and please\n";
	cout << "remember to put your wrapper\n";
	cout << "in a recycling bin.\n";
	goto exit;
 
refund:
	REFUND=BANK-COST;
	cout << "Your "<<CHOCCHOICE<<" is at \n";
	cout << "the bottom of the machine. \n";
	cout << "Please collect your change, "<<(char)156<<REFUND<<".\n";
	cout << "Thanks for buying and please\n";
	cout << "remember to put your wrapper\n";
	cout << "in a recycling bin.\n"; 
	goto exit;
 
exit:
return 0; //This causes the code to finish and exits the programme
}

Open in new window

0
edmacey
Asked:
edmacey
  • 4
  • 3
  • 3
  • +4
4 Solutions
 
Infinity08Commented:
>> and the C++ doesn't seem to be that different.

I assure you, it is quite different ;) I can see from your code that you are approaching it as a kind of BASIC language with all the goto's etc. But that's not how you should write code in C++.

The first thing that you should do is :

1) properly indent your code to make it easier to read
2) get rid of the goto's, to make the call flow easier to follow, and the code easier to maintain. Avoid spaghetti code (code that jumps in all directions) - if you don't know the term, look it up ;) - make use of loops instead.


And then a few more things to improve the code :

1) always initialize your variables as soon as you declare them. It avoids a lot of problems.

2) introduce a few functions for commonly used pieces of code and/or pieces of code that can easily be separated. It again makes the code easier to read, modular and re-usable :

        http://cplusplus.com/doc/tutorial/functions/
        http://cplusplus.com/doc/tutorial/functions2/

3) don't compare two double values using ==. double values are floating point types, and doing calculations on them can introduce small rounding errors that can make two values that should logically be the same have a slightly different value (which would make the == return false). Compare them by taking into account these small differences - ie. if the difference between the two values is sufficiently small, consider them equal.

4) if you want to compare a character for both its lowercase or uppercase variant, consider using the toupper function :

        http://cplusplus.com/reference/clibrary/cctype/toupper/
0
 
mrjoltcolaCommented:
Since you are a student, I would like to add my suggestions, please don't take this is a negative criticism, I am trying to be constructive.

If I can suggest, the comments in your program are not really useful comments.

They come across as "I know how to write comments and I am writing comments to satisfy a class assignment" instead of "here is what the intent of this piece of code is"

I say this because the only things you have commented are things that a C++ programmer already knows. Examples:

1) // This is a directive for the preprocessor, etc...

   Don't comment a standard statement like #include, its unnecessary

2) // cout outputs whatever text is contained by the quotation marks ...

   Don't comment something so common / standard as cout, again, a C++ programmer knows what cout is for just like a BASIC programmer knows what PRINT is for.


Your comments should be about the program itself, in your case, about the vending machine, the logic, why you wrote it a certain way, what a certain variable is used for, etc. Comments are not to teach a reader how to program C++. Comment things that are not obvious, otherwise, comments can obscure code rather than illuminate.

Good luck, I hope this helps.

0
 
ewest02Commented:
I will add that comments should not be an after thought. In real world coding it is many times useful to write  functions that contain little else but comments as a way to outline the code flow, before implementing the function. Comments written before a function should describe what the function will do,  the arguments and return value. Granted in a programming class you are creating toy programs. However it is the place to learn good habits...

With respect to the assignment and myvariable() function -- I suspect there is more detail/function description to be had...

 --Eric
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
evilrixSenior Software Engineer (Avast)Commented:
Personally, I don't like comments... they make programmers lazy and sloppy. If code is well written and self documenting (such as good descriptive function and variable names) and the code is well structured then comments are rarely needed. In fact comments can be misleading because when the code is modified (and it will be) so must the comments to match. Often though comments get overlooked and in time they no longer match the code. Inexperienced programmers may later read the comments and make incorrect assumptions about what the code does. The only time I think comments are useful is if it's not obvious what some code is doing and it's not possible to make the code any clearer (maybe you are manipulating data at a bit level), a small comment explaining what and why is then a good idea.
0
 
efnCommented:
My guess is that the instructor wants you to use functions and this "void myvariable (int x, int n, int w)" stuff is just an example of a function declaration and not something you are supposed to use literally.  So the answer is Infinity08's second point 2, "use functions."  That just means that you extract some (preferably cohesive) chunks of functionality and package them as functions.  For example, in this case, you could have a function to get the product selection, another to collect the money, and another to deliver the final result.  Then you could convert the main function from a long list of details to a few function calls that give the reader a high-level overview of what the program does, which is useful.
0
 
peprCommented:
Off topic: I am the opposite of evilrix. I consider comments important. This is true that lazy and slopy coders do leave comments unchanged after modification and this way they make the code less understandable. I do not believe that programmers must be flagelants only for purpose not to be considered lazy and sloppy. I can see no advantage to learn the purpose of the code all the time when one gets to the block of code. Once you have say 100 000 lines, it is very bad idea to think you will be able to keep everything in your head. Moreover, when working in team, programmers tend to have slightly different way of thinking. Deciphering the purpose may be difficult for the others. It means they must spend the time to learn the purpose instead of just reading few sentences to understand the purpose of the function.
0
 
peprCommented:
I personally consider a good idea not to write the extra programmer's documentation. I prefer generating the documentation from the comments in sources. I personally like the Doxygen tool (http://www.doxygen.org/) but any similar tool may be valuable for understanding the code not written by myself, or even my own but old code. The tools like help you to understand what comments are valuable and what are not.
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> I am the opposite of evilrix.
:)

>> I consider comments important
So do I (hence my concern about them not being maintained) , but I consider self documenting code to be more so. My main concern is the reliance on comments to make code understandable. Well written code doesn't need comments and a seasoned programmer, should need comments to follow well written code (IMHO).

>> I can see no advantage to learn the purpose of the code all the time when one gets to the block of code.
Because the code and the comments may not reflect each other accurately... what if the code contains a defect and the original author doesn't realise this and as such the comments don't reflect this? You should read the codes first and the comments second. Comments should serve to backup the code logic, not define it.

e.g. (really crappy example, but just to make a point)

// Defined a string of 11 characters
char str[11] = "hello world";

This misleading comment might just make you overlook the buffer overrun

>> when working in team, programmers tend to have slightly different way of thinking.
Hence the importance of well defined coding standard.

When's all said and done though... this is just my opinion, and I respect yours is just as valid :)
0
 
edmaceyAuthor Commented:
Thank you all for your comments. I won't have a chance to look at the programme again until tomorrow evening when I will re-purpose the code.

Regarding commenting the code, I think that the lecturer would like us to demonstrate that we understand what the code is doing rather than simply signposting what is being done for future reading.

I got 85% for my last assignment which I did heavily comment but haven't seen my lecturer since for specific feedback. Term starts tomorrow though so I should be able to ask him then.

Once again thank you for your comments, if it's okay with everyone can I leave the post open so I can hear your thoughts on my new code.
0
 
Infinity08Commented:
>> if it's okay with everyone can I leave the post open so I can hear your thoughts on my new code.

Sure. Just post it here whenever you're ready, and we'll have a look at it for you.
0
 
edmaceyAuthor Commented:
Okay, I was able to get back on with it during class today and have run it by my tutor, he is happy with it even though it doesn't contain functions.

I got rid of the gotos, although had to sacrifice my doublechecking that they really wanted that chocolate bar.

I used do while loop to achieve the two main things. I have also idented the text a little bit more neatly.
I read the two pages from cplusplus.com (I had been using that site anyway). I did try to start again but couldn't quite see how to call the functions separately.

It might have been that I was trying to make it a little bit too visual and a programme that was more about numbers might enable the use of functions as described on the page a little bit better.
Question 2 is about step calculations of voltage through a capacitor so that should enable me to focus a little better on that.

Regarding the commenting, I kept my comments sparse (I hope!) more to display that I was confident with what I was doing that to show that I new exactly what every bit was doing.

I would enjoy your revised thoughts.

Thanks Ed.
/* Assignment 2 - Question 1
   Ed Macey - PT EEE - Student No. 2802204
   Mob. 07811 185 749 Email edmacey@gmail.com
   
   This programme mimics the behaviour of chocolate vending machine. For full details of the question please see Assignment 2(C++) document on blackboard*/
 
 
#include <iostream>
#include <string> // Adding this so can make use of declaration string
#include <stdlib.h>
#include <iomanip> // Adding this so can set the precision of decimal point and in effect get the zero to show after the decimal point, ie 0.10 for 10p rather than 0.1
using namespace std;
int main()
{
	double COINSLOT, BANK=0, COST=0;  // Define all the variables we will be using in the programme
	char KEYSTROKE;
	int NUMPAD;
	string CHOCCHOICE;
	cout << "ACME Chocolate Vending Machine\n"; // I like making it look a little bit nicer than most, hence the \n empty areas.
	cout << "______________________________\n";
	cout << "\n";
	cout << "Plain Bar               "<<(char)156<<" 0.30\n"; // char 156 allows me to use the sterling sign as £ returns a u when the programme is run
	cout << "Brazil Nut Bar          "<<(char)156<<" 0.35\n";
	cout << "Luxury Bar              "<<(char)156<<" 0.50\n";
 
	do // starting do.. while, it makes sure whatever is happening below carries on happening until the while statement is fullfilled. In this case cost has got to equal something which becomes an error checker to get a choice.
	{
		cout << "\n";
		cout << "Which bar would you like?\n";
		cout << "P, B or L? ";
		cin >> KEYSTROKE;
	switch (KEYSTROKE) // switch replaces multiple if else statements, if keystroke is equal to anything listed it will do that action
		{
		case 'P': // so if keystroke is P or p then chochoice = plain bar and cost is 0.30
		case 'p':
		CHOCCHOICE="Plain Bar";
		COST=0.30;
		break;
		case 'B':
		case 'b':
		CHOCCHOICE="Brazil Nut Bar";
		COST=0.35;
		break;  
		case 'L':
		case 'l':
		CHOCCHOICE="Luxury Bar";
		COST=0.50;
		break;
		default: // default catches for any other key presses
		cout << "\n";
		puts("You must choose either P, B or L!");
		COST=0; // we set cost to nothing so that it is caught by the do ... while statement.
		break;
		}
	}
while (COST<0.1);
do	// again going to use the do... while function until BANK is filled enough to pay for the chocolate.
	{
		system("cls");
		cout << "ACME Chocolate Vending Machine\n";
		cout << "______________________________\n";
		cout << "\n";
		cout << CHOCCHOICE<<" is "<<(char)156<< setprecision(2)<< fixed << COST<<"\n";
		cout << "\n";
		cout << "               Balance:" << BANK <<"\n";
		cout << "\n";
		cout << "Please insert money below,\n";
		cout << "One coin at a time\n";
		cout << "\n";
		cout << "1 for one pence\n";
		cout << "2 for two pence\n";
		cout << "3 for five pence\n";
		cout << "4 for ten pence\n";
		cout << "5 for twenty pence\n";
		cout << "6 for fifty pence\n";
		cout << "7 for one pound\n";
		cout << "8 for two pounds\n";
		cout << "\n";
		cin >> NUMPAD;
			switch (NUMPAD) 
				{
				case 1:
					COINSLOT=0.01;
					break;
				case 2:
					COINSLOT=0.02;
					break;	
				case 3:
					COINSLOT=0.05;
					break;
				case 4:
					COINSLOT=0.10;
					break;
				case 5:
					COINSLOT=0.20;
					break;
				case 6:
					COINSLOT=0.50;
					break;
				case 7:
					COINSLOT=1.00;
					break;
				case 8:
					COINSLOT=2.00;
					break;
				default:
				cout << "\n";
				puts("It's not free, you need to add some money!");
					COINSLOT=0;
				break;
				}
			BANK = BANK+COINSLOT; // bank continually grows at the end of this process , it is itself plus whatever has just been added to the coinslot.
	}
	while (BANK<COST);
//the do while statement means the adding coins section can never be left while bank is less than COST
system("cls");
cout << "ACME Chocolate Vending Machine\n";
	cout << "______________________________\n";
	cout << "\n";
	if (BANK > COST) // if it's larger, we need to give them some change
			cout << "Your "<<CHOCCHOICE<<" is at \nthe bottom of the machine. \nPlease collect your change, "<<(char)156<<BANK-COST<<".\nThanks for buying and please\nremember to put your \nwrapper in a recycling bin.\n";
	// if not jsut ask them to be responsible with their rubbish
	else cout << "Your "<<CHOCCHOICE<<" is at \nthe bottom of the machine.\nThanks for buying and please\nremember to put your wrapper\nin a recycling bin.\n"; 
return 0; 
}

Open in new window

0
 
evilrixSenior Software Engineer (Avast)Commented:
I'd like to object to the fact that it doesn't contain Mars Bars :)

My biggest critisism (apart from the above) is that it is just one big function... not very modular, maintainable or readable.
0
 
Infinity08Commented:
All I did in the below code, is change the indentation to make it more readable and more consistent, and added some spacing to let some "air" into the code - otherwise you have to deal with a big lump of code, and your brain might just lock out on it. Finally, I've split up certain long comments over multiple lines, so they don't break the code flow, and fit on a screen 80 characters wide (standard).

Now, those were just ways of making the code easier to read, follow and maintain.

There are a few more things you could do to improve the code :

(a) You sometimes use puts for output ... you should stick to cout to keep things consistent.

(b) Instead of \n, you can use std::endl

(c) Instead of the switches, you can use arrays, and use the value that the user gave as an index in those arrays.
/* Assignment 2 - Question 1
   Ed Macey - PT EEE - Student No. 2802204
   Mob. 07811 185 749 Email edmacey@gmail.com
   
   This programme mimics the behaviour of chocolate vending machine. For full
   details of the question please see Assignment 2(C++) document on blackboard
*/
 
 
#include <iostream>
#include <string> // Adding this so can make use of declaration string
#include <stdlib.h>
#include <iomanip> // Adding this so can set the precision of decimal point
                   // and in effect get the zero to show after the decimal
                   // point, ie 0.10 for 10p rather than 0.1
 
using namespace std;
 
int main()
{
	// Define all the variables we will be using in the programme
	double COINSLOT, BANK=0, COST=0;
	char KEYSTROKE;
	int NUMPAD;
	string CHOCCHOICE;
 
	// I like making it look a little bit nicer than most, hence the \n
	// empty areas.
	cout << "ACME Chocolate Vending Machine\n";
	cout << "______________________________\n";
	cout << "\n";
	// char 156 allows me to use the sterling sign as £ returns a u when
	// the programme is run
	cout << "Plain Bar               "<<(char)156<<" 0.30\n";
	cout << "Brazil Nut Bar          "<<(char)156<<" 0.35\n";
	cout << "Luxury Bar              "<<(char)156<<" 0.50\n";
 
	// starting do.. while, it makes sure whatever is happening below
	// carries on happening until the while statement is fullfilled. In
	// this case cost has got to equal something which becomes an error
	// checker to get a choice.
	do
	{
		cout << "\n";
		cout << "Which bar would you like?\n";
		cout << "P, B or L? ";
 
		cin >> KEYSTROKE;
		// switch replaces multiple if else statements, if keystroke
		// is equal to anything listed it will do that action
		switch (KEYSTROKE)
		{
			case 'P': // so if keystroke is P or p then
			case 'p': // chochoice = plain bar and cost is 0.30
				CHOCCHOICE="Plain Bar";
				COST=0.30;
				break;
			case 'B':
			case 'b':
				CHOCCHOICE="Brazil Nut Bar";
				COST=0.35;
				break;  
			case 'L':
			case 'l':
				CHOCCHOICE="Luxury Bar";
				COST=0.50;
				break;
			default: // default catches for any other key presses
				cout << "\n";
				puts("You must choose either P, B or L!");
				COST=0; // we set cost to nothing so that it is
					// caught by the do ... while statement.
				break;
		}
	}
	while (COST<0.1);
 
	// again going to use the do... while function until BANK is filled
	// enough to pay for the chocolate.
	do
	{
		system("cls");
		cout << "ACME Chocolate Vending Machine\n";
		cout << "______________________________\n";
		cout << "\n";
		cout << CHOCCHOICE<<" is "
		     << (char)156<<setprecision(2)<<fixed<<COST<<"\n";
		cout << "\n";
		cout << "               Balance:" << BANK <<"\n";
		cout << "\n";
		cout << "Please insert money below,\n";
		cout << "One coin at a time\n";
		cout << "\n";
		cout << "1 for one pence\n";
		cout << "2 for two pence\n";
		cout << "3 for five pence\n";
		cout << "4 for ten pence\n";
		cout << "5 for twenty pence\n";
		cout << "6 for fifty pence\n";
		cout << "7 for one pound\n";
		cout << "8 for two pounds\n";
		cout << "\n";
 
		cin >> NUMPAD;
		switch (NUMPAD) 
		{
			case 1:
				COINSLOT=0.01;
				break;
			case 2:
				COINSLOT=0.02;
				break;	
			case 3:
				COINSLOT=0.05;
				break;
			case 4:
				COINSLOT=0.10;
				break;
			case 5:
				COINSLOT=0.20;
				break;
			case 6:
				COINSLOT=0.50;
				break;
			case 7:
				COINSLOT=1.00;
				break;
			case 8:
				COINSLOT=2.00;
				break;
			default:
				cout << "\n";
				puts("It's not free, you need to add some money!");
				COINSLOT=0;
				break;
		}
 
		// bank continually grows at the end of this process , it is
		// itself plus whatever has just been added to the coinslot.
		BANK = BANK+COINSLOT;
	}
	while (BANK<COST);
	// the do while statement means the adding coins section can never be
	// left while bank is less than COST
 
	system("cls");
	cout << "ACME Chocolate Vending Machine\n";
	cout << "______________________________\n";
	cout << "\n";
 
	if (BANK > COST) // if it's larger, we need to give them some change
		cout << "Your "<<CHOCCHOICE<<" is at \n"
		     << "the bottom of the machine. \n"
		     << "Please collect your change, "
		     << (char)156<<BANK-COST<<".\n"
		     << "Thanks for buying and please\n"
		     << "remember to put your \n"
		     << "wrapper in a recycling bin.\n";
	// if not jsut ask them to be responsible with their rubbish
	else
		cout << "Your "<<CHOCCHOICE<<" is at \n"
		     << "the bottom of the machine.\n"
		     << "Thanks for buying and please\n"
		     << "remember to put your wrapper\n"
		     << "in a recycling bin.\n";
 
	return 0; 
}

Open in new window

0
 
edmaceyAuthor Commented:
Guys I would like to thank you for your input, I made the changes as Infinity08 suggested although didn't swap the switches for arrays as not sure how to do this.
Evilrix, i'm still unsure how functions are meant to work and so need to go back to the drawing board on that one.
I have allocated points on how helpful i found the comments but please don't get angry or take offence, if you would like more points then say and I will ask another question.
You have helped a student though. Thanks Ed.
0
 
edmaceyAuthor Commented:
If anybody wanted to comment on the second question of my assignment that would be brilliant. Thanks Ed.

http://www.experts-exchange.com/Programming/Languages/CPP/Q_24375114.html
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 4
  • 3
  • 3
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now