Skip to main content
C++ Fundamentals for Beginners to Advanced
CHAPTER 10 Beginner

Arrays and Strings in C++

Updated: May 17, 2026
5 min read

# CHAPTER 10

Arrays and Strings

1. Introduction

If you need to store the scores of 50 students, creating 50 separate variables (score1, score2, etc.) is a nightmare. Arrays allow you to store multiple values of the same data type in a single, contiguous block of memory. Strings are essentially arrays of characters used to store text.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Declare and initialize arrays.
  • Access and modify array elements using loops.
  • Create multi-dimensional arrays (matrices).
  • Differentiate between C-style strings and C++ std::string.
  • Use built-in string methods.

3. Arrays in C++

An array is a collection of elements of the same type placed in contiguous memory locations.

Syntax: dataType arrayName[arraySize];

cpp
12345678910111213141516
#include <iostream>
using namespace std;

int main() {
    // Declare and initialize an array of 5 integers
    int scores[5] = {85, 90, 78, 92, 88};

    // Access elements using the index (starts at 0!)
    cout << "First score: " << scores[0] << endl; // 85
    cout << "Third score: " << scores[2] << endl; // 78

    // Modify an element
    scores[1] = 95; 
    
    return 0;
}

4. Looping Through Arrays

Loops and arrays are a perfect match.
cpp
1234567891011
int scores[5] = {85, 90, 78, 92, 88};

// Traditional For Loop
for (int i = 0; i < 5; i++) {
    cout << scores[i] << " ";
}

// Modern C++ Range-Based For Loop (Much cleaner!)
for (int score : scores) {
    cout << score << " ";
}

5. Multidimensional Arrays

Arrays can have multiple dimensions. A 2D array is like a grid or a spreadsheet (Rows and Columns).
cpp
1234567
// A 2D array with 2 rows and 3 columns
int matrix[2][3] = {
    {1, 2, 3}, // Row 0
    {4, 5, 6}  // Row 1
};

cout << matrix[1][2]; // Access Row 1, Col 2 -> prints 6

6. C-Style Strings (Character Arrays)

In the C language, strings were just arrays of characters ending with a special null character \0. While you can still use them in C++, they are hard to work with.
cpp
123
char greeting[6] = {&#039;H&#039;, &#039;e&#039;, &#039;l&#039;, &#039;l&#039;, &#039;o&#039;, &#039;\0&#039;};
// OR
char greeting2[] = "Hello"; // Compiler adds \0 automatically

7. Modern C++ Strings (std::string)

C++ provides a much better way to handle text: the string class (requires #include <string>).
cpp
12345678910111213141516171819
#include <iostream>
#include <string>
using namespace std;

int main() {
    string firstName = "John";
    string lastName = "Doe";
    
    // Concatenation (Joining strings)
    string fullName = firstName + " " + lastName;
    
    // Built-in methods
    cout << "Length: " << fullName.length() << endl; // Or fullName.size()
    
    // Accessing characters
    cout << "First letter: " << fullName[0] << endl;
    
    return 0;
}

8. Mini Project: Student Marks Management

cpp
123456789101112131415161718192021
#include <iostream>
using namespace std;

int main() {
    int marks[5];
    int total = 0;

    cout << "Enter marks for 5 subjects:" << endl;
    for (int i = 0; i < 5; i++) {
        cout << "Subject " << (i + 1) << ": ";
        cin >> marks[i];
        total += marks[i];
    }

    float average = total / 5.0f;
    cout << "--- REPORT CARD ---" << endl;
    cout << "Total Marks: " << total << "/500" << endl;
    cout << "Average: " << average << "%" << endl;

    return 0;
}

9. Memory-Level Explanation

Arrays are stored in contiguous memory. If an int is 4 bytes, and you have int arr[3], the OS allocates 12 consecutive bytes.
text
123
Index:      0         1         2
Value:    [ 10 ]    [ 20 ]    [ 30 ]
Address:  0x100     0x104     0x108

The variable name arr actually holds the memory address of the first element (0x100).

10. Common Mistakes

  • Out of Bounds Error: Accessing scores[5] in a 5-element array. Valid indices are 0 to 4. C++ does NOT check array bounds; it will simply read random garbage memory or crash (Segmentation Fault).
  • String Concatenation Bug: string x = "Hello" + "World"; is illegal because you can't add two raw string literals. At least one must be a std::string variable.

11. Exercises

  1. 1. Create an array of 10 integers. Use a loop to find and print the largest number in the array.
  1. 2. Create a string variable. Use a loop to print the string backwards.
  1. 3. Write a program using a 2D array to represent a 3x3 Tic-Tac-Toe board and print it to the screen.

12. MCQ Quiz with Answers

Question 1

Array indices in C++ start at:

Question 2

What happens if you access an array out of its bounds (e.g., index 10 in a 5-element array)?

Question 3

Which library is required for modern C++ strings?

Question 4

What is the null terminator used in C-style character arrays?

Question 5

How do you find the length of a std::string str?

Question 6

What does int matrix[3][4] create?

Q7. Is string a primitive data type in C++ (like int or char)? a) Yes b) No, it is a class from the Standard Library Answer: b) No, it is a class from the Standard Library
Question 8

In the memory layout of int arr[2], if arr[0] is at address 1000, where is arr[1] (assuming 4-byte ints)?

Question 9

Which loop is best for iterating over all elements in an array without using indices?

Q10. Can you change the size of a standard array after it is declared? a) Yes b) No Answer: b) No (Arrays are fixed size. For dynamic sizes, you need vectors or dynamic allocation).

13. Interview Questions

  • Q: Explain why C++ arrays do not have bounds checking, and what the consequences are.
  • Q: Differentiate between a C-string (char[]) and a C++ std::string. Which is preferred and why?
  • Q: How do you pass an array to a function? Does it pass by value or by reference? (Answer: By reference (pointer)).

14. Summary

Arrays group variables of the same type into a single, contiguous block of memory, accessed via zero-based indexing. Modern C++ relies on the std::string class for robust and safe text manipulation, replacing the older, error-prone C-style character arrays.

15. Next Chapter Recommendation

In Chapter 11: Pointers and References, we will unlock the true power (and danger) of C++ by learning how to manipulate memory addresses directly.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·