Object-Oriented Programming: Writing a C Program to Work with Fractions

Suppose you need to write a program to work with fractions. Perhaps you need to deal with adding, subtracting, multiplying them, and so on.You could define a structure to hold a fraction, and then develop a set of functions to manipulate them.

The basic setup for a fraction using C might look like Program 19.1. Program 19.1 sets the numerator and denominator and then displays the value of the fraction.


Program 19.1   Working with Fractions in C

// Simple program to work with fractions

#include <stdio.h>

typedef struct {

int numerator;

int denominator;

} Fraction;

int main (void)


Fraction myFract;

myFract.numerator = 1;

myFract.denominator = 3;

printf (“The fraction is %i/%i\n”, myFract.numerator, myFract.denominator);

return 0;


Program 19.1   Output

The fraction is 1/3

The next three sections illustrate how you might work with fractions in Objective-C, C++, and C#, respectively. The discussion about OOP  that follows the presentation of Program 19.2 applies to OOP  in general, so you should read these sections in order.

Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.

Leave a Reply

Your email address will not be published. Required fields are marked *