Loops in Java
Loops in Java
To repeat a set of statements more then one time without using any structure is pretty hard. For example : if we want to display 100 times “Welcome to Java” on the screen. The following line we have to write 100 times to achieve results.
System.out.println("Welcome to java");
Instead of repeating hundred lines java facilitates a control structure know as loop with great flexibility to repeat the set of statements.
For example, the following peace of code will print “Welcome to java” hundred time over the screen.
for(int i=0; I<99; i++) System.out.println("Welcome to java");
While Loop
While loop is based on boolean expression to control the execution and body having set of statement to perform a number iteration on it. One time iteration of body after successful evaluation of boolean express is known as one iteration. Pseudocode for while loop is given bellow.
while ( boolean-expression ) statement
Programming Example :
int count = 1; while (count =< 100) { System.out.println("Welcome to Java!"); count++; }
Above example prints welcome to java hundred times. While loop evaluates boolean expression if it is true, continue iteration otherwise terminate entire loop. Boolena expression in example remain true hundred time and successfully prints "Welcome to java" hundred time.
do - while Loop
do while loop is a variation of while loop. In do while body is executed first then boolean expression is evaluated. If the evaluation is true the body will be executed again otherwise terminate the loop. Pseudocode for do-while loop is given bellow.
do { statement(s); } while(boolean expression);
Programming Example :
int count =0; do{ System.out.println("Welcome to java"); count++; } while(count<=100);
for Loop
for loop uses the variable to control the sequence. Pseudocode for for loop is given bellow:
for(intialization; condition; increment / decrement;){ statements(s); }
Programming Example :
for(int i=0; i<99; i++) System.out.println("Welcome to java");
No Responses