LearnFrenzy
Sign in Take a free test

C Variables · Variable Programs · Question 5

Track min and max readings with static variables in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Write record() that remembers the lowest and highest values seen so far and prints them after each reading.

Solution
main.c
#include <stdbool.h>
#include <stdio.h>

void record(int reading) {
    static bool first = true;
    static int lo, hi;
    if (first || reading < lo)
        lo = reading;
    if (first || reading > hi)
        hi = reading;
    first = false;
    printf("reading %3d -> min %3d, max %3d\n", reading, lo, hi);
}

int main(void) {
    int temps[] = {31, 28, 35, -2, 30};
    for (int i = 0; i < 5; i++)
        record(temps[i]);
    return 0;
}

Output Verified by compiling and running

reading  31 -> min  31, max  31
reading  28 -> min  28, max  31
reading  35 -> min  28, max  35
reading  -2 -> min  -2, max  35
reading  30 -> min  -2, max  35

A static first flag lets the very first reading start both min and max, so the code works for any values – no magic starting numbers like 0 or 9999.

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