Open In App

Finding the maximum value in a vector using a for loop?

In this article, we will discuss how to find the maximum value in a vector with its working example in the R Programming Language using R for loop. In R programming, loops are essential constructs that allow us to repeat a set of instructions multiple times. The for loop is one such construct that repeatedly executes a block of code until a certain condition is met. This loop is particularly useful when you want to iterate over elements without knowing the exact number of iterations in advance. In this article, we will explore how to use the for loop to print the maximum value in a vector and understand its step-by-step implementation.

Syntax:

# Vector of numbers
numbers <- c(...)
# Initialize a variable to store the maximum value
max_value <- numbers[1]
# Loop through the vector using a for loop
for (num in numbers) {
    if (num > max_value) {
        max_value <- num
    }
}

Example 1: Maximum value in a vector using a for loop




numbers <- c(10, 5, 8, 3, 15, 7)
 
maximum_value <- numbers[1]
 
for (num in numbers) {
  if (num > maximum_value) {
    maximum_value <- num
  }
}
 
cat("The maximum value in the vector is:", maximum_value)

Output:



The maximum value in the vector is: 15

Example 2: Maximum value in a vector using a for loop




numbers <- c(27, 12, 35, 18, 42, 9)
 
maximum_value <- numbers[1]
 
for (num in numbers) {
    if (num > maximum_value) {
        maximum_value <- num
    }
}
 
cat("The maximum value in the vector is:", maximum_value)

Output:

The maximum value in the vector is: 42

Example 3: Using a For Loop with max Function




vector <- c(12, 45, 67, 34, 89, 23)
 
maximum_value <- vector[1]
 
for (element in vector) {
  maximum_value <- max(maximum_value, element)
}
 
print(maximum_value)

Output:



[1] 89

Example 4: Using a For Loop with ifelse Function




my_vector <- c(12, 45, 67, 34, 9, 23)
 
max_value <- my_vector[1]
 
for (element in my_vector) {
  max_value <- ifelse(element > max_value, element, max_value)
}
 
print(max_value)

Output:

[1] 67

Example 5: Using a For Loop and Reduce Function




my_vector <- c(1,2,3,4,5)
 
max_value <- my_vector[1]
for (element in my_vector[-1]) {
  max_value <- Reduce(max, c(max_value, element))
}
 
print(max_value)

Output:

[1] 5

Article Tags :