What is for and while loop?
- loops are used to repeat a block of code. For example, if we want to show a message 100 times,then rather than typing the same code 100 times, we can use a loop.
- loop is used to run a specific code until a certain condition is met.
while loop:
- A while loop evaluates the expression inside the parenthesis ().
- If the expression evaluates to true, the code inside the while loop is executed.
- The expression is evaluated again.
- This process continues until the expression is false.
- When the expression evaluates to false, the loop stops.
Example :
class LearWhileLoop{
public static void main(String[] args) {
int i = 1;
while(i <= 5) {
System.out.println(i);
i++;
}
}
}
output :
1
2
3
4
5
for loop:
- The initialexpression initializes and/or declares variables and executes only once.
- The condition is evaluated. If the condition is true, the body of the for loop is executed.
- The updateexpression updates the value of initialexpression.
- The condition is evaluated again. The process continues until the condition is false.
Example :
class LearForLoop{
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= 5; ++i) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
- We use for loop when we know how many times the loop should run.
- We use while when the loop depends on a condition, not a fixed number.
Example :
public static void main(String args[]) {
{
Scanner sc = new Scanner(System.in);
boolean bl = true;
while(bl)
{
System.out.print("Enter a character in small alphabet: ");
char ch = sc.next().charAt(0);
if(ch >='a' && ch <= 'z') {
System.out.println("Good! you have entered a vowel");
bl = false;
}
else
System.out.println("Entered Character is not vowel");
}
}
But we can also do this in for loop
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
boolean bl = true;
for (; bl; ) {
System.out.print("Enter a character in small alphabet: ");
char ch = sc.next().charAt(0);
if (ch >= 'a' && ch <= 'z') {
System.out.println("Good! you have entered a vowel");
bl = false;
} else
System.out.println("Entered Character is not vowel");
}
}


Top comments (0)