For, While, Do While 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/decrement)
{
            statements;
 }

Example 1: -

Write a program for Table using for loop
class ForLoopExample
{
public static void main(String args[])
{
int i, n = 4;
for(i=1;i<=10;i++)
{
System.out.println(n +"*" + i +"="+ n*i);
}
}
}
Output:-
4x1=4
4x2=8
4x3=12
4x4=16
4x5=20
4x6=24
4x7=28
4x8=32
4x9=36
4x10=40
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 WhileLoop
{
public static void main(String args[])
{
            int i = 1;
while(i<=10)
            {
                        System.out.println(i);
                        i++;
            }
}
}
OUTPUT:-
1
2
3
4
5
6
7
8
9
10


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 DoWhile
{
public static void main(String args[])
{
            int n =5, i=1;
do
            {

                        System.out.println(n+"*"+i+"="+n*i);
                        i++;
            }
while(i<=10);
}
OUTPUT:-
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
Previous page                                           Next Page
                                                                 if, if else, nested if else

You Like my post please share with friends. Any thing you do not understand please comment it. 

No comments:

Post a Comment