#include <iostream>
int main() {
int arr[] = {5, 3, 8, 2, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
std::cout << "The maximum element in the array is: " << max << std::endl;
return 0;
}
- Include the necessary header file
iostream
for input/output operations. - Define the
main()
function, which is the entry point of the program. - Declare an integer array
arr
with initial values {5, 3, 8, 2, 9}
. - Calculate the number of elements in the array by dividing the size of the array (
sizeof(arr)
) by the size of a single element (sizeof(arr[0])
). Store the result in an integer variable n
. - Declare an integer variable
max
and initialize it with the first element of the array (arr[0]
). - Start a
for
loop with an initialization statement (int i = 1
) that sets the loop counter variable i
to 1. The loop will iterate as long as the condition i < n
is true. After each iteration, the loop counter is incremented by 1 (i++
). - Inside the loop, check if the current element
arr[i]
is greater than the current maximum max
. If it is, update the value of max
to the current element. - After the loop ends, the variable
max
will contain the maximum element in the array. - Use
std::cout
to print the message "The maximum element in the array is: " followed by the value of max
, and then use std::endl
to insert a newline character. - Return 0 to indicate successful program execution to the operating system.