I am looking for help with tracing through a program (not certain the terminology to use there...) to help me understand nested for loops. Below is a sample program with results from my textbook, and some of my failed trace attempts.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include<iostream>
using namespace std;
int main()
{
int lastNum;
int numToPrint;
for (lastNum = 1; lastNum <= 7; lastNum++)
{
for (numToPrint = 1; numToPrint <= lastNum; numToPrint++)
cout << numToPrint;
cout << endl;
}
return 0;
}
|
Result:
1
12
123
1234
12345
123456
1234567
Trace Attempt 1:
lastNum starts as 1
lastNum(1) meets condition of <= 7
Enter nested loop
numToPrint starts as 1
numToPrint(1) meets condition of <= lastNum(1)
Print numToPrint(1)
Linefeed
numToPrint is incremented to 2.
lastNum is incremented to 2
lastNum(2) meets condition of <=7
Enter nested loop.
numToPrint(2) meets condition of <= lastNum(2)
Print numToPrint(2)
Linefeed
Trace Attempt 2:
lastNum starts as 1
lastNum(1) meets condition of <= 7
Enter nested loop
numToPrint starts as 1
numToPrint(1) meets condition of <= lastNum(1)
Print numToPrint(1)
Linefeed
numToPrint is incremented to 2.
numToPrint(2) does not meet condition <= lastNum(1)
Do not print numToPrint
Do not print linefeed
lastNum is incremented to 2
...and now I'm just back to the first trace attempt.
Trace Attempt 3:
lastNum starts as 1
lastNum(1) meets condition of <= 7
Enter nested loop
numToPrint starts as 1
numToPrint(1) meets condition of <= lastNum(1)
Print numToPrint(1)
linefeed
increment numToPrint(2)
increment lastNum(2)
numToPrint(2) meets condition of <= lastNum(2)
print numToPrint(2)
linefeed
I know I'm doing something wrong with tracing through the loop, but I can't figure out my misstep. I appreciate the help. Thank you!