OneBite.Dev - Coding blog in a bite size

Create An Array Of String In C++

Code snippet for how to Create An Array Of String In C++ with sample and detail explanation

Working with arrays in C++ is a fundamental concept that every aspiring C++ programmer should grasp deeply. More so, understanding how to create an array of strings in C++ will enable you to manipulate textual data efficiently.

Code snippet for Creating an Array of Strings in C++

#include <iostream>
using namespace std;

int main() {
    string fruits[4] = {"Apple", "Orange", "Banana", "Pear"};

    for(int i = 0; i < 4; i++) {
        cout << fruits[i] << "\n";
    }

    return 0;
}

Code Explanation for Creating an Array of Strings in C++

This simple program creates an array of strings, assigns the strings with four fruit names, and then uses a loop to print each of them in the console.

Let’s break it down:

  1. #include <iostream>: This is a preprocessor directive that includes the iostream standard library file in the program which allows the program to perform standard input and output operations, such as cout.

  2. using namespace std;: This line allows us to use things in the standard (std) namespace, without requiring us to type std:: in front of many common C++ objects, such as string and cout.

  3. string fruits[4] = {"Apple", "Orange", "Banana", "Pear"};: Here, we are declaring an array of strings called ‘fruits’. The square brackets indicate the size of the array or the number of elements it can hold, which, in this case, is four.

  4. Next, we have a for loop for(int i = 0; i < 4; i++). Loops are used in C++ to repeatedly execute a block of code. In this case, the code inside the loop will be executed four times.

  5. The statement cout << fruits[i] << "\n"; inside the loop prints the string data in each index of the array. The object ‘cout’ represents the standard output stream in C++, it works with the stream insertion operator ’<<’, which outputs the string followed by a newline character.

  6. return 0; is used to indicate that the program has run successfully. It’s common practice to return zero from the main function.

This complete program is an elementary way to understand arrays of strings in C++. Remember, the index of an array always starts at 0 in C++, so an array that can hold four strings will have indices from 0 to 3.

c-plus-plus