An array is collection of elements. But in C++ and some low level languages we must state what will be data type of those elements.
To create array, we must state specify data tupe, name for array and number of elements array will receive.
In this example our array "numbers" will be filled with 5 integers.
To print individual intefers positions/indexes are used. First element will be at position 0. It's a little bit weird to start from 0, but most of programming languages use that approach.
You will get used to it.
Run this code:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {45, 234, 5000, 0, 567};
cout << "Number at position 0: " << numbers[0] << endl;
cout << "Number at position 1: " << numbers[1] << endl;
cout << "Number at position 2: " << numbers[2] << endl;
cout << "Number at position 3: " << numbers[3] << endl;
cout << "Number at position 4: " << numbers[4] << endl;
return 0;
}
Result:
Number at position 0: 45
Number at position 1: 234
Number at position 2: 5000
Number at position 3: 0
Number at position 4: 567
Process returned 0 (0x0) execution time : 0.285 s
Press any key to continue.
In next example we have an array of characters. Sometimes when we don't know how much elements will end up in specific array we can just use empty square brackets.
Please note, when working with individual characters single quotes must be used around elements.
To get each of them individually, we will use positions/indexes just as with any other array:
#include <iostream>
using namespace std;
int main() {
char characters[] = {'B', 'A', 'T'};
cout << "Character at position 0: " << characters[0] << endl;
cout << "Character at position 1: " << characters[1] << endl;
cout << "Character at position 2: " << characters[2] << endl;
return 0;
}
Result:
Character at position 0: B
Character at position 1: A
Character at position 2: T
Process returned 0 (0x0) execution time : 0.184 s
Press any key to continue.
No comments:
Post a Comment