DEV Community

velvizhi Muthu
velvizhi Muthu

Posted on

Module-2 For loop Program

  1. What is a for loop?

A for loop is a control structure used in programming to repeat a block of code a specific number of times. It’s commonly used when you know in advance how many times you want to run a piece of code.

  1. Why do we use a for loop?

The short answer is:

πŸ” To repeat a task a known number of times, or to go through items in a sequence (like a list, string, or array)

Print 1 to 10 :
public class Main {
public static void main(String[] args) {
for(int no = 1; no <=10 ;no++)
{
System.out.println(no);
}
}

}

Print Even Numbers from 1 to 20 :
public class Main {
public static void main(String[] args) {
for(int no = 1; no <= 20 ;no++)
{
if(no % 2 == 0)
{
System.out.println("Even number is " + no );
}
else if(no % 2 == 1){
System.out.println("Odd number is " + no);
}
}
}

}

Print Multiplication Table of 5 :
public class Main {
public static void main(String[] args) {
for(int no = 1; no <=5; no++)
{
System.out.println(no +" * 5 = " + no * 10 );
}
}

}

Sum of First 10 Natural Numbers :
public class SumNatural {
public static void main(String[] args) {
int sum = 0;
for(int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
}

}

Reverse Numbers from 10 to 1 :
public class ReverseNumbers {
public static void main(String[] args) {
for(int no = 10; no>=1 ; no--)
{
System.out.print(no);
}
}
}


Check Prime Number :
public class PrimeCheck {
public static void main(String[] args) {
int num = 7;
boolean isPrime = true;
if(num % 2 == 0)
{
isPrime = false;
}

    if(isPrime)
        System.out.println(num + " is a prime number.");
    else
        System.out.println(num + " is not a prime number.");
}
Enter fullscreen mode Exit fullscreen mode

}

Count the Number of Digits in a Number :

public static void main(String[] args) {
int count = 0;

    for(int i = 1;i<=5;i++)
    {
        count = count + i;
    }
    System.out.println(count);

}
Enter fullscreen mode Exit fullscreen mode

Print All Alphabets (A to Z) :

public static void main(String[] args) {
for(char ch = 'A'; ch <= 'Z'; ch++) {
System.out.print(ch + " ");
}
}

for(char ch = 'A'; ch <= 'Z'; ch++) {

        if(ch == 'N') {
            System.out.println("Nanthakumar");
        }
        else {
            System.out.println(ch);
        }
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)