Flowchart of for Loop

Example: Program to Demonstrate How to Use for Loop

C




// C Program to illustrate the use of for loop
#include <stdio.h>
  
int main()
{
    // loop variable
    int i = 0;
  
    // for loop that prints "GFG" 5 times
    for (i = 5; i < 10; i++) {
        printf("GFG\n");
    }
  
    return 0;
}


C++




// CPP program to demonstrate
// for loop
  
#include <iostream>
using namespace std;
  
int main()
{
    // Initialize variable 'i' with a value of 0
    int i = 0;
  
    // Iterate using a for loop from 5 to 9 (inclusive)
    for (i = 5; i < 10; i++) {
  
        // Print "GFG" on each iteration
        cout << "GFG\n";
    }
  
    return 0;
}


Java




// Java program to illustrate the use of for loop
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        // loop variable
        int i = 0;
  
        // for loop
        for (i = 5; i < 10; i++) {
            System.out.println("GfG");
        }
    }
}


Output

GFG
GFG
GFG
GFG
GFG

Looping Infinite Times

C




// C program to demonstrate
// infinite for loop
#include <stdio.h>
  
int main()
{
  
    // Infinite loop using a for loop with no condition
    // specified The absence of a condition means the loop
    // will continue indefinitely until it is explicitly
    // interrupted or terminated.
    for (;;) {
        printf("GFG\n");
    }
  
    return 0;
}


C++




// C++ program to demonstrate
// infinite for loop
#include <iostream>
using namespace std;
  
int main()
{
    // Infinite loop using a for loop with no condition
    // specified The absence of a condition means the loop
    // will continue indefinitely until it is explicitly
    // interrupted or terminated.
    for (;;) {
  
        // Print "GFG" on each iteration
        cout << "GFG\n";
    }
  
    return 0;
}


Java




// Java program to illustrate the use of for loop
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        // infinite for loop
        for (;;) {
            System.out.println("GFG!");
        }
    }
}


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.

Similar Reads

for Loop

A for loop provides a concise way of writing the loop structure. Unlike a while loop, a for loop declaration consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping....

Flowchart of for Loop

...

while Loop

...

Flowchart of while Loop

...

Difference Between for Loop and while Loop

...