Introduction
In this lab, you will learn how to manipulate arrays and strings in C++. The lab covers a range of topics, including creating and initializing one-dimensional arrays, accessing and modifying array elements, implementing two-dimensional arrays, working with C-style strings and the String class, sorting array elements, performing linear search, and handling string input with getline(). Through these hands-on exercises, you will develop a strong understanding of fundamental array and string operations in C++ programming.
Create and Initialize One-dimensional Arrays
In this step, you'll learn how to create and initialize one-dimensional arrays in C++. Arrays are fundamental data structures that allow you to store multiple elements of the same type in a contiguous memory location.
Open the WebIDE and create a new file called arrays_intro.cpp in the ~/project directory. We'll explore different ways to initialize arrays.
touch ~/project/arrays_intro.cpp
Add the following code to the arrays_intro.cpp file:
#include <iostream>
int main() {
// Method 1: Declare and initialize an array with specific size
int numbers[5] = {10, 20, 30, 40, 50};
// Method 2: Let compiler determine array size
int scores[] = {85, 92, 78, 95, 88};
// Method 3: Initialize array with default value zero
int zeros[6] = {0};
// Method 4: Create an array and initialize later
int temperatures[4];
temperatures[0] = 72;
temperatures[1] = 68;
temperatures[2] = 75;
temperatures[3] = 80;
// Print array elements
std::cout << "First method - numbers array:" << std::endl;
for (int i = 0; i < 5; i++) {
std::cout << "Element " << i << ": " << numbers[i] << std::endl;
}
return 0;
}
Let's break down array initialization:
int numbers[5] = {10, 20, 30, 40, 50};: Explicitly define array size and initialize all elementsint scores[] = {85, 92, 78, 95, 88};: Let compiler determine array sizeint zeros[6] = {0};: Initialize all elements to zero- Manually assign values using index
temperatures[index] = value
Compile and run the program:
g++ arrays_intro.cpp -o arrays_intro
./arrays_intro
Example output:
First method - numbers array:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
Key points about arrays:
- Arrays have a fixed size once declared
- Array indexing starts at 0
- You can initialize arrays in multiple ways
- Always ensure you don't exceed array bounds
Access and Modify Array Elements Using Index
In this step, you'll learn how to access and modify array elements using their index in C++. Building upon the previous step of array initialization, we'll explore how to interact with individual array elements.
Open the WebIDE and create a new file called array_indexing.cpp in the ~/project directory:
touch ~/project/array_indexing.cpp
Add the following code to the array_indexing.cpp file:
#include <iostream>
int main() {
// Create an array of student scores
int scores[5] = {85, 92, 78, 95, 88};
// Accessing array elements by index
std::cout << "First student's score: " << scores[0] << std::endl;
std::cout << "Third student's score: " << scores[2] << std::endl;
// Modifying array elements
std::cout << "Original second student's score: " << scores[1] << std::endl;
scores[1] = 96; // Update the second student's score
std::cout << "Updated second student's score: " << scores[1] << std::endl;
// Calculating array element sum
int total_score = 0;
for (int i = 0; i < 5; i++) {
total_score += scores[i];
}
std::cout << "Total class score: " << total_score << std::endl;
// Average score calculation
double average_score = static_cast<double>(total_score) / 5;
std::cout << "Average class score: " << average_score << std::endl;
return 0;
}
Key points about array indexing:
- Array indices start at 0
- Use square brackets
[]to access elements - You can read and modify elements using their index
- Be careful not to access indices outside the array bounds
Compile and run the program:
g++ array_indexing.cpp -o array_indexing
./array_indexing
Example output:
First student's score: 85
Third student's score: 78
Original second student's score: 92
Updated second student's score: 96
Total class score: 442
Average class score: 88.4
Important indexing rules:
- First element is at index 0
- Last element is at index (array size - 1)
- Accessing an index outside the array range causes undefined behavior
Implement Two-dimensional Arrays for Matrix
In this step, you'll learn how to create and work with two-dimensional arrays in C++. Two-dimensional arrays are like tables or matrices with rows and columns, allowing you to store and manipulate data in a grid-like structure.
Open the WebIDE and create a new file called matrix_arrays.cpp in the ~/project directory:
touch ~/project/matrix_arrays.cpp
Add the following code to the matrix_arrays.cpp file:
#include <iostream>
int main() {
// Method 1: Declare and initialize a 3x3 matrix
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Method 2: Declare matrix and initialize later
int grades[2][4];
grades[0][0] = 85;
grades[0][1] = 92;
grades[0][2] = 78;
grades[0][3] = 95;
grades[1][0] = 88;
grades[1][1] = 90;
grades[1][2] = 82;
grades[1][3] = 87;
// Print the first matrix
std::cout << "First Matrix:" << std::endl;
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
std::cout << matrix[row][col] << " ";
}
std::cout << std::endl;
}
// Print the grades matrix
std::cout << "\nGrades Matrix:" << std::endl;
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 4; col++) {
std::cout << grades[row][col] << " ";
}
std::cout << std::endl;
}
return 0;
}
Key points about two-dimensional arrays:
- Use two indices to access elements:
array[row][column] - First index represents the row, second index represents the column
- Can be initialized in multiple ways
- Nested loops are typically used to iterate through rows and columns
Compile and run the program:
g++ matrix_arrays.cpp -o matrix_arrays
./matrix_arrays
Example output:
First Matrix:
1 2 3
4 5 6
7 8 9
Grades Matrix:
85 92 78 95
88 90 82 87
Important two-dimensional array concepts:
- Arrays can have more than two dimensions
- Each row can have a different number of columns
- Always be careful with array bounds to avoid errors
Initialize C-style Strings with Null Terminator
In this step, you'll learn about C-style strings and the importance of the null terminator in C++. C-style strings are character arrays that end with a special '\0' character to mark the string's end.
Open the WebIDE and create a new file called c_style_strings.cpp in the ~/project directory:
touch ~/project/c_style_strings.cpp
Add the following code to the c_style_strings.cpp file:
#include <iostream>
#include <cstring>
int main() {
// Method 1: Initialize string with explicit null terminator
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
std::cout << "Greeting: " << greeting << std::endl;
// Method 2: Initialize as a string literal (automatically adds null terminator)
char name[] = "John Doe";
std::cout << "Name: " << name << std::endl;
// Method 3: Declare with fixed size and initialize
char message[20] = "Welcome to C++!";
std::cout << "Message: " << message << std::endl;
// Demonstrate string length
std::cout << "Length of name: " << strlen(name) << std::endl;
// Manual string length calculation
int length = 0;
while (name[length] != '\0') {
length++;
}
std::cout << "Manual length of name: " << length << std::endl;
return 0;
}
Key points about C-style strings:
- Null terminator
'\0'marks the end of the string - Always allocate one extra character for the null terminator
- String literals automatically add the null terminator
strlen()function counts characters before the null terminator
Compile and run the program:
g++ c_style_strings.cpp -o c_style_strings
./c_style_strings
Example output:
Greeting: Hello
Name: John Doe
Message: Welcome to C++!
Length of name: 8
Manual length of name: 8
Important string initialization concepts:
- Null terminator is crucial for string operations
- Always ensure enough space for the null terminator
- Be careful with string buffer sizes to prevent overflow
Use String Class Methods (length, substr, find)
In this step, you'll learn about the powerful string class methods in C++ that make string manipulation easier and more intuitive. We'll explore key methods like length(), substr(), and find().
Open the WebIDE and create a new file called string_methods.cpp in the ~/project directory:
touch ~/project/string_methods.cpp
Add the following code to the string_methods.cpp file:
#include <iostream>
#include <string>
int main() {
// Create a string
std::string message = "Hello, C++ Programming!";
// Using length() method
std::cout << "String length: " << message.length() << std::endl;
// Using substr() method
std::cout << "First 5 characters: " << message.substr(0, 5) << std::endl;
std::cout << "Substring from index 7: " << message.substr(7) << std::endl;
// Using find() method
std::string search_word = "Programming";
size_t position = message.find(search_word);
if (position != std::string::npos) {
std::cout << "'" << search_word << "' found at index: " << position << std::endl;
} else {
std::cout << "Word not found" << std::endl;
}
// Additional find() example
std::string email = "user@example.com";
size_t at_symbol = email.find('@');
size_t dot_symbol = email.find('.');
std::cout << "Username: " << email.substr(0, at_symbol) << std::endl;
std::cout << "Domain: " << email.substr(at_symbol + 1, dot_symbol - at_symbol - 1) << std::endl;
return 0;
}
Key points about string class methods:
length(): Returns the number of characters in the stringsubstr(): Extracts a portion of the string- First argument is start index
- Second argument (optional) is length of substring
find(): Searches for a substring or character- Returns index of first occurrence
- Returns
std::string::nposif not found
Compile and run the program:
g++ string_methods.cpp -o string_methods
./string_methods
Example output:
String length: 23
First 5 characters: Hello
Substring from index 7: C++ Programming!
'Programming' found at index: 11
Username: user
Domain: example
Important string method concepts:
- String methods provide powerful text manipulation
- Indexing starts at 0
- Always check return values to handle potential errors
Convert Between C-style and String Class
In this step, you'll learn how to convert between C-style strings and the C++ string class. These conversions are essential when working with different string representations in C++.
Open the WebIDE and create a new file called string_conversion.cpp in the ~/project directory:
touch ~/project/string_conversion.cpp
Add the following code to the string_conversion.cpp file:
#include <iostream>
#include <string>
#include <cstring>
int main() {
// C-style string to C++ string
const char* c_style_str = "Hello, C++ World!";
std::string cpp_string(c_style_str);
std::cout << "C++ String: " << cpp_string << std::endl;
// C++ string to C-style string
std::string message = "Converting strings";
const char* c_str = message.c_str();
std::cout << "C-style String: " << c_str << std::endl;
// Manual conversion using strcpy
char buffer[50];
strcpy(buffer, message.c_str());
std::cout << "Copied to buffer: " << buffer << std::endl;
// String length comparison
std::cout << "C++ string length: " << message.length() << std::endl;
std::cout << "C-style string length: " << strlen(c_str) << std::endl;
return 0;
}
Key conversion methods:
std::string(c_style_str): Convert C-style string to C++ string.c_str(): Convert C++ string to C-style stringstrcpy(): Manually copy string to a character array
Compile and run the program:
g++ string_conversion.cpp -o string_conversion
./string_conversion
Example output:
C++ String: Hello, C++ World!
C-style String: Converting strings
Copied to buffer: Converting strings
C++ string length: 18
C-style string length: 18
Important conversion concepts:
- Use
.c_str()to get a const char* from a C++ string - Be careful with buffer sizes when converting
strlen()works with C-style strings.length()works with C++ strings
Sort Array Elements Using Bubble Sort
In this step, you'll learn how to implement the Bubble Sort algorithm to sort array elements in C++. Bubble Sort is a simple sorting method that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
Open the WebIDE and create a new file called bubble_sort.cpp in the ~/project directory:
touch ~/project/bubble_sort.cpp
Add the following code to the bubble_sort.cpp file:
#include <iostream>
int main() {
// Initialize an unsorted array
int numbers[5] = {64, 34, 25, 12, 22};
int size = 5;
// Print original array
std::cout << "Original Array: ";
for (int i = 0; i < size; i++) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
// Bubble Sort implementation
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
// Compare adjacent elements
if (numbers[j] > numbers[j + 1]) {
// Swap elements
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
// Print sorted array
std::cout << "Sorted Array: ";
for (int i = 0; i < size; i++) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}
Key Bubble Sort concepts:
- Compares adjacent elements
- Swaps elements if they are in the wrong order
- Repeats passes through the array until sorted
- Time complexity: O(n²)
Compile and run the program:
g++ bubble_sort.cpp -o bubble_sort
./bubble_sort
Example output:
Original Array: 64 34 25 12 22
Sorted Array: 12 22 25 34 64
Important sorting notes:
- Bubble Sort is simple but inefficient for large arrays
- Good for educational purposes
- More efficient sorting algorithms exist for real-world applications
Implement Linear Search in Arrays
In this step, you'll learn how to implement a Linear Search algorithm in C++. Linear Search is a simple method of finding an element in an array by checking each element sequentially until the target is found or the end of the array is reached.
Open the WebIDE and create a new file called linear_search.cpp in the ~/project directory:
touch ~/project/linear_search.cpp
Add the following code to the linear_search.cpp file:
#include <iostream>
int linearSearch(int arr[], int size, int target) {
// Iterate through each element in the array
for (int i = 0; i < size; i++) {
// Check if current element matches the target
if (arr[i] == target) {
return i; // Return the index if found
}
}
return -1; // Return -1 if target is not found
}
int main() {
// Create an array of student scores
int scores[] = {85, 92, 78, 95, 88, 76, 90};
int size = sizeof(scores) / sizeof(scores[0]);
// Target score to search
int targetScore = 78;
// Perform linear search
int result = linearSearch(scores, size, targetScore);
// Display search results
if (result != -1) {
std::cout << "Target score " << targetScore
<< " found at index " << result << std::endl;
} else {
std::cout << "Target score " << targetScore
<< " not found in the array" << std::endl;
}
// Try another search
int missingScore = 100;
result = linearSearch(scores, size, missingScore);
if (result != -1) {
std::cout << "Score " << missingScore
<< " found at index " << result << std::endl;
} else {
std::cout << "Score " << missingScore
<< " not found in the array" << std::endl;
}
return 0;
}
Key Linear Search concepts:
- Checks each array element sequentially
- Returns the index of the target if found
- Returns -1 if target is not in the array
- Time complexity: O(n) - linear time
- Simple and works for unsorted arrays
Compile and run the program:
g++ linear_search.cpp -o linear_search
./linear_search
Example output:
Target score 78 found at index 2
Score 100 not found in the array
Important search notes:
- Linear Search is straightforward but inefficient for large arrays
- Suitable for small arrays or unsorted collections
- More efficient search algorithms exist for sorted arrays
Handle String Input with getline()
In this step, you'll learn how to use getline() to read complete lines of text input in C++. Unlike cin >>, getline() can read strings with spaces and handle more complex input scenarios.
Open the WebIDE and create a new file called getline_input.cpp in the ~/project directory:
touch ~/project/getline_input.cpp
Add the following code to the getline_input.cpp file:
#include <iostream>
#include <string>
int main() {
// Declare a string to store input
std::string fullName;
std::string address;
// Prompt for full name input
std::cout << "Enter your full name: ";
std::getline(std::cin, fullName);
// Prompt for address input
std::cout << "Enter your full address: ";
std::getline(std::cin, address);
// Display input with additional information
std::cout << "\n--- User Information ---" << std::endl;
std::cout << "Name: " << fullName << std::endl;
std::cout << "Address: " << address << std::endl;
// Demonstrate reading multiple lines
std::string multiLineText;
std::cout << "\nEnter a multi-line description (press Ctrl+D to finish):" << std::endl;
std::string line;
while (std::getline(std::cin, line)) {
multiLineText += line + "\n";
}
std::cout << "\nYour description:" << std::endl;
std::cout << multiLineText;
return 0;
}
Key getline() concepts:
- Reads entire line of text, including spaces
- Syntax:
std::getline(input_stream, string_variable) - Can read multiple lines of input
- Handles complex input with spaces
- Useful for reading full names, addresses, etc.
Compile the program:
g++ getline_input.cpp -o getline_input
./getline_input
Example interaction:
Enter your full name: John Michael Smith
Enter your full address: 123 Main Street, Anytown, USA
--- User Information ---
Name: John Michael Smith
Address: 123 Main Street, Anytown, USA
Enter a multi-line description (press Ctrl+D to finish):
This is a sample
multi-line description
with several lines of text.
Your description:
This is a sample
multi-line description
with several lines of text.
Important input handling notes:
getline()reads until newline character- Useful for capturing full text input
- Can be combined with other input methods
Summary
In this lab, you will learn how to create and initialize one-dimensional arrays in C++, access and modify array elements using index, implement two-dimensional arrays for matrix, initialize C-style strings with null terminator, use string class methods, convert between C-style and string class, sort array elements using bubble sort, implement linear search in arrays, and handle string input with getline().
You will explore different ways to initialize arrays, including specifying the size and initializing all elements, letting the compiler determine the size, initializing all elements to zero, and manually assigning values using index. You will also learn how to access and modify array elements using index, and how to handle array bounds to avoid errors. Additionally, you will work with two-dimensional arrays, C-style strings, and the string class, learning how to convert between them and perform various operations.



