PLC Structured Text: Basic Array Element Search
PROGRAM Main VAR searchArray : ARRAY[1..5] OF INT; targetValue : INT; foundIndex : INT; END_VAR // Initialize array and target searchArray[1] := 10; searchArray[2] := 25; searchArray[3] := 5; searchArray[4] := 30; searchArray[5] := 15; targetValue := 5; // Find the index of the t...
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...
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.
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