Review Arrays
What is an Array?
An array is a fundamental data structure in C++ that allows you to store multiple elements of the same data type under a single name. These elements can be accessed using an index, making arrays a powerful tool for handling collections of data efficiently.
Declaration and Initialization:
In C++, declaring an array involves specifying the data type of its elements and the array’s name. Initialization can be done during declaration or later using assignment statements. Let’s take a look at the syntax:
// Declaration int myArray[5]; // Initialization during declaration int anotherArray[] = {1, 2, 3, 4, 5}; // Accessing elements cout << anotherArray[2]; // Output: 3
Array Indexing:
Array indexing starts from 0, meaning the first element is accessed using index 0, the second with index 1, and so on. Be cautious not to access elements beyond the array’s bounds, as it can lead to undefined behavior.
Manipulating Arrays:
Iterating Through an Array:
Looping through an array is a common operation. You can use a for loop to access each element:
for (int i = 0; i < 5; ++i) { cout << myArray[i] << " "; }
Array Size:
Determining the size of an array is crucial for avoiding index out-of-bounds errors. You can use the sizeof operator or calculate the size using the number of elements and data type size:
int size = sizeof(anotherArray) / sizeof(anotherArray[0]);
Example 1:
#include <iostream> using namespace std; int main() { int arr[7]; for (int i = 0; i < 7; i++) { cin >> arr[i]; } for (int i = 0; i < 7; i++) { cout << arr[i] << " "; } return 0; }
This program takes input for an array of integers and then prints the entered values.
Example 2:
#include <iostream> using namespace std; int main() { int arr[7]; for (int i = 0; i < 7; i++) { cin >> arr[i]; } for (int i = 0; i < 7; i++) { cout << "index" << i << " = " << arr[i]; cout << endl; } cout << endl; return 0; }
This program is a simple console application that takes input for an array of 7 integers from the user and then displays each element along with its index.
Example 3:
#include <iostream> using namespace std; int main() { char g[5]; cin.get(g, 5); cout << g << endl; return 0; }
This program demonstrates reading a character array from user input using cin.get().
char g[5];
This line declares a character array named g that can hold 5 characters.
cin.get(g, 5);
This line uses cin.get() to read up to 4 characters (since the array size is 5, one space is reserved for the null terminator \0) from the user and stores them in the character array g. It stops reading when it encounters a newline character, the end of the stream, or when the specified number of characters have been read.
In summary, this program prompts the user to enter up to 4 characters (excluding the null terminator) and then prints the entered characters using cout.
The null terminator
Often represented by the character \0 (backslash followed by zero), is a special character used in C and C++ to denote the end of a string. It is essential for string manipulation functions to determine where a string ends in memory.
In memory, a string is represented as an array of characters. The null terminator is placed at the end of this array to indicate the boundary of the string. When a program processes a string, it can keep reading characters until it encounters the null terminator, signifying the end of the string data.
For example:
const char myString[] = "Hello";
In memory, this would be stored as follows:
H e l l o \0
Here, the null terminator \0 follows the characters of the string, indicating the end of the string. Functions that operate on strings, like those in the C Standard Library or C++ Standard Library, use the null terminator to determine the length of the string and to recognize the end of the string when performing operations.
Example 4:
#include <iostream> using namespace std; int main() { char g1[10]; char g2[10]; cin.getline(g1, 10); cin.getline(g2, 10); cout << g1 << endl; cout << g2 << endl; return 0; }
This program demonstrates the use of the cin.getline() function to read input lines into character arrays and then prints them.
char g1[10]; char g2[10];
These lines declare two character arrays, g1 and g2, each capable of holding up to 9 characters plus the null terminator \0.
cin.getline(g1, 10); cin.getline(g2, 10);
These lines use cin.getline() to read lines of input from the user into the character arrays g1 and g2. The function takes two arguments: the array to store the input (g1 or g2) and the maximum number of characters to read (9 in this case, leaving one space for the null terminator). The getline function reads characters until it encounters a newline character (‘\n’) or reaches the specified limit.
In summary, this program allows the user to input two lines of text, each up to 9 characters long, and then prints the entered lines. The use of cin.getline() ensures that the input is read as a line, and the program avoids potential issues with the input buffer.
Example 5:
#include <iostream> #include <cstring> using namespace std; int main() { char a1[] = "A"; char a2[] = "B"; cout << strcmp(a1, a2); return 0; }
This C++ program compares two strings using the strcmp function from the C Standard Library.
This code includes the necessary header files for input/output operations (iostream) and string-related functions (cstring). The cstring header is included for the strcmp function.
char a1[] = "A"; char a2[] = "B";
These lines declare and initialize two character arrays, a1 and a2. Each array contains a single character and is automatically null-terminated by the compiler. Remember that a string in C/C++ is essentially an array of characters terminated by the null character (‘\0’).
cout << strcmp(a1, a2);
This line uses the strcmp function to compare the strings stored in a1 and a2. The result is printed to the console. The strcmp function returns an integer value:
- If the strings are equal, it returns 0.
- If a1 is lexicographically less than a2, it returns a negative value.
- If a1 is lexicographically greater than a2, it returns a positive value.
The result of the comparison is printed to the console. This will be either 0 if the strings are equal, a negative value if a1 is less than a2, or a positive value if a1 is greater than a2.
Multi-dimensional Arrays:
C++ supports multi-dimensional arrays, which can be thought of as arrays of arrays. A 2D array, for example, can be declared and accessed like this:
int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Additional Tips:
Passing Arrays to Functions:
When passing an array to a function, you need to use pointers. Here’s a quick example:
void printArray(int arr[], int size) { for (int i = 0; i < size; ++i) { cout << arr[i] << " "; } }
Standard Template Library (STL) Arrays:
For more advanced functionalities, consider using the array class from the C++ Standard Template Library (STL). It provides additional features and safety checks.
#include <array> std::array<int, 5> stlArray = {1, 2, 3, 4, 5};
Example 6:
#include <iostream> #include <cstring> using namespace std; void search(int arr[], int s, int k) { bool g = false; for (size_t i = 0; i < s; i++) { if (arr[i] == k) g = true; } if (g) cout << "Found\n"; else cout << "Not Found\n"; } int main() { int arr[] = {22, 55, 88, 99, 1, 0, 7}; search(arr, 7, 55); return 0; }
This program defines a function called search that searches for a specific value in an integer array. The main function then calls this search function to check if a particular value is present in the given array.
The function called search takes three parameters: arr (an integer array), s (the size of the array), and k (the value to search for).
It initializes a boolean variable g to false, which will be used to track whether the value k is found in the array.
The function then iterates through the array using a for loop. If the current element is equal to the target value k, it sets g to true.
After the loop, it checks the value of g and prints either “Found” or “Not Found” based on whether the target value was found in the array.
The main function initializes an integer array arr with values.
It then calls the search function, passing the array arr, the size of the array (7), and the value to search for (55).
Depending on whether the value 55 is found in the array, the program will output either “Found” or “Not Found.”
Example 7:
#include <iostream> using namespace std; void sort(int arr[], int s) { int t; for (size_t i = 0; i < s - 1; i++) { for (size_t j = 0; j < s - 1; j++) { if (arr[j] > arr[j+1]) { t = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = t; } } } } int main() { int t; int arr[] = {22, 55, 88, 99, 1, 0, 7}; sort(arr, 7); for (size_t i = 0; i < 7; i++) { cout << arr[i] << " "; } return 0; }
This program implements a simple sorting algorithm known as the Bubble Sort.
The sort function implements the Bubble Sort algorithm for sorting an array of integers.
It takes two parameters: arr (the integer array to be sorted) and s (the size of the array).
The function uses nested for loops to iterate through the array. The inner loop compares adjacent elements and swaps them if they are in the wrong order, pushing the larger element towards the end of the array.
The process repeats until the entire array is sorted in ascending order.
The main function initializes an integer array arr with values.
It then calls the sort function, passing the array arr and its size (7), which sorts the array using the Bubble Sort algorithm.
Finally, the sorted array is printed using a for loop.
The program will output the sorted array: 0 1 7 22 55 88 99
Conclusion:
Mastering arrays in C++ is a crucial step in becoming a proficient programmer. They serve as the building blocks for more complex data structures and algorithms. If you’ve found this review helpful, don’t forget to check out our video tutorials on [Adel Nasim] for hands-on examples and practical insights.