C++ Arrays C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
C++ Arrays
C++ Arrays
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:
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.
To create an array of three integers, you could write:
Access the Elements of an Array
You access an array element by referring to the index number. This statement accesses the value of the first element in cars.
Example
#include <iostream>
#include <string>
using namespace std;int main() {
string cars[4] = {"Tesla", "BMW", "Ford", "TATA"};
cout << cars[0];
return 0;
}
Output:
Tesla
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.