Time limit exceeded

I've just started learning to code as a hobby and when I am already stuck. I'm trying to write a simple program that prints the numbers 5-1 using the "while" loop. Whenever I put this into the compiler it says "Time limit exceeded." Is there some obvious problem that I am missing or does this tiny program really take too long?

Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main(){
  int x = 5;

  while(x>0){
    cout << "number: " << x << endl;
    x=x++;
  }
return 0;
}
Line 9 x=x++; gives you an undefined result because x is modified twice in this expression. Even if this code was well-defined it would not work because x++ increments x but returns the value of x before it was incremented so x would be assigned the old value of x (meaning x would not change).

To increment the value of x you just need to write x++; (or ++x;).

After a closer look I think you might want to decrement the value of x. In that case you can use -- instead of ++.
Last edited on
So you are increasing value of x and because of that x is always positive (> 0) and that loop is infinite.
You have to write x--, or x = x - 1 instead.
Last edited on
Topic archived. No new replies allowed.