1. // FunctionDemo - demonstrate the use of functions 2. // by breaking the inner loop of the 3. // NestedDemo program off into its own 4. // function 5. 6. #include 7. #include 8. 9. // sumSequence - add a sequence of numbers entered from 10. // the keyboard until the user enters a 11. // negative number. 12. // return - the summation of numbers entered 13. int sumSequence() 14. { 15. // loop forever 16. int nAccumulator = 0; 17. for(;;) 18. { 19. // fetch another number 20. int nValue = 0; 21. cout << "Enter next number: "; 22. cin >> nValue; 23. 24. // if it's negative... 25. if (nValue < 0) 26. { 27. // ...then exit from the loop 28. break; 29. } 30. 31. // ...otherwise add the number to the 32. // accumulator 33. nAccumulator = nAccumulator + nValue; 34. } 35. 36. // return the accumulated value 37. return nAccumulator; 38. } 39. 40. int main(int nArg, char* nArgs[]) 41. { 42. cout << "This program sums multiple series\n" 43. << "of numbers. Terminate each sequence\n" 44. << "by entering a negative number.\n" 45. << "Terminate the series by entering two\n" 46. << "negative numbers in a row\n"; 47. 48. // Continue to accumulate numbers... 49. int nAccumulatedValue; 50. do 51. { 52. // sum a sequence of numbers entered from 53. // the keyboard 54. cout << "\nEnter next sequence\n"; 55. nAccumulatedValue = sumSequence(); 56. 57. // now output the accumulated result 58. cout << "\nThe total is " 59. << nAccumulatedValue 60. << "\n"; 61. 62. // ...until the sum returned is 0 63. } while (nAccumulatedValue != 0); 64. cout << "Program terminating\n"; 65. return 0; 66. } 67.