Group
Arrays and Vectors in C++
Objective
1. Define an array with several integer values.
2. Implement a function that iterates through the array.
3. Compare each element of the array with the current largest number.
4. Update the largest number whenever a larger value is found.
5. After the loop, return or print the largest number.
6. Test the program with different arrays to ensure its accuracy.
Implement a function that finds the largest number in an array.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// 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) { // If the current element is larger than the current largest
largest = arr[i]; // Update the largest number
}
}
return largest; // Return the largest number found
}
int main() {
// Define an array of numbers
int numbers[] = {15, 22, 4, 67, 30, 90, 12};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
// Call the function to find the largest number
int largest = findLargestNumber(numbers, size);
// Output the largest number
cout << "The largest number in the array is: " << largest << endl;
return 0; // End of program
}
Output
The largest number in the array is: 90