Showing posts with label for. Show all posts
Showing posts with label for. Show all posts

Tuesday, 20 November 2007

Java control structures

Hey guys, today's lesson will be about Java control structures.

Just like other languages, Java has support for if-then-else, switch case, for loop and while loop.

Here is an example of an if-then-else:
if (x <= 1336) {
System.out.println("Too low!");
} else if (x >= 1338) {
System.out.println("Too high!");
} else {
System.out.println("You got it!");
}
Can you interpret the example? Every number less than or equal to 1336 is considered too low, and every number greater than or equal to 1338 is considered too high. A number between 1336 and 1338 (probably 1337 :P) is the right solution.

A few things you should remember:
- The if expression must be enclosed within round brackets () and it must return a boolean value.
- The curly brackets {} are optional if there is only 1 statements inside. However it is a good practice to always use them.

When you are comparing a variable against many values you can use a switch case instead of multiple if-then-else. Here's an example of switch case:
switch (x) {
case 1336:
System.out.println("A little too low!");
break;
case 1338:
System.out.println("A little too high!");
break;
case 1337:
System.out.println("You got it!");
break;
default:
System.out.println("So far :P");
break;
}
Note that the break is important. Without it the control flow will fall through to the next case.

Most of the time when working on a challenge you will need loops to do something repeatedly. In Java you can use 2 types of loop: for loop and while loop.

The for loop is usually used when counting is involved. For example, the following code prints all the numbers from 0 to 1337:
for (int i = 0; i <= 1337; i++)
System.out.println(i);
The for loop consists of 3 parts:
  • The first part (int i = 0) is the initialization. It initializes the value at the beginning of the loop.
  • The second part (i <= 1337) is the termination condition. When its value is false the loop will terminate.
  • The last part (i++) is the increment. After each iteration of the loop is done this statement will be executed once.
You can omit any part of the loop, as long as it won't lead to infinite loop :P If you want the loop to terminate under another condition you can use the break statement. The above example can be rewritten like this:
int i = 0;
for (;;) {
System.out.println(i);
if (i > 1337) break;
i++;
}
Basically you can do everything with just the for loop. But for convenience you might want to use the while loop too:
int i = 0;
while (i <= 1377) {
System.out.println(i);
i++;
}
Here is another variation of the while loop, with the condition checked at the end of each iteration:
int i = 0;
do {
System.out.println(i);
i++;
} while (i <= 1337);
You can use break inside while loops too:
int i = 0;
while(true) {
System.out.println(i);
i++;
if (i > 1337) break;
}