Okay, let's first take the original source code and analyze it.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
using namespace std;
int main() {
int i = 1, n;
// Get number from the keyboard and initialize i.
cout << "Enter a number and press ENTER: ";
cin >> n;
while (i <= n) { // While i less than or equal n,
cout << i << " "; // Print i,
i = i + 1; // Add 1 to i.
}
return 0;
}
|
First of all, what does this code do?
Enter a number and press ENTER: 4
1 2 3 4 |
Enter a number and press ENTER: 7
1 2 3 4 5 6 7 |
It allows the user to input a number, then counts to that number, starting with 1. Pretty simple.
And how does it do this? It initializes the variable
i to 1, and then uses the following loop:
1 2 3
|
while (i <= n) { // While i less than or equal n,
cout << i << " "; // Print i,
i = i + 1; // Add 1 to i.
|
to count from
i (1) to
n. Since
i starts out at 1, we print out every number from 1 to
n, stopping when
i is greater than
n.
So the program counts from 1 to n. We want it to count from n1 to n2.
In the original program, we set
i to 1 and continued through the loop until it was bigger than
n. But what if we set
i equal to
n1, and continued through the loop until it's bigger than
n2? In that case, our loop would start at
n1, and then continue through
n2. Perfect!
I'd imagine it'd look like this (comments mine):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
using namespace std;
int main() {
int i; //variable to count through loop
int n1, n2; //two numbers the user will enter
//Get the first (assumed to be smaller) number
cout << "Enter a number: ";
cin >> n1;
//Get the second (assumed to be bigger) number
cout << "Enter a BIGGER number: ";
cin >> n2;
//Here's the magic - set i equal to n1, so we
// start counting at n1!
i = n1;
while (i <= n2) { // While i less than or equal n2
cout << i << " "; // Print i,
i = i + 1; // Add 1 to i.
}
return 0;
system("PAUSE");
}
|
And the output:
Enter a number: 3
Enter a BIGGER number: 8
3 4 5 6 7 8 |
I hope this was clear. Please let me know if you don't understand in any way.