Introduction
A computer program is well suited for perform certain operation. Every computer language or computer programe have featuer that instruct the program for repetitive task. The process of repeatedly execution of blocks of statement is known as Looping. The statement of block will execute any number of times, from zero to infinite number.
Fig. Loop Control structure
Java supports such a looping feature. In looping, a sequence of program will executed until some condition for the termination of the loop are satisfied. So looping have two segments, Aprogram loop means its body and control statement means its condition.
The test condition should be carefully stated in order to perform the desired number of loop executions. Java language provides three constructs for looping operation.
- while
- do
- for
1. While:
The simplest of all looping structure in java is the While loop. The basic format is as below:
Initialization;
while( test condition ){
body of loop;
}
The while loop is entry-controlled loop statement. The test condition is check first, if the condition is true the body of loop will executed. This process will repeated until the condition will get false. For example:
public class WhileStatement {
public static void main(String[] args) {
int number=5;
while(number>=0){
System.out.println("Number is "+number);
number--;
}
}
}
Output:
Number is 5
Number is 4
Number is 3
Number is 2
Number is 1
Number is 0
2. do statement:
The while loop is check the condition first and if the condition is true then the body of loop statement executed. In some of occasions it might be necessary to execute the body of the loop before test is perform or checking condition, in this setuation we use the do statement. The basic format is below:
Initialization;
do{
body of loop;
}while(text condition);
- Initialization is controll variable which is declare first, using assignment statement such as i=0 or count=0. The i and count is called loop-control variable.
- The value of the control variable is tested using the text condition. The test condition is a relational expression, such as i < 10 that determins that loop will exit when it satisfy this condition until that body of loop will execute.
- At the time of each iteration of execution we increase/decrease the control variable value using assignment statement such as i=i+1 OR i=i-1.
Comments
Post a Comment