Vous êtes sur la page 1sur 9

What Is a Nested Loop?

1. Now that we have seen for and while loops, we are ready to introduce a slightly more advanced
topic – nested loops. Nested loops are instances when you have one loop inside of another loop.
For example, this program uses nested for loops to simulate an odometer for a vehicle.

main()
{
int ones = 0; // Initialize variables
int tens = 0; // For an odometer
int km = 0;

for (tens=0 ; tens<10 ; tens=tens+1) // Outer loop counts tens of km


{
for (ones=0 ; ones<10 ; ones=ones+1) // Inner loop counts km
{
km = 10*tens + ones; // Total number of km traveled
}
}

while(1); // Stop here when you get to 99 km

2. The program begins by creating and initializing three variables. km will contain the total number
of kilometers traveled. The ones and tens variables hold the place values for the total number
of kilometers traveled.

For example, if 37 kilometers have been traveled:

km = 37
tens = 3
ones = 7

3. Next, we have the nested loops. The outermost loop counts the “tens” of kilometers that have
been traveled. Therefore, it is initially 0.

4. Inside of the “tens” loop, the innermost loop counts the “ones” of kilometers that have been
traveled. It also is initialized to 0.

Copyright © 2012-2015 Page 1 of 9


Valparaiso University
5. When the program first begins, it gets to the outer loop and tens=0.

The program then goes into the inner loop and the number of kilometers starts to increase by one
each time through the inner loop.

As you would expect from an odometer, the “tens” value remains 0 while the “ones” is
counting up from 0 to 9.

6. However, after ones=9 and km is also updated to 9, the program again returns to the top of the
inner for loop.

The loop then increments the value of ones, and ones=10.

However, odometers don’t want the ones place to be equal to 10, therefore, the inner for loop
fails the condition test because ones is not less than 10.

for (ones=0 ; ones<10 ; ones=ones+1) // Inner loop counts km


{
km = 10*tens + ones; // Total number of km traveled
}

7. At that point, the first iteration of the outer for loop is complete. Tens is incremented from 0 to
1. Now, since tens < 10, the program proceeds re-run the inner for loop again.

for (tens=0 ; tens<10 ; tens=tens+1) // Outer loop counts tens of km


{

8. Now, if you are like most people, this is starting to sound a little confusing. Don’t worry, though.
We can run the program in the CCS Debugger and watch as it executes line-by-line.

9. Create a new CCS project by selecting New / CCS Project from the File menu.

Copyright © 2012-2015 Page 2 of 9


Valparaiso University
10. In the New CCS Project window, create a project called Loops_Nested.

Specify the MSP430FRxxx Family and the MSP430FR6989 microcontroller.

Also, make sure you select Empty Project (with main.c) from the
Project templates and examples pane before clicking Finish.

11. Copy the program from above and paste it into the main.c file in the CCS Editor.

12. Save your program, but DO NOT Build it yet.

13. In the Project Explorer pane, right click on your project name and select Properties from
the pop-up menu.

In the Properties window, select Optimization under Build / MSP430 Compiler and
make sure that the Optimization level is set to off.

14. Build your project. If you have any errors, make sure you did not accidentally modify your
program.

Copyright © 2012-2015 Page 3 of 9


Valparaiso University
15. After successfully Building your project, launch the CCS Debugger.

16. When it is ready, your screen should look something like this. You should see both x and y in the
Variables pane, although their values may be different.

If x and y are not shown in base 10, right click on their Value column and
select Number Format / Decimal.

17. Click the Step Into button and execute the program line-by-line.

Take care to watch how the program runs primarily inside the inner most loop except for when
the ones variable overflows and we need in increment the tens value.

Copyright © 2012-2015 Page 4 of 9


Valparaiso University
18. Remember to be patient, you cannot click too quickly. However, take the time to Step Into the
program until km is 25.

19. Ok, that was a lot of clicking. Sometimes, we want to see how loops (especially larger loops and
nested loops) run, especially at their “end points” when the loop is about to end.

CCS allows us to edit the values in the variables to fast-forward through the program iteration.

Double-click the value of the tens variable. This will highlight the value.

Copyright © 2012-2015 Page 5 of 9


Valparaiso University
20. You can now type in a new value. For now, enter a value of 9 for tens and press the enter key.

21. Notice that nothing else has changed. km is still equal to 25, and the same instruction is
highlighted to be performed next.

22. Now, you can continue to click the Step Into button. As you go, you will see that the value in
km is updated fairly quickly.

Copyright © 2012-2015 Page 6 of 9


Valparaiso University
23. As you continue clicking Step Into, you will momentarily see the program return to the outer
loop when km=99.

24. When you click the Step Into button again, two things will happen. First, the outer for loop
will update the tens value by incrementing it to 10. Second, because tens is no longer less than
10, the condition test will fail, and the program will move on to the next instruction,
while(1);.

Copyright © 2012-2015 Page 7 of 9


Valparaiso University
25. If you want to try this again, click the Soft Reset button. Also, at any time, you can edit the
values in the variables to jump quicker through uninteresting parts of the loop.

26. Looking for a challenge? Try modifying the program to also use hundreds, thousands, and
tenthousands variables to allow the odometer to count up to 99999.

Looking for a little more of a challenge?

Make it so that when the odometer rolls over from 99999, it starts over at 00000 and begins
counting again.

Copyright © 2012-2015 Page 8 of 9


Valparaiso University
All tutorials and software examples included herewith are intended solely for
educational purposes. The material is provided in an “as is” condition. Any
express or implied warranties, including, but not limited to the implied warranties
of merchantability and fitness for particular purposes are disclaimed.

The software examples are self-contained low-level programs that typically


demonstrate a single peripheral function or device feature in a highly concise
manner. Therefore, the code may rely on the device's power-on default register
values and settings such as the clock configuration and care must be taken when
combining code from several examples to avoid potential side effects.
Additionally, the tutorials and software examples should not be considered for use
in life support devices or systems or mission critical devices or systems.

In no event shall the owner or contributors to the tutorials and software be liable
for any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services; loss of
use, data, or profits; or business interruption) however caused and on any theory
of liability, whether in contract, strict liability, or tort (including negligence or
otherwise) arising in any way out of the use of this software, even if advised of
the possibility of such damage.

Copyright © 2012-2015 Page 9 of 9


Valparaiso University

Vous aimerez peut-être aussi