Arrays

Arrays

Arrays are a series of objects of the same type. To declare an array of five integers we use:

#include <iostream>
int main(){
	int myarray[5];
}

Array of 10 characters:

#include <iostream>
int main(){
	char myarray[10];
}

After being declared array can be initialized with values:

#include <iostream>
int main(){
	int myarray[5] = { 10, 20, 30, 40, 50 };
}

Arrays are indexed. Each array element has its index. Indexes start from 0 so the first array element is accessed through:

#include <iostream>
int main(){
	int myarray[5] = { 10, 20, 30, 40, 50 };
	std::cout << "First array element is: " << myarray[0] << std::endl;
}

To print out a third element of an array we can use the following code.

#include <iostream>
int main(){
	int myarray[5] = { 10, 20, 30, 40, 50 };
	std::cout << "First array element is: " << myarray[2] << std::endl;
}

To print out the entire array we can use the for loop:

#include <iostream>
int main(){
	int myarray[5] = { 10, 20, 30, 40, 50 };
	for (int i = 0; i < 5; i++){
		std::cout << myarray[i] << std::endl;
	}
}

To set the value of a second and fourth element we can use:

#include <iostream>
int main(){
	int myarray[5] = { 10, 20, 30, 40, 50 };
	myarray[1] = 123;
	myarray[3] = 456;
	for (int i = 0; i < 5; i++){
		std::cout << myarray[i] << std::endl;
	}
}

Array containers

Good practice is to store the array elements into a std::array container:

#include <iostream>
#include <array>
int main(){
	std::array<int, 5> myarray = { 10, 20, 30, 40, 50 };
	for (int i = 0; i < 5; i++){
		std::cout << myarray[i] << std::endl;
	}
}

Or even better inside a std::vector container:

#include <iostream>
#include <vector>
int main(){
	std::vector<int> myarray = { 10, 20, 30, 40, 50 };
	for (int i = 0; i < 5; i++){
		std::cout << myarray[i] << std::endl;
	}
}