11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

82 Part II: Becoming a Functional C++ ProgrammerCalling the function sumSequence()Let’s concentrate on the main program contained in the braces followingmain(). This section of code looks similar to the outer loop in NestedDemo.The main difference is the expression accumulatedValue = sumSequence();that appears where the inner loop would have been. The sumSequence()statement invokes the function of that name. A value returned by the functionis stored in the variable accumulatedValue. Then this value is displayed.The main program continues to loop until sumSequence() returns a sum ofzero, which indicates that the user has finished calculating sums.Divide and conquerThe FunctionDemo program has split the outer loop in main() from theinner loop into a function sumSequence(). This division wasn’t arbitrary:sumSequence() performs a separate role — worth considering by itself —apart from the control features within FunctionDemo.A good function is easy to describe. You shouldn’t have to use more than asingle sentence, with a minimum of such words as and, or, unless, or but. Forexample, here’s a simple, straightforward definition:“The function sumSequence accumulates a sequence of integer values enteredby the user.”This definition is concise and clear. It’s a world away from the ContinueDemoprogram description:“sums a sequence of positive values AND generates an error if the user entersa negative number AND displays the sum AND starts over again until the userenters two zero-length sums.”The output of a sample run of this program appears much like that generatedby the NestedDemo program, as follows:This program sums multiple seriesof numbers. Terminate each sequenceby entering a negative number.Terminate the series by entering twonegative numbers in a rowEnter next sequenceEnter next number: 1Enter next number: 2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!