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
Expand|Select|Wrap|Line Numbers
- if month is October
- then write "new term"
- if month is June
- then write "exams!"
a)
Expand|Select|Wrap|Line Numbers
- if mark is greater than or equal to 40
- then write "pass"
- else write "fail"
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)
Expand|Select|Wrap|Line Numbers
- if (mark>=40)
- System.out.println("pass");
- else System.out.println("fail");
Expand|Select|Wrap|Line Numbers
- if (mark>=70)
- System.out.println("brilliant");
- else if (mark>=40)
- System.out.println("pass");
- else System.out.println("fail");
< <= > >= == !=
A program using Scanner to read data from the keyboard and if-then-else:
Expand|Select|Wrap|Line Numbers
- 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");
- }
- }
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
Expand|Select|Wrap|Line Numbers
- 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");
- }