C function that returns two values

advertisements

I have to complete the following assignment in C.

Write a function that asks the user to enter two positive integer numbers, reads these two numbers, say a and b, and keeps asking for them until the user enters two such numbers. The function returns both numbers to the place where it was called.

I'm a little confused here. How would I ask the user to enter two values from a function? Can't you only do this from the main() function? As of now I have the following functioning code. It works fine, but of course I need this in an external function.

#include <stdio.h>

int main() {

int a(2); // initialize just as some positive number so as not to set off negative alert.
int b(2);
printf("Enter two positive numbers: \nFirst: ");
do {
    if (a <= 0 || b <= 0) { // negative alert
        printf("Woops. Those are negative. Try again. \nFirst: ");
    }
    scanf(" %d", &a);
    printf("Second: ");
    scanf(" %d", &b);
    printf("\n");
} while (a <= 0 || b <= 0);

return(0);
}


One trick that no one mentioned is that another way to return multiple values from a function is to pass pointers as parameters. A common function that does this is scanf:

int x,y;
scanf("%d %d", &x, &y);

You can sort of view this code as the scanf returninf two values and assigning them to x and y.