Chapter 5 — C++ Arrays & Strings
📚 Chapter Overview
Managing large collections of data is easier with Arrays. In this chapter, you will learn how to store multiple values in a single variable using 1D and 2D Arrays, and how to handle text using C++ Strings.
Learning Objectives:
- Understand Indexing and Memory layout of Arrays.
- Master Multi-dimensional (2D) Arrays for matrix math.
- Use the
stringclass for robust text manipulation.
5.1 One-Dimensional Arrays
Part 1 — Definition
An Array is a collection of items of the same data type stored at contiguous memory locations. Each item is accessed using an Index number, starting from 0. Arrays are useful for storing lists like marks, prices, or coordinates.
Part 2 — Syntax
int marks[5] = {90, 85, 88, 70, 95};
cout << marks[0]; // Access first element
Part 3 — Example
Problem: Calculate the average of 5 numbers entered by the user.
int numbers[5], sum = 0;
for(int i=0; i<5; i++) {
cin >> numbers[i];
sum += numbers[i];
}
float avg = sum / 5.0;
cout << "Average: " << avg;
Part 4 — Video
Video: Coming Soon
5.2 C++ Strings
Part 1 — Definition
While C uses character arrays, C++ provides a powerful string class in the standard library. Strings are objects that can store text and come with built-in functions for length, concatenation, and comparison.
Part 2 — Syntax
#include <string>
string name = "Intelle Learn";
string fullName = name + " Academy"; // Concatenation
Part 3 — Example
Problem: Take a full name as input (including spaces) and print its length.
string name;
cout << "Enter full name: ";
getline(cin, name); // Reads space-separated text
cout << "Length: " << name.length();
Observation: cin >> stops at a space; use getline() to read a whole line of text.
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "Matrix Addition" program using 2D Arrays.
Requirements
- Take values for two 2x2 matrices as input.
- Add them and store the result in a third 2x2 matrix.
- Display the resulting matrix in a grid format.
Step-by-Step Process
- Declare
int A[2][2], B[2][2], C[2][2];. - Use nested
forloops to take inputs for A and B. - Use another nested loop for
C[i][j] = A[i][j] + B[i][j]. - Print C using
cout << C[i][j] << " ";.
Expected Deliverables
matrix_add.cppsource file.