Computer Applications
Answer
The for loop is used when number of iterations is fixed and known. It is also referred to as a fixed or known iterative looping construct.
The following parameters are commonly used in a for loop:- An initial value for the loop control variable.
- A condition—loop will iterate as long as this condition remains true.
- An update expression to modify the loop control variable after every iteration.
- Body of the loop which consists of the statements that needs to be repeatedly executed.
Below is an example of for loop, it prints the table of 2 till 12:
for (int i = 1; i <= 12; i++) {
int a = 2 * i;
System.out.println("2 x " + i + "\t= " + a);
}
Related Questions
Rewrite the following program using for loop:
int i=1; int d=5; do { d=d*2; System.out.println(d); i++; } while (i<=5);
Rewrite the following program using while loop:
import java.util.*; class Number { public static void main(String args[]) { int n,r; Scanner in = new Scanner(System.in); System.out.println("Enter a number"); n=in.nextInt(); do { r=n%10; n=n/10; System.out.println(r); } while(n!=0); } }
Define the following with their constructs:
(a) Entry controlled loop
(b) Exit controlled loop
Write down the syntax of:
(a) do - while
(b) while loop