C: Division that reports failure

Write a division function that signals an error, and has an optional result.

What to build

A function that combines a success flag, output parameters and a NULL check.

Requirements

  • Write int divide(int a, int b, int *q, int *r).
  • It returns 0 if b is 0, and changes nothing.
  • Otherwise, it stores the quotient in *q, stores the remainder in *r unless r is NULL, and returns 1.
  • The starter calls it with NULL for the q command. Do not change main.

Input

The first line has n. Each of the next n lines is d A B, asking for both results, or q A B, asking for the quotient only.

Output

One line per command: Q R or Q, or cannot divide.

Constraints

n is from 1 to 50.

Example

Input:

2
d 17 5
q 17 5

Output:

3 2
3

Why it works

NULL is a common way of saying "I do not need this result". Checking it first means the same function can serve both kinds of caller safely.

Examples

Example 1 · Input
2
d 17 5
q 17 5
Expected output
3 2
3
Example 2 · Input
1
d 7 0
Expected output
cannot divide

Hints

Hint 1

The return value says whether the division worked.

Hint 2

Only write through r after checking that r is not NULL.

Hint 3

C's / and % both truncate towards zero.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int divide(int a, int b, int *q, int *r) {
    if (b == 0) {
        return 0;
    }
    *q = a / b;
    if (r != NULL) {
        *r = a % b;
    }
    return 1;
}

int main(void) {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        char c;
        int a, b, q, r;
        scanf(" %c %d %d", &c, &a, &b);
        if (c == 'd') {
            if (divide(a, b, &q, &r)) printf("%d %d\n", q, r);
            else printf("cannot divide\n");
        } else {
            if (divide(a, b, &q, NULL)) printf("%d\n", q);
            else printf("cannot divide\n");
        }
    }
    return 0;
}

Lesson: Pointers →