Flowchart of while Loop
Example: CPP Program to Demonstrate while Loop
C
// C program to demonstrate while loop #include <stdio.h> int main() { // loop variable definition int i = 5; // while loop that prints "GFG" 5 times while (i < 10) { printf ( "GFG\n" ); i++; } return 0; } |
C++
// C++ program to demonstrate // while loop #include <iostream> using namespace std; int main() { // Initialize variable 'i' with a value of 5 int i = 5; // Execute the loop as long as 'i' is less than 10 while (i < 10) { // Increment 'i' by 1 on each iteration i++; // Print "GFG" on each iteration cout << "GFG\n" ; } return 0; } |
Java
import java.io.*; class GFG { public static void main(String[] args) { int i = 5 ; while (i < 10 ) { i++; System.out.println( "GfG" ); } } } |
Output
GFG GFG GFG GFG GFG
Looping Infinite Times
C
// C program to domonstrate // infinite while loop #include <stdio.h> int main() { // Condition is always true which results in infinite // loop while (1) printf ( "GFG\n" ); return 0; } |
C++
// C++ program to domonstrate // infinite while loop #include <iostream> using namespace std; int main() { // Condition is always true which results in infinite // loop while (1) cout << "GFG\n" ; return 0; } |
Java
// C++ program to domonstrate // infinite while loop import java.io.*; class GFG { public static void main(String[] args) { // loop variable int i = 5 ; // while loop while (i < 10 ) { System.out.println( "GFG\n" ); } } } |
Output
GFG GFG GFG ... ... ... {truncated}
Difference between for and while loop in C, C++, Java
In C, C++, and Java, both for loop and while loop is used to repetitively execute a set of statements a specific number of times. However, there are differences in their declaration and control flow. Let’s understand the basic differences between a for loop and a while loop.