0% found this document useful (0 votes)
56 views

Control Flow and Decision Making Statement (Module 3) - 110945

Uploaded by

carterhiney10
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Control Flow and Decision Making Statement (Module 3) - 110945

Uploaded by

carterhiney10
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

MODULE 3:

CONTROL FLOW AND DECISION MAKING STATEMENT

Objectives

i. Understand and explain the use of if, if-else, if-else-if, and switch statements in Java.
ii. Write Java programs that make decisions using if, if-else, if-else-if, and switch
statements.
iii. Identify and correct errors in Java programs using selection statements.
iv. Apply selection statements to solve real-world problems.

Control Statement

Control statements are important building blocks in every programming language. They let a
programmer to control the flow of a program's execution, allowing activities to be performed
conditionally and repeatedly. In Java, control statements are divided into three types:

1. Selection Statements: These are used to switch between distinct execution routes based
on criteria. The most common selection statements in Java are if, if-else, if-else-if, and
switch.

Key Selection Statements:


if Statement: This is the simplest form of selection statement. It evaluates a boolean
expression and executes a block of code if the expression evaluates to true.
if (condition) {
// code to be executed if condition is true
}
if-else Statement: This extends the if statement to execute a block of code if the
conditionis false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
if-else-if Ladder: This is used when you need to check multiple conditions.
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
switch Statement: This is used when you have a variable that can have multiple possible
values and you want to execute different code blocks based on the value.
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases
default:
// code to be executed if no cases match
}

2. Iteration Statements: These enable the repeating running of a block of code. For, while,
and do-while loops are among the most used iteration statements in Java.

3. Jump Statements: These allow the software to navigate to another section of the
program. Java has break, continue, and return statements for this purpose.

Importance of Selection Statements

Selection statements, often known as conditional statements, are critical decision-making tools
within programs. They let a program to behave differently under different conditions, resulting in
more dynamic and adaptable code. Let's go into the details of why selection statements are
important:

1. Decision-Making: Selection statements enable programs to make judgments based on


specific circumstances. For example, if a user enters a certain value, the software can
reply by executing several blocks of code.

2. Flow Control: Selection statements allow a programmer to regulate the course of


execution within a program. This implies that the software may take several pathways
and execute alternative code blocks, making it more adaptable and capable of dealing
with varied conditions.

3. Error Handling: Selection statements are frequently used in mistake detection and
treatment. For example, before completing an action, a program can check whether
certain criteria are satisfied, and if not, it can take a different path to handle the issue or
offer feedback to the user.

4. User Interaction: In applications that need user input, selection statements aid in
verifying and processing the data. Depending on the input, several actions can be
conducted, making the application more interactive and user-friendly.

5. Efficiency: By directing the flow of execution to the relevant parts of the program,
selection statements can help in optimizing the performance. They ensure that only
necessary code blocks are executed, thus saving computational resources.

Overview of Selection Statements

The if Statement: The if statement is the most basic form of a selection statement. It
evaluates a boolean expression and, if it is true, executes the corresponding block of
code.
Syntax:
if (condition) {
// code to be executed if condition is true
}
Example: Write a java program to show if a person is eligible to vote.

Hint: given age>=18


In this example, the program checks if the age is 18 or older. If the condition is true, it prints a
message indicating that the person is eligible to vote.

The if-else Statement: The if-else statement extends the if statement by including an alternate
block of code that will be run if the condition is false.

Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
In this example, the program prints a different message depending on whether the age is 18 or
older.

The if-else-if Ladder: The if-else-if ladder is used to examine various conditions. It allows the
software to select one of several alternative execution pathways.

Syntax:

if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
Example:

Write a java program that reads a score and prints the corresponding grade based on the following
examination scores

Scores Grade

70-100 A

60-69 B

50-59 C

45-49 D

<45 F
This example assigns a grade based on the value of score.

The switch Statement: The switch statement is used to run one block of code from among many
based on the value of an expression. It is an alternative to utilizing numerous if-else-if statements
and can improve code readability when dealing with various situations.

Syntax:

switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
// more cases
default:
// code to be executed if none of the cases match
}
Example:

int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
In this example, the program prints the day of the week based on the value of day.

Loop
While loop: The while loop in Java is a fundamental control flow statement that facilitates the
repeated execution of a block of code as long as a specified boolean condition remains true. This
type of loop is particularly useful when the number of iterations is not predetermined and
depends on dynamic conditions during runtime.

Syntax

The basic syntax of a while loop is as follows:

while (condition) {
// code block to be executed
}
Explanation of Components
1. Initialization: Any required initialization for variables that control the loop can be done
before entering the while loop. This setup is crucial to ensure that the condition can be
correctly evaluated right from the start.
2. Condition: The condition is a boolean expression evaluated before each iteration of the
loop. If the condition evaluates to true, the loop body is executed. If it evaluates to false,
the loop terminates, and control passes to the next statement following the loop. This pre-
condition check makes while loops ideal for scenarios where the number of iterations is
unknown beforehand.
3. Code Block: The code block inside the {} braces is the body of the loop. This block
contains the statements that need to be executed repeatedly. It is crucial to include logic
within this block that influences the condition to eventually become false; otherwise, the
loop may run indefinitely.
4. Update: Typically, within the loop body, there will be statements that modify the
variables involved in the condition, ensuring progress toward terminating the loop. This
is often done through increment or decrement operations.
Basic Example
Here’s a simple example demonstrating a while loop that prints numbers from 1 to 5:
Example 2
The do-while Loop

