LearnFrenzy
Sign in Take a free test

Pointers and Dynamic Memory · Pointer Programs · Question 1

Return minimum and maximum through pointer parameters in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write a function that receives an array and its size and returns the minimum and maximum through two pointer parameters.

Solution
main.cpp
#include <iostream>

void min_max(const int* a, int n, int* lo, int* hi) {
    *lo = *hi = a[0];
    for (const int* p = a + 1; p < a + n; ++p) {
        if (*p < *lo) *lo = *p;
        if (*p > *hi) *hi = *p;
    }
}

int main() {
    int data[] = {42, 17, 93, 8, 61};
    int lo, hi;
    min_max(data, 5, &lo, &hi);
    std::cout << "min " << lo << ", max " << hi << '\n';
    return 0;
}

Output Verified by compiling and running

min 8, max 93

The caller passes the addresses of lo and hi, and the function writes results through them. const int* promises the array is only read.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links