Thursday, March 31, 2016

While Loop

Hey guys, today we're gonna learn about "While Loop".

Then what's this while loop?
In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

if you have an idea about Flow Charts this would be helpful.

Image result for what's while loop

public class main {

public static void main(String []args){

int counter = 0;                                                             * variable called "counter"

while (counter < 10 ){                                                  * Start the while loop
System.out.println("Hello Blogger!!");             * Print "Hello Blogger"

}                                                                                     * While loop ends

}
}

You'll see this loop will never ever ends because condition always correct. OK let's take an example like this. You wanna display 'Hello World' 10 times.
Simple logic add 1 to counter each time. Let's go ahead

public class main {

public static void main(String []args){

int counter = 0;

while (counter < 10 ){
System.out.println("Hello World!!");
counter = counter + 1;                                           
}

}
}


  1. At the start 'counter' equals to 0. Dispaly "Hello World"
  2. Next add 1. Now the counter equals to 1. Dispaly "Hello World" again.
  3. Again Add 1. counter equals to 2. Dispaly "Hello World".
  4. And so on
When the condition becomes wrong it exits from the loop and go to next statement.






Try your own to make this.

 X = 18. Put X into a while loop & run for 10 times. finally the value of thee X must be 28.


No comments:

Post a Comment