Skip to main content

Section 25.3 The Fraction Calculator Using Structures

Subsection 25.3.1 Define a New Data Type

Remember our fraction calculator? We’ll start rewriting it using structures now.

Activity 25.1.

Let’s start by defining a new data type fraction_t, designed to store the numerator and denominator of a fraction (as integers). Try implementing this below:

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    
    return 0;
}

Subsection 25.3.2 Declare the Variables

Activity 25.2.

Now that we have our fraction type, let’s declare two variables, frac1 and frac2, of this type, and make them correspond to the fractions \(\frac{5}{3}\) and \(\frac{-2}{5}\text{.}\)

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    
    return 0;
}

Subsection 25.3.3 Print the Fractions

Now let’s see if we can print out these fractions.

Activity 25.3.

What’s the best way to go about that?

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    
    return 0;
}

Subsection 25.3.4 Adding Fractions

Activity 25.4.

Since we are working on a fraction calculator, how would we go about adding these two fractions? Let’s store the result in a third variable, result. Can we simply say the following?
result = frac1 + frac2

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    
    return 0;
}

Subsection 25.3.5 Print-Fraction Function

You can see that it would be great to write some functions in order to re-use our code.

Activity 25.5.

Let’s try to write a function that prints a fraction.

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    
    return 0;
}

Subsection 25.3.6 Add-Fractions Function

Activity 25.6.

Now let’s try our luck with a function that adds two fractions...

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    
    return 0;
}

Subsection 25.3.7 Enter-Fraction Function

Activity 25.7.

Now we need a function that allows the user to enter a fraction. Be sure to prevent the user from entering a denominator of zero!

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    
    return 0;
}

Subsection 25.3.8 Multiplying Fractions

Multiplying two fractions is now easy!

Activity 25.8.

Let’s multiply two fractions!

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    
    return 0;
}

Subsection 25.3.9 Additional Steps

Activity 25.9.

What else do we need to make our fraction calculator work?

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void) {
    
    return 0;
}