# Swift Program to get the numerator from a rational number

In this article, we will learn how to write a swift program to get the numerator from a rational number. A rational number is a number which represents in the form of n/m where m is not equal to zero. Here n is known as the numerator and m is known as the denominator. For example, 7/9, 13/23, etc. Here, 7 and 13 are numerators whereas 9 and 23 are denominators.

## Algorithm

Step 1 − Create a structure to create a rational number.

Step 2 − In this structure, create two properties of integer type to store the numerator and denominator of the rational number.

Step 3 − Create a method to display rational numbers.

Step 4 − Create a struct instance and initialize the numerator and denominator properties of the struct.

Step 5 − Access the numerator property using the dot operator to get the numerator.

Step 6 − Print the output.

## Example

Following Swift program to get the numerator from a rational number.

import Foundation
import Glibc

// Structure to create rational number
struct RationalNumber {
var numerator: Int
var denominator: Int

func display(){
print("Rational number: \(numerator) / \(denominator)")
}
}

// Initialize numerator and denominator of the rational number
let rNumber = RationalNumber(numerator: 123, denominator: 871)
rNumber.display()

// Finding numerator
let num = rNumber.numerator
print("Numerator: \(num)")


## Output

Rational number: 123 / 871
Numerator: 123


Here in the above code, we create a rational number using structure. In this struct, we declare two properties of the same type to store the value of the numerator and denominator of the rational number. Now we create a struct instance and initialize the numerator with 123 and denominator with 871. To get the numerator we access the numerator property using the dot operator along with the struct instance, store the result into a num variable, and display the output that is 123.

## Conclusion

Therefore, this is how we can find the numerator from the rational number in Swift.

Updated on: 09-Jan-2023

83 Views 