# loop problem with time delay

8 views (last 30 days)
Hayden O'Neil on 5 Oct 2017
Answered: DUY Nguyen on 2 Mar 2023
Write Matlab code using a loop structure that displays the following text to the command window: “Man, I am getting older and wiser by the second” And (after a carriage return) on the following line displays the phrase: “and now I am 1 second older”
And after waiting a full second in real time (approximate) increments and displays the phrase: “and now I am 2 seconds older” [Note that I want you to update the units on “second” to show correct number –second(s) ]
And after waiting a full second in real time (approximate) increments and displays the phrase: “and now I am 3 seconds older”
And so on and so on until 10 full carriage returns of textual display have been reached and the final line reads: “and Prof. Koz just wasted approximately blank seconds of my life”
I have no idea how to do this problem or delay output by one second for each line.

James Tursa on 6 Oct 2017
Edited: James Tursa on 6 Oct 2017
Hint: You could use tic and toc for this. Start your code with a tic statement. Then you can examine the toc result in a loop and take appropriate action (display a message, break out of the loop, etc). The toc result will be in seconds. E.g., experiment with the following code and see if you can modify it to do what you want.
time_delay = 5;
tic
while( true )
if( toc >= time_delay )
fprintf('It has been %f seconds\n',time_delay);
break;
end
end
Alternatively, you could look into using the pause() function, maybe with a for loop or something similar.

DUY Nguyen on 2 Mar 2023
Hi Hayden,
for i = 1:10
if (i==1)
fprintf('Man, I am getting older and wiser by the second\n');
fprintf('and now I am 1 second older\n', i);
else
fprintf('and now I am %d seconds older\n', i);
end
pause(1);
end
fprintf('and Prof. Koz just wasted approximately %d seconds of my life\n', i);