Lesson 14: Introduction to Arrays

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

#include <iostream>
#include <string>
 
using namespace std;
int main(){
  //What is an array?
  //An array is a container of like-type variables
  //An array groups variables together
 
  //type name[size];
 
  //Values     | 1 | 2 | 3 | 4 | 5 |
  //Positions  | 0 | 1 | 2 | 3 | 4 |
  //myArray of number -- Aka myArray of 1 == myArray[1]
  // {1,2,3,4,5}  initialization
  // square brackets with a number inside  -- Array subscript [1] -- [varName]
  // When we access using a subscript it's called "Random Access"
 
 
  int myArray[5] = {0};
 
 
 
  for (int i = 0; i < 5; i++){
    cout << "myArray[" << i << "] = " << myArray[i] <<endl;
  }
  cout << endl;
  system("PAUSE");
  return 0;
}

[/spoiler]

Homework: None



Arrays
Back in the lesson about strings, I eluded a lot to how strings were an object(lesson 21) that contains same-type variables (in the case of strings, chars). A collection of same-type variables in a single container is known as an array. In ++ you can make an array of any type of variable, even user-made types. The typical way to make an array is as follows:

type arrayName[arraySize];
Examples:
string names[10]; //Creates an array of 10 strings
int prices[10]; //Creates an array of 10 ints
double sales[5]; //Creates an array of 5 doubles

Array Indexing
One of the most common error among beginner programmers is that they don’t realize that arrays are 0-indexed. This means that the first item you add in an array goes into the position array[0], rather than array[1]. This means that if you make an array with the values 1,2,3,4,5 the values would be in array[0] – array[4] respectively.

Iterating through an array with a loop
Using a for loop to output the contents of an array is fairly simple when you use the following structure: for (int counter = 0; counter < arraySize; conuter++){ cout << array[counter] << endl; Below is an example of how this might look in real-code

int myArray[5] = { 10,20,30,40,50}; 
for (int i = 0; i< 5; i++){
    cout << myArray[i] << endl;
}

Output:
10
20
30
40
50