

C++ Arrays Declaration - Access - Loop
In programing languages Arrays are used to store multiple values in one variable rather than creating multiple variables. In C++ we declare an array using braces and length of array between braces. Examplefruits[4]
C++ example of declaring an array
#include <iostream>
#include <string>
using namespace std;
int main() {
string fruits[4] = {"Banana", "Apple", "Orange", "Strawberry"};
return 0;
}
C++ Access an element in an Array
In C++ we access an element in an array by using the index of that element between braces. See below examplecout << fruits[0];
:#include <iostream>
#include <string>
using namespace std;
int main() {
string fruits[4] = {"Banana", "Apple", "Orange", "Strawberry"};
cout <<"Accessing first element of the array: " << fruits[0];
return 0;
}
Output
Accessing first element of the array: Banana
C++ Change an element in an Array
In C++ we change an element in an array by using the index of that element between braces. See below examplefruits[0] = "Blueberry";
:#include <iostream>
#include <string>
using namespace std;
int main() {
string fruits[4] = {"Banana", "Apple", "Orange", "Strawberry"};
fruits[0] = "Blueberry";
cout <<"Accessing first element of the array: " << fruits[0];
return 0;
}
Output
Accessing first element of the array: Blueberry
C++ Loop through Array elements
#include <iostream>
#include <string>
using namespace std;
int main() {
string fruits[4] = {"Banana", "Apple", "Orange", "Strawberry"};
for(int i = 0; i < 4; i++) {
cout << fruits[i] << "\n";
}
return 0;
}
Output
Banana
Apple
Orange
Strawberry
Apple
Orange
Strawberry
Conclusion
In this page (written and validated by A. Gawali) you learned about C++ Arrays Declaration - Access - Loop . What's Next? If you are interested in completing Cpp tutorial, your next topic will be learning about: Cpp Create a function.
Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.
Share On: |
Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.