Arrays
An array stores a fixed number of values of one type.
C++
#include <iostream>
using namespace std;
int main() {
int marks[5] = {67, 82, 91, 58, 74};
int total = 0;
for (int i = 0; i < 5; i++) {
total += marks[i];
}
cout << "Average: " << (double)total / 5 << endl;
cout << "Third mark: " << marks[2] << endl;
return 0;
}Reading into an array
C++
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int a[100];
for (int i = 0; i < n; i++) cin >> a[i];
int lo = a[0], hi = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < lo) lo = a[i];
if (a[i] > hi) hi = a[i];
}
cout << "min " << lo << ", max " << hi << endl;
return 0;
}Passing an array to a function
C++
#include <iostream>
using namespace std;
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) cout << arr[i] << " ";
cout << endl;
}
void doubleAll(int arr[], int n) {
for (int i = 0; i < n; i++) arr[i] *= 2;
}
int main() {
int v[4] = {1, 2, 3, 4};
doubleAll(v, 4); // arrays are not copied: the original changes
printArray(v, 4);
return 0;
}Sorting: bubble sort
Sorting by hand is a classic exercise. Bubble sort repeatedly swaps neighbours that are in the wrong order:
C++
#include <iostream>
using namespace std;
int main() {
int a[6] = {29, 10, 14, 37, 13, 5};
int n = 6;
for (int pass = 0; pass < n - 1; pass++) {
for (int i = 0; i < n - 1 - pass; i++) {
if (a[i] > a[i + 1]) {
int t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}
}
for (int i = 0; i < n; i++) cout << a[i] << " ";
cout << endl;
return 0;
}In real C++ you'd call std::sort from <algorithm>, covered in the Standard Library module.
2D arrays
C++
#include <iostream>
using namespace std;
int main() {
int m[3][4];
for (int r = 0; r < 3; r++)
for (int c = 0; c < 4; c++)
m[r][c] = (r + 1) * (c + 1);
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) cout << m[r][c] << "\t";
cout << endl;
}
return 0;
}Finished this lesson?Mark it complete to earn +20 XP and move your progress on.