Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0055 Control Variables Inside the for Loop

It is possible to declare the variable inside the initialization portion of the for. public class Main { public static void main(String args[]) { for (int n = 10; n > 0; n--){ System.out.println("tick " + n); } } } The output: tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 The scope n ends when the for statement ends. Here is a program that tests for prime numbers using for loop statement. public class Main { public static void main(String args[]) { int num; boolean isPrime = true; num = 50; for (int i = 2; i <= num / 2; i++) { if ((num % i) == 0) { isPrime = false; break; } } if (isPrime) System.out.println("Prime"); else System.out.println("Not Prime"); } } The output: Not Prime