Looping statement are the statements execute one or more statement repeatedly several number of times.Java programming language provides mainly three iteration statements such as :
- for statement
- while statement
- do-while statement
- Reduce length of Code
- Take less memory space.
- Burden on the developer is reducing.
- Time consuming process to execute the program is reduced.
The while loop
The simplest loop is the while loop. The general format of the while loop is as follows:
Syntax :
initialization; while ( test condition) { statements; increment; } |
Example while loop
class whileDemo { public static void main(String args[]) { int i=0; while(i<5) { System.out.println(+i); i++; }
Output
1 2 3 4 5
The do-while loop
The do-while loop is a special looping statement. Generally significance of having this loop is to get atleast one time body statements to execute. Here looping follows some different pattern as compare to other loops. Lets look at the general format of the do-while loop :
Syntax :
initialization; do { statements; increment; } while ( test condition); |
Example do..while loop
class dowhileDemo { public static void main(String args[]) { int i=0; do { System.out.println(+i); i++; } while(i<5); } }
Output
1 2 3 4 5
The for loop
The for loop is highly and most loved looping statement for the programmers. Lets look at the general format of the for loop :
Syntax :
for ( init; condition; increment ) { statement; } |
Example of for loop
class Hello { public static void main(String args[]) { int i; for (i=0: i<5; i++) { System.out.println("Hello Friends !"); } } }
Output
Hello Friends ! Hello Friends ! Hello Friends ! Hello Friends ! Hello Friends !
Output for while and do while loops will be
ReplyDelete0
1
2
3
4
please check it