-
Changing function based on a condition?
I was wondering if it's possible to have ONE function perform a different task, depending on some condition, or would I have to make separate functions? Here's my example:
Code:
int x, y, z, product;
x = getData();
y = getData();
z = getData();
int getData()
{
int num;
cout << "Please enter a number: ";
cin >> num;
return num;
}
That was an in-class exercise. BUT... can I have getData say something like "Please enter first number: " then "Please enter second number: ", etc? ... or would I need three separate functions saying three separate things? I am working on a different project, and if I can do this, it would be great! So... is there a way? I don't know enough yet to figure that out. By the way... just pointing me in the right direction is fine... I don't want to have the answer handed over - I want to learn how myself. Also, we haven't learned pointers or any of that stuff yet... just doing functions now.
-
Re: Changing function based on a condition?
Quote:
Originally Posted by
LogicWavelength
I was wondering if it's possible to have ONE function perform a different task, depending on some condition, or would I have to make separate functions?
Yes, it is possible.
Whether you "have to make separate functions" or not as usual depends... :rolleyes:
-
Re: Changing function based on a condition?
Generally speaking, this is what function parameters are for.
-
Re: Changing function based on a condition?
Yes, you can use the same function..pass parameters with the help of the function getdata() you are calling..hope this helps!!
-
Re: Changing function based on a condition?
...so I can use a placeholder variable as a parameter to send the function different info... then based on the parameter, use an if statement to make the function cout something new?
Code:
int x, y, z, product, variable;
variable = 0;
x = getData(variable);
variable = 1;
y = getData(variable);
variable = 2;
z = getData(variable);
int getData()
{
int num;
if (variable = 0)
{
cout << "Please enter the first number: ";
cin >> num;
}
else if.... etc, etc, etc.
return num;
}
-
Re: Changing function based on a condition?
Quote:
Originally Posted by
LogicWavelength
...so I can use a placeholder variable as a parameter to send the function different info... then based on the parameter, use an if statement to make the function cout something new?
Just try it and see:
Code:
#include <iostream>
using namespace std;
int getData(int nWhichData)
{
const char* varName = "xyz";
cout << "Please enter value for " << varName[nWhichData] << " : " ;
int value;
cin >> value;
return value;
}
int main()
{
int x, y, z;
x = getData(0);
y = getData(1);
z = getData(2);
}
Regards,
Paul McKenzie
-
Re: Changing function based on a condition?
Thanks Paul! That's actually over my head with some of the code you wrote... I actually got back to my computer and tried what I wrote before - and it worked... minus the assignment error I had in my function. I'm sure yours would work too... but if I handed in something that had that in there my professor would know I didn't do it! Can't wait until I understand what you wrote there.
-
Re: Changing function based on a condition?
You should be covering arrays soon if you haven't already.
-
Re: Changing function based on a condition?
Quote:
Originally Posted by
LogicWavelength
...so I can use a placeholder variable as a parameter to send the function different info... then based on the parameter, use an if statement to make the function cout something new?
... or you can send the prompt string as a parameter to the input function.
How you generalize a function by the use of parameters may differ. The lesson is that parametrisation is one major way of making code more abstract in order to make it more general. Isolate what differs and make it a parameter.
-
Re: Changing function based on a condition?
Quote:
Originally Posted by
Lindley
You should be covering arrays soon if you haven't already.
We actually did arrays first... I just don't understand what you mean or how that applies to this problem.... I didn't get the varName[nWhichData] part he wrote. I have a lot to learn, I know.
-
Re: Changing function based on a condition?
Well then, which part is unclear?
-
Re: Changing function based on a condition?
Maybe its clearer like this?
Code:
#include <iostream>
using namespace std;
int getData(int nWhichData)
{
const char varName[4] = "xyz";
cout << "Please enter value for " << varName[nWhichData] << " : " ;
int value;
cin >> value;
return value;
}
int main()
{
int x, y, z;
x = getData(0);
y = getData(1);
z = getData(2);
}
This uses array semantics rather than pointer semantics. It is morally equivalent. There are subtle differences between the two, but nothing you need to worry about.
-
Re: Changing function based on a condition?
ummm... yea that part. I don't understand how that array solution really works. I mean, I see what it does, but I'd never have thought of that. Here's some snippets from my actual (now, finished) project:
Code:
//--GETTING DATA FROM USER--//
int foo = 0;
studio = getData(foo);
foo = 1;
oneBed = getData(foo);
foo = 2;
twoBed = getData(foo);
and here is the function definition:
Code:
int getData(int foo)
{
int num;
if (foo == 0)
{
cout << "How many studio apartments?: ";
cin >> num;
}
else if (foo == 1)
{
cout << "How many one-bedroom apartments?: ";
cin >> num;
}
else if (foo == 2)
{
cout << "How many two-bedroom apartments?: ";
cin >> num;
}
return num;
}
EDIT: On a umpteenth look at it, I see that you are using the array to send the 0, 1, 2 to the function parameter rather than manually assigning it like I did... correct? ...and that would allow the program to call those specific actions of the function later if needed, whereas my foo is now stuck assigned to 2... correct?
-
Re: Changing function based on a condition?
Code:
//--GETTING DATA FROM USER--//
int foo = 0;
studio = getData(foo);
foo = 1;
oneBed = getData(foo);
foo = 2;
twoBed = getData(foo);
There's no need to assign a value to a variable just to pass it. Since the function is making a copy of its argument anyway (pass-by-value), you can just pass the constant directly. So this is equivalent to:
Code:
//--GETTING DATA FROM USER--//
studio = getData(0);
oneBed = getData(1);
twoBed = getData(2);
regardless of what's in getData() (and assuming you don't need the fact that foo == 2 later in the main function of course).
Code:
int getData(int foo)
{
int num;
if (foo == 0)
{
cout << "How many studio apartments?: ";
cin >> num;
}
else if (foo == 1)
{
cout << "How many one-bedroom apartments?: ";
cin >> num;
}
else if (foo == 2)
{
cout << "How many two-bedroom apartments?: ";
cin >> num;
}
return num;
}
We can use an array in place of your if/else structure here, because the only difference between the three conditions is the type of apartment, and because your valid foo values are conveniently array-friendly anyway. This is simply a matter of condensing code, it doesn't change the behavior at all:
Code:
int getData(int foo)
{
const std::string apttypes[3] = {"studio", "one-bedroom", "two-bedroom"};
int num;
assert(foo >= 0 && foo < 3);
cout << "How many " << apttype[foo] << " apartments?: ";
cin >> num;
return num;
}
I added the assert() to catch any invalid parameters. Note this check is only done when debugging; an optimized build will omit it (that's how assert works).
We could have made apttype an array of const char*s rather than std::strings, it wouldn't make a difference in this case.
-
Re: Changing function based on a condition?
I just realized, by looking at your examples, that my function call was over-complicated. Here is a better version. Sorry for the noob-ness.
Code:
//--GETTING DATA FROM USER--//
studio = getData(0);
oneBed = getData(1);
twoBed = getData(2);
EDIT: I posted that without seeing your response, Lindley! Haha...
-
Re: Changing function based on a condition?
Actually, there may be an even better way to design the function because it's more "self-documenting":
Code:
studio = getData("studio");
oneBed = getData("one-bedroom");
twoBed = getData("two-bedroom");
Code:
int getData(const std::string &apttype)
{
int num;
cout << "How many " << apttype << " apartments?: ";
cin >> num;
return num;
}
Again we could have used a const char* rather than a std::string const reference, but in this case it isn't *quite* the same-----this way allows you to pass either a char* in or a string object.
-
Re: Changing function based on a condition?
Do I need to include a different header file? I tried to test it your way and it won't work... it underlines the << after "How many " and says no operator matches these operands. I excluded assert, as we haven't learned that yet - but it didn't seem to make a difference either way...
Code:
int getData(int bar)
{
const string foo[3] = {"studio", "one-bedroom", "two-bedroom"};
int num;
cout << "How many " << foo[bar] << " apartments?: ";
cin >> num;
return num;
}
-
Re: Changing function based on a condition?
You should #include <iostream>, #include <string>, and #include <cassert> for assert.
-
Re: Changing function based on a condition?
I forgot about string... I'm stuck with all these simple exercise programs so when I finally write a decent size one for a project I forget stuff. Anyway - Here's my final program, incorporating what I learned here. Anybody feel free to rip it apart - just remember to explain because that's how I learn!
Code:
/***************************************\
| ACME Planning Program |
| Written by: Ben ******** |
| v1.3 Last mod: 02/22/11 |
\***************************************/
#include <iostream>
#include <iomanip>
using namespace std;
//--FUNCTION PROTOTYPES--//
char run_program();
int getData(int);
void studioInfo();
void oneInfo();
void twoInfo();
int spaceCalc();
int costCalc();
int incCalc();
void results(int, int, int, int, int, int, int, int, int, int,
int, int, int, int, int);
char rerun_program(char);
//--VARIABLES--//
int studio, oneBed, twoBed;
const int studioSq = 200; const int oneSq = 300; const int twoSq = 450;
int studioSize, oneSize, twoSize;
const int cost = 75;
int studioCost, oneCost, twoCost;
int studioInc, oneInc, twoInc;
const int studioProf = 450; const int oneProf = 550; const int twoProf = 700;
int spaceTotal, costTotal, incTotal;
int main()
{
cout << "This program calculates income totals for" << endl
<< "ACME Real Estate Company." << endl;
char rerun = run_program();
while (rerun == 'y' || rerun == 'Y')
{
//--GETTING DATA FROM USER--//
studio = getData(0);
oneBed = getData(1);
twoBed = getData(2);
//--PROCESSING DATA--//
studioInfo();
oneInfo();
twoInfo();
//--CALCULATING RESULTS--//
spaceTotal = spaceCalc();
costTotal = costCalc();
incTotal = incCalc();
//--PRINT RESULTS--//
results(studio, oneBed, twoBed, studioSize, studioCost, studioInc,
oneSize, oneCost, oneInc, twoSize, twoCost, twoInc,
spaceTotal, costTotal, incTotal);
//--RERUN--//
rerun = rerun_program(rerun);
}
cout << "THANK YOU!" << endl << endl;
return 0;
}
//--FUNCTION DEFINITIONS--//
//************************//
//--Run Program--//
char run_program()
{
char rerun;
int valid = 0;
while (valid == 0)
{
cout << "Would you like to run this program (y/n)?: ";
cin >> rerun;
//validate input
if (rerun == 'y' || rerun == 'Y' || rerun == 'n' || rerun == 'N')
valid = 1;
}
system("cls");
return rerun;
}
//--Getting data from user--//
int getData(int bar)
{
const char* foo[3] = {"studio", "one-bedroom", "two-bedroom"};
int num;
cout << "How many " << foo[bar] << " apartments?: ";
cin >> num;
return num;
}
//--Processing data--//
void studioInfo()
{
studioSize = studio*studioSq;
studioCost = studioSize*cost;
studioInc = (studio*studioProf)*12;
}
void oneInfo()
{
oneSize = oneBed*oneSq;
oneCost = oneSize*cost;
oneInc = (oneBed*oneProf)*12;
}
void twoInfo()
{
twoSize = twoBed*twoSq;
twoCost = twoSize*cost;
twoInc = (twoBed*twoProf)*12;
}
//--Calculations--//
int spaceCalc()
{
int spaceTotal = studioSize+oneSize+twoSize;
return spaceTotal;
}
int costCalc()
{
int costTotal = studioCost+oneCost+twoCost;
return costTotal;
}
int incCalc()
{
int incTotal = studioInc+oneInc+twoInc;
return incTotal;
}
//--Print Results--//
void results(int studio, int oneBed, int twoBed, int studioSize, int studioCost, int studioInc,
int oneSize, int oneCost, int oneInc, int twoSize, int twoCost, int twoInc,
int spaceTotal, int costTotal, int incTotal)
{
cout << "Report for " << studio << " apartments" << endl
<< oneBed << " one-bedroom apartments" << endl
<< twoBed << " two-bedroom apartments" << endl
<< "\t\tSpace\t\t Costs\t\tIncome" << endl
<< " Studios:\t " << studioSize << "\t\t "
<< studioCost << "\t\t " << studioInc << endl
<< "One-Bedrooms:\t " << oneSize << "\t\t"
<< oneCost << "\t\t " << oneInc << endl
<< "Two-Bedrooms:\t " << twoSize << "\t\t"
<< twoCost << "\t\t " << twoInc << endl
<< "---------------------\t\t------\t\t------" << endl
<< " Total Space:\t " << spaceTotal << " Cost:\t"
<< costTotal << "\t\t" << incTotal << endl;
}
//--Re-run Program--//
char rerun_program(char rerun)
{
int valid = 0;
while (valid == 0)
{
cout << "Do you want to enter another set of data (y/n)? ";
cin >> rerun;
//validate input
if (rerun == 'y' || rerun == 'Y' || rerun == 'n' || rerun == 'N')
valid = 1;
}
system("cls");
return rerun;
}
-
Re: Changing function based on a condition?
Couple of things.
Don't put multiple statements on a single line, even variable declarations. Readability is very important.
In your function prototypes, give your arguments names. It makes the functions self-documenting and if you're using and IDE with an intellisense feature, it will be much more user friendly.
In C++, 0 indicates a false condition, anything else true. So code such as
Code:
int valid = 0;
while (valid == 0)
is counterintuitive. Better style would be
Code:
bool valid = true;
while (valid)
-
Re: Changing function based on a condition?
Quote:
Originally Posted by
GCDEF
Better style would be
Code:
bool valid = true;
while (valid)
I think to get the same meaning as the original, better style would be
Code:
bool valid = false;
while (! valid)
(and then set valid = true in when the string entered is valid).
Best regards,
John
-
Re: Changing function based on a condition?
Quote:
Originally Posted by
GCDEF
Couple of things.
Don't put multiple statements on a single line, even variable declarations. Readability is very important.
In your function prototypes, give your arguments names. It makes the functions self-documenting and if you're using and IDE with an intellisense feature, it will be much more user friendly.
In C++, 0 indicates a false condition, anything else true. So code such as
Code:
int valid = 0;
while (valid == 0)
is counterintuitive. Better style would be
Code:
bool valid = true;
while (valid)
Can you give me an example of naming the function prototype? I don't know if you mean to use a comment or something... I name my functions based on what they do in this program, such as "getData" or "results."
-
Re: Changing function based on a condition?
A function prototype introduces a function to the compiler but doesn't yet give an implementation. This allows the compiler to know which and in what order to push arguments onto the stack and the return type so that it can decide if the return should be stack or register based. This means in essence that you can declare a function in 1 file of your project and define it in another and call it from the file its just been declared in, or for a single file you can call the function before the compiler has seen the implementation, ie...
Code:
int Add( int num1, int num2 ); // this could be simply int Add( int, int ) but adding names self-documents better
int main()
{
int a = 3;
int b = 5;
int c = Add( a,b ); // the compiler here knows the return type is an int and the arguments are ints. It doesn't need to know what add does
return 0;
}
// we can now define the function after its been called because we introduced it to the compiler. This bit could even be in a different file.
int Add( int num1, int num2 )
{
return num1 + num2;
}