Showing posts with label java for loop. Show all posts
Showing posts with label java for loop. Show all posts

Thursday, 16 May 2013

Nested for loop



A loop inside another loop is called the nesting of loops. So a for loop inside the body of another for loop is called a nested for loop. Nesting of for loop are essential for handling multidimensional arrays. Also nested for loop are needed for handling table of contents (rows & columns).  

 Syntax of a Nested for loop:
  
                                                        for ( initialization ; condition ; updating)
                                                        { // Starting of outer loop
                                                       
                                                       for ( initialization ; condition ; updating)
                                                        { // Starting of inner loop
                                                         Statement / Statements ;                                                   
                                                        }
                                                         Statement / Statements ;        

                                                        }

Nested for loop example:

  1. class NestedDemo
  2. {
  3. public static void main(String args[])
  4. {
  5. for(int i = 0 ;i<10; i++ ) // outer loop
  6. {
  7. for(int j = 1; j<=i+1; j++ )// inner loop
  8. {
  9. System.out.print("*");
  10. }
  11. System.out.println();
  12. }
  13. }
  14. }




Wednesday, 15 May 2013

java for loop

for loop in java is one of the most important control statement in java.
Java for loop syntax:

for (initialization ; condition ; updating)
{
statement / statements;

}


  • Initialization perform only once at the starting of the loop. It is also possible to initialize more than one variable at the same time but separates them with comma operator. (int i = 0, j = 1 ;) 
  • Condition is always a Boolean statement. If more than one condition present, then separates them with any of logical operators. 
  • Updating is generally an increment / decrements (++ / --) statement.
  • First perform initialization and check the condition, if the condition is true then the loop body executes and then perform updating. Again check the condition, and if it is true again executes the loop body. This will continues till the condition become false.
for loop example in java:

  1. import java.io.*;
  2. class ForDemo
  3. {
  4. public static void main(String args[])throws IOException
  5. {
  6. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  7. int num;
  8. int result = 1;
  9. System.out.println("Enter any number :");
  10. num = Integer.parseInt(br.readLine());
  11. System.out.println("Multiplication table of "+num);
  12. for(int i=1; i<=10; i++)
  13. {
  14. result = num * i ;
  15. System.out.println(num+" * "+i+" = "+result);
  16. }
  17. }
  18. }