5th_Chap(Arrays & Strings)
5th_Chap(Arrays & Strings)
COMPUTER SCIENCE_2
nd
Year (Notes)
Introduction to Arrays
An array is a collection of items stored at contiguous memory locations. It allows you to store multiple
values of the same type in a single variable. Each value in an array is identified by an index or key.
Real-life Example: Think of an array as a row of mailboxes where each mailbox (index) holds a
specific letter (value). If you have 5 mailboxes, you can store 5 letters, and each letter is accessed by its
position in the row.
Concepts of Arrays
1. Indexing: Arrays are indexed from 0. The first element is at index 0, the second element is at
index 1, and so on.
2. Fixed Size: The size of an array is defined at the time of its creation and cannot be changed
dynamically.
3. Homogeneous Elements: All elements in an array are of the same data type (e.g., all integers, all
characters).
Representation of Arrays
1. Declaration and Initialization
Declaration: Defines the type and size of the array.
Initialization: Sets initial values for the array elements.
Syntax:
type arrayName[size];
Example:
int numbers[5]; // Declaration of an array of 5 integers
Initialization:
int numbers[5] = {1, 2, 3, 4, 5}; // Initialization with values
Diagram of Array Representation
Array Representation Diagram
Here's a simple diagram to represent an array in memory:
Memory Address | Value
------------------------
1000 | 1
1004 | 2
1008 | 3
1012 | 4
1016 | 5
Explanation:
Memory Address: Arrays are stored in contiguous memory locations.
Value: Each element is stored at a specific address and can be accessed using its index.
Accessing Array Elements
To access or modify an element in the array, you use its index.
Syntax:
arrayName[index] = value; // Set value at index
value = arrayName[index]; // Get value from index
Example:
numbers[2] = 10; // Sets the value at index 2 to 10
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
return 0;
}
Explanation: This program uses a for loop to iterate through the array and print each element.
Example 2: Sum of Array Elements
Scenario: Calculate the sum of elements in an integer array.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
int sum = 0;
return 0;
}
Explanation: This program calculates the sum of all elements in the array and prints the result.
Example 3: Find the Largest Element
Scenario: Find the largest element in an integer array.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
int max = numbers[0];
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
return 0;
}
Terminology Used in Arrays
Let's break down some key terms related to arrays in simple terms and provide real-life examples for
better understanding.
1. Element
Definition: An individual item stored in an array.
Example: In a shopping list array with items like "milk," "bread," and "eggs," each item is an
element.
2. Index
Definition: The position of an element in the array, usually starting from 0.
Example: If you have an array of books, the index of the first book might be 0, the second book
1, and so on.
3. Size
Definition: The total number of elements the array can hold.
Example: If your array is like a shelf with 10 compartments, the size is 10.
4. Subscript
Definition: Another term for index; the number used to access a specific element.
Example: On a numbered calendar, the subscript for the date "15" is 15.
5. Array Name
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
return 0;
}
Example 2: Sum of Array Elements
Scenario: Calculate the sum of elements in an integer array.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[4] = {5, 10, 15, 20};
int sum = 0;
return 0;
}
Example 3: Find the Largest Element
Scenario: Find the largest number in an integer array.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[6] = {3, 8, 2, 9, 5, 7};
int max = numbers[0];
return 0;
}
Example 4: Reverse Array Elements
Scenario: Reverse the elements of an integer array.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
return 0;
}
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
return 0;
}
Explanation: This code accesses the element at index 2 of the array and prints it.
Example 2: Modify Array Element
Scenario: Change the value at a specific index and print the modified array.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
return 0;
}
Explanation: This code changes the value at index 3 to 100 and prints the entire array to show the
modification.
Example 3: Update Array Element Based on User Input
Scenario: Allow the user to input an index and a new value, then update the array.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {5, 10, 15, 20, 25};
int index, newValue;
return 0;
}
Explanation: This code takes user input for the index and new value, updates the array at the given
index, and prints the updated array.
Example 4: Array with Multiple Indices Access and Modification
Scenario: Access and modify elements at multiple indices in the array.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[6] = {2, 4, 6, 8, 10, 12};
return 0;
}
Explanation: This code accesses and prints elements at specific indices, modifies elements at other
indices, and prints the entire array to show the changes.
int main() {
float expenses[7] = {45.50, 60.25, 55.75, 40.00, 75.10, 50.60, 30.00};
return 0;
}
Explanation: The for loop iterates from index 0 to 6, accessing and printing each element in the
expenses array.
2. While Loop
Scenario: Calculate and print the total amount spent for the week.
C++ Code:
#include <iostream>
using namespace std;
int main() {
float expenses[7] = {45.50, 60.25, 55.75, 40.00, 75.10, 50.60, 30.00};
int i = 0;
float total = 0;
while (i < 7) {
total += expenses[i]; // Add current expense to total
i++;
}
return 0;
}
Explanation: The while loop continues until i is less than 7, summing up the values in the expenses
array.
3. Do-While Loop
Scenario: Find and print the maximum expense for the week.
C++ Code:
#include <iostream>
using namespace std;
int main() {
float expenses[7] = {45.50, 60.25, 55.75, 40.00, 75.10, 50.60, 30.00};
int i = 0;
float maxExpense = expenses[0];
return 0;
}
Explanation: The do-while loop iterates through the array, updating the maxExpense with the highest
value found.
4. Nested Loop
Scenario: A 2D array of weekly expenses for two weeks and print all values.
C++ Code:
#include <iostream>
using namespace std;
int main() {
float expenses[2][7] = {
{45.50, 60.25, 55.75, 40.00, 75.10, 50.60, 30.00}, // Week 1
{35.00, 45.75, 50.20, 55.30, 65.00, 40.00, 25.50} // Week 2
};
return 0;
}
Explanation: The nested for loop iterates through each week and each day, printing out all expenses
from the 2D array.
Sizes of Operators
In programming, especially in C++, operators are used to perform operations on variables and values.
Each operator can have different sizes, and it's important to understand this to ensure that operations are
performed correctly.
Real-Life Examples with Diagrams
1. Basic Arithmetic Operators
Scenario: Think of a kitchen where you measure ingredients using different-sized cups.
Addition (+): Adding ingredients together (e.g., 1 cup of sugar + 2 cups of sugar).
Subtraction (-): Removing a portion of ingredients (e.g., 3 cups of flour - 1 cup of flour).
Multiplication (*): Scaling up recipes (e.g., 2 eggs * 3 recipes).
Division (/): Dividing ingredients among servings (e.g., 10 cups of milk divided by 5 servings).
Diagram:
1 cup of sugar + 2 cups of sugar = 3 cups of sugar
int main() {
float applePrice = 1.50;
float bananaPrice = 0.75;
int appleCount = 4;
int bananaCount = 6;
return 0;
}
int main() {
int itemCount = 0;
cout << "Total items in cart: " << itemCount << endl;
return 0;
}
Explanation: Uses += to add items and -= to remove items from the cart.
Example 3: Comparison Operators
Scenario: Check if a user’s age qualifies for a discount.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int age = 25;
return 0;
}
Explanation: Uses >= to check if the age is 18 or more, qualifying for a discount.
Example 4: Logical Operators
Scenario: Check if a user can enter a club based on age and membership status.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int age = 21;
bool hasMembership = true;
return 0;
int main() {
// 2D array representing a theater seating arrangement
int theaterSeats[3][5] = {
{101, 102, 103, 104, 105},
{106, 107, 108, 109, 110},
{111, 112, 113, 114, 115}
};
return 0;
}
Explanation: The code initializes a 2D array with seat numbers and then prints a specific seat number.
It also loops through the entire array to display all seat numbers.
Code Example 2: Chessboard Representation
C++ Code:
#include <iostream>
using namespace std;
int main() {
// 2D array representing a chessboard
char chessBoard[8][8] = {
{'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'},
{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
{'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'}
return 0;
}
Explanation: This code initializes a 2D array to represent a chessboard. It prints the piece at a specific
position and loops through the entire array to display the chessboard layout.
Summary
2D Arrays: Useful for storing data in a grid or matrix format, like seating arrangements or a
chessboard.
Declaration and Initialization: A 2D array is declared with two indices and can be initialized
with values.
Accessing Elements: Elements are accessed using row and column indices.
Definition of 2D Arrays
A 2D array, or two-dimensional array, is a type of array in which the data is organized in rows and
columns, forming a grid or matrix. Each element in this array can be accessed using two indices: one for
the row and one for the column.
Example: A Classroom Seating Chart
Scenario: Imagine a classroom where students are seated in rows and columns. Each seat can be
identified by a specific row and column number.
Rows: The horizontal lines of seats.
Columns: The vertical lines of seats.
Diagram:
Columns
0 1 2 3 4
+-----+-----+-----+-----+-----+
0 | S1 | S2 | S3 | S4 | S5 | Row 0
+-----+-----+-----+-----+-----+
1 | S6 | S7 | S8 | S9 | S10 | Row 1
+-----+-----+-----+-----+-----+
2 | S11 | S12 | S13 | S14 | S15 | Row 2
+-----+-----+-----+-----+-----+
In this example:
S1 is at Row 0, Column 0.
S9 is at Row 1, Column 3.
Initializing a 2D Array
In C++, a 2D array can be declared and initialized as follows:
int classroom[3][5] = {
{1, 2, 3, 4, 5},
int main() {
// 2D array representing a classroom seating chart
string classroom[3][5] = {
{"S1", "S2", "S3", "S4", "S5"},
{"S6", "S7", "S8", "S9", "S10"},
{"S11", "S12", "S13", "S14", "S15"}
};
return 0;
}
Explanation: This code initializes a 2D array representing a classroom's seating chart and prints a
specific seat along with the entire chart.
int main() {
// 2D array representing monthly sales data
int sales[3][5] = {
{100, 150, 120, 130, 160},
{200, 210, 190, 220, 230},
{300, 310, 320, 330, 340}
};
return 0;
}
Explanation: This code initializes a 2D array representing monthly sales data for different products and
prints specific sales data along with the entire table.
Code Example 3: Temperature Data for Different Cities
Scenario: Suppose you have temperature data for three cities over a week.
C++ Code:
#include <iostream>
using namespace std;
int main() {
// 2D array representing temperature data for 3 cities over 7 days
float temperatures[3][7] = {
{30.5, 32.0, 31.8, 33.1, 30.0, 29.9, 32.5},
{25.2, 26.8, 27.1, 28.0, 24.9, 26.0, 27.5},
{20.1, 21.5, 22.3, 23.0, 19.8, 20.5, 21.9}
};
int main() {
// 2D array for multiplication table
int multiplicationTable[5][5];
return 0;
}
Explanation: This code creates a 5x5 multiplication table using a 2D array and then prints it.
int main() {
int data[3][3] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
return 0;
}
Explanation: This program accesses the element at Row 1, Column 2, which is 60, and displays it.
Example 2: Writing to an Element
C++ Code:
#include <iostream>
using namespace std;
int main() {
int data[3][3] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
return 0;
}
Explanation: This program changes the value at Row 2, Column 1 from 80 to 100 and displays the
updated value.
Example 3: Modifying a Specific Row
Scenario: Imagine updating the scores of a particular row in a table.
C++ Code:
#include <iostream>
using namespace std;
return 0;
}
Explanation: This code modifies all elements in Row 0 by increasing each score by 5, then prints the
updated row.
Example 4: Modifying a Specific Column
Scenario: Updating the sales data for a particular month.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int sales[3][3] = {
{200, 250, 300},
{150, 180, 210},
{100, 120, 140}
};
return 0;
}
Explanation: This code modifies all elements in Column 1 by increasing each sales figure by 50, then
prints the updated column.
What are Strings?
A string is a sequence of characters, similar to a word or sentence in human language. In programming,
strings are used to represent text. For example, the word "Hello" is a string made up of the characters 'H',
int main() {
char name[9] = {'J', 'o', 'h', 'n', ' ', 'D', 'o', 'e', '\0'}; // Character
array with a null terminator
return 0;
}
Explanation: Here, we define a character array named name, which stores the string "John Doe". The \0
at the end marks the end of the string in C++.
Example 2: Using std::string
The std::string class is a more modern and flexible way to work with strings in C++. It allows you to
define and manipulate strings more easily.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "John Doe"; // Using the string class
return 0;
}
Explanation: This code defines a string using the std::string class, which simplifies working with
text data.
int main() {
string firstName = "John";
string lastName = "Doe";
// Concatenating strings
string fullName = firstName + " " + lastName;
return 0;
}
Explanation: This code concatenates the firstName and lastName strings to create a fullName string.
Example 4: Finding Length of a String
You can find out how many characters are in a string using the .length() or .size() method.
#include <iostream>
#include <string>
using namespace std;
int main() {
string sentence = "The quick brown fox";
cout << "Length of sentence: " << length << " characters" << endl;
return 0;
}
Explanation: This code finds and prints the length of the sentence string, which is the number of
characters in the string.
Example 5: Accessing Individual Characters
You can access individual characters in a string by using an index, similar to accessing elements in an
array.
#include <iostream>
#include <string>
using namespace std;
int main() {
string word = "Hello";
return 0;
}
Explanation: This code accesses and prints the first and last characters of the string word.
Example 6: Modifying a String
You can change the contents of a string by modifying its characters.
#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = "Hello";
return 0;
}
Explanation: This code changes the first character of the string greeting from 'H' to 'J', resulting in the
modified string "Jello".
Summary
Strings: A sequence of characters used to represent text.
Defining Strings: Can be defined using a character array or the std::string class.
Real-Life Examples: Names, sentences, or any text-based data.
Initializing Strings
Initializing a string means assigning a value to a string variable at the time of its creation. In C++,
strings can be initialized in various ways, depending on how you want to use them.
Naming a File
Imagine you're saving a document on your computer. The document needs a name before you can save
it, such as "Report.docx." The name you give is like initializing a string.
Diagram:
+-----------------------------+
| Save As: "Report.docx" | <-- String Initialization
+-----------------------------+
In this example, "Report.docx" is the string that represents the name of the file.
Ways to Initialize Strings in C++
1. Using a Character Array
A character array is an older method to initialize a string in C++. You must manually define the size and
assign each character, including the null terminator \0 that marks the end of the string.
Example 1:
#include <iostream>
using namespace std;
int main() {
return 0;
}
Explanation: This code initializes a string using a character array. The string "Report.docx" is stored in
the array, and \0 is added to mark the end of the string.
2. Using String Literals
String literals are the most straightforward way to initialize a string. You simply assign the text directly
to the string variable.
Example 2:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fileName = "Report.docx"; // String literal
cout << "File Name: " << fileName << endl;
return 0;
}
Explanation: Here, the string is initialized with a value directly, making the code easy to read and write.
3. Using the std::string Class and Input
You can initialize a string by getting input from the user or another source.
Example 3:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fileName;
cout << "Enter file name: ";
cin >> fileName; // User inputs file name
cout << "File Name: " << fileName << endl;
return 0;
}
Explanation: This code allows the user to input the file name, which is then stored in the fileName
string.
4. Initializing an Empty String
You can initialize a string as empty, and later assign or modify its value.
Example 4:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fileName; // Empty string initialization
fileName = "Report.docx"; // Assigning a value later
int main() {
string name = "John Doe";
cout << "Length of name: " << name.length() << endl; // or name.size()
return 0;
int main() {
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // Using + operator
return 0;
}
Explanation: This code concatenates the first name "John" and the last name "Doe" to create the full
name "John Doe".
3. Accessing Characters in a String ([] operator)
Real-Life Example: Imagine you want to find out the first letter of your name.
Function: The [] operator is used to access individual characters in a string by their index.
Diagram:
+-------------------+
| "John Doe" | <-- String
+-------------------+
|
v
+-------+
| 'J' | <-- First Character
+-------+
Code Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "John Doe";
cout << "First letter of the name: " << name[0] << endl; // Accessing first
character
return 0;
int main() {
string word1 = "apple";
string word2 = "orange";
if (word1.compare(word2) == 0) {
cout << "The words are the same." << endl;
} else {
cout << "The words are different." << endl;
}
return 0;
}
Explanation: This code compares the two strings "apple" and "orange". Since they are different, the
output will be "The words are different."
5. Finding a Substring (find())
Example: Imagine searching for a specific word in a sentence, like finding the word "fox" in "The quick
brown fox jumps over the lazy dog."
Function: The find() function is used to search for a substring within a string and returns the index
where the substring starts.
Diagram:
+--------------------------------------------------+
| "The quick brown fox jumps over the lazy dog." | <-- String
+--------------------------------------------------+
|
v
+------------------------+
| Substring "fox" found | <-- Result
| at index 16 |
+------------------------+
Code Example:
#include <iostream>
#include <string>
using namespace std;
return 0;
}
Explanation: The code searches for the word "fox" in the sentence and finds it at index 16.
6. Replacing a Substring (replace())
Example: Imagine editing a document where you want to replace every instance of "cat" with "dog."
Function: The replace() function replaces a part of a string with another string.
Diagram:
+----------------------------+
| "I have a black cat." | <-- Original String
+----------------------------+
|
v
+----------------------------+
| "I have a black dog." | <-- After Replacement
+----------------------------+
Code Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string sentence = "I have a black cat.";
string oldWord = "cat";
string newWord = "dog";
return 0;
}
Explanation: The code finds the word "cat" in the sentence and replaces it with "dog," resulting in "I
have a black dog."
Summary
Length of a String (length() or size()): Determines the number of characters in a string.
String Concatenation (+ or append()): Combines two or more strings.
Accessing Characters ([] operator): Retrieves individual characters from a string.
String Comparison (compare()): Compares two strings to see if they are the same.