0% found this document useful (0 votes)
13 views21 pages

Lecture 4

The document explains control statements in programming, focusing on sequential execution, selection, and repetition. It details the use of if, if-else, and switch statements for selection control, as well as while, do-while, and for loops for repetition control in Java. Examples are provided to illustrate the syntax and functionality of these control structures.

Uploaded by

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

Lecture 4

The document explains control statements in programming, focusing on sequential execution, selection, and repetition. It details the use of if, if-else, and switch statements for selection control, as well as while, do-while, and for loops for repetition control in Java. Examples are provided to illustrate the syntax and functionality of these control structures.

Uploaded by

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

Control Statements

Statements in a program, normally execute one after the other in the order in which they are
written. This is called sequential execution. However this sequential execution can be altered by
transferring control. The three control structures are:
• sequence,
• selection and
• repetition.
Selection
This is achieved using the if…, if…else or switch selection statement.
The if… selection statement
The if selection statement is a single-selection statement because it selects or ignores a single
action depending on whether a condition is true or not. The syntax is as follows:
if ( expression )
Statement(s);

true
If……
false

Statement(s)
Consider this example:

import java.util.Scanner;
//program to demonstrate the use of if statement
public class ifStatementDemo
{
public static void main (String[] args)
{
int score;
System.out.println("Enter score");
Scanner inputValue = new Scanner (System.in);
score = inputValue.nextInt();
if(score >= 40)
System.out.println("you passed");
}
}
Some if… statements can be nested. An if… statement can be nested if it is contained within 1 or 2 if statements. The next example shows a nesting of
if statements, it is a program designed to compute the grade of a student given the score attained.

import java.util.Scanner;
public class DisplayText //program file name is Calculator.java
{
public static void main (String[] args)
{
char grade;
int score;
System.out.println("Please enter your score \n");
Scanner inputValue = new Scanner (System.in);
score = inputValue.nextInt();
if (score >=40)
{
grade = 'E';
if (score > 44)
{
grade = 'D';
if (score > 49)
{
grade = 'C';
if (score > 59)
{
grade = 'B';
if (score > 69)
{
grade = 'A';
}
}
}
}
}
}
}
If…else Selection Statement

The if…else selection statement is a double-selection statement because it selects between two different actions. If the
condition is satisfied the first statement or block of statements is executed otherwise the second statement or block of
statements is executed. The syntax is as follows:
if (expression)
{
Statement_1;
Statement_2;
. true
. If……
. false
Statement_n;
}
else
{ Statement(s) Statement(s)
Statement_1;
Statement_2;
.
.
.
Statement_n;
}
Next is a program to show the use of the if...else statement:

if (score > =40)


{
System.out.println("Congratulations you Passed!");
}
else
{
System.out.println("Sorry you failed!");
}
import java.util.Scanner;
//program to demonstrate the use of if statement
public class ifElseDemo
{
public static void main (String[] args)
{
int score;
System.out.println("Enter score");
Scanner inputValue = new Scanner (System.in);
score = inputValue.nextInt();
if(score >= 40)
System.out.println("you passed");
else
{
System.out.println("Sorry, you failed");
System.out.println("You must take this course again");
}
}
}
Nested if…else statements provides multiple selection by placing if…else statements within other if…else statements. The example
code below shows a nested if…else statement. The program is designed to compute the grade of a student given the score attained.
if (score < 40)
grade = 'F';
else
{
if (score <45)
grade = 'E';
else
{
if (score <50)
grade = 'D';
else
{
if (score <60)
grade = 'C';
else
{
if (score <70)
grade = 'B';
else
{
grade = 'A';
}
}
}
}
}
Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte,
short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long.

Points to Remember
 There can be one or N number of case values for a switch expression.

 The case value must be of switch expression type only. The case value must be literal or constant. It doesn't allow variables.

 The case values must be unique. In case of duplicate value, it renders compile-time error.

 The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.

 Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch
expression. If a break statement is not found, it executes the next case.
 The case value can have a default label which is optional.
Switch Statements
We try to find a match (i.e. the only comparison operator used is ==). Execution does not break out once a
match is found like in the ‘if’ statement. We break out with a break statement. If this is not done the
compiler goes through all the cases.
switch(test_value)
{
case value_1:
statements;
break;
case value_2:
statements;
break;
.
.
.
case value_n:
statements;
break;
default:
statements;
}
The default statement is equivalent to the else catch all without a Boolean expression so that if none of the
preceding cases is executed then the default case will. The following code is an example showing how the
switch statement can be used.

Scanner inputValue = new Scanner (System.in);


int x;
System.out.println("Enter a positive integer less than 5");
x = inputValue.nextInt();
switch (x)
{
case 1:
System.out.println("x is 1");
break;
case 2:
System.out.println("x is 2");
break;
case 3:
System.out.println("x is 3");
break;
case 4:
System.out.println("x is 4");
break;
default:
System.out.println("value of x is out of range");
break;
}
Java Switch Statement is fall-through
The Java switch statement is fall-through. It means it executes all statements after the first match if a break statement
is not present.
Example:
//Java Switch Example where we are omitting the
//break statement
public class SwitchExample2 {
public static void main(String[] args) {
int number=20;
//switch expression with int value
switch(number){
//switch cases without break statements
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Repetition
This is achieved using loops. Loops repeat a statement a certain number of times or while a
condition is fulfilled. In Java we have 3 types of loops:
• while,
• do…while and the
• for loop.
false
true
If……

Statement(s)
The while loop
The syntax for the while loop is:

while (Expression)
Statement;

Or

while (Expression)
{
Statement_1;
Statement_2;
.
.
.
Statement_n;
}
We will take an example which would require a loop to execute. We want to
add all integers from 1 to 50.

int x = 1;
int sum = 0;
while (x <= 50)
{
sum = sum + x;
x++;
}
System.out.printf("the sum of integers from 1 to 50 is %d\n", sum);
The do…while
The syntax is as follows:
do
{
Statement
}
while (expression);
Example

Scanner inputValue = new Scanner (System.in);


final int SENTINEL = -1;//flag value, -1 is constant
int num_of_courses = 0;
int grade = 0, total = 0; //variables to score each grade and total grade
do
{
System.out.printf("Enter grades or %d to quit\n", SENTINEL);
grade = inputValue.nextInt(); //reads and stores input value
total = total + grade;
num_of_courses++;
}
while (grade != SENTINEL);
double average = total++/(num_of_courses - 1);
System.out.printf("Average grade obtained is: %f", average);
The For Loop

A for loop is preferred for count controlled loops. Its syntax is:

for (initialization; test_expression; increment/decrement)


{
Statement(s);
}
Example

Scanner inputValue = new Scanner (System.in);


int num_of_stars;
System.out.println("Enter the number of stars: \n");
num_of_stars = inputValue.nextInt();
for( int i=1; i<=num_of_stars; i++)
{
System.out.print("*");
}

The output is as follows:


Enter the number of stars:

7
*******
Example on nested for loops

import java.util.Scanner;
public class DisplayTriangle //program file name is DisplayTriangle.java
{
public static void main (String[] args)
{
Scanner inputValue = new Scanner (System.in);
int n;
System.out.println("Enter number of stars at the base of the triangle: \
n");
n = inputValue.nextInt();
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
}
}
The output is:
*
**
***
****
*****
******
*******

You might also like