Difference between for and while loop in C, C++, Java
for loop:
for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. Syntax:
for (initialization condition; testing condition; increment/decrement) { statement(s) }
C
#include <stdio.h> int main() { int i = 0; for (i = 5; i < 10; i++) { printf ( "GFG\n" ); } return 0; } |
C++
#include <iostream> using namespace std; int main() { int i = 0; for (i = 5; i < 10; i++) { cout << "GFG\n" ; } return 0; } |
Java
import java.io.*; class GFG { public static void main(String[] args) { int i = 0 ; for (i = 5 ; i < 10 ; i++) { System.out.println( "GfG" ); } } } |
Output:
GFG GFG GFG GFG GFG
Looping Infinite times:
C++
#include <iostream> using namespace std; int main() { for ( ; ; ) cout << "GFG\n" ; return 0; } |
C
#include <stdio.h> int main() { for ( ; ; ) printf ( "GFG\n" ); return 0; } |
Output:
Network Error
while loop:
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax :
while (boolean condition) { loop statements... }
C
#include <stdio.h> int main() { int i = 5; while (i < 10) { printf ( "GFG\n" ); i++; } return 0; } |
C++
#include <iostream> using namespace std; int main() { int i = 5; while (i < 10) { i++; 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++
#include <iostream> using namespace std; int main() { while (1) cout << "GFG\n" ; return 0; } |
C
#include <stdio.h> int main() { while (1) printf ( "GFG\n" ); return 0; } |
Output:
Network Error
Here are few differences:
For loop | While loop |
---|---|
Initialization may be either in loop statement or outside the loop. | Initialization is always outside the loop. |
Once the statement(s) is executed then after increment is done. | Increment can be done before or after the execution of the statement(s). |
It is normally used when the number of iterations is known. | It is normally used when the number of iterations is unknown. |
Condition is a relational expression. | Condition may be expression or non-zero value. |
It is used when initialization and increment is simple. | It is used for complex initialization. |
For is entry controlled loop. | While is also entry controlled loop. |
for ( init ; condition ; iteration ) { statement(s); } | while ( condition ) { statement(s); } |
used to obtain the result only when number of iterations is known. | used to satisfy the condition when the number of iterations is unknown |
Please Login to comment...