0% found this document useful (0 votes)
8 views13 pages

Control Structures

Uploaded by

solomonmukhobe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views13 pages

Control Structures

Uploaded by

solomonmukhobe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Control Structures

Control structures determine the flow of program execution. By default statements inside your source files
are generally executed from top to bottom, in the order that they appear. Control structures (Control flow
statements), however, break up the flow of execution by employing decision making, looping, and
branching, enabling your program to conditionally execute particular blocks of code. This section describes
the types of control structures:

• Sequence
• Selection/decision-making statements (if switch),
• Iterations (looping statements) -for, while, do-while

Selection/Decision Structure

The if Statement

The if statement is the most basic of all the control flow statements. It tells your program to execute a
certain section of code only if a particular test evaluates to true. For example, the Bicycle class could
allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible
implementation of the applyBrakes method could be as follows:

Example

void applyBrakes() {
// the "if" clause: bicycle
// must be moving
if (isMoving){
// the "then" clause: decrease
// current speed
currentSpeed--;
}
}

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if
statement.

49 |
In addition, the opening and closing braces are optional, provided that the "then" clause contains only one
statement:

void applyBrakes() {
// same as above, but
// without braces
if (isMoving)
currentSpeed--;
}

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more
brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to
add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.

Example 2
int age
if (age>=18)
{
System.out.println(“adult”);
}

The if-else Statement

The if else statement provides a secondary path of execution when an "if" clause evaluates to false.
You could use an if else statement in the applyBrakes method to take some action if the brakes are
applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating
that the bicycle has already stopped.

void applyBrakes() {
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has " +"already stopped!");
}
}

50 |
Example
int age
if (age>=18)
{
System.out.println(“adult”);
}
else
System.out.println(“child”);

If- else if – else statement

This is applicable where there are more than two statements to choose from.

Syntax
If (condition1)
Statement1;
else if(condition2)
Statement2;
else if(condition3)
Statement3;
.
.
.
.
else
Statement n;

