0

For the following c++ program :

#include<iostream>
using namespace std;
int main()
{
    int i=1;
    while(i<=10)
    {
        if(i==5)
         continue;

       cout<<endl<<i;
       i++;
    }
    return 0;

}

The outputs given by codeblock and online compilers vis. https://www.programiz.com/cpp-programming/online-compiler/ and https://www.onlinegdb.com/online_c++_compiler is different.

The output given by the codeblocks :

1
2
3
4

The outputs by the online compilers :

1
2
3

According to me the output given by the codeblock should be correct . Hence, I am unable to understand why the two online compilers are not giving 4 as an output. Is it because of the while loop running infinite times ?

mch
  • 9,424
  • 2
  • 28
  • 42
  • 3
    Once `i` reaches 5, your loop gets stuck in an infinite cycle. You are seeing minor differences in output stream buffering, I guess. Try putting the `i` *before* the `endl` in the `cout` statement. Basically, there is no call to `endl` after the `4` is sent to the stream. – Adrian Mole Dec 27 '22 at 09:05
  • Yes, it's because of the infinite while loop. – john Dec 27 '22 at 09:10
  • 3
    The program has Undefined behaviour as when `i` reaches 5 it is in a [Infinite loop without side-effects](https://en.cppreference.com/w/cpp/language/ub#Infinite_loop_without_side-effects) – Richard Critten Dec 27 '22 at 09:10
  • `std::cout<<"\n"<< i << std::flush;` may be what you are looking for. More info in the doc: https://en.cppreference.com/w/cpp/io/manip/endl – pepece Dec 27 '22 at 09:21

0 Answers0