Write two versions of a program that displays the follwing table:
X X cubed
------------- -----------
Have the table continue until X is 20.
a. For the first version, write a function to do the cube calculation that takes
a single parameter. If the parameter is 2 on entry to the function, the parameter
should have the value 8 on exit from the function. That is, implement a
"pass by reference" on the function's parameter and have the cubed value
passed back in the parameter.
b. For the second version, write a function that does the cubing, but, have
the cubed value passed back to the main program as the return value of the function.
C program....?
JFalt's answer is right on, but it's C++ syntax, not C.
(I don' tmean to nitpick, but this is obviously important if you are trying to compile with a C compiler that doesn't understand C++).
#include %26lt;stdio.h%26gt;
void cubeByReference(int* val);
int cubeByValue(int val);
int main()
{
int initialValue = 2;
int val = cubeByValue(initialValue);
printf("cubeByValue of %d is %d\n", initialValue, val);
val = initialValue;
cubeByReference(%26amp;val);
printf("cubeByReference of %d is %d\n", initialValue, val);
}
int cubeByValue(int val)
{
return val * val * val;
}
void cubeByReference(int *val)
{
*val = (*val) * (*val) * (*val);
}
HTH-
Reply:#include %26lt;iostream%26gt;
using namespace std;
void cubeByReference(int* val);
int cubeByValue(int val);
int main()
{
int initialValue = 2;
int val = cubeByValue(initialValue);
cout %26lt;%26lt; "cubeByValue(" %26lt;%26lt; initialValue %26lt;%26lt;") = " %26lt;%26lt; val %26lt;%26lt; endl;
val = initialValue;
cubeByReference(%26amp;val);
cout %26lt;%26lt; "cubeByReference(" %26lt;%26lt; initialValue %26lt;%26lt;") = " %26lt;%26lt; val %26lt;%26lt; endl;
}
int cubeByValue(int val)
{
return val * val * val;
}
void cubeByReference(int *val)
{
*val = *val * *val * *val;
}
Reply:hehehe is this for your homework.. I wish I had this back when I was in school thats funny
dogwood
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment