Programming Fundamentals 10
Programming Fundamentals 10
PROGRAMMING
ARRAYS
ARRAY
• Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
• To declare an array, define the variable type, specify the name of the array followed
by square brackets and specify the number of elements it should store:
• string cars[4];
• We have now declared a variable that holds an array of four strings. To insert values to it,
we can use an array literal - place the values in a comma-separated list, inside curly
braces:
• You access an array element by referring to the index number inside square brackets [].
• Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
LOOP THROUGH AN ARRAY
• You can loop through the array elements with the for loop.
• Example
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
EXAMPLE
int main() {
int numbers[5];
return 0;
}
PROGRAM WHICH PRINTS THE SUM OF ALL THE
ELEMENTS IN AN ARRAY:
#include <iostream>
include <string>
int main()
int sum = 0;
for(int i = 0;i<5;i++)
sum += myarray[i];
}
ADVANTAGES OF AN ARRAY IN C/C++: