Java – For Loop

for loop: Execute a block of instructions repeatedly as long as the condition is valid. We use for loop only when we know the number of iterations to do.

Syntax:

for(init ; condition ; modify)
{
            statements;
}
 
for(start ; stop ; step)
{
            statements;
}

FlowChart:

Print 1 to 10 Numbers:

class Code
{
            public static void main(String[] args) {
                        for (int i=1 ; i<=10 ; i++){
                                    System.out.println(“i val : ” + i);
                        }
            }
}

Program to Print 10 to 1 numbers

class Code
{
            public static void main(String[] args) {
                        for (int i=10 ; i>=1 ; i–){
                                    System.out.println(“i val : ” + i);
                        }
            }
}

Program to display A-Z alphabets

class Code
{
            public static void main(String[] args) {
                        for (char ch=’A’ ; ch<=’Z’ ; ch++){
                                    System.out.print(ch + ” “);
                        }
            }
}

Program to Print 1 to N numbers

import java.util.Scanner;
class Code
{
            public static void main(String[] args)
            {
                        Scanner scan = new Scanner(System.in);
                        System.out.print(“Enter n val : “);
                        int n = scan.nextInt();
                        for (int i=1 ; i<=n ; i++)
                        {
                                    System.out.println(“i val : ” + i);
                        }
            }
}

Program to display A-Z alphabets with ASCII values

class Code
{
            public static void main(String[] args)
            {
                        for (char ch=’A’ ; ch<=’Z’ ; ch++)
                        {
                                    System.out.println(ch + ” : ” + (int)ch);
                        }
            }
}

Program to display ASCII character set

class Code
{
            public static void main(String[] args)
            {
                        for (int i=0 ; i<256 ; i++)
                        {
                                    System.out.println(i + ” : ” + (char)i);
                        }
            }
}
Scroll to Top