My program is going in infinite loop and does not print required output please help anyone
Asked
Active
Viewed 310 times
-4

Remy Lebeau
- 555,201
- 31
- 458
- 770

Apoorva Sunkad
- 3
- 2
-
Please add code and data as text ([using code formatting](//stackoverflow.com/editing-help#code)), not images. Images: A) don't allow us to copy-&-paste the code/errors/data for testing; B) don't permit searching based on the code/error/data contents; and [many more reasons](//meta.stackoverflow.com/a/285557). Images should only be used, in addition to text in code format, if having the image adds something significant that is not conveyed by just the text code/error/data. – Suraj Rao Nov 21 '21 at 06:30
-
Little hint for you: `while(space)` – justANewb stands with Ukraine Nov 21 '21 at 06:38
-
that is why they invented a skill named debugging, what is wrong with copy/paste text – rioV8 Nov 21 '21 at 07:29
2 Answers
1
On the 2nd and subsequent iterations of the outer while
loop, space
will be initialized with a non-zero value, and then the while(space)
loop will keep incrementing space
for a long time until it overflows to a negative value, and then keep looping for a long time further until space
eventually increments to 0, finally breaking the loop. When an int
is evaluated as a boolean, only 0 evaluates as false, all other values evaluate as true. And a 32bit int
can hold 4294967296 unique values (-2147483648..2147483647), giving the illusion that your loop is infinite.

Remy Lebeau
- 555,201
- 31
- 458
- 770
1
while(space)
{
std::cout << ' ';
space = space + 1;
}
When space
is 1
, this loop will increment i
, so it keeps looping. It will loop until space
overflow, and increment until space
is 0
You probably want:
while(space)
{
std::cout << ' ';
--space;
}

justANewb stands with Ukraine
- 4,535
- 3
- 14
- 39