ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

PLC Structured Text: Basic Array Element Search

PLC Structured Text

Goal -- WPM

Ready
Exercise Algorithm Area
1PROGRAM Main
2
3VAR
4searchArray : ARRAY[1..5] OF INT;
5targetValue : INT;
6foundIndex : INT;
7END_VAR
8
9// Initialize array and target
10searchArray[1] := 10;
11searchArray[2] := 25;
12searchArray[3] := 5;
13searchArray[4] := 30;
14searchArray[5] := 15;
15targetValue := 5;
16
17// Find the index of the target value
18foundIndex := FindElementIndex(searchArray, targetValue);
19
20END_PROGRAM
21
22
23// Function to find the index of a specific element in an array
24FUNCTION FindElementIndex : INT
25VAR_INPUT
26dataArray : ARRAY[1..5] OF INT;
27elementToFind : INT;
28END_VAR
29VAR
30i : INT;
31END_VAR
32
33// Iterate through the array to find the element
34FOR i := 1 TO 5 DO
35IF dataArray[i] = elementToFind THEN
36RETURN i; // Return the index if found
37END_IF
38END_FOR
39
40// Return -1 if the element is not found
41RETURN -1;
42
43END_FUNCTION
Algorithm description viewbox

PLC Structured Text: Basic Array Element Search

Algorithm description:

This program searches for a specific integer element within a predefined integer array. It returns the index of the first occurrence of the element if found, otherwise, it returns -1. This is a fundamental operation used in many data processing tasks within industrial automation, such as locating a specific sensor reading or configuration parameter.

Algorithm explanation:

The `FindElementIndex` function performs a linear search on a fixed-size integer array. It iterates through each element of the array from the first to the last. If the current element matches the `elementToFind`, the function immediately returns the current index `i`. If the loop completes without finding a match, it means the element is not present in the array, and the function returns -1 as an indicator. The time complexity is O(n) in the worst case, where n is the size of the array (5 in this case), as it might need to check every element. The space complexity is O(1) as it uses a constant amount of extra space for the loop counter. The correctness is guaranteed by checking every element and returning the first match or a designated 'not found' value.

Pseudocode:

FUNCTION FindElementIndex(array, element):
  FOR i from 1 to array_size:
    IF array[i] equals element:
      RETURN i
  
  RETURN -1 // Element not found
END FUNCTION