The do-while loop in Java is a control flow statement that repeatedly executes a block of code at
least once, and then continues to execute the block as long as a specified boolean condition
remains true. Unlike the while loop, the do-while loop ensures that the code block is executed at
least once before the condition is tested.

Syntax

The basic syntax of a do-while loop is as follows:

do {

// code block to be executed

} while (condition);
Explanation of Components

1. Initialization: Any required initialization for variables used in the loop can be done
before entering the do-while loop. This setup is crucial to ensure that the condition can be
correctly evaluated in subsequent iterations.

2. Code Block: The code block inside the {} braces is the body of the loop. This block
contains the statements that need to be executed repeatedly.

3. Condition: The condition is a boolean expression evaluated after each iteration of the
loop. If the condition evaluates to true, the loop body is executed again. If it evaluates to
false, the loop terminates, and control passes to the next statement following the loop.

For example:1

public class DoWhileExample1 {

public static void main(String[] args) {

int i = 1; // Initialization

do {

System.out.println(i); // Code block

i++; // Update
} while (i <= 5); // Condition

import java.util.Scanner;

example 2:

public class DoWhileExample4 {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int number;

int sum = 0;

do {

System.out.print("Enter a number (0 to stop): ");

number = scanner.nextInt();

sum += number;

} while (number != 0); // Condition

System.out.println("The total sum is: " + sum);

scanner.close();

The for Loop in Java

The for loop in Java is a control flow statement that allows code to be executed repeatedly based
on a given boolean condition. It is particularly useful when the number of iterations is known
beforehand. The for loop provides a concise way to initialize a variable, test a condition, and
increment or update the variable, all in one line.

Syntax

The basic syntax of a for loop is as follows:

for (initialization; condition; update) {

// code block to be executed

Explanation of Components

1. Initialization: This part is executed once at the beginning of the loop. It typically
initializes the loop control variable(s).

2. Condition: The condition is evaluated before each iteration of the loop. If the condition
evaluates to true, the loop body is executed. If it evaluates to false, the loop terminates.
3. Update: This part is executed after each iteration of the loop. It typically updates the loop
control variable(s).

Example 1: Simple for Loop

This example demonstrates a basic for loop that prints numbers from 1 to 5.

public class ForLoopExample1 {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) { // Initialization, condition, and update

System.out.println(i); // Code block

public class ConditionExpr {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) { // Outer loop

for (int j = 1; j <= 5; j++) { // Inner loop

System.out.print(i + "*" + j + " = " + (i * j) + "\n"); // Print product

System.out.println(); // New line

}
DECLARATION OF STRING &FORMATTING CONSOLE OUTPUT

DECLARATION OF STRING

Syntax

String stringname =new String (“value”);

For example

Note: if you declare a string with the syntax the value are not the same

For example:
The second output which is false in the above output is so because they are not of the same pool.

In java, a string is a sequence of characters that is treated as an object. Strings are immutable, meaning
that once a string is created its value cannot be changed.

WAYS TO DECLARE STRING

There are several ways to declare strings in java

1. Using string literals


2. Using the new keywords
3. Using string concatenation
4. Using string Builder and string Buffer
5. Using the inter()method

USING STRING LITERALS:

Most common ways to create a string is by using string literals. String literals are enclosed within double
quotes””. For example

String greeting= “ Hello world!”;


USING THE NEW KEYWORD

You can also create a string using the new keyword and the string constructor. This is useful when you
want to create a string from other datatypes , such as an array of characters. For example

Char[]charArray= {‘H’, ‘e’,’l’,’l’,’o’};

String greeting =new string(charArray);

USING STRING CONCANTENATION:

You can combine strings using the + operator. This is known as string concatenation. For example

String firstName=”John”;

String lastName=”Doe”;

String fullName= firstName+””+lastName;//johnDoe

USING STRING BUILDER AND STRING BUFFER:

These classes provides methods for dynamically building and modifying strings. They are useful when
you need to perform a series of string operations, as they can be more efficient than repeated
concatenating string. String Builder is non- synchronized, while string Buffer is synchronized.

For example:

StringBuilder sb+ newStringBuilder();

Sb.append(“Hello”);

Sb.append(“,”);

Sb.append(“world!”);

String greeting =sb.to String();//”Hello, world!”

USING THE INTERN()METHOD: The intern()method returns a canonical representation for the string
object . it checks if the String pool and if so , if so it returns the pooled instance . if the string does not
exist in the pool, it is added to the pool; and the reference to the pooled instance is returned

For example

String s1= “Java”;

String s2= new String (“java”):

System.out.println(s1==s2);//false

System.out.println(s1==s2.intern());//true

Strings in java are not primitive types they are object types and are one of the most powerful types in
java.

METHODS THAT CAN BE USED ON STRINGS


For example:

Note: plus sign is used to concatenate(to add together).


Formatted String

Formatted specifiers

% s= String.

%d = integer (short or long)

%c =character

%b = Boolean.

TO CHECK FOR THE LENGTH OF A STRING

In the example above , to print the length of the name which is Ekundayo Oluwasayo. To do this we
have Ekundayo is of length 8 the space is 1 and the last which is oluwasayo is of length 9, there for we
have 8+1+9=18 as seen above.

TO CHECK IF A STRING IS EMPTY OR NOT

If a string is empty it returns false otherwise it returns true.

For example:
The example below test if the string is empty
CONVERSION OF A STRING FROM UPPERCASE TO LOWERCASE OR FROM LOWERCASE TO UPPERCASE

The example changes the name given, which is Ekundayo Oluwasayo to Upper case
Then let’s try for lowercase as well
TO REPLACE A STRING

You might also like