Write a C program to find the maximum and minimum elements in the array.

 

Problem Statement:

Write a C program to find the maximum and minimum elements in the array.

Program:


      #include 

// Function to find maximum and minimum elements
void findMaxMin(int arr[], int n, int *max, int *min) {
    *max = *min = arr[0]; // Initialize max and min with the first element

    // Traverse the array to update max and min
    for (int i = 1; i < n; i++) {
        if (arr[i] > *max)
            *max = arr[i];
        else if (arr[i] < *min)
            *min = arr[i];
    }
}

int main() {
    int arr[] = {10, 5, 20, 8, 15};
    int n = sizeof(arr) / sizeof(arr[0]);
    int max, min;

    findMaxMin(arr, n, &max, &min);

    printf("Maximum element: %d\n", max);
    printf("Minimum element: %d\n", min);

    return 0;
}

Explanation:

  • The findMaxMin function takes the array, its size n, and two pointers to integers max and min.
  • It initializes max and min with the first element of the array.
  • It then traverses the array and updates max and min accordingly.
  • In the main function, an array of integers is declared and initialized.
  • The size of the array is determined using sizeof.
  • The findMaxMin function is called with the array, its size, and pointers to max and min.
  • Finally, the maximum and minimum elements are printed.

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post