for loop in java

By: Abinaya Emailed: 1728 times Printed: 2329 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Here is the general form of the for statement:

for(initialization; condition; iteration) {
// body
}

If only one statement is being repeated, there is no need for the curly braces.

The for loop operates as follows. When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop. It is important to understand that the initialization expression is only executed once. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable. The loop then
iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false. Here is a version of the "tick" program that uses a for loop:

// Demonstrate the for loop.
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}

Declaring Loop Control Variables Inside the for Loop

Often the variable that controls a for loop is only needed for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for. For example, here is the preceding program recoded so that the loop control variable n is declared as an int inside the for:

// Declare a loop control variable inside the for.
class ForTick {
public static void main(String args[]) {
// here, n is declared inside of the for loop
for(int n=10; n>0; n—)
System.out.println("tick " + n);
}
}

When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) Outside the for loop, the variable will cease to exist. If you need to use the loop control variable elsewhere in your program, you will not be able to declare it inside the for loop. When the loop control variable will not be needed elsewhere, most Java programmers declare it inside the for. For example, here is a simple program that tests for prime numbers. Notice that the loop control variable, i, is declared inside the for since it is not needed elsewhere.

// Test for primes.
class FindPrime {
public static void main(String args[]) {
int num;
boolean isPrime = true;
num = 14;
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");
}
}

Using the Comma

There will be times when you will want to include more than one statement in the initialization and iteration portions of the for loop. For example, consider the loop in the following program:

class Sample {
public static void main(String args[]) {
int a, b;
b = 4;
for(a=1; a<b; a++) {
System.out.println("a = " + a);
System.out.println("b = " + b);
b—;
}
}
}

As you can see, the loop is controlled by the interaction of two variables. Since the loop is governed by two variables, it would be useful if both could be included in the for statement, itself, instead of b being handled manually. Fortunately, Java provides a way to accomplish this. To allow two or more variables to control a for loop, Java permits you to include multiple statements in both the initialization and iteration portions of the for. Each statement is separated from the next by a comma.
Using the comma, the preceding for loop can be more efficiently coded as shown here:

// Using the comma.
class Comma {
public static void main(String args[]) {
int a, b;
for(a=1, b=4; a<b; a++, b—) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}

In this example, the initialization portion sets the values of both a and b. The two comma separated statements in the iteration portion are executed each time the loop repeats. 

The program generates the following output:

a = 1
b = 4
a = 2
b = 3

Note : If you are familiar with C/C++, then you know that in those languages the comma is an operator that can be used in any valid expression. However, this is not the case with Java. In Java, the comma is a separator that applies only to the for loop.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(12)


1. View Comment

Java is very queit Langauge.

View Tutorial          By: Ashutosh Srivasatava at 2008-10-16 06:24:02
2. View Comment

syntax of java program in looping statement

View Tutorial          By: lokesh at 2009-03-25 06:57:56
3. View Comment

// Using the comma.
class Comma {
public static void main(String args[]) {
int a, b;
for(a=1, b=4; a<b; a++, b—) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}
its output is wrong
please check out


View Tutorial          By: jatin kapoor at 2011-01-22 03:43:10
4. View Comment

class loop8
{
public static void main(String args[])
{
int sum=0;
for (int i=0; i<10; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print(j);



}
sum=sum+i;
System.out.print(sum);
System.out.println(" ");
}
}
}


View Tutorial          By: ankush singh at 2011-11-04 16:26:36
5. View Comment

for(i=0;i<10;i++)
for(j=0;j<90;j++)
we two for loop.explan me in detail what the two for loop will do


View Tutorial          By: karthikeyan at 2012-05-23 05:33:10
6. View Comment

int m,m2,n,n2;
for( m=0 , m2=0 ; m<r1 , m2<c2 ; m++ , m2++ ){
for( n=0 , n2=0 ; n<c1, n2<r2 ; n++, n2++){
}
}
there is an error in this program kindly find out this error compiler show the comma mistake in this code


View Tutorial          By: muhammad abdullah at 2012-10-11 05:27:02
7. View Comment

There is possible to include 2 conditions in for loop using commas like
Ex:for(int i=0,j=5;i<j,j>0;i++,j--)


View Tutorial          By: aarthi at 2012-12-10 12:08:50
8. View Comment

required the flag set loop stutruce ..............

View Tutorial          By: savita at 2013-05-12 04:52:30
9. View Comment

Write a times table programme. The programme should ask a user to input a number. This number is then used as the times table. So if the user enters 10, the 10 times table should be displayed. Your Output window should look something like this, when your programme is run.

Output of a Java Times Tables programme is run:
Which times table do you want?
10
1 times 10 = 10
2 times 10 = 20
3 times 10 = 30
4 times 10 = 40
5 times 10 = 50
6 times 10 = 60
7 times 10 = 70
8 times 10 = 80
9 times 10 = 90
10 times 10 = 10


View Tutorial          By: Hannah Jambalos at 2014-09-03 12:07:34
10. View Comment

sir, i want if,if else,nested if..... concept in one(same) program...........

View Tutorial          By: krishna at 2015-08-14 08:58:01
11. View Comment

sir i want this following pattern using loops
**********
*******
*****
***
*
***
*****
*******
*********


View Tutorial          By: teju at 2015-09-13 22:46:58
12. View Comment

hi sir can you help me with this problem

3. Formulate program SumNumbers that computes the sum of numbers depending on the entries. User terminates input after inputting 0. (30 points)
Sample Input/Output:
Enter number[0 to terminate]: 25.4
Enter number[0 to terminate]: 26.0
Enter number[0 to terminate]: 25.5
Enter number[0 to terminate]: 0
Sum is 76.9


View Tutorial          By: Lee at 2015-10-01 09:08:26

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Abinaya
How to compile a Java program - javac
The clone() Method in Java
Data Types in Java
JSP Example to connect to MS SQL database and retrieve records
faces-config.xml to DirectTraffic in the JSF Application
Enabling Expression Language Evaluation in JSP
Using malloc() Function in C
ActionErrors and ActionError in Struts
Open, Creat, Close, Unlink system calls sample program in C
Structures and Functions in C
Introduction to JSP expression language
Multi-dimensional Arrays in C (Explained using date conversion program)
A C program similar to grep command in UNIX
Type Conversions in C (String to Integer, isdigit() etc)
Basics of C

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
Method Overloading (function overloading) in Java
XML and Java - Parsing XML using Java Tutorial
How to Send SMS using Java Program (full code sample included)
FileReader and FileWriter example program in Java
Vector example in Java
Method Overriding in Java
What is Java?
Stack example in Java - push(), pop(), empty(), search()
Read from a COM port using Java program
The Basic Structure of a Simple Java program
arraycopy example in Java
append() in Java
for loop in java
Calendar - sample program in Java
How to use ArrayList in Java
Most Emailed Articles (in Java)
Applet Notinited : Applet xxxxxxxxxxxx notinited
Basics of Exception Handling in Java
Tomcat and httpd configured in port 8080 and 80
Calculate average sale of the week in Java
Vector in Java - Sample Program
LinkedList in Java
Taking the size of an Array at runtime & generate random numbers to populate the Array
Getting Started with Java
Configuring a DataSource in Tomcat
What is JasperReports?
java.lang.reflect package
instanceof operator example in Java
The Unary Operators example in Java
Operator Precedence in Java
toRadians() and toDegrees() Sample program in Java