Ite001a - Function

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 12

FUNCTION

C++ Programming
This method of tasking and subtasking is implemented
elegantly through
subprograms which are called functions. These
subprograms accomplish specific tasks that
contribute to the completion of an overall task.
Example. Problem Tasks: Compute CMPROG1 grade
1. Ask for input
2. Compute grade
Subtasks: 1. Compute average of 2 quizzes
2. Compute average of 2 projects
2. Use average to compute final grade
3. Show output
Functions which Return a Value
NOT FUNCTION FUNCTION

dQAve = (dQ1 + dQ2) / 2; dQAve = ComputeAverage(dQ1, dQ2);


dPAve = (dP1 + dP2) / 2; dPAve = ComputeAverage(dP1,dP2);
Function name ComputeAverage
double ComputeAverage (double dNum1, double dNum2)
{ double dAve;
dAve = (dNum1 + dNum2) / 2;
return (dAve);
}
Function Syntax
The actual value to be returned must be given in a return statement. The
return statement in C++ gives up control of the program to the invoking element and
passes the value of the expression specified. Instead of an expression, a value of a
variable, constant, or literal can be returned.

By assigning the value to a variable, while the other way is to use the value
automatically.
main()
{
double dQ1, dQ2, dP1, dP2;
double dFE, dFG, dTE, dQAve;
cin >> dQ1;
cin >> dQ2;
cin >> dP1;
cin >> dP2;
cin >> dFE);
cin >> dTE;
/* This assigns the returned value to dQAve */
dQAve = ComputeAverage(dQ1, dQ2);
/* The computed average of dP1 and dP2 will be used automatically in
the computation */
dFG = 0.5 * dQAve + 0.3 * ComputeAverage(dP1,dP2) + 0.2 * dFE +
0.05 * dTE;
cout<< “The final grade = “;
cout<< dFG;
}
Creating Functions That Use Parameters
RECURSION – FACTORIAL
main()
#include<iostream> {
using namespace std; double dQ1, dQ2, dP1, dP2;
double dFE, dFG, dQAve;
double ComputeAverage (double dNum1, cin >> dQ1;
double dNum2) cin >> dQ2;
{ cin >> dP1;
cin >> dP2;
double dAve;
cin >> dFE;
dAve = (dNum1 + dNum2) / 2; // cin >> dTE;
return (dAve);
} /* This assigns the returned value to dQAve */
dQAve = ComputeAverage(dQ1, dQ2);
if (dQAve < 60.0)
double ComputeFinal(double dAve1, double cout<< "Not good\n";
d1, double d2, double dFinals) /*returned value compared*/
{ if (ComputeAverage(dP1,dP2) > 90)
/* usng returned value in expression */ cout<< "Good\n";
/*show returned value on screen*/
cout<< "Final Score: ";
return( dAve1*0.45 + cout << ComputeFinal(dQAve,dP1,dP2, dFE);
ComputeAverage(d1,d2)*0.25 + dFinals*
0.3); }
}

You might also like