LearnFrenzy
Sign in Take a free test

C Const · const Programs · Question 7

Largest element of a read-only array in C Solution, output & explanation

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

Write max_of() that finds the largest element of an array it promises not to modify, and call it with both a const and a normal array.

Solution
main.c
#include <stdio.h>

int max_of(const int *a, size_t n) {
    int best = a[0];
    for (size_t i = 1; i < n; i++)
        if (a[i] > best)
            best = a[i];
    return best;
}

int main(void) {
    static const int fixed[] = {12, 99, 34};
    int scores[] = {71, 88, 64, 90};
    printf("%d %d\n", max_of(fixed, 3), max_of(scores, 4));
    return 0;
}

Output Verified by compiling and running

99 90

Because the parameter is const int *, the same function works for read-only and modifiable arrays. Without the const, passing fixed would discard the qualifier and draw a warning.

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