Question
For loops are a good structure to count things or to do something TO each element in an array. In this case we will use
For loops are a good structure to count things or to do something TO each element in an array. In this case we will use a for loop to give feedback to a user who is waiting for an event to occur. You will create a program that counts down from 10 and ends with "blast off!"
Start:
Open a new script and put the comment header at the top.
Counting down:
You want to create a series of numbers that goes from 10 to 1 in steps of -1. A sequence in MATLAB can be specified by starting number : step : final number. So if you wanted to go from 1 to 20 by steps of 2 you would use 1:2:20
Think about how that would look to start at 10 and count down.
Make a for loop:
A for loop will automatically increment the variable assigned to it (the index variable) every time it goes through the loop, until it runs out of numbers to index to. Therefore you need to tell the loop where to start, where to stop and how to step between the two. An example would be:
for x=1:10
This will run through the loop 10 times, and each time it does x will have the value of the next number in the sequence. The first time through the loop x will have the value of 1, and the next time it will have the value of 2 and so on.
At the end of the for loop, just like the while loop, is the "end" statement. This limits what the loop does each time. It won't get to anything after the "end" statement until the loop has executed its set number of times.
In between the "for" and the "end" is what you want the program to DO. In this case you want it to count down. If you have set up your increment well, then your indexing variable (your "x") will have that value. You can use the disp() command to print out its value.
Run your program
If you have done everything right so far, when you run your program you should see it give the following on the command line:
10
9
8
.... and on until it reaches 1 and then it will stop.
Timing:
Currently the numbers count down as fast as the computer can run the code. To make it a real countdown, add a pauseof 1 second inside the loop, after printing the number. Now when you run the program it should print the same thing as before, but with a one-second delay after every number.
Type "doc pause" in the command window for more information on the pause() function.
Add the "blast off"
After the end statement use the disp() command to add the phase "blast off". Now when you run your program it should count down from 10 to 1 and end with "blast off".
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started