C Programming

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

#include<stdio.

h>

struct rational {
int num;
int den;
};

int hcf(int a, int b) {


int h;
for (int i = 1; i <= a && i <= b; i++) {
if (a % i == 0 && b % i == 0) {
h = i;
}
}
return h;
}

void add(struct rational r1, struct rational r2) {


struct rational r3;
r3.num = r1.num * r2.den + r1.den * r2.num;
r3.den = r1.den * r2.den;
int common_factor = hcf(r3.num, r3.den);
printf("The sum of the rational numbers is %d/%d", r3.num / common_factor,
r3.den / common_factor);
}

int main() {
struct rational r1, r2;
printf("Enter the first number (a/b): ");
scanf("%d%d", &r1.num, &r1.den);
printf("Enter the second number (c/d): ");
scanf("%d%d", &r2.num, &r2.den);

if (r1.den != 0 && r2.den != 0) {


add(r1, r2);
}
else {
printf("Invalid input");
}

return 0;
}

You might also like