Two Results at Once

With return, a function gives back only one value. But some calculations have two results. For example, 135 minutes is 2 hours and 15 minutes: two numbers. With pointers, a function can store as many results as it needs in the caller's variables:

#include <stdio.h>

void split_time(int total_minutes, int *hours, int *minutes) {
    *hours = total_minutes / 60;
    *minutes = total_minutes % 60;
}

int main(void) {
    int hours = 0;
    int minutes = 0;
    split_time(135, &hours, &minutes);
    printf("%d h %d min\n", hours, minutes);
    return 0;
}

This prints:

2 h 15 min

The function only reads the first parameter, so it's an ordinary int, and you can pass it a number. It writes to the other two, so they are pointers, and you must pass them the addresses of variables. Such parameters are called output parameters: the function doesn't read them, it fills them in. The stars in the function's first line tell you which parameters are results.

The variables hours and minutes must exist before the call. Here they start at 0, and the function overwrites them. When you call the function again with the same variables, it overwrites them again. And as usual, when you forget the & in the call, compiling ends with an error that says take the address with &.

Instructions

In place of the comment, write a function share with four parameters: candies and children of type int, which it only reads, and the pointers each and left_over of type int *, where it stores the results. The function shares the candies among the children: each child gets candies / children candies, and candies % children are left over.

In main, below printf, create the variables each and left_over with the value 0. Call share with candies, children and the addresses of the two new variables. Then print Each child: 3, left over: 2, with %d for both numbers.

One more child comes. Below the last printf, add 1 to children, call share again with the same variables and print the result the same way. The program prints Each child: 2, left over: 5.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/11