Translate

Basic Arrays with C++

Array basics
Let’s start by looking at a single variable used to store a person’s age.
#include <iostream>
———————————————
int main()
{
short age;
age=23;
std::cout << age << std::endl;
return 0;
}
————
———————————
Not much to it. The variable age is created at line (5) as a short. A value is assigned to age. Finally, age is printed to the screen.

Now let’s keep track of 4 ages instead of just one. We could create 4 separate variables, but 4 separate variables have limited appeal. (If using 4 separate variables is appealing to you, then consider keeping track of 93843 ages instead of just 4). Rather than using 4 separate variables, we’ll use an array.
Here’s how to create an array and one way to initialize an array:
————————————————-
1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: age[0]=23;
7: age[1]=34;
8: age[2]=65;
9: age[3]=74;
10: return 0;
11: }
————————————————-
On line (5), an array of 4 short’s is created. Values are assigned to each variable in the array on line (6) through line (9).

Accessing any single short variable, or element, in the array is straightforward. Simply provide a number in square braces next to the name of the array. The number identifies which of the 4 elements in the array you want to access.

No comments:

Post a Comment