< Prev
Next >



While Loop in C++





C++ provides another decision making looping structure known as while loop, in which the condition of while loop is tested for the boolean value - true or false.






while loop example


// C++ while loop example

#include<iostream>

using namespace std;
int main() // main method starts
{

int i=0;

while(i<3)
{
	cout<<"i = " << i <<"\n";
	i++;
}

return 0;
}   // main method ends and program ends too 


Output


i = 0
i = 1
i = 2





While loop must have an iteration part in its body or it ends an endless loop


// Endless while loop 

#include<iostream>

using namespace std;
int main() // main method starts
{

int i=0;

while(i<3)
{
	cout<<"i = "<< i <<"\n";
}

return 0;
}  /*main method and program ends here */


Output


This program when executed, runs indefinitely in a loop because of the absence of incremental part to increment the value of i.



Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter




< Prev
Next >
< Do-While Loop
Break Statement >
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
Python

Ad2