Wednesday, June 30, 2010

Loops


1.How to write while loop statements
2.How to write do while loop statements
3.How to write for loop statements

How to write while loop statements

class LoopSamples {

public static void main(String[] args) {
int x = 1;
while (x < 2) {
System.out.println(x);
++x;
}
}
}

The output will be: 1

How to write do while loop statements

class LoopSamples {

public static void main(String[] args) {
int x = 1;
do {
System.out.println(x);
++x;
} while (x < 2);
}
}

The output will be: 1
Note: The loop will exected atleast one ( first) time

How to write for loop statements

class LoopSamples {

public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("i is " + i);
}

int y = 6;
for (int x = 0; (x < 2); x++, y++) {
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
}

No comments:

Post a Comment