Imagine you have 30 students in a class. Would you create 30 separate variables for their grades? That would be like having 30 separate lockers scattered around the school! Arrays are like a row of lockers - organized, numbered, and easy to access.
// Method 1: Declare then initialize
int scores[5]; // Creates array of 5 integers
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
scores[3] = 95;
scores[4] = 88;
// Method 2: Declare and initialize together
int scores[5] = {85, 92, 78, 95, 88};
// Method 3: Let compiler count
int scores[] = {85, 92, 78, 95, 88}; // Size is 5
// Method 4: Partial initialization
int scores[5] = {85, 92}; // Rest are 0: {85, 92, 0, 0, 0}
// Method 5: Initialize all to zero
int scores[5] = {0}; // All elements are 0
Arrays use zero-based indexing - like floor numbers in some countries where the ground floor is 0!
Arrays and loops are best friends - they work together perfectly!
const int SIZE = 5;
int numbers[SIZE] = {5, 3, 8, 2, 7};
// 1. Find sum and average
int sum = 0;
for (int i = 0; i < SIZE; i++) {
sum += numbers[i];
}
double average = static_cast(sum) / SIZE;
// 2. Find maximum value
int max = numbers[0];
for (int i = 1; i < SIZE; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
// 3. Search for a value
int target = 8;
bool found = false;
for (int i = 0; i < SIZE; i++) {
if (numbers[i] == target) {
found = true;
cout << "Found at index " << i << endl;
break;
}
}
// 4. Reverse the array
for (int i = 0; i < SIZE/2; i++) {
int temp = numbers[i];
numbers[i] = numbers[SIZE-1-i];
numbers[SIZE-1-i] = temp;
}
2D arrays are like spreadsheets or chess boards - they have rows and columns!
// Declare a 3x3 tic-tac-toe board
char board[3][3] = {
{'X', 'O', 'X'},
{'O', 'X', 'O'},
{'X', 'X', 'O'}
};
// Access elements
cout << board[0][0]; // Prints 'X' (top-left)
cout << board[1][1]; // Prints 'X' (center)
// Process with nested loops
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
cout << board[row][col] << " ";
}
cout << endl;
}
// Grade table for multiple students
int grades[4][6] = {
{85, 92, 78, 95, 88, 91}, // Student 0
{79, 87, 73, 89, 92, 85}, // Student 1
{92, 95, 89, 97, 94, 96}, // Student 2
{76, 82, 71, 85, 79, 80} // Student 3
};
Before the string class, C++ used character arrays - like spelling words letter by letter!
// C-style string declaration
char name[20] = "Alice"; // Can hold up to 19 chars + '\0'
char city[] = "New York"; // Size determined automatically
// Important: Always leave room for null terminator!
char word[6] = "Hello"; // Needs 6 spaces: H-e-l-l-o-\0
// String input (be careful with buffer overflow!)
char username[50];
cout << "Enter username: ";
cin >> username; // Stops at first space
cin.getline(username, 50); // Gets entire line
// String functions (need #include )
char str1[20] = "Hello";
char str2[20] = "World";
char str3[40];
strlen(str1); // Returns 5
strcpy(str3, str1); // Copies str1 to str3
strcat(str3, " "); // Appends space
strcat(str3, str2); // str3 now contains "Hello World"
strcmp(str1, str2); // Compares strings
The string class is like having a smart container that grows and shrinks as needed!
#include
using namespace std;
// Declaration and initialization
string name = "Alice";
string empty; // Empty string
string greeting("Hello"); // Alternative syntax
// String operations
string first = "John";
string last = "Doe";
string full = first + " " + last; // "John Doe"
// String methods
string text = "Hello World";
cout << text.length() << endl; // 11
cout << text.size() << endl; // 11 (same as length)
cout << text[0] << endl; // 'H'
cout << text.at(6) << endl; // 'W' (with bounds checking)
// String modification
text.append("!"); // "Hello World!"
text.insert(5, ","); // "Hello, World!"
text.erase(5, 1); // Remove the comma
text.replace(0, 5, "Hi"); // "Hi World!"
// Finding substrings
size_t pos = text.find("World"); // Returns position or string::npos
if (pos != string::npos) {
cout << "Found at position: " << pos << endl;
}
// Substring extraction
string sub = text.substr(3, 5); // Extract 5 chars starting at pos 3
Going outside array bounds is like trying to access locker #31 when there are only 30 lockers!
Create a program that manages student grades:
#include <iostream>
#include <string>
using namespace std;
int main() {
const int NUM_STUDENTS = 5;
const int NUM_TESTS = 3;
string names[NUM_STUDENTS];
int grades[NUM_STUDENTS][NUM_TESTS];
// TODO: Input student names and grades
// TODO: Calculate averages
// TODO: Find highest and lowest
// TODO: Display report
return 0;
}
// Input phase
for (int i = 0; i < NUM_STUDENTS; i++) {
cout << "Enter name for student " << i+1 << ": ";
cin >> names[i];
cout << "Enter 3 test grades: ";
for (int j = 0; j < NUM_TESTS; j++) {
cin >> grades[i][j];
}
}
// Calculate averages
double averages[NUM_STUDENTS];
for (int i = 0; i < NUM_STUDENTS; i++) {
int sum = 0;
for (int j = 0; j < NUM_TESTS; j++) {
sum += grades[i][j];
}
averages[i] = sum / 3.0;
}
// Common string operations
string sentence = "The quick brown fox";
// Convert to uppercase
for (int i = 0; i < sentence.length(); i++) {
sentence[i] = toupper(sentence[i]);
}
// Count words
int wordCount = 0;
bool inWord = false;
for (int i = 0; i < sentence.length(); i++) {
if (sentence[i] != ' ' && !inWord) {
wordCount++;
inWord = true;
} else if (sentence[i] == ' ') {
inWord = false;
}
}
// Reverse a string
string reversed = "";
for (int i = sentence.length() - 1; i >= 0; i--) {
reversed += sentence[i];
}
// Check if palindrome
string word = "racecar";
bool isPalindrome = true;
for (int i = 0; i < word.length() / 2; i++) {
if (word[i] != word[word.length() - 1 - i]) {
isPalindrome = false;
break;
}
}
Create a program that analyzes a sentence and reports:
C++ also offers dynamic arrays called vectors - they're like arrays that can grow!