Demo 2 - Parallel Array
Here's an example that demonstrates the use of parallel arrays to store information about books, their authors, and their prices. The three arrays are parallel, meaning the book title, its author, and its price at a specific index all correspond to the same book.
//Parallel Arrays Demo (3 Arrays)
#include <iostream>
#include <string>
using namespace std;
int main() {
// Parallel arrays to store book information
string bookTitles[] = {"The Catcher in the Rye", "To Kill a Mockingbird", "1984", "Moby-Dick"};
string bookAuthors[] = {"J.D. Salinger", "Harper Lee", "George Orwell", "Herman Melville"};
double bookPrices[] = {10.99, 9.99, 11.99, 12.99};
// The number of books (make sure this is the same for all arrays)
const int numBooks = 4;
// set the formatting for the output
cout << showpoint << fixed << setprecision(2);
// Displaying the book information
cout << "Book Information:" << std::endl;
for (int i = 0; i < numBooks; ++i) {
cout << "Title: " << bookTitles[i] << ", Author: " << bookAuthors[i]
<< ", Price: $" << bookPrices[i] << endl;
}
return 0;
}
When you run this code, you'll get output like this:
Book Information:
Title: The Catcher in the Rye, Author: J.D. Salinger, Price: $10.99
Title: To Kill a Mockingbird, Author: Harper Lee, Price: $9.99
Title: 1984, Author: George Orwell, Price: $11.99
Title: Moby-Dick, Author: Herman Melville, Price: $12.99
Each index in the arrays bookTitles
, bookAuthors
, and bookPrices
represents a single book. So, bookTitles[0]
, bookAuthors[0]
, and bookPrices[0]
all pertain to the first book, "The Catcher in the Rye" by J.D. Salinger, priced at $10.99.
While parallel arrays like these are simple and easy to understand, they can become difficult to manage as your program grows. In future Modules, we will look at more advanced data structures like a struct
or class
to encapsulate these related pieces of information into a single object. Nonetheless, parallel arrays are a concept you'll often encounter, especially in beginner-level programming.
COSC-1336 / ITSE-1302 Computer Science - Author: Dr. Kevin Roark