How to generate numbers until they are bigger than 10 000

Viewed 129
    #include <iostream>

using namespace std;

int main()
{
    int num=1;
    while(num<10000)
    {
        num=num*3;
        cout<<num<<",";
    }
}

The last output is 19683, but it should be 6561. How should I change the condition?

4 Answers

With num being 6561, condition num < 10000 is still fulfilled and so the loop is entered once more.

Write...

int num=1;
do 
{
    cout<<num<<",";
    num=num*3;
}
while(num<10000);

such that the loop is left once num exceeds 10000, and cout will not be executed any more for such a value. Note that cout and num*=3 have been switched, so this loop also prints 1 (in contrast to yours). But I think it should print 1 as well, so that's why I dared to slightly change the semantics :-). Otherwise, you'd have to init num like int num = 3.

Using do-while block:

#include <iostream>

int main() {
  int num = 1;
  do {
    std::cout << num << " ";
  } while ((num *= 3) < 10000);
  return 0;
}

It will prints:

1 3 9 27 81 243 729 2187 6561

Live.

Make use of the fact that you can use the result of an assignment:

#include <iostream>

int main()
{
    int num = 1;
    while((num *= 3) < 10000)
    {
        std::cout << num << '\n';
    }
}

Prints:

3
9
27
81
243
729
2187
6561

Put cout before multiplication , program will first show a number which is less than 10000 and then multiplies num by 3.Thus 6561 will be shown and 6561*3>10000 so it exits the loop without printing 19683.

Related