Difference between a while loop & do/while loop.
int i = 0; while(i < 3) { System.out.println("Good jobs!"); i++; } System.out.println("END"); |
int i = 0; do { System.out.println("Good jobs!"); i++; } while(i < 3); System.out.println("END"); |
for(int i=0; i<3; i++) { System.out.println("Good jobs!"); } System.out.println("END"); |
What will be output of the above three program segments?
If the i is inialized to be 5, what will be output of each?
int i = 5; while(i < 3) { System.out.println("Good jobs!"); i++; } System.out.println("END"); |
int i = 5; do { System.out.println("Good jobs!"); i++; } while(i < 3); System.out.println("END"); |
for(int i=5; i<3; i++) { System.out.println("Good jobs!"); } System.out.println("END"); |
do/while loop will always do at least
one time jobs.
while loop may not do the jobs at all.
for(int i=0; i<3; i++)
{
System.out.println("Good jobs!");
}
System.out.println("END");
Steps to run the above "for" loop:
1. initalize i to be 0.
2. check whether i < 3?
3. If the condition is true, do the job - print "Good jobs".
4. Increase i, i++ ( i = 1 now)
5. check whether i < 3?
6. If the condition is true, do the job - print "Good jobs".
7. Increase i, i++ ( i = 2 now)
8. check whether i < 3?
9. If the condition is true, do the job - print "Good jobs".
10. Increase i, i++ (i = 3 now)
11. check whether i < 3?
12. It is false. Therefore jump out the loop. Also, print "END".