Convert the given Java code into its equivalent code using ‘for’ loop:- [3]
int i=7;
while( i<=11)
{
++i;
System.out.println(i+” \t ”);
}
Answers
Answer:
Playing with loops makes programming fun. Before we try to understand loop, you should be thorough with all the previous topics of Java. If not, practice a considerable number of problems of all the previous topics.
Suppose we have to print first 10 natural numbers.
One way to do this is to print the first 10 natural numbers individually using System.out.println statement. But what if you are asked to print the first 100 natural numbers !
Broadly classifying, there are three types of loops in Java programming which are:
1. while loop
2. for loop
3. do...while loop
while loop
while loop makes it quite easy.
Let's first look at the syntax of while loop.
while(condition)
{
statement(s)
}
while loop checks whether the condition written in ( ) is true. If the condition is true, statements written in the body of the while loop i.e. inside the braces { } are executed.Then, again the condition is checked, and if found true, again the statements inside body of the while loop are executed. This process continues until the condition becomes false.
An example will make this clear.
class L1{
public static void main(String[] args){
int n = 1;
while( n <= 10){
System.out.println(n);
n++;
}
}
}
Output
In our example, firstly, we assigned a value 1 to a variable 'n'.
while(n <= 10) checks the condition 'n <= 10'. Since the value of n is 1 which is less than 10, the statements within the braces { } are executed.
The value of 'n' i.e. 1 is printed and n++ increases the value of 'n' by 1. So, now the value of 'n' becomes 2.
Now, again the condition is checked. This time also 'n <= 10' is true because the value of 'n' is 2. So, again the value of 'n' i.e. 2 gets printed and the value of 'n' gets increased to 3.
When the value of 'n' becomes 10, again the condition 'n <= 10' is true and 10 gets printed for the tenth time. Now, n++ increases the value to 'n' to 11.
This time, the condition 'n <= 10' becomes false and the program terminates.
Quite interesting. Isn't it !
while loop in java
The following animation will also help you to understand the while loop.
gif of while loop in Java
Let's see one more example of while loop
import java.util.*;
class L2{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int choice = 1;
while(choice == 1){
int a;
System.out.println("Enter a number to check odd or even");
a = s.nextInt();
if(a%2==0){
System.out.println("Your number is even");
}
else{
System.out.println("Your number is odd");
}
System.out.println("Want to check more 1 for yes 0 for no");
choice = s.nextInt();
}
System.out.println("I hope you checked all your numbers.");
}
}