Sunday, 8 January 2017

For, While, Do Loop

Loop Control Statements: -

There are three types of loop control statements
1) For Loop                 2) While Loop             3) Do While Loop

1)       For Loop: -

The initialization statement is executed only once at the beginning of the For loop then the test expression is checked If the test expression is false, for loop is terminated/exit.

Syntax:-

for (Initialization; Condition; Increment/decrements) {
            statements;
 }

Example 1: -

//W.A.P for Table
class Table
{
public static void main(String args[])
{
int i, n = 4;
for(i=1;i<=10;i++)
{
System.out.println(n +"*" + i +"="+ n*i);
}
}
}
OUTPUT

2)       While Loop: -

While loop checks whether the test condition is true or false if it is true, code inside the braces { } are executed. Then again the test expression is checked whether test condition is true or false if it is false, then loop exit

Syntax:-

while (Test Condition) {
Statement;
}

Example: -

Write a program to print counting using while statement
class count
{
public static void main(String args[])
{
            int i = 1;
while(i<=10)
            {
                        System.out.println(i);
                        i++;
            }
}
}
OUTPUT

3)       Do While Loop: -

In do while statement inside body of code is executed then the test condition is checked. If it is true code inside the braces { } are executed. Then again the test expression is checked whether test condition is true or false if it is false, then loop exit

Syntax:-

do
 {
            Statement;
 } while (Test Condition);

Example: -

Write a program to print table using do while statement.
class Sahil {

   public static void main(String args[]) {
      int x = 10;

      do {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }while( x < 20 );
   }
}














No comments:

Post a Comment