मराठी

How does for differ from WHILE? Explain with example programs.

Advertisements

प्रश्न

How does for differ from WHILE? Explain with example programs.

फरक स्पष्ट करा
Advertisements

उत्तर

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
shaalaa.com
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 7: Statements and their Scope - EXERCISE [पृष्ठ १६३]

APPEARS IN

धीरज मेहरोत्रा Computer Science [English] Class 12
पाठ 7 Statements and their Scope
EXERCISE | Q 6. | पृष्ठ १६३
Advertisements
Share
Notifications



      Forgot password?
Use app×