Learn the for loop statement in java

The for loop statement in java

In this article, you will learn for loop statement of java in details with programming examples.

The loop statement:

Q: what is for loop statement in java.

Ans: for loop statement in java is the same as the statement of the other language like C, C++, and C#. In for loop first, initialize the variable, then condition check, after execution of statement increment or decrement the value.

Syntax of for loop:

for(initialization; condition; iteration) {

// body of the for loop

}

 

Q: write a program in java to demonstrate the for loop

Solution:

public class forLoopexp {

public static void main(String args[] ) {

int i;

for(i=0;i<9;i++) {

System.out.println(“tik tok –>” +i);

}

}

}

 

 

 

Output of this program:

tik tok –>0

tik tok –>1

tik tok –>2

tik tok –>3

tik tok –>4

tik tok –>5

tik tok –>6

tik tok –>7

tik tok –>8

 

 

  • Write the above program in declaring loop control variable inside the for loop
public class forLoopexp {

public static void main(String args[] ) {

for(int i=0;i<=9;i++) {

System.out.println(“tik tok –>” +i);

}

}

}

 

  • Write the above program, an input is given by the user from a keyboard

Solution:

import java.util.Scanner;

public class forLoopexp {

public static void main(String args[] ) {

int i,n;

System.out.print(“Enter a number: “);

Scanner sc=new Scanner(System.in);

n=sc.nextInt();

for(i=0;i<=n;i++) {

sc.close();

System.out.println(“tik tok –>” +i);

}

}

}

 

Output of this program:

 

Enter a number: 9

tik tok –>0

tik tok –>1

tik tok –>2

tik tok –>3

tik tok –>4

tik tok –>5

tik tok –>6

tik tok –>7

tik tok –>8

tik tok –>9

 

 

  • Write the above program in declaring loop control variable inside the for loop input is given by user from the keyboard.
import java.util.Scanner;

public class forLoopexp {

public static void main(String args[] ) {

System.out.print(“Enter a number: “);

Scanner sc=new Scanner(System.in);

int n=sc.nextInt();

for(int i=0;i<=n;i++) {

sc.close();

System.out.println(“tik tok –>” +i);

}

}

}

 

Output of this program:

Enter a number: 12

tik tok –>0

tik tok –>1

tik tok –>2

tik tok –>3

tik tok –>4

tik tok –>5

tik tok –>6

tik tok –>7

tik tok –>8

tik tok –>9

tik tok –>10

tik tok –>11

tik tok –>12

 

Leave a Reply

Your email address will not be published. Required fields are marked *