C++ Tutorial - Arrays 07-20-2013, 09:19 PM
#1
Hello CC Members, and welcome to my basic array tutorial!
In order for you to understand this tutorial, You'll need basic c++ knowledge such as knowing how to get input and output by including the iostream and other important things like for loops.
I'll break this tutorial into five sections:
What's an array?
By now you're probably wondering what an array is. I'll do my utmost to explain what it is.
Basically, an array is a variable that can hold multiple different values of the same type.
For example:
Code:
#include <iostream>
using namespace std;
int main()
{
int number[5]; // This variable holds five integers.
}
How do we declare an array then?
Good question!
An array is usually declared like this:
Code:
type name [numberofelements];
Here's an example of me declaring an int array:
Code:
int numbers[5]; //This means the variable "numbers" will contain 5 integers
But this not enough because we need to
Initialize the array!
What does it mean to initialize an array?
Basically, when you are initializing an array, you are giving values to the integers in the array. Confusing? Here's an example of what I mean:
Code:
int numbers[5] = {1, 4, 6, 5, 9};
You can leave the [] empty. What will happen then is that the compiler will give just enough space for all those numbers to fit. It basically assumes a size that matches the number of values that is between the braces {}.
Accessing the array!
Wouldn't this be useless if there were no way to access it? I think so. Luckily, you can access individual elements in the array and assign values to them. The format is as follows:
Code:
name[index]
It's pretty easy! Here's an example:
Code:
int numbers[3] = {1, 4, 6}; // Initializing the array
numbers[0] = 15; //Setting the first element to 15
Note that the first element in an array always starts with 0. That means if /*you were to assign the second element a value, you'd do: numbers[1] = 16;*/
Let's do an experiment!
Let's try and use the array to make a message!
Code:
#include <iostream>
using namespace std;
int main()
{
const int numOfChars = 3; //Declaring the array's size
string chars[numOfChars] = {"Coding", "Is", "Fun!"}; //Initializing the array
int i;
for (i = 0; i < numOfChars; i++) {
cout << chars[i] << endl; //Looping through the array and displaying the values.
}
system("PAUSE"); //Prevents the Console Window from closing right after the code is executed
}
If there is something about this concept that you can't seem to 'grasp', don't hesitate to ask me questions. I won't bite, I promise!
I'm really sorry if this was hard to understand. This tutorial isn't complete yet. I'll add more things to it eventually. Thanks for reading, and I hope this tutorial helped aid you in the process of learning c++!
![[Image: WV5eQ42.jpg]](http://i.imgur.com/WV5eQ42.jpg)
If you've got any questions regarding c++ or java, feel free to hit me up with a private message at any time.
http://adf.ly/UyTEk