Arrays represent a fundamental data structure that allows programs to work with collections of related data using a common identifier. This chapter explores how arrays are defined, initialized, and manipulated in C++, covering one-dimensional and multi-dimensional arrays. It examines common array operations such as searching, sorting, and traversal, along with the mathematical relationship between array indices and memory addresses. The chapter also introduces parallel arrays and discusses the challenges of boundary checking and memory management when working with arrays.
Chapter 8: Arrays
Arrays are fundamental data structures that allow the storage of multiple elements of the same data type under a single name. They provide a way to represent collections of related data items efficiently. This chapter explores the concept of arrays in C++ and their various applications.
Introduction to Arrays
An array is a collection of elements, all of the same type, stored in contiguous memory locations and accessed using a common name.
Key characteristics of arrays:
- Fixed size (determined at declaration)
- Elements must be of the same data type
- Elements are stored in consecutive memory locations
- Individual elements are accessed by their position (index)
- Indices start at 0 (zero-based indexing)
Advantages of Arrays:
- Efficient storage of multiple values
- Fast access to elements (constant time)
- Simple syntax for processing collections of data
- Support for various operations like sorting and searching
Limitations of Arrays:
- Fixed size (cannot be resized at runtime)
- All elements must be of the same type
- Inefficient insertion and deletion operations
- No built-in bounds checking
Declaration and Initialization of Arrays
Array Declaration
Syntax:
data_type array_name[size];
Examples:
int marks[5]; // Array of 5 integers
float temperatures[7]; // Array of 7 floating-point numbers
char name[20]; // Array of 20 characters
Array Initialization
Arrays can be initialized at the time of declaration:
// Method 1: Initialize all elements
int scores[5] = {85, 92, 78, 90, 88};
// Method 2: Partial initialization (remaining elements are set to 0)
int values[5] = {10, 20}; // Equivalent to {10, 20, 0, 0, 0}
// Method 3: Size deduction
int numbers[] = {1, 2, 3, 4, 5}; // Compiler determines size as 5
// Method 4: Initialize all elements to zero
int zeros[10] = {0};
Accessing Array Elements
Array elements are accessed using their index values:
int marks[5] = {85, 92, 78, 90, 88};
// Accessing individual elements
cout << "First element: " << marks[0] << endl; // Output: 85
cout << "Third element: " << marks[2] << endl; // Output: 78
// Modifying an element
marks[1] = 95; // Change second element from 92 to 95
Processing Arrays
Iterating Through Arrays
Using loops to process array elements:
int scores[5] = {85, 92, 78, 90, 88};
// Using a for loop
for (int i = 0; i < 5; i++) {
cout << "Score " << i+1 << ": " << scores[i] << endl;
}
// Using a range-based for loop (C++11 and later)
for (int score : scores) {
cout << score << " ";
}
Common Array Operations
Finding the Sum and Average:
int numbers[5] = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
float average = static_cast<float>(sum) / 5;
cout << "Sum: " << sum << endl;
cout << "Average: " << average << endl;
Finding the Maximum and Minimum Values:
int values[6] = {12, 45, 7, 23, 56, 9};
int max_value = values[0];
int min_value = values[0];
for (int i = 1; i < 6; i++) {
if (values[i] > max_value) {
max_value = values[i];
}
if (values[i] < min_value) {
min_value = values[i];
}
}
cout << "Maximum value: " << max_value << endl;
cout << "Minimum value: " << min_value << endl;
Searching for an Element:
int numbers[5] = {10, 20, 30, 40, 50};
int search_value = 30;
bool found = false;
int position = -1;
for (int i = 0; i < 5; i++) {
if (numbers[i] == search_value) {
found = true;
position = i;
break;
}
}
if (found) {
cout << "Value " << search_value << " found at position " << position << endl;
} else {
cout << "Value " << search_value << " not found in the array" << endl;
}
Multi-dimensional Arrays
C++ supports arrays with multiple dimensions. The most common are two-dimensional arrays (matrices).
Declaration and Initialization of 2D Arrays
// Declaration
int matrix[3][4]; // 3 rows, 4 columns
// Initialization
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
// Alternative initialization
int another_grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
Accessing Elements in 2D Arrays
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
// Accessing an element
cout << "Element at row 1, column 2: " << matrix[1][2] << endl; // Output: 6
// Modifying an element
matrix[0][1] = 10; // Change the element at row 0, column 1 from 2 to 10
Processing 2D Arrays
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
// Calculate the sum of all elements
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum += matrix[i][j];
}
}
cout << "Sum of all elements: " << sum << endl;
Arrays and Functions
Passing Arrays to Functions
When passing arrays to functions, only the address of the first element is passed (not a copy of the array):
// Function prototype
void displayArray(int arr[], int size);
// Function definition
void displayArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// Function call
int numbers[5] = {10, 20, 30, 40, 50};
displayArray(numbers, 5);
Returning Arrays from Functions
C++ doesn’t allow direct returning of arrays from functions. Instead, you can:
- Return a pointer to the array
- Pass the array as a reference parameter
- Use dynamic memory allocation
- Use container classes like
std::array
orstd::vector
Example using dynamic memory:
int* createArray(int size) {
int* arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i * 10;
}
return arr;
}
int main() {
int size = 5;
int* myArray = createArray(size);
for (int i = 0; i < size; i++) {
cout << myArray[i] << " ";
}
cout << endl;
delete[] myArray; // Don't forget to free the memory!
return 0;
}
Practical Applications of Arrays
Example 1: Sorting an Array (Bubble Sort)
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int numbers[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(numbers) / sizeof(numbers[0]);
cout << "Original array: ";
for (int i = 0; i < n; i++) {
cout << numbers[i] << " ";
}
cout << endl;
bubbleSort(numbers, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}
Example 2: Matrix Addition
#include <iostream>
using namespace std;
void addMatrices(int A[][3], int B[][3], int C[][3], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}
void displayMatrix(int matrix[][3], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
int main() {
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[2][3] = {{7, 8, 9}, {10, 11, 12}};
int C[2][3];
cout << "Matrix A:" << endl;
displayMatrix(A, 2, 3);
cout << "Matrix B:" << endl;
displayMatrix(B, 2, 3);
addMatrices(A, B, C, 2, 3);
cout << "Matrix A + B:" << endl;
displayMatrix(C, 2, 3);
return 0;
}
Example 3: Student Marks Analysis
#include <iostream>
using namespace std;
int main() {
const int NUM_STUDENTS = 5;
const int NUM_SUBJECTS = 3;
int marks[NUM_STUDENTS][NUM_SUBJECTS] = {
{85, 90, 78},
{92, 88, 95},
{78, 72, 81},
{90, 86, 90},
{75, 81, 79}
};
// Calculate total and average for each student
cout << "Student-wise Analysis:" << endl;
cout << "--------------------------" << endl;
cout << "Student\tTotal\tAverage" << endl;
cout << "--------------------------" << endl;
for (int i = 0; i < NUM_STUDENTS; i++) {
int total = 0;
for (int j = 0; j < NUM_SUBJECTS; j++) {
total += marks[i][j];
}
float average = static_cast<float>(total) / NUM_SUBJECTS;
cout << i+1 << "\t" << total << "\t" << average << endl;
}
// Calculate subject-wise average
cout << "\nSubject-wise Analysis:" << endl;
cout << "--------------------------" << endl;
cout << "Subject\tAverage" << endl;
cout << "--------------------------" << endl;
for (int j = 0; j < NUM_SUBJECTS; j++) {
int total = 0;
for (int i = 0; i < NUM_STUDENTS; i++) {
total += marks[i][j];
}
float average = static_cast<float>(total) / NUM_STUDENTS;
cout << j+1 << "\t" << average << endl;
}
return 0;
}
Arrays are versatile data structures that form the foundation for many more complex data structures and algorithms. Understanding how to work with arrays is essential for any programmer, as they are widely used in various applications from simple data storage to complex scientific computations.
Complete Chapter-wise Hsslive Plus One Computer Science Notes
Our HSSLive Plus One Computer Science Notes cover all chapters with key focus areas to help you organize your study effectively:
- Chapter 1 The Discipline of Computing
- Chapter 2 Data Representation and Boolean Algebra
- Chapter 3 Components of the Computer System
- Chapter 4 Principles of Programming and Problem Solving
- Chapter 5 Introduction to C++ Programming
- Chapter 6 Data Types and Operators
- Chapter 7 Control Statements
- Chapter 8 Arrays
- Chapter 9 String Handling and I/O Functions
- Chapter 10 Functions
- Chapter 11 Computer Networks
- Chapter 12 Internet and Mobile Computing