C++ Programming/Scope/Examples/Program Average

From Wikibooks, open books for an open world
Jump to: navigation, search
// Program Average
#include <iostream>

using namespace std;

float a[10];                      /* a is now in scope.*/
int length;                       /* length is now in scope.*/

float average(){
  float result = 0.0;             /* result is now in scope.*/

  for(int i = 0; i < length; i++){ /* i is now in scope.*/
    result += a[i];
  }                               /* i is now out of scope.*/

  return result/length;
}                                 /* result is now out of scope.*/

int main(){
  length = 0;
  cout << "enter a number for each of the next 10 lines" << endl;

  while( length != 10 )
    { cin >> a[length++]; }

  float av = average();            /* av is now in scope.*/
  cout << endl << "average: " << av << endl;

  return 0;
}                                 /* All variables now out of scope.*/