Please explain each line of this code: This is the answer to the code, please ex
ID: 3833238 • Letter: P
Question
Please explain each line of this code:
This is the answer to the code, please explain each line of this code :
% the function that takes a word and
% a letter as input and returns the position
% of that letter in that word
function [x] = find_letter_positions(word,letter,case_sensitive)
x=[];
i=1;
j=1;
opt=false;
if nargin == 3
if(case_sensitive==true)
opt = true;
end
end
for l = word
if(opt==true)
if(l==letter)
x(j)=i;
j=j+1;
end
else
if(lower(l)==lower(letter))
x(j)=i;
j=j+1;
end
end
i=i+1;
end % end of loop
end % end of function
main
% the function that takes a word and
% a letter as input and returns the position
% of that letter in that word
find_letter_positions('bEtween','e',true)
find_letter_positions('bEtween','e',false)
Explanation / Answer
Answer:
function [x] = find_letter_positions(word,letter,case_sensitive)
x=[];
i=1; % initialization of i value to 1
j=1; % initialization of j value to 1
opt=false; % if case_sensitive is false then opt is set to false
if nargin == 3 % if nargin is equal to 3
if(case_sensitive==true) if case_sensitive is equal to true
opt = true; % if case_sensitive is true and nargin is equal to 3 then opt is set to true
end
end
for l = word % for a letter l in word
if(opt==true) % if option is true
if(l==letter) % if l is letter
x(j)=i; % then i is stored in x(j)
j=j+1; % j is incremented by one to iterate through the for loop
end
else % if case_sensitive is false then
if(lower(l)==lower(letter)) % then convert the letter and the current letter in the word to be checked into lower case % and then check
x(j)=i; % i is stored in x(j)
j=j+1; % j is incremented by one to iterate through out the loop
end
end
i=i+1; and then i is incremented by 1
end % end of loop
end % end of function
main
% the function that takes a word and
% a letter as input and returns the position
% of that letter in that word
find_letter_positions('bEtween','e',true) % invoking the function by giving required arguments in the function
find_letter_positions('bEtween','e',false) % invoking the function by giving required arguments in the function