Wednesday, April 18, 2012

How to perform loops/iterations in JAVA?

   In Java there are also different kinds of looping/iterations. But before that, why are we using such method? Loopings usually use to prevent or to avoid line redundancy in a program, by performing this techniques, you will be able to organize your program in a very simple way. For example, you will be printing 5 or more lines "Ako si Real Myn". You can code as simple as below, but how is it if you have to print more than this? A hundred?2 hundred?

                           System.out.println("Ako si Real Myn");
                           System.out.println("Ako si Real Myn");
                           System.out.println("Ako si Real Myn");
                           System.out.println("Ako si Real Myn");
                           System.out.println("Ako si Real Myn");
Output:
                           Ako si Real Myn
                           Ako si Real Myn
                           Ako si Real Myn
                           Ako si Real Myn
                           Ako si Real Myn  

   Are willing to type those lines and made sure you have got the right number?

Example: "Ako si Real Myn" in 20 times.

Solution 1: Do-While Loop

                           /*initialize integer type variable "counter" to 0,
                              ito ang taga bilang kung ilang ulit gagawin ang statement*/
                          int counter=0;
                         
                          do //Gawin ito
                             {
                                 System.out.println("Ako si Real Myn");
                                counter++; //magdagdag ng isa(1) ang counter sa tuwing uulit
                             }
                          while (counter<20); //Gawin (do), while counter is less than 20

Solution 2: For Loop
                       
                         
                         for (int counter=0;counter<20;counter++)
                               System.out.println("Ako si Real Myn");

Solution 3: While Loop

                         int counter=0;
                        while (counter<20)
                              {
                              System.out.println("Ako si Real Myn");
                              counter++;
                              }

   Pwede gamitin kahit alin sa mga types of looping na ito para sa program, sa halip na ita-type mo paulit ulit un basic codes sa pag print ng line.



SHARE and LEARN!


No comments:

Post a Comment