How does for differ from WHILE? Explain with example programs.
Advertisements
Question
How does for differ from WHILE? Explain with example programs.
Distinguish Between
Advertisements
Solution
|
for |
while |
| 1. The for loop is generally used when the number of iterations is known in advance. | 1. The while loop is generally used when the number of iterations is not known in advance. |
| 2. In a for loop, initialization, condition checking, and updation are written together in the loop header. | 2. In a while loop, initialization is usually performed before the loop, condition checking is written in the loop header, and updation is performed inside the loop body. |
| 3. The for loop provides a compact structure for controlling iterations. | 3. The while loop provides a simple structure for executing statements based on a condition. |
| 4. The for loop is commonly used for counter-controlled repetition. | 4. The while loop is commonly used for condition-controlled repetition. |
| 5. The condition is checked before executing the loop body. Therefore, the loop may execute zero times. | 5. The condition is also checked before executing the loop body. Therefore, the loop may execute zero times. |
Example Program 1: for
class ForExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
Example Program 2: while
class WhileExample
{
public static void main(String[] args)
{
int i = 1;
while (i <= 5)
{
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
2
3
4
5
shaalaa.com
Is there an error in this question or solution?
