%% While loops

%Previous lecture: For Loops
%Runs for a specified number of iterations, which is equal to the length of
%the vector that is iterated over

%For loop syntax
for i=1:10
  %statements that execute at each iteration
  disp(i)
end


%While loops:
%Execute the statements in the body until the boolean
%expression evaluates to false

%Saw an example of this in homework 3, where the user was prompted
%until they chose the quit option


%While loop syntax:
%while boolean_expression
% statements that execute repeatedly when the boolean_expression is true
%end

%If statements: check boolean expression and execute statements if it is
%true
%while loops: check boolean expression at every iteration and execute
%statements every time it is true

%Basic execution of a while loop:
%1. Evaluate boolean expression
%2. If boolean is true, execute the statements in the body
%3. After executing the statements, evaluate the boolean expression
%4. If the boolean is still true, execute the statements in the body again
%5. Repeat this process until the boolean expression evaluates to false
%6. If the boolean expression is false, the statements in the body of the
%while loop are not executed, and control continues after the end statement



%While loop example: Roll a die until 3 10's have been seen
%and display the number of rolls required to see 3 10's.
numthrees = 0;
numrolls = 0;
while numthrees < 10
  %randi(6) generates a random integer between 1 and 6
  roll = randi(6);
  numrolls = numrolls + 1;
  if roll == 3
    numthrees = numthrees + 1;
  end
end
disp(numrolls)


%Warning: while loop will run until boolean_expression is false. If
%boolean_expression is never false, the loop executes forever. Known as an
%infinite loop. If you get stuck in an infite loop, ctrl+C in MATLAB (this
%kills code execution)
%Simple infinite loop example:
%x = 0;
%while x >=0
% x = x + 1;
% disp(x);
%end

% for vs while vs if
%Body of for executes once for each item in its control vector

%Body of while executes repeatedly while boolean_expression is true

%Body of if statement executes once if boolean_expression is true

for x = 5 : 10
    disp(x)
end
disp(x)


x = 5;
while x <= 10
    disp(x)
    x = x + 1;
end
disp(x)


x = 5;
if x <= 10
    disp(x)
    x = x + 1;
end
disp(x)


