On this mastery I will show you what are arrays in C++ and how to use them.

Arrays are some sort of lists that can be input by the user, stored in the program, and then used in the program in order to do something with them later. This may sound pretty similar to how variables work, but the difference with arrays is that you just have to state the values that will be used inside the array instead of making tons of variables. For example, if you want the user to input 5 variables, you just need an array of size 5, instead of declaring variable1, variable2, variable3,

variable4, and

variable5.

An array needs a type (chech out mastery 9 where I talk about types) a name and the number of elements that will be inside of it. Arrays are written: type name [elements].

Now, let’s create a program that allows the user to input 5 elements inside the array and then make a sum and an average of the elements inside the array. So, do as follows:

  1. Create our “basic program”
  2. Declare two variables of type float (this will allow us to have non-integer numbers as the result) with initial value= 0
  3. Create an array of type float with 5 elements (or as many you want). Remember, float NAME[# of elements].
  4. Let the user input the values by calling your array beginning the count of the elements in 0. (cin >> NAME[0]; cin >> NAME[1]; … cin >> NAME[4];) 
  5. Create a for loop (like we learned on mastery 20) that will add the values of the array and will display the total.
  6. Calculate the average (average = total/5)
  7. Print the variables, they will now display a value.

Your program should look something like this:

image

Now let’s run the program:

image

Great! Now you know what are arrays and how to use them, congrats!

CC BY 4.0 Mastery 24 by Omar Peza is licensed under a Creative Commons Attribution 4.0 International License.