Arrays

Motivate: 10 scores. 10 int variables score1, score2,...score10 ???

cin >> score1;
cin >> score2;
...
Find largest score, or sort them, or sum them ... Infeasible to make such code. So,

Array: one name, many elements/components each of same type, easily accessed with numeric index.

int score[10];   //declare an array of 10 ints

Access an element: Name of array, integer value index in brackets:

score[2] = 29;
if (score[9] > score[8])...
cin >> score[i];
cout << score[0];
Programmer's responsibility to ensure that index is within bounds (size of the array): major source of errors in programs.
score[i] = x;  // i better be between 0 and 9, else bad thing happens: 
               //crash or garbage introduced into memory
Element can be any type: (but all elements of an array can only be same type)
float gpa[100];   //array of 100 floats
char code[10], name[20];   //aka C strings
Also,

Examples:

// read scores, sum them
sum = 0;             	//loop over elements of array
for (i=0; i<10; i++) {  //process elts, index from 0 to end in for loop
  cin >> score[i];  //input to Ith element
  sum += score[i];  //add it to sum
}
cout << "Sum is " << sum;



// find largest score.  search for max value in array.
int largest=0;           // assumuption that scores are positive 
for (i=0; i<10; i++)
  if (score[i] > largest)   //if this one larger than largest so far
    largest = score[i];      //make it largest so far
cout << "Largest score is " << largest;

//How to finc minimum value?


// find largest score, alternate version
int largest=score[0];  //first is largest so far (only one so far)
for (i=1; i<10; i++)   //start with second (index 1)
  if (score[i] > largest)
    largest = score[i];
cout << "Largest score is " << largest;



// change a value of an element
cout << "Change which element: ";
cin >> index;
if (index>=0 && index<10) {
  cout << "Current value: " << score[index] << endl;
  cout << "Change to what: " ;
  cin >> score[index];
}
else
  cout << "Invalid index";



// each score's percentage of total
float percent[10];     //array of 10 floats
for (i=0; i<10; i++)
  percent[i] = score[i] / float(sum);


//count number of positive values, number of negative values.
//You try it now.



// squares and square roots of first 50 numbers
float sqrs[50], sqrts[50];
for (i=0; i<50; i++) {
  sqrs[i] = (i+1) * (i+1);  // 1*1, 2*2, 3*3, 4*4 ... 
  sqrts[i] = sqrt(i+1);
}




// search for particular score value
int found=-1;                   //no such index
cout << "Search for what: ";
cin >> val;
for (i=0; i<10; i++)
  if (score[i] == val)
    found = i;                  //found it at this index
if (found != -1)
  cout << "Found at index: " << found;
else
  cout << "Not found in array";
//Will continue to search to end of array even if finds it early.




// search, alternate version
found = false;            // "not yet found"
i = 0;
while (i<10 && !found)    //within bounds and not yet found
  if (score[i] == val)
    found = true;         //true  Found it
  else
    i++;                  //next element index
if (found)
  cout << "Found at index: " << i;
else
  cout << "Not found in array";






// count #times each uppercase letter in input
// 26 separate variables: acount,bcount...zcount? UGH!
int letter[26]; 	//26 counters
for (i=0; i<26; i++)	//initialize each counter element to 0
  letter[i] = 0;
do {
  cin >> c;
  if (isupper(c))    	//c is ABC...Z
    letter[c-'A']++; 	//A-A=0, B-A=1, C-A=2,...Z-A=25
	          //index of element that is count for that letter
} while (c != '$');  	//assume $ marks end of input



// average #times each uppercase letter 
int sum=0;
for (i=0; i<26; i++)
  sum += letter[i];
cout << "Average is " << float(sum) / 26;

Size of the array is the maximum number of values that can be stored in it. Not obligated to use every element.

const int max_scores=100;

int scores[max_scores];
int num_scores;
cout << "How many scores: ";
cin >> num_scores;     // num_scores is the logical/virtual 
                       //size of the array now
if (num_scores > max_scores)
  cout << "Sorry, too many!";
else {              //will use first num_scores number of elements, 
                    //from 0 thru num_scores-1
  cout << "Enter the scores: ";
  for (i=0; i<num_scores; i++)
    cin >> scores[i];
}

// largest score
largest = 0;
for (i=0; i<num_scores; i++)
  if (scores[i] > largest)
    largest = scores[i];






const int max_grades=100;

char grades[max_grades];
cout << "Enter number of grades: ";
cin >> num_grades;
if (num_grades > max_grades)
  cout << "ERROR Maximum of " << max_grades;
else {
  cout << "Enter the grades: ";
  for (i=0; i<num_grades; i++)
    cin >> grades[i];
}


// count number of each grade ABCDF and other
int grade_count[6]={0}; //initialize all to 0
                       // (only value that all can be init to)
for (i=0; i<num_grades; i++)
  switch (grades[i])    // a char
  case 'a':
  case 'A': grade_count[0]++;
            break;
  case 'b':
  case 'B': grade_count[1]++;
            break;
  case 'c':
  case 'C': grade_count[2]++;
            break;
  case 'd':
  case 'D': grade_count[3]++;
            break;
  case 'f':
  case 'F': grade_count[4]++;
            break;
  default: grade_count[5]++;
}

cout << "   A   B   C   D   F other" << endl;
cout << setw(4) << grade_count[0]
     << setw(4) << grade_count[1]
     << setw(4) << grade_count[2]   
     << setw(4) << grade_count[3]
     << setw(4) << grade_count[4]
     << setw(4) << grade_count[5] << endl;

Program to do several things with an array array.cpp

Program to compute the standard deviation stddev.cpp

Program to compute the prime factorization of a number primefac.cpp

Next (array arguments)


©David Wills