Prerequisite: while loop in C/C++
In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The boolean condition is either true or false.
while(1)
It is an infinite loop which will run till a break statement is issued explicitly. Interestingly not while(1) but any integer which is non-zero will give a similar effect as while(1). Therefore, while(1), while(2) or while(-255), all will give infinite loop only.
We write conditions in brackets(). Condition can either resolve to true or false. So 0 represents false and any value except it is true.
so logically:
while(true) ==while(1)==while(any value representing true);
while(false)==while(0);
while(1) or while(any non-zero integer)
{
// loop runs infinitely
}
A simple usage of while(1) can be in the Client-Server program. In the program, the server runs in an infinite while loop to receive the packets sent from the clients.
But practically, it is not advisable to use while(1) in real-world because it increases the CPU usage and also blocks the code i.e one cannot come out from the while(1) until the program is closed manually. while(1) can be used at a place where condition needs to be true always.
C
#include <stdio.h>
int main()
{
int i = 0;
while (1) {
printf ( "%d\n" , ++i);
if (i == 5)
break ;
}
return 0;
}
|
C++
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (1) {
cout << ++i << "\n" ;
if (i == 5)
break ;
}
return 0;
}
|
while(0)
It is opposite of while(1). It means condition will always be false and thus code in while will never get executed.
while(0)
{
// loop does not run
}
C
#include<stdio.h>
int main()
{
int i = 0, flag=0;
while ( 0 )
{
printf ( "%d\n" , ++i );
flag++;
if (i == 5)
break ;
}
if (flag==0)
printf ( "Didn't execute the loop!" );
return 0;
}
|
C++
#include <iostream>
using namespace std;
int main() {
int i = 0, flag=0;
while ( 0 )
{
cout << ++i << "\n" ;
flag++;
if (i == 5)
break ;
}
if (flag==0)
cout << "Didn't execute the loop!" ;
return 0;
}
|
Output
Didn't execute the loop!
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Nov, 2022
Like Article
Save Article