For Loop in Java

A for loop in Java iterates over a sequence of code for a defined number of times. It's structured with initialization, condition, and update statements, and is commonly used for iterating over arrays, collections, or executing a block of code repeatedly.


  • What is a For Loop?
  • A for loop in Java is a control flow statement that allows you to execute a block of code repeatedly based on a condition. It's commonly used when you know in advance how many times you want to execute the code. The loop has three main parts: initialization, condition, and iteration.

  • Basic Syntax of For Loop:
  • for(initialization; condition;update){
      //code block to be excuted
    }

    i. Initialization:This part initializes the loop control variable. It's executed once at the beginning of the loop.
    ii.Condition:This is the condition for continuing the loop. If the condition evaluates to true, the loop continues; otherwise, it exits.
    iii.Update: This part updates the loop control variable. It's executed after each iteration of the loop.


  • Real-life examples :
  • Example-1:

    import java.util.Scanner; class HelloPBA { public static void main(String[] args) { Scanner scr = new Scanner(System.in); int i, n, count = 0; System.out.println("Enter the number:"); n = scr.nextInt(); for (i = 1; i <= n; i++) { if (n % i == 0) { count++; } } if (count == 2) { System.out.print("Number is prime"); } else { System.out.println("Number is not prime"); } } }

    OUTPUT:

    Enter the number:
    5
    Number is prime.

    Example-2:Write aprogram to Generate Multiplication Table.Input-5.

    import java.util.*; class HelloPBA { public static void main(String args[]){ int a=5; for(int i=1;i<=5;i++){ System.out.println(a +"*" +i +"="+ a*i); } } }

    OUTPUT:

    5*1=5
    5*2=10
    5*3=15
    5*4=20
    5*5=25

    Example-3Write a program to find Factors of a given number e.g. factors of 12 are 1, 2, 3, 4, 6, 12.

    import java.util.*; class HelloPBA { public static void main(String args[]){ int n; Scanner sc=new Scanner(System.in); System.out.println("Enter the number :"); n=sc.nextInt(); for(int i=1;i<=n;i++){ if(n%i==0){ System.out.print(i +","); } } } }

    OUTPUT:


    enter the number:
    12
    1,2,3,4,6,12,

  • Practice Exercises:
  • 1. Write a program that asks the user for a positive number and prints the sum of all numbers from 1 to that number (inclusive).
    2.Write a program to accept a number and generate next 10 numbers. For example: Input:5 Output- 6,7,8,9,10,11,12,13,14,15.