c-plus-plus
  1. c-plus-plus-find-max-in-array-function

C++ Program to Find Maximum in an Array using a Function

In this program, we will write a C++ function to find the maximum element in an array. We will declare this function outside the main() function for better code organization.

Syntax

int findMax(int arr[], int size) {
    int max = arr[0];
    for(int i = 1; i < size; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

Example

#include <iostream>
using namespace std;

// Function to find maximum element in an array
int findMax(int arr[], int size) {
    int max = arr[0];
    for(int i = 1; i < size; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

int main() {
    int arr[] = {5, 7, 2, 8, 1};
    int size = sizeof(arr)/sizeof(arr[0]);
    cout << "Max Element: " << findMax(arr, size) << endl;
    return 0;
}

Output

Max Element: 8```

## Explanation

In the above example, we have an array of integers with 5 elements. We pass this array to the findMax() function which returns the maximum element in the array. We then print this value to the console.

## Use

This program can be used to find the maximum element in an array of integers in C++. The findMax() function can be reused in other programs to avoid the need for duplicate code.

## Important Points

- The function to find the maximum element in an array takes two arguments: the array and its size.
- We initialize the starting maximum element as the first element of the array.
- We then iterate through the rest of the array comparing each element to the current maximum element. If it is greater, we update the maximum element.
- The function returns the maximum element.

## Summary

In summary, this program demonstrates how to find the maximum element in an array of integers in C++ using a function that takes the array and its size as arguments. By using a function, we can reuse this code in other programs and avoid duplicate code.
Published on: