While loop and arrays

2 views (last 30 days)
Tuna KISAAGA
Tuna KISAAGA on 23 Apr 2021
Commented: DGM on 23 Apr 2021
I wanted to create a loop and store the values of "secsum" until the value of it is equal to "firstsum" or 7. But it doesn't work :( What do you think is wrong with it?
firstsum = floor(rand*6+1) + floor(rand*6+1);
j=1;
while j>=1
secsum(j) = floor(rand*6+1) + floor(rand*6+1);
if (secsum(j)==firstsum)
fprintf('You WIN with the sequence: %.0f %.0f',firstsum,secsum);
j=0;
elseif (secsum(j)==7)
fprintf('You LOSE with the sequence: %.0f %.0f',firstsum,secsum);
j=0;
else
j=j+1;
end
end
  1 Comment
DGM
DGM on 23 Apr 2021
secsum is a vector, so either exit condition will produce multiple lines. If you only want to print the last result of secsum, just do
fprintf('You WIN with the sequence: %.0f %.0f\n',firstsum,secsum(j));
If you want to print the whole secsum vector, you can try using mat2str or some other method to get it into the output string.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!