Doubt in Life, the Universe, and Everything

Hello, I am new to programming. Please help me with what is wrong with my code.

#include <iostream>
using namespace std;

int main() {
	int x;
	//while(cin>>x)
	while(true)
	{
	    cin>>x;
	    if(x!=42)
	    cout<<x<<endl;
	    else
	    break;
	}
	return 0;
}

I am getting the message time limit exceeded. But the following code is work.

#include <iostream>
using namespace std;

int main() {
	int x;
	while(cin>>x)
	//while(true)
	{
	    //cin>>x;
	    if(x!=42)
	    cout<<x<<endl;
	    else
	    break;
	}
	return 0;
}

What is the difference in using while(1) and while(cin>>x)?

Thanks in advance!

while(1) in an infinte loop wheather u will give input or not that will run continiously on the other hand while(cin>>x) is alternative of EOF in cpp means this will run untill u are giving inputs.

1 Like

Thank you.

I assumed that 42 would definitely come in the sequence. I understand that the program won’t end if 42 is not given in the sequence.