LearnFrenzy
Sign in Take a free test

Typedef · typedef Programs · Question 1

Fraction type with typedef struct and gcd reduction in C Solution, output & explanation

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

Create a Fraction type with add and multiply functions that always return the fraction in lowest terms, with the sign in the numerator.

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

typedef struct {
    long num, den;
} Fraction;

static long gcd(long a, long b) {
    a = labs(a);
    b = labs(b);
    while (b != 0) {
        long t = a % b;
        a = b;
        b = t;
    }
    return a;
}

static Fraction make(long num, long den) {
    if (den < 0) {                 /* keep the sign in the numerator */
        num = -num;
        den = -den;
    }
    long g = gcd(num, den);
    return (Fraction){num / g, den / g};
}

Fraction add(Fraction a, Fraction b) { return make(a.num * b.den + b.num * a.den, a.den * b.den); }
Fraction mul(Fraction a, Fraction b) { return make(a.num * b.num, a.den * b.den); }

int main(void) {
    Fraction half = {1, 2}, third = {1, 3}, f23 = {2, 3}, f34 = {3, 4}, neg = {-3, 4};
    Fraction r1 = add(half, third), r2 = mul(f23, f34), r3 = add(half, neg);
    printf("%ld/%ld %ld/%ld %ld/%ld\n", r1.num, r1.den, r2.num, r2.den, r3.num, r3.den);
    return 0;
}

Output Verified by compiling and running

5/6 1/2 -1/4

Every result passes through make(), which normalises the sign and divides by the gcd, so 6/12 becomes 1/2. Small typedef'd structs returned by value make the API feel like built-in arithmetic.

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