Breaking The Records in C (pointer arithmetic related)

For context, I'm trying to write code that solve this problem in C.

The problem is relatively simple. The first input is an integer that represent the number of scores in a stream of scores. The following inputs are all integers that represent scores. The program should read through the stream of scores and return two values: the number of times the record for best score was broken, and the number of times the record for worst score was broken.

I have this solution written down.

#include <stdio.h>

int getRecord(int n, int s[], int *max_records, int *min_records)
{
    int max_score, min_score;
    max_score = min_score = s[0];

    for (int i = 1; i < n; i++)
    {
        if (s[i] > max_score)
        {
            (*max_records)++;
            max_score = s[i];
        }
        if (s[i] < min_score)
        {
            (*min_records)++;
            min_score = s[i];
        }

        printf("%d %d\n", max_score, min_score);  // inserted to see values
        return 0;
    }
}

int main(char args[])
{
    int n;
    scanf("%d", &n);
    int s[n];
    for (int i = 0; i < n; i++)
        scanf("%d", &s[i]);
    int max_records = 0;
    int min_records = 0;

    getRecord(n, s, &max_records, &min_records);
    printf("%d %d\n", max_records, min_records);
}

For some reason, the for loop iterates only once when this program is running, no matter what input I use.

1 answer

  • answered 2017-06-17 19:04 Jack

    You have return 0 inside your loop.

    Change it to:

    for (int i = 1; i < n; i++)
    {
        if (s[i] > max_score)
        {
            (*max_records)++;
            max_score = s[i];
        }
        if (s[i] < min_score)
        {
            (*min_records)++;
            min_score = s[i];
        }
    
        printf("%d %d\n", max_score, min_score);  // inserted to see values
    }
    return 0;