Nested While and If Loops

13 views (last 30 days)
MiauMiau
MiauMiau on 1 May 2015
Answered: Jan on 1 May 2015
Hi
The code I wrote is supposed to do the following for a given array containing numbers:
- Prompt the user to enter a number, compare it to array(1). If they do not match, increase a given initialspeed - If they do match, prompt the user for the next number: If it does not match array(2) - increase initialspeed. If they do match - prompt the user for the third input - if it does match array(3), now decrease initialSpeed. If they do not match, again increase.
I have coded it as follows, however would like to know if there is a more efficient way to code it? Also, it seems that I get prompted for an input even when the length of the initial array is exceeded - why is that?
initialspeed = 300;
sequenceArray = [12345,54321,12435,51234,42315] % compare the input to this array
k = 1 % loop variable
sequence = zeros(1,length(sequenceArray)) % store the input here
while k < length(sequenceArray)+1
prompt = 'Type in participants answer:';
sequence(k) = input(prompt);
if sequence(k) ~= sequenceArray(k)
initialspeed = initialspeed + 50;
disp(initialspeed)
k = k+1;
else
k = k+1;
prompt = 'Type in participants answer:';
sequence(k) = input(prompt);
if sequence(k) ~= sequenceArray(k)
initialspeed = initialspeed + 50;
disp(initialspeed)
k = k+1;
else
k = k+1;
prompt = 'Type in participants answer:';
sequence(k) = input(prompt);
if sequence(k) ~= sequenceArray(k)
initialspeed = initialspeed + 50;
disp(initialspeed)
k = k+1;
else
initialspeed = initialspeed - 40;
disp(initialspeed)
k = k+1;
end
end
end
end

Answers (1)

Jan
Jan on 1 May 2015
Some code indentation and moving common code outside the IF branches:
initialspeed = 300;
sequenceArray = [12345,54321,12435,51234,42315]; % compare the input to this array
k = 1; % loop variable
sequence = zeros(1,length(sequenceArray)); % store the input here
prompt = 'Type in participants answer:';
while k < length(sequenceArray)+1
sequence(k) = input(prompt);
if sequence(k) ~= sequenceArray(k)
initialspeed = initialspeed + 50;
else
k = k+1;
sequence(k) = input(prompt);
if sequence(k) ~= sequenceArray(k)
initialspeed = initialspeed + 50;
else
k = k+1;
sequence(k) = input(prompt);
if sequence(k) ~= sequenceArray(k)
initialspeed = initialspeed + 50;
else
initialspeed = initialspeed - 40;
end
end
end
disp(initialspeed)
k = k+1;
end
You are prompted for further inputs even if the length is actually reached, because there are up to 3 input commands inside the loop.
The intention of the code is hard to recognize. I boldly guess, that you want something else, most of all because you are surprised, when the prompts appear more often than you expect.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!