R Markdown Activity

Problem: Problem Statement

Find the maximum element in a finite sequence of integers.

Pseudocode

Algorithm FindMax(L)

replace the blanks with the words and numbers and letters used in the lecture video.

## Input: A list L of n integers
## Output: The maximum element in the list

## max = L[1]
## for i = 2 to length(L) do
    ## if L[i] > max  then
        ## max = L[i]
## return max

Explanation of Pseudocode

Finish the bullet points below.

1. Initilize max with the first element of the list: Assume the first element is the largest for now.

2. Loop through the rest of the elements in the list: Start from the second element and go to the end.

3. Compare each element with max: If the current is greater than max, update max.

4. Return max: After the loop ends, the maximum element is the result.

Example Execution

Finish the bullet points below.

Let’s go through the list using our Pseudocode𝐿={5,−1,2,8,3,1} step-by-step:

1. Initialize max with the first element: max = 5

2. Compare -1 with max: -1 < 5 (no change)

3. Compare 2 with max: 2 < 5 (no change)

4. Compare 8 with max: 8 > 5 (update max = 8)

5. Compare 3 with max: 3 < 8 (no change)

6. Compare 1 with max: 1 < 8 (no change)

The final value of max is 8.

# Initialize the list
L <- c(5, -1, 2, 8, 3, 1)

# Initialize max with the first element
max <- L[1] # max is now 5
            
# Loop through the rest of the elements in the list
for (i in 2:length(L)) {
# note that "i" is the index of the entry of the place value of domain.

    # 'i' will take values 2, 3, 4, 5, 6 sequentially
    
   if (L[i] > max) { 
        # Compare the current element L[i] with max
     max <- L[i]
         # Update max if L[i] is greater
   }
}

# Return the maximum element
max
## [1] 8

Convert to HTML