# MATLAB/Cookbook/for and while loops

For & While Loops

%Loops are meant for running an operation or program a multiple times to be effectively useful.

```%for loop - runs for a specified period of cycles

num = input('how many times do you want this to run?')
%{variable 'num' is given a value by user input}

for k = 1:num
%k is a variable that allows loop to work, allows program to cycle what the programmer wants (2,3,4.... times)}

y(k) = 3*k + sqrt(k + 5)
%loop runs # times and # indexes & helps compute 'y'}{sqrt = square root}

end %'end' terminates the loop and stops execution}

%Each time the loop runs through the program, y(1) is computed, y(2) is computed......'k' is % given a new value each time a new loop starts

%while loop - runs until a specific condition is met

x = 0;           %x needs to have an established starting value for a 'loop counter' to see how %many times it runs}
y = 0;           %y needs to have an established starting value}
while y < 100    %conditional statement stating while 'y' is less than 100, keep running the program,
%once it equals/greater than 100-program stops
x = x + 1       %'x' serves as a 'loop counter'}
y = 2*x + 5     %simple math to get 'y' to desired condition}
end             %end' terminates the loop and stops execution}
```