Program Structures
Structured programming has only three structures:
Sequence, Selection and Iteration.
Selection allows choice of paths in program.
The if statement
if (condition)
then operation
e.g. in pseudo code
-
if month is October
-
then write "new term"
-
if month is June
-
then write "exams!"
This may be extended to include an else clause:
a)
-
if mark is greater than or equal to 40
-
then write "pass"
-
else write "fail"
To take this further:
b) [code]
if mark is greater than or equal to 70
then write "brilliant"
else if mark is greater than or equal to 40
then write "pass"
else write "fail" [code]
Indentation: line else up with corresponding if.
Indentation makes meaning clear. Else is lined up to match the if that it belongs to.
Assume that mark is int
a)
-
if (mark>=40)
-
System.out.println("pass");
-
else System.out.println("fail");
b)
-
if (mark>=70)
-
System.out.println("brilliant");
-
else if (mark>=40)
-
System.out.println("pass");
-
else System.out.println("fail");
The comparison operators are:
< <= > >= == !=
A program using Scanner to read data from the keyboard and if-then-else:
- import java.util.*;
-
-
public class Ifmarks
-
{
-
public static void main(String args[])
-
{
-
Scanner keyboard=new Scanner(System.in); // open Scanner
-
final int PASS = 40;
-
final int DISTINCTION = 70;
-
System.out.print("type a mark: ");
-
int mark = keyboard.nextInt(); //read an integer
-
if (mark>=DISTINCTION)
-
System.out.println(" brilliant");
-
else if (mark>=PASS)
-
System.out.println(" pass");
-
else System.out.println(" fail");
-
}
-
}
Here we also see the use of constants: if a value will not change it may be declared as a constant which, by convention, are written in upper case. This has the advantage that if a constant changes (such as the distinction mark above) it need only be changed once rather than having to edit multiple occurances in a large program.
More than one statement can be placed on a branch of an if by including in {}. e.g. assuming that i is int indicate if it 0, positive or negative and if negative change its sign
-
if (i<0)
-
{
-
System.out.println("i is negative, inverting");
-
i=-i;
-
}
-
else
-
if (i==0) System.out.println("zero");
-
else
-
{
-
System.out.println("i is positive");
-
System.out.println("no change");
-
}
-
The else is lined up with corresponding if and the {} are lined up vertically