Connecting Tech Pros Worldwide Forums | Help | Site Map

Converting Existing Code into a Function

Newbie
 
Join Date: Mar 2008
Posts: 5
#1: Mar 20 '08
I have my code all ready and everything works fine with the correct answers, but I don't know how to make functions in it. I only have the main() function at the beginning. how do I even begin to make a function? The examples they have in the book don't really help me because it's not even close to what I am doing.

Like here is one part of my code..

//Declare the variables
double F, S, C, P;

//Obtain a Fixed Cost
while (1)
{
printf ("Input a fixed cost of placing/receiving an order:");
scanf ("%lf", &F);

//If fixed cost is less then $1, the question is asked again
if (F<=0)
{
printf ("Fixed cost cannot be less then $1.\n");
continue;
}
else
break;
}

do I change anything to this part? or do I only focus on the calculation part?

(calculation part)

// Calculate the Economic Ordering Quantity (EOQ)
double EOQ;
EOQ = sqrt ((2*F*S)/(C*P));

//Output value for EOQ
printf ("The economic ordering quantity is %.2lf units.\n", EOQ);


I know I have to come up with a function prototype (a name), but what goes before main() and where do the return values go? also, do i completly get rid of the printf statements?

Familiar Sight
 
Join Date: Jan 2007
Posts: 189
#2: Mar 20 '08

re: Converting Existing Code into a Function


The calculation part could and probably should be made the function. Typically
it should be declared before the main () function. Its implementation definition is is typically positioned below main. There does not need to be any difference between the function declaration name and the function definition name. That is the fuction arguements must define type with associated variable names being optional in the declaration but mandatory in the function definition name. The declaration name and arguements end with a semi-colon.
Expand|Select|Wrap|Line Numbers
  1. convert_temp(float x); //declaration, x variable identity may be ommitted.
  2.  
  3. convert_temp(float x)   // function implementation - x variable identity required
  4.   {
  5.      //function formula in this body
  6.      return temp;
  7.  }
Reply