Tuesday, August 6, 2013

[PART-6] JAVA : Looping

From now onwards use DrJava to write your programs, compile and run it.
It is very handy and easy to use.
Download it from here :
http://www.drjava.org/
You will find compile and run buttons in drjava. Hence it is easy to use.

There may be situations where we have to execute a piece of code several times. For this looping is used. There are 3 kinds of loops in java :


  1. for loop
  2. while loop
  3. do while loop

1.)for loop
i=0;
Here we have assigned the value of integer i variable to 0.
So it will start from 0.

i<=5; (i is less than or equal to 5)
i will start from number 0 and will stop when its value becomes 5.
if it was i<5; (i is less than 5) then it will stop when its value becomes 4

i++ (will increase the value of i with 1, note that 1st time it will not increase the value of i)


2.)while loop
  I have assigned value of i to 1.
now while loop will execute the piece of code until the condition is true. Here the condition is if i is less than or equal to 5 it will print the value of i.
i++ willl increment or increase the value of i by 1 each time the loop is executed.

3.)do while loop
I have done the same thing here.
Initially do while loop will execute whatever is between the { } without checking for any condition.
Then it will check for conidtion i.e. while(i<=5)
Whereas in case of while loop it will initially check the condition and then go ahead only if the condition is true.

See the video for better understanding...




0 comments:

Post a Comment