Hello friends how are you, today in this blog i will teach you what is do while loop, syntax of do while loop , how do while loop works and many programs using do while loop in a very simple way.
Let's start
- It's body will execute until the given condition is true.
- here after the while semi colon is compulsory.
Here we are going to print number from 1 to 9 so there is a need of only one variable. Here we are taking variable x and we are initializing it with 1 and inside the body of do while loop we are printing value of i and after that there is a condition which is x < 10 that means loop will execute from 1 to 9. Here we can also use x<=9 in place of x < 10 for similar output.
class Easy { public static void main(String[] args) { int x=1; do { System.out.println(x); x++; } while(x<10); } } /* ### Output ### 1 2 3 4 5 6 7 8 9 */
In the above example the body of while will execute again and again as long as variable x is less than 10.
Factorial of any number is the product of number from 1 to given number. So we will use three variables to make this program. One for number ,second for storing the result and last one for running loop. After taking user input we will execute loop from 1 to number and multiply the numbers from 1 to number and after multiplying the numbers we will store it to a variable and at last we will print it and this will be the factorial of the given number.
//factorial of 5=1x2x3x4x5 //factorial of 6=1x2x3x4x5x6 //factorial of N=1x2x3x....xN import java.util.Scanner; class Easy { public static void main(String[] args) { Scanner in=new Scanner(System.in); int no,f=1,i=1; System.out.println("Enter any number"); no=in.nextInt(); do { f=f*i; i++; } while(i<=no); System.out.println("The factorial of "+no+" is "+f); } } /* ### Output ### Enter any number 6 The factorial of 6 is 720 */
Difference between while and do while loop
- The difference between while loop and do while is that in the case of while loop if the condition is false it's body will not execute but in the case of do while loop it's body will execute at least one time either condition true or false.
- While loop is a entry control loop and do while loop is a exit control loop.
Request:-If you found this post helpful then let me know by your comment and share it with your friend.
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all.
If you have not subscribed my website then please subscribe my website.
Try to learn something new and teach something new to other. Thanks.
0 Comments