Basic Loop Question.

Jun 30, 2011 at 9:10pm
Heya, guys. So I took a giant step back and decided to re-do the fundamentals of loops. I started with the While Loop. I made a successful code that asks the user to input two numbers, a Maximum number and a starting number.

Max = 50

Start = 1

The loop will add 1 each time until it reaches 50. :)

Now, what I want to do, is make it so that the starting number multiplies itself until it reaches the maximum number, but I have one small problem.

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main()
{
    int maxNumber;
    int startNumber;

    cout << "Hello, there!  Choose a maximum number for this loop, please." << endl;
    cin  >> maxNumber;

    cout << "Now, enter the starting number of the loop." << endl;
    cin  >> startNumber;

        while (startNumber != maxNumber){
            cout << startNumber * startNumber << endl;
            startNumber ++;
        }

    return 0;
}


So, I put 50 as the max number, and 2 as the starting number.

The output is this:

1
2
3
4
5
6
7
8
9
10
11
12
2
4
9
16
25
36
...
...
...
2209
2304
2401


Why is this? Thanks for the help.
Jun 30, 2011 at 9:33pm
Perhaps because startNumber never exactly equals maxNumber, so the loop never terminates? Try using greater than or less than instead of simple equality.
Jun 30, 2011 at 9:33pm
Right! I just thought of that. Okay, give me a couple of minutes. Haha, it just hit me! :P
Topic archived. No new replies allowed.