0

Executing this command is getting me an infinite loop also in the while condition I wrote i=30 instead of i<=30 wanna know what does i=30 does to my code:

#include <iostream>
using namespace std;
int main()
{
  
  int i=30;//initialization
  
  while (i =30)
  {
      cout<< i<< ' '; 
      i=i+1;
  } 
 
    
} 
Yu Hao
  • 119,891
  • 44
  • 235
  • 294

1 Answers1

0

while (i = 30) assigns the value 30 to the variable i, and then uses the resulting i as a condition. Since i is non-zero, it is considered true, and the loops runs forever.

As such, the cout will always print 30 and the increment of i will be undone at every iteration.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
  • also whatever value i assign to while initializing it runs infinite loop of 30 only what can be the reason..? – Tejas Aditya Oct 03 '21 at 21:03
  • @TejasAditya like Jeffrey said, `while (i = 30)` is assigning 30 to `i`, so it doesn't matter what initial value you set `i` to, it is being overwritten on every iteration. You need to use `==` (equality comparison), not `=` (assignment), eg: `while (i == 30)` – Remy Lebeau Oct 03 '21 at 21:14