The following program assigns a grade based on the value of a test score: an A for a score of 90% or above,
a B for a score of 80% or above, and so on.
class IfElseIFDemo {
public static void main(String[] args) {

int testscore = 76;


char grade;

51 |
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

The output from the program is:

Grade = C

You may have noticed that the value of testscore can satisfy more than one expression in the compound
statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are
executed (grade = 'C';) and the remaining conditions are not evaluated.

Switch Statement

Another way to control the flow of your program is with a switch statement. A switch statement gives you
the option to test for a range of values for your variables. They can be used instead of long, complex if …
else if statements. The structure of the switch statement is this:

switch ( variable_to_test ) {
case value1:
code_here;
break;
case value2:
code_here;
break;
default:
values_not_caught_above;
52 |
}

So you start with the word switch, followed by a pair of round brackets. The variable you want to check
goes between the round brackets of switch. You then have a pair of curly brackets. The other parts of the
switch statement all go between the two curly brackets. For every value that you want to check, you need
the word case. You then have the value you want to check for:

case value:

e.g

case 1:
case 2:
case 3:
case ‘a’:
case ‘b’:

case “Kenya”:
case “Uganda”

After case value comes a colon. You then put what you want to happen if the value matches. This is your
code that you want executed. The keyword break is needed to break out of each case of the switch
statement.

The default value at the end is optional. It can be included if there are other values that can be held in your
variable but that you haven't checked for elsewhere in the switch statement.

Example:

53 |
The first thing the code does is to set a value to test for. Again, we've set up an integer variable and called it
user. We've set the value to 18. The switch statement will check the user variable and see what's in it. It
will then go through each of the case statements in turn. When it finds one that matches, it will stop and
execute the code for that case. It will then break out of the switch statement.

Try the programme out. Enter various values for the user variable and see what happens.

Sadly, you can't test for a range of values after case, just the one value. So you can't do this:

case (user <= 18):

But you can do this:

case 1: case 2: case 3: case 4:

So the above line tests for a range of values, from 1 to 4. But you have to "spell out" each value. (Notice
where all the case and colons are.)

To end this section on conditional logic, try these exercises.

54 |
Example
class switchTest2{
public static void main(String arg[])
{
int num;
num=3;
switch(num)
{
case 1:
System.out.println("Number=1");
break;

case 2:
System.out.println("Number=2");
break;
case 3:
System.out.println("Number=3");
break;

case 4:
System.out.println("Number=4");
break;
case 5:
System.out.println("Number=5");
break;
default:
System.out.println("No match for your number");
}
}
}

Example : shows how a statement can have multiple case labels. The code example calculates the number
of days in a particular month:

class SwitchDemo2 {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
55 |
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}

Exercise
Write a programme that accepts user input from the console. The programme should take a number and
then test for the following age ranges: 0 to 10, 11 to 20, 21 to 30, 30 and over. Display a message in the
Output window in the following format:

user_age + " is between 21 and 30"

So if the user enters 27 as the age, the Output window should be this:

If the user is 30 or over, you can just display the following message:

"Your are 30 or over"

56 |
Help for this exercise

To get string values from the user, you did this:

String age = user_input.next( );

But the next( ) method is used for strings. The age you are getting from the user has to be an integer, so you
can't use next( ). There is, however, a similar method you can use: nextInt( ).

Exercise
If you want to check if one String is the same as another, you can use a Method called equals.

String user_name = "Bill";

if ( user_name.equals( "Bill" ) ) {
//DO SOMETHING HERE
}

In the code above, we've set up a String variable and called it user_name. We've then assigned a value of
"Bill" to it. In between the round brackets of IF we have the variable name again, followed by a dot. After
the dot comes the word "equals". In between another pair of round brackets you type the string you're
trying to test for.

NOTE: When checking if one string is the same as another, they have to match exactly. So "Bill" is
different from "bill". The first has an uppercase letter "B" and the second has a lowercase "b".

For this exercise, write a program that asks a user to choose between four colours: black, white, red, or
blue. Use IF … ELSE IF statements to display one of the following messages, depending on which colour
was chosen:

BLACK "You must be a Goth!"


WHITE "You are a very pure person"

57 |
RED "You are fun and outgoing"
BLUE "You're not a Chelsea fan, are you?"

When your programme ends, the Output window should look like something like this:

Loops
The purpose of loop statements is to repeat Java statements a given number of times until certain conditions occur. A
programming loop is one that forces the program to go back up again. If it is forced back up again you can execute
lines of code repeatedly.There are three kinds of loop statements in Java.

While loop
The while statement continually executes a block of statements while a particular condition is true. Its
syntax can be expressed as:

while (expression)
{
statement(s)
}
NB: In while loot, the test is done at the start.ie test then execute.

The while statement evaluates expression, which must return a boolean value. If the expression evaluates
to true, the while statement executes the statement(s) in the while block. The while statement continues
testing the expression and executing its block until the expression evaluates to false. Using the while
statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo
program:

class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
58 |
System.out.println("Count is: " + count);
count++;
}
}
}

You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}

Do while

The Java programming language also provides a do-while statement, which can be expressed as follows:

do {
statement(s)
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the bottom of the
loop instead of the top. Therefore, the statements within the do block are always executed at least once, as
shown in the following DoWhileDemo program:

class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}

Example :

class DoWhileTest{

public static void main(String arg[])

int count=1;
59 |
do

System.out.println("Hello number :"+count);

count++;

} while(count<=5);

System.out.println("End of Hello!!");

For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:

The syntax of a for loop is:


for(initialization; Boolean_expression; update)
{
//Statements
}

Here is the flow of control in a for loop:


1. The initialization step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false,
the body of the loop does not execute and flow of control jumps to the next statement past the for
loop.
3. After the body of the for loop executes, the flow of control jumps back up to the update statement.
This statement allows you to update any loop control variables. This statement can be left blank, as
long as a semicolon appears after the Boolean expression.
4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then update step,then Boolean expression). After the Boolean
expression is false, the for loop terminates.

60 |
Example:
public class Test {
public static void main(String args[]){

for(int x = 10; x < 20; x = x+1)


{
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

This would produce following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

61 |

You might also like