Examples of Arrays

Suppose you wanted to write a program to average your grades for you. You could read in the grades one at a time and store them in separate variables, then add them up and divide by the number of grades. So, consider the following :

// file : avg.C
#include <iostream.h>
int main()
{
  int grade1, grade2, grade3, grade4, grade5;
  int sum;
  float average;

  cout << "Enter your five grades : ";
  cin >> grade1 >> grade2 >> grade3 >> grade4 >> grade5;
  sum = grade1 + grade2 + grade3 + grade4 + grade5;
  average = sum / 5.0;
  cout << "Your average is " << average << endl;
  return 0;
}

Question : Why did I divide by 5.0 and not just 5?

This program will work, but it is somewhat restricted. You must have exactly five grades to average, otherwise you have to modify the program to suit your other needs. We can use arrays to make this program more robust. Check this out :

// file : avg_array.C
#include <iostream.h>
const int MAX=100;
int main()
{
  int grade[MAX];
  int num;
  int sum=0;
  float average;
  int i;

  cout << "How many grades to enter? : ";
  cin >> num;
  cout << "Enter your grades now." << endl;
  for (i=0 ; i<num ; i++)
    {
      cout << "Grade #" << i+1 << " : ";
      cin >> grade[i];
    }
  for (i=0 ; i<num ; i++)
    {
      sum += grade[i];
    }
  average = sum / (float)num;
  cout << "Your average is " << average << endl;
  return 0;
}


Arrays of characters...

// file : char1.C
#include <iostream.h>

const int MAX=256;

int main()
{
  char string[MAX];
  int i;

  cout << "Type in a four letter word : ";
  for (i=0 ; i<4 ; i++)
    cin >> string[i];
  cout << "You typed in the word '";
  for (i=0 ; i<4 ; i++)
    cout << string[i];
  cout << "'" << endl;

  return 0;
}

And now, a better way of doing to above...

// file : char2.C
#include <iostream.h>
#include <stdio.h>
const int MAX=256;
int main()
{
  char string[MAX];
  int i;

  cout << "Type in any word or words : ";
  gets(string);
  cout << "You typed in : " << string << endl;
  cout << "Again, you typed in : ";
  puts(string);

  return 0;
}