#9 Introducing Control Statements in JAVA

Introducing Control Statements



These statements will be dealt with in more detail further on in this booklet. For now we will learn about the if and the for loop.


class Example11



{
 public static void main(String args[])
 {
int a,b,c;
a = 2; b = 3;
 c = a - b;
if (c >= 0)
System.out.println("c is a positive number");
 if (c < 0)
 System.out.println("c is a negative number");
 System.out.println();
 c = b - a;
 if (c >= 0) System.out.println("c is a positive number");
 if (c < 0)
System.out.println("c is a negative number");


 }

 }

Predicted output:


 c is a negative number c is a positive number The ‘if’ statement evaluates a condition and if the result is true, then the following statement/s are executed, else they are just skipped (refer to program output). The line System.out.println() simply inserts a blank line. Conditions use the following comparison operators:

Loop



The for loop is an example of an iterative code, i.e. this statement will cause the program to repeat a particular set of code for a particular number of times. In the following example we will be using a counter which starts at 0 and ends when it is smaller than 5, i.e. 4. Therefore the code following the for loop will iterate for 5 times

class Example12



{
public static void main(String args[])
{
 int count;
 for(count = 0; count < 5; count = count+1)
System.out.println("This is count: " + count);
System.out.println("Done!");
 }

 }

Predicted Output:

 This is count: 0
 This is count: 1
 This is count: 2
 This is count: 3
 This is count: 4

 Done! Instead of count = count+1, this increments the counter, we can use count++

Comments

Popular Posts