Open In App

How to Find Maximum Value in an Array in C?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C, arrays are data structures that allow the user to store a collection of data of the same type. In this article, we will learn how we can find the maximum value in an array in C.

Example

Input: arr = {5,3,1,2,4}

Output: The maximum value of the array is: 5

Finding Maximum Value in an Array in C

We can find the maximal value in an array by taking a variable max and repeatedly comparing it to the elements of the array using loops.

Algorithm

  1. Initialize a variable maxVal with value arr[0].
  2. Traverse through the whole array. During traversal:
    1. If maxVal is less than the current value of array update the value of maxVal.
    2. Else continue.
  3. Exit the loop after whole traversal and Print res which denotes the maximum value in array.

C Program to Find the Maximum Value in an Array

C




// C program to find maximum value in an array
#include <stdio.h>
  
int main()
{
  
    // Initialize an array
    int arr[] = { 23, 12, 45, 20, 90, 89, 95, 32, 65, 19 };
  
    // Find the size of the array
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Intialize the variable which will denote the  maximum
    // element
    int res = arr[0];
  
    // Find the maximum value in the array and store it in
    // res
  
    for (int i = 0; i < n; i++) {
        if (res < arr[i])
            res = arr[i];
    }
    // print the elements of the array
    printf("Array Elements: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    // print the  maximum value
    printf("The maximum value of the array is: %d", res);
  
    return 0;
}


Output

Array Elements: 23 12 45 20 90 89 95 32 65 19 
The maximum value of the array is: 95

Time Complexity: O(N) where N is the number of elements in the array.
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads