do while Loop in Java
The do-while loop in Java is a control flow statement that allows you to execute a block of code repeatedly based on a condition. It's similar to the while loop, but with one crucial difference: the do-while loop guarantees that the block of code will execute at least once, even if the condition is initially false.
// Code block to be executed..
} while (condition);
i.The 'do' keyword marks the beginning of the loop.
ii.The block of code to be executed is enclosed within curly braces '{}'.
iii.After the code block, the 'while' keyword is used, followed by a condition.
iv.The condition is evaluated after each iteration. If it evaluates to 'true', the loop continues. If it evaluates to 'false', the loop terminates.
Example-1print numbers from 1 to 7 using do while loop.
OUTPUT:
1 2 3 4 5 6 7
i.We initialize a counter variable 'j' to 1..
ii.Inside the 'do' block, we print the value of 'j' and then increment it.
iii.After executing the code block once, the loop checks the condition 'j<= 7'. If it's true, the loop continues; otherwise, it terminates.
iv.The loop continues to execute until the condition 'j <= 7' becomes false.
Question-2calculates the sum of numbers from 1 to 10 using a do-while loop.
OUTPUT:
Sum of numbers from 1 to 10 is: 55
1. Write a program to print your name 7 times using 'do while loop'.
2. Write a program to accept a number and display the Sum of its digits. Input: 213 Output: 6 .