Our social:

Wednesday, October 5, 2016

For Loop in Java-Tutorial

For loop is another kid of iteration that Java provides one. It is the most used iteration technique in Java. And, personally I believe that it provides much more flexibility while programming.

Basic structure for "for loop"

for(initialization; condition; iteration) {
// do something
}

Example (Again same example for printing 10 to 1)

public class ForDemo {                                          
                                                                    
 // we want to print 10 to 1 backwards
 //now using For loop                                          
 public static void main(String[] args) {
  for(int i = 10; i>0; i--)
  { 
   System.out.print(i + " ");
  }
 }
}
Try It
The output will be:
10 9 8 7 6 5 4 3 2 1

The underlying process for the above loop is:

Using multiple initialization and multiple increment in for loop 

Sometimes we may need to operate on more than one variable in a single for loop. This that case we can use multiple initialization and multiple iteration in a single for loop. But, keep in mind that there can be ONLY ONE CONDITION! No exception.
public class ForDemo {

 public static void main(String[] args) {

  for(int i = 10, j = 0  ; i>0;  i--, j++  )
  {
   System.out.print(i + "/"+ j+ " ");
  }
 }
}
Try It
The output will be:
10/0 9/1 8/2 7/3 6/4 5/5 4/6 3/7 2/8 1/9

       

 Nested Loops in Java

0 comments:

Post a Comment

Hello Every One thanks For Visit My site You Can Suggest any Idea About site And Related Education Information Provide me Its Best Content For you am Include in this Site And feel free contact And email now I hope This site very help full you