Simplest looping statement in Java | Java For loop with examples | Loop Control | Control Statements

So far we learnt the mechanism of if-else statements and switch statement, where the main task was to execute a particular block if the condition is true, else execute the other one. Hence, these are useful in one-to-one operation, where we have to do one particular task once. But what if, our question demands something more, like to do a specific work repeated number of times. At this moment, our if-else would not work. To overcome this, developers came up with the concept of loops.

What are Loops?

As the name suggests, it helps in executing a task in a loop, or working in a loop,i.e repetitively yet sequentially. In general, Loops allow us to execute/run a statement or a bunch of statements repeatedly, until a condition(that binds the statements) tends to be true. As soon as the condition gets false, the loop ends.

For example: Suppose we are washing dishes in the kitchen, we need to wash each dish properly in the same manner, until no un-washed dish is left. Here we have to perform the task of washing the plate or utensil, the task or the way to do the task is same for each item, so we can say we'll do this task in a loop, as we are washing 1 plate, we do the same for about 10 times or for the number of plates left. This is loop.
Remember, a sequence is followed in loops, the statement arriving first will be executed first, than othe statements.

Java like every other programming language provides us with the functionality of loops, to do the tasks repeatedly and efficiently. There are 3 types of Loops in Java:
  • For loop
  • While loop
  • Do-while loop

For Loop in Java

For loop are mainly used when we are aware about how many number of time we have to iterate or perform the execution of the set of statements.
* This action of repeated execution of statements in more general form is known as Iterating. Thats why, these looping statements are also known as Iteration statements.
Hence, the number of iterations are fixed in a For loop, Infact this is the main feature why for loop is the most used and popular loop amongst others.

Syntax:
for(initialization;condition;increment/decrement)
{
statements.....
}

Just a raw example of how to use in code:
for(int i=1;i<=10;i++)
{
System.out.println("ProgrammerStudios");
}

This would simply print "ProgrammerStudio" for the number of times defined in the condition part, i.e 10 times.

Working: 

1. While working with loops, we require an iterating variable, that would tell us for what n-th time the loop is working, whether its first time, second time or so on. Here in this case, we have our variable i as the iterator variable, (Note, that i is integer type, not char, float etc, this is because, the number of times a loop is gonna run would be a whole number, whether 10 or 10000).

2. After writing the for keyword and starting the brackets, our first task is to initialize our iterating variable with a value, which will tell from where our loop will start, to have a loop from 1 to 5, we'll initialize i with 1, which will increase over the iterations, until the provided condition gets false.

3. Then after a semicolon, comes the condition part, which is checked everytime, an iteration occurs, for example:
for(int i=1;i<=10;i++)
{
System.out.println("ProgrammerStudios");
}
Here, i is initialized with 1, and condition is i should be less than equal to 10, for everytime after the execution of the statement block, loop will check, whether the value of i now formed is less than 10 or not, and if i<=10 then again loop body will execute. Otherwise it will end.

4. Then again after a semicolon, comes the increment part, which will decide with what style i would be changing, whther i would increase by one after every iteration, or decrease by one, or anything.
In the above example, i would increase by 1, everytime. It will start from 1, then increase to 2, then 3 and so on. Until, i <=10. As soon as i will become 11 and condition will become false, Loop will end.
We can also write the increment part as i = i + 1, instead of i++

Flow of execution:

for(int i=1;i<=10;i++)
{
System.out.println("ProgrammerStudios");
}

In this example, firstly i=1, then it would check the condition, whether i<=10, if true, the loop body will be executed and "ProgrammerStudios" would be printed for the first time, then increment will be there i would now become 2, and again condition would be checked, and if again true, the loop body will be executed and "ProgrammerStudios" would be printed for the second time. And same process would be carried out, and in the 10th iteration, after printing "ProgrammerStudios" for the 10th time, i will again be incremented and become 11, now on condition checking, the condition would become false, as 11 is not less than equal to 10. So loop will end.

This concept of Loops is very useful in finding Factorials, Fibonacci Series, Reverse of a number or String and solutions of many such problems.

Program 1: Write a program to print the Factorial of the number.
public class factorial {
    public static void main(String[] args) {

        int fact=1, i , num = 5;
        for ( i=1;i<=5;i++)
        {
            fact=fact*i;
        }
        System.out.println("Factorial of "+num+" is "+fact);

    }
}

OUTPUT
Factorial of 5 is 120

Program 2: Write a program to print the Fibonacci Series upto n.
public class Fibonacci {
    public static void main(String[] args) {
        int n=10;
        int ab ;
        int c =0;
        a = 0;
        b = 1;
        int s;
        System.out.print(a+" "+b+" ");
        while(c<n){
            c++;
            s = a+b;
            System.out.print(s+" ");
            a=b;
            b=s;
        }   
    }
}

OUTPUT
0 1 1 2 3 5 8 13 21 34 55 89

Modified version of For Loop : For-each Loop

It is a loop exclusively for the array elements. It is mainly used to traverse an array or collection in Java. Many more languages like C, C++, PHP, Python, Javascript etc support this concept. It is considered easier than traditional For loop, as we need not increment the value, by specifying an expression, this task is done automatically. It works on element basis not Index, by returning elements one by one.
Syntax:
for(type variableName : arrayName)
{
statements...
}

Example:
public class ForEachLoop {  
    public static void main(String[] args) {  
        int arr[]={1,2,3,4,5};  
        for(int i:arr){  
            System.out.println(i);  
        }  
    }  
    }

OUTPUT
1 2 3 4 5 

Ritish

Just a novice blogger

Post a Comment (0)
Previous Post Next Post