C++ PROGRAMMING:Module 6: Arrays and Strings
Mastering module 6: arrays and strings concepts and implementation.
Arrays and Strings
Arrays and strings are fundamental data structures for storing collections of data. Understanding them is crucial for C++ programming.
Arrays
An array is a collection of elements of the same type stored in contiguous memory locations.
Array Declaration
Syntax:
type arrayName[size];
Example:
int numbers[5]; // Array of 5 integers
double prices[10]; // Array of 10 doubles
char letters[26]; // Array of 26 characters
Array Initialization
Method 1: Initialize at declaration
int arr[5] = {1, 2, 3, 4, 5};
int arr2[] = {1, 2, 3}; // Size automatically determined
int arr3[5] = {1, 2}; // Rest filled with 0
Method 2: Initialize later
int arr[5];
arr[0] = 10;
arr[1] = 20;
// ...
Accessing Array Elements
Arrays use zero-based indexing:
int arr[5] = {10, 20, 30, 40, 50};
cout << arr[0] << endl; // First element: 10
cout << arr[4] << endl; // Last element: 50
Important: Array indices range from 0 to size - 1.
Array Size
Get size:
int arr[5] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]); // 5
Note: This only works for arrays, not pointers!
Common Array Operations
Traversing Array:
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
Finding Maximum:
int arr[5] = {10, 5, 20, 15, 8};
int max = arr[0];
for (int i = 1; i < 5; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
Sum of Elements:
int arr[5] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += arr[i];
}
Multi-dimensional Arrays
2D Array (Matrix):
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Access element
cout << matrix[1][2] << endl; // 7
Traversing 2D Array:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
Arrays as Function Parameters
Passing arrays to functions:
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5);
return 0;
}
Note: Arrays are passed by reference (pointer) by default!
Strings
In C++, strings can be handled in two ways:
- C-style strings (character arrays)
- C++ string class (recommended)
C-style Strings
Character arrays ending with null terminator (\0):
Declaration:
char str1[20] = "Hello";
char str2[] = "World";
char str3[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
Common Functions (from <cstring>):
#include <cstring>
char str1[20] = "Hello";
char str2[20] = "World";
strlen(str1); // Length: 5
strcpy(str1, str2); // Copy str2 to str1
strcat(str1, str2); // Concatenate str2 to str1
strcmp(str1, str2); // Compare: 0 if equal
C++ String Class
Modern, safer way to handle strings (from <string>):
Declaration:
#include <string>
using namespace std;
string str1 = "Hello";
string str2("World");
string str3;
Common Operations:
Length:
string str = "Hello";
int len = str.length(); // or str.size()
Concatenation:
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2; // "Hello World"
str1 += str2; // Append
Accessing Characters:
string str = "Hello";
char first = str[0]; // 'H'
char last = str[str.length() - 1]; // 'o'
str[0] = 'h'; // Modify
Comparison:
string str1 = "Hello";
string str2 = "World";
if (str1 == str2) { } // Equal
if (str1 < str2) { } // Less than (lexicographic)
if (str1.compare(str2) == 0) { } // Compare method
Substring:
string str = "Hello World";
string sub = str.substr(0, 5); // "Hello"
string sub2 = str.substr(6); // "World"
Finding:
string str = "Hello World";
int pos = str.find("World"); // 6
int pos2 = str.find("xyz"); // string::npos (not found)
Replacing:
string str = "Hello World";
str.replace(6, 5, "C++"); // "Hello C++"
Inserting:
string str = "Hello";
str.insert(5, " World"); // "Hello World"
Erasing:
string str = "Hello World";
str.erase(5, 6); // "Hello"
String Input/Output
Reading strings:
string name;
cin >> name; // Reads until whitespace
getline(cin, name); // Reads entire line
getline(cin, name, ','); // Reads until comma
Example:
string firstName, lastName;
cout << "Enter first name: ";
cin >> firstName;
cout << "Enter last name: ";
cin >> lastName;
string fullName = firstName + " " + lastName;
cout << "Full name: " << fullName << endl;
String Iteration
Using index:
string str = "Hello";
for (int i = 0; i < str.length(); i++) {
cout << str[i] << " ";
}
Using range-based for (C++11):
string str = "Hello";
for (char c : str) {
cout << c << " ";
}
Using iterators:
string str = "Hello";
for (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << " ";
}
Common Patterns
Pattern 1: Reverse String
string str = "Hello";
string reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str[i];
}
Pattern 2: Count Characters
string str = "Hello World";
int count = 0;
for (char c : str) {
if (c == 'l') count++;
}
Pattern 3: Check Palindrome
bool isPalindrome(string str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}
Pattern 4: Split String
vector<string> split(string str, char delimiter) {
vector<string> tokens;
string token = "";
for (char c : str) {
if (c == delimiter) {
tokens.push_back(token);
token = "";
} else {
token += c;
}
}
tokens.push_back(token);
return tokens;
}
Best Practices
- ✅ Use C++ string class instead of C-style strings when possible
- ✅ Check bounds when accessing array elements
- ✅ Initialize arrays to avoid garbage values
- ✅ Use meaningful names for arrays and strings
- ✅ Prefer range-based for loops for iteration
- ✅ Use `size()` or `length()` for string length
- ✅ Be careful with array size - no automatic bounds checking
- ✅ Use `std::vector` for dynamic arrays (we'll cover this later)
Common Mistakes
- ❌ Array index out of bounds
- ❌ Forgetting null terminator in C-style strings
- ❌ Using
=to compare C-style strings (usestrcmp) - ❌ Not checking if string is empty before operations
- ❌ Mixing C-style and C++ strings incorrectly
- ❌ Forgetting to include
<string>header
Next Module
In Module 7, we'll learn about Pointers and References - how to work with memory addresses and create more efficient programs!
Hands-on Examples
Basic Array Operations
#include <iostream>
using namespace std;
int main() {
// Array declaration and initialization
int arr[5] = {10, 20, 30, 40, 50};
// Accessing elements
cout << "First element: " << arr[0] << endl;
cout << "Last element: " << arr[4] << endl;
// Traversing array
cout << "All elements: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
// Modifying elements
arr[2] = 99;
cout << "After modification: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
// Finding sum
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += arr[i];
}
cout << "Sum: " << sum << endl;
return 0;
}Arrays store multiple values of the same type. Elements are accessed using zero-based indexing. Arrays are useful for storing collections of data that you need to process together.
Practice with Programs
Reinforce your learning with hands-on practice programs
Related Program Topics
Recommended Programs
Array Max & Min
BeginnerFind maximum and minimum element in an array in C++.
Array Average
BeginnerCalculate average of array elements in C++.
Merge Arrays
BeginnerMerge two arrays into one in C++.
Hello World
BeginnerPrints "Hello World" in C++ with cout. Covers #include, main, and return 0.
Display Your Name
BeginnerStore a name in a C++ string and print it with cout.