Jump to content

C++ Programming/Scope/Examples/Program Average1

From Wikibooks, open books for an open world
// Program Average rewritten using a class
#include <iostream>

using namespace std;

class StatisticsPackage{
private:
  float aa[20];                     /* aa scope start*/
  int length;                       /* length scope start*/
public:                           
  float average(){
    float result = 0.0;             /* result scope start*/
 
    for(int i = 0; i < length; ++i) /* i scope start*/
      result += aa[i];
 
  return result/length;
  }                                 /* result and i scope end*/

  void get_data(){
    length = 0;
    while(cin >> aa[length++]);
    --length;
  }
};                                  /* aa and length scope end*/

int main(){
  StatisticsPackage sp;             /* aa and length lifetimes start */
  sp.get_data();
  float av = sp.average();          /* av scope start*/
  cout << av << endl;
  return 0;
}                                   /* av scope end*/