Find the Largest Number in an Array in C++
In this exercise, you will implement a function that finds the largest number in an array. This task is fundamental when working with datasets where you need to extract the maximum value or determine peak performance.
The function will iterate through the collection, compare each element against a tracker, and store the highest value found. This exercise helps you master array traversal and comparison logic in C++.
Logic Components
1. Initialization
We assume the first element (arr[0]) is the largest to start our comparison.
2. Linear Scan
Using a for loop, we visit every element starting from the second index to verify our assumption.
3. Update Rule
If the current element is greater than our tracker, we update the tracker with the new maximum value.
Pro Tip:
For modern C++ projects, you can use std::max_element from the <algorithm> header to find the largest value in a single line of code.
Learning Objectives
- 1. Traversal of static arrays using zero-based indexing.
- 2. Implementation of conditional comparison logic.
- 3. Efficient use of
sizeof()to calculate array length dynamically. - 4. Functional decomposition by separating the search logic into a reusable function.
Solution Implementation
#include <iostream>
using namespace std;
// Function to find the largest number in the array
int findLargestNumber(int arr[], int size) {
int largest = arr[0]; // Assume the first element is the largest
// Loop through the array starting from the second element
for (int i = 1; i < size; i++) {
if (arr[i] > largest) { // Comparison logic
largest = arr[i]; // Update the largest number
}
}
return largest; // Return the final result
}
int main() {
// Define an array of integers
int numbers[] = {15, 22, 4, 67, 30, 90, 12};
int size = sizeof(numbers) / sizeof(numbers[0]);
// Execute the search function
int largest = findLargestNumber(numbers, size);
// Display the result
cout << "The largest number in the array is: " << largest << endl;
return 0;
}