ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

Loop Control

Loop Control

We use loop statement if we want to execute a statement or group of statements multiple times.
1.for loop:A for loop is used for fixed number of iterations.
Example:Table of 5

  1. public class table
  2. {
  3. public static void main(String args[])
  4. {
  5. int i,k=0;
  6. for(i=5;i<=50;i=i+5)
  7. {
  8. k=k+i;
  9. System.out.println(k);
  10. }
  11. }
  12. }

Output:
5
10
15
20
25
30
35
40
45
50

2.while loop:this is another way to generate loop in the program.We can be used even when the number of iterations is not fixed.
Example:

  1. /*display a message on the screen 5 times */
  2.  
  3. public class display
  4. {
  5. public static void main(String args[])
  6. {
  7. int x=0;
  8. while(i<=5)
  9. {
  10. System.out.println(This is the tutorial for while loop”);
  11. i++;
  12. }
  13. }
  14. }

Output:

This is the tutorial for while loop
This is the tutorial for while loop
This is the tutorial for while loop
This is the tutorial for while loop
This is the tutorial for while loop

3.do while loop:Just like while loop it can also be used even when number of iterations is not fixed but unlike while loop it checks the condition after executing the loop once.

Example:

  1. /*factorial of 5*/
  2.  
  3. public class factorial
  4. {
  5. public static void main(String args[])
  6. {
  7. int i,f;
  8. I=1;f=1;
  9. do
  10. {
  11. f=f*i;
  12. i++;
  13. }
  14. while(i<=5);
  15. System.out.println(f);
  16. }
  17. }

Output:
120

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!