You are on page 1of 11

CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala

Instructor: Ahmed Bashir Decisions

Control Structures
There are mainly three steps involved in a computer program.
1. Input
2. Processing
3. Output

A computer can process a program in one of three ways:


 In sequence – this is what we have been doing so far
 By making a selection or a choice, which is also called a selection/decision/branch.
 By repetition, executing a statement over and over again.
We are now familiar with a Sequential structure i.e. statements executes in a sequence one after the other. We
have been writing programs in which statements are executed in a sequence i.e. if there are 50 lines of code they
will be executed in a sequence one after the other. There is no capability of making a selection. For example,
execute line 4 – 10 on some condition etc.

Various Java statements, which we’ll soon discuss, enable you to specify that the next statement to execute is
not necessarily the next one in sequence. This is called transfer of control.

In this lecture, we will try to understand what selection means.

Decisions

We, as a human, make decisions every day. These decisions may include small scale or large scale decisions.
For example, we take an umbrella with us if it is raining outside.
How do we make decision in this case?
1. We ask ourselves a question i.e. Is it raining outside?
2. To find the answer, we use some means to check the weather condition outside, maybe by actually
looking outside, checking the weather on smartphone etc.
3. We get an answer in the form of YES or NO.
4. Based on this answer, we decide our action. In our example, there are two main actions:
a. In case of raining, take an umbrella.
b. Otherwise, don’t take an umbrella.
So, we normally take these steps to make a decision. Can we enable the computer to make such decisions based
on condition(s)?

CS-114 Lecture Handout Page 1


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Coffee Making Machine and Decisions

You have seen such Coffee making machine in


café. As you can see in the picture, there are 8
buttons with different labels(types) of coffees
e.g. Latte, Espresso, Mocha, Cappuccino etc.
What happens when you press on the button
with label Espresso?
The disposable coffee cup fills with Espresso. It
does not fill any other coffee. How the machine
makes decision? How it decides to make
Espresso when that particular button is pressed?
This all is possible due to programming. The
machine is programmed to make decision i.e.
when X button is pressed make X type of coffee
and not any other type of coffee. Or we can put
this in terms of programming like when X
button is pressed execute this piece of code,
when Y button is pressed execute piece of code
associated with Y i.e. when Espresso’s button is pressed the program for making Espresso coffee is executed.
Similarly, when Latte’s button is pressed the program for making Latte coffee is executed which means that the
program associated with the button is executed only, the other programs are not executed (program for making
cappuccino, mocha etc.
What if all code executes sequentially and not conditionally? Things will be messed up if this happens. So, as
discussed earlier execution of program is done in three ways: sequential, selection(decision) and repetition.
Now, we will be focusing on selection(decisions).

CS-114 Lecture Handout Page 2


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Flowchart
Flowcharts graphically represents an algorithm. Flowcharts are very useful in explaining programs.
Flowcharts are independent of the programming language. You use simple, easy to understand terms in
flowchart symbols so that any person can understand the flow and logic of the program.
Following are some flowchart symbols and their purpose:

Symbol Purpose Description

Flow line indicates flow of logic

used to show start / end of a


Terminal
program

used to show input / output


Input/Output
operation

used to show data manipulation


Processing
(expressions, statements)

Decision used to show decision (condition)

used to connect two or more parts


Connector of flow chart when they become
large

CS-114 Lecture Handout Page 3


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Sequential Control Structure Flow Chart

Here, we can easily see that the statements are executed one after another, there are no
branches/decisions/selections. Also, we can easily get an idea about the program that it is calculating profit on
sales.

CS-114 Lecture Handout Page 4


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Selection (Branch/Decision) Control Structure Flow Chart

In selection or decision making flowchart, there will be at least one decision (diamond) symbol.

CS-114 Lecture Handout Page 5


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Before we further proceed, consider the following statements:


1. If it is cold outside, I will wear a coat.
2. If it is raining outside, I will take an umbrella with me.
3. If the obtained marks are greater than 85, then grade is A.
4. If hours worked are less than or equal to 40, then:
wages = rate * hours
otherwise,
wages = (rate * 40) + 1.5 * (rate * (hours – 40))

All of these statements contain some condition (written in red) and based on the result of that condition
some action is performed.

In first three statements, we have only one choice of action when the condition is met (true)
but in the 4th statement we have two choices of action. One choice is performed if the condition
is met (true), other choice is performed if the condition is not met (false).
Do you see that the answer to each of these conditions is either true or false?
Yes, those expressions which either evaluate to true or false are called boolean expressions.
Java allow us to program such statements. The first decision making structure Java gives us is if statement.

if Statement (One-Way Selection)


The if statement is used to create a decision structure, which allows a program to have more than one
path of execution. The if statement causes one or more statements to execute only when a boolean
expression is true.
Why is it called One-way selection?
For example, a bank wants to send a notice to a customer if her or his checking account balance falls below the
required minimum balance. That is, if the balance is below the required minimum, the bank should send a
notice to the customer; otherwise, it should do nothing. Similarly, an online shopping website adds shipping
charges if the amount is less than 1000 PKR. Both of these examples involves one-way selection. In Java, one-
way selections are incorporated using if statement.

Syntax:
if ( boolean expression ) {
statement(s) to be executed when logical expression is true
}

Note that if is a keyword followed by a boolean expression also called a condition in parenthesis,
followed by a statement or a set of statements inside curly brackets. The statement(s) is/are executed when the
boolean expression is true. These statements are also called action statements.

CS-114 Lecture Handout Page 6


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Flowchart to show flow of execution of if statement

true
logical
statement(s)
expression

false

Relational Operators
To make decisions, you must be able to express conditions and make comparisons. For example, a bank wants
to send a notice to a customer if her or his checking account balance falls below the required minimum balance.
That is, if the balance is below the required minimum, the bank should send a notice to the customer; otherwise,
it should do nothing. Similarly, an online shopping website adds shipping charges if the amount is less than
1000 PKR. Both of these examples involves some sort of comparison. You can compare items for equality, and
inequality. You can also determine whether one item is greater than another, less than another and so on.

An expression that has a value of either true or false is called a logical (boolean) expression.
The values true and false are called logical (boolean) values. In Java, a condition is represented by
a logical (boolean) expression; conditions are either true or false.

Java provides us relational operators to make comparisons and check for equality/inequality.

Math representation Java representation Description


> > greater than
≥ >= greater than or equal to
< < less than
≤ <= less than or equal to
= == equal to
≠ != not equal to

CS-114 Lecture Handout Page 7


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Precedence of Relational Operators


Relational Operators (order of precedence) Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not Equal to

Code Examples

Program: SimpleIf.java

import java.util.Scanner;

public class SimpleIf{


public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int number = keyboard.nextInt();
if(number>10){
System.out.println("Yes, it is greater than 10");
}
System.out.println("Program Ended");
}//main
}//class

CS-114 Lecture Handout Page 8


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Program: RelationalOperators.java
import java.util.Scanner;

public class RelationalOperators{


public static void main(String[] args){
boolean expression1 = 10 > 4; //true
boolean expression2 = 5 >= 5; //true
boolean expression3 = 4 < 1; //false
boolean expression4 = 5 <= 6; //true
boolean expression5 = 1 != 5; //true
boolean expression6 = 2 == 2; //true
boolean expression7 = 2 == 5; //false
boolean expression8 = 2 != 2; //false

System.out.println("10 > 4 = " + expression1);


System.out.println("5 >= 5 = " + expression2);
System.out.println("4 < 1 = " + expression3);
System.out.println("5 <= 6 = " + expression4);
System.out.println("1 != 5 = " + expression5);
System.out.println("2 == 2 = " + expression6);
System.out.println("2 == 5 = " + expression7);
System.out.println("2 != 2 = " + expression8);
}//main
}//class

CS-114 Lecture Handout Page 9


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Program: PositiveNegative.java

import java.util.Scanner;

public class PositiveNegative{


public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");

int number = keyboard.nextInt();

if(number < 0){


System.out.println(number + " is negative");
}else{
System.out.println(number + " is positive");
}

}//main
}//class

CS-114 Lecture Handout Page 10


CS-114-Programming Fundamentals Lecture # 7 GIFT University, Gujranwala
Instructor: Ahmed Bashir Decisions

Common Errors
1. Using semi-colon after if condition
if(condition);{

2. Using semi-colon after curly bracket

if(condition){

};

3. Using assignment operator instead of equality operator in condition

if(a = b){

System.out.println(“a and b are equal”);


}

Correct Way
if(a == b){
System.out.println(“a and b are equal”);
}

Tip: Always use braces


if( condition ) {

Above way or this way

if( condition )
{

CS-114 Lecture Handout Page 11

You might also like