R Program to Find Maximum of Two Numbers

1. Introduction

Determining the larger value between two numbers is a fundamental operation in both mathematics and programming. This kind of comparison finds its way into various algorithms, data analysis tasks, and daily decision-making scenarios. In this guide, we will create an R program that finds the maximum between two user-provided numbers.

2. Program Overview

The primary aim of this program is to prompt the user for two distinct numbers. 

It will then analyze and compare these numbers to decide which one is larger. 

Following this, it will display the maximum number to the user.

3. Code Program

# Ask the user for the first number
cat("Enter the first number: ")
number1 <- as.numeric(readLines(n=1))

# Ask the user for the second number
cat("Enter the second number: ")
number2 <- as.numeric(readLines(n=1))

# Compare the two numbers to identify the larger one
if (number1 > number2) {
    cat("The maximum between", number1, "and", number2, "is:", number1, "\n")
} else if (number1 < number2) {
    cat("The maximum between", number1, "and", number2, "is:", number2, "\n")
} else {
    cat("Both numbers are equal.\n")
}

Output:

Enter the first number: 12
Enter the second number: 15
The maximum between 12 and 15 is: 15

4. Step By Step Explanation

1. The program kicks off with the cat function, prompting the user for the first number.

# Ask the user for the first number
cat("Enter the first number: ")

2. readLines(n=1) captures the user's input. Since the default form is a character, the as.numeric function converts it to a numeric value, which is stored in the number1 variable.

number1 <- as.numeric(readLines(n=1))

3. Using a similar approach, the program gathers the second number and saves it in the number2 variable.

# Ask the user for the second number
cat("Enter the second number: ")
number2 <- as.numeric(readLines(n=1))

4. With both numbers in place, the program moves on to the comparison phase. Using an if-else conditional structure, the two numbers are evaluated against each other.

5. If number1 is greater than number2, the program displays number1 as the maximum. Conversely, if number1 is less than number2, number2 is showcased as the larger value. Should both numbers be equal, the program informs the user accordingly.

# Compare the two numbers to identify the larger one
if (number1 > number2) {
    cat("The maximum between", number1, "and", number2, "is:", number1, "\n")
} else if (number1 < number2) {
    cat("The maximum between", number1, "and", number2, "is:", number2, "\n")
} else {
    cat("Both numbers are equal.\n")
}

6. The final result is presented to the user via the cat function.

Comments