C4 Control Structures Student Copy
C4 Control Structures Student Copy
Objectives
In the previous chapters, you have seen examples of sequential programs,
wherein statements are executed one after another in a fixed order. In this chapter, we will
be discussing control structures, which allows us to change the ordering of how them
statements in our programs are executed. There are two types of control structures. The
first one is decision control structures, which allows us to select section of codes to be
executed and the other one is repetition control structures, which allows us to execute
specific section of codes a number of times.
At the end of the lesson, the students should be able to:
1. Analyze control structures that affect control flow of a program.
2. Write programs that uses simple and complex decision control structures.
3. Demonstrate understanding the syntactical differences of the different types of
decision control structures.
4. Apply various coding guidelines specific to decision and repetition control structures.
5. Identify and describe the components of loops.
6. Differentiate each type of loop.
7. Create programs using the different types of loop.
Introduction
Control structures is considered as the heart of any programming language
because you can create, enhance, modify, and convert simple program into a more
complicated application that makes it efficient, useful, and convenient for the end users. It
is used to have an order of execution of statements in a program.
Control flow instruct the program how to make a decision and how further
processing should proceed on the basis of that decision. Hence, it gets your computer to
start doing some of thinking for you.
There are two types of control structures in java language. The first one is
decision/conditional control structure, which allows your program to select specific
sections of code to be executed and looping/repetition control structures, which allows
your program to execute specific sections of the code a number of times.
if conditional statement
The if-statement specifies that a statement (or block of code) will be executed if
and only if a certain boolean statement is true.
Statement
or
int grade = 68;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}
Coding guidelines:
1. The expression/condition part of a statement should evaluate to a boolean
value. That means that the execution of the condition should either result to a
value of true or false.
2. Indent the statements inside the if-block. For example,
if( expression/condition ){
//statement1;
//statement2;
}
3. Curly braces are required if there are 2 or more statements in an if statement.
Sample Problems:
1. Create a program that will determine if the input value is positive. Get the value from
the user.
import java.util.*;
public class PositiveNum{
do{
try{
System.out.println();
System.out.print("Enter number number: ");
number = Input.nextInt();
}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
}//end of catch block
if (number > 0)
System.out.println("The number " + number + " is
positive");
Output:
2. Create a program that determine if the input value if Even number. Get the value
from the user.
import java.util.*;
public class EvenNumber{
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
int number = 0;
char choice;
if (number %2 == 0)
System.out.println("The number " + number + " is
Even");
Output:
if (expression/condition)
statement;
else True False
Expression/
statement; condition
or
if (/condition){
statement1;
statement2;
Statement Statement
……
}
else {
statement1;
statement2;
……
}
Sample Problems:
1. Create a program that will determine if the input value is positive or negative number.
Get the value from the user.
import java.util.*;
public class PositiveNum{
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
int number = 0;
char choice;
do{
try{
System.out.println();
System.out.print("Enter number number: ");
number = Input.nextInt();
}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
}//end of catch block
if (number > 0)
System.out.println("The number " + number + "
is positive");
else
System.out.println("The number " + number + "
is negative");
Output:
import java.util.*;
public class EvenOdd{
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
int number = 0;
char choice;
do{
try{
System.out.println();
System.out.print("Enter number number: ");
number = Input.nextInt();
}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
}//end of catch block
if (number %2 == 0)
System.out.println("The number " + number + "
is Even");
else
System.out.println("The number " + number + "
is Odd");
Output:
3. Write a program that finds the largest of two numbers from the user input.
import java.util.*;
public class LargestNum{
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
int firstnum = 0;
int secondnum = 0;
Programming Logic and Design using Java Programming
51
char choice;
do{
try{
System.out.println();
System.out.print("Enter number number: ");
firstnum = Input.nextInt();
System.out.print("Enter number number: ");
secondnum = Input.nextInt();
}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
}//end of catch block
Output:
4. The ABC Manufacturing Company plans to give a year - end bonus to each of its
employee. Design and algorithm and flowchart which will compute the bonus of each
employee. Consider the following criteria: If the employee’s monthly salary is less than
10,000.00 pesos, the bonus is 50% of the salary; for employees with salaries greater
than 10,000.00 pesos, the bonus is 1,000.00. Print out the corresponding bonus of the
employee.
import java.util.*;
public class YearEndBonus{
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
Formatter frmtbonus = new Formatter();
Formatter frmtbonus1 = new Formatter();
double monthlysalary= 0;
double bonus= 0;
char choice;
}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
}//end of catch block
Output:
Take note that you can have many else-if blocks after an if-statement. The else-
block is optional and can be omitted. In the syntax shown above, if expression1/condition1
is true, then the program executes statement1 and skips the other statements. If
expression2/condition2 is true, then the program executes statement 2 and skips to the
statements following statement3. If expression1/condition1 and expression2/condition2 is
false, then statement3 will be executed.
Sample Problems:
1. Create a program that will input grade and will display its corresponding equivalent
based on the given table below.
do{
try{
System.out.println();
System.out.print("Enter Grades: ");
grades = Input.nextInt();
}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
}//end of catch block
Output:
2. Design a program that ask the complete name of students, year level and displays the
complete name and status of students based on their year entry number below.
import java.util.*;
public class YearLevel{
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
int yearlevel = 0;
char choice;
do{
cname2 = Input.nextLine();
System.out.println();
System.out.print("Enter Complete Name: ");
cname = Input.nextLine();
try{
//System.out.println();
System.out.print("Enter Year Level: ");
yearlevel = Input.nextInt();
}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
}//end of catch block
if (yearlevel == 1)
{
System.out.println("Welcome " +cname +" to the
Computer Engineering Department");
System.out.println("Your are in a Freshman Status");
}
else if (yearlevel == 2)
{
System.out.println("Welcome " +cname+ " to the
Computer Engineering Department");
System.out.println("Your are in a Sophomore Status");
}
else if (yearlevel == 3)
{
System.out.println("Welcome " +cname +" to the
Computer Engineering Department");
System.out.println("Your are in a Junior Status");
}
else if (yearlevel == 4)
{
System.out.println("Welcome " +cname +" to the
Computer Engineering Department");
System.out.println("Your are in a Senior Status");
}
else
System.out.println("Please Check Your Year Level!");
import java.util.*;
public class VowelConsonant {
public static void main(String[ ] arg){
Scanner Input=new Scanner(System.in);
char choice;
do{
System.out.println();
System.out.print("Enter a character : ");
choice=Input.next( ).charAt(0);
if(choice=='a'||choice=='e'||choice=='i'||choice=='o'
||choice=='u'||choice=='A'||choice=='E'||choice=='I'
||choice=='O'||choice=='U')
{
System.out.println("Entered character "+choice+" is
Vowel");
}
else if((choice>='a'&&choice<='z')||
(choice>='A'&&choice<='Z'))
{
System.out.println("Entered character "+choice+" is
Consonant");
}
else
System.out.println("Entered character " + choice+
" is Not an alphabet");
Output:
Switch Statement
With the switch/case conditional statement, we can simplify some of the tasks that
are long and cumbersome when we use the if / else if / else conditional statements. In
other words, the switch/case statement can be the best substitute command and function
to write a clearer and concise multi-way decision program compared to the messy if / else
if / else conditional statements. The switch construct allows branching on multiple
outcomes. However, this switch/case conditional statements have its own limitation. They
cannot test or evaluate floating point and string values or variables. This further means that
only those variables that are declared as integer or character are the candidates that can
be tested or evaluated by the switch/case conditional statement.
switch(switch_expression ){
case case_selector1:
statement1; //
statement2; //block 1
. . . //
True
break;
Case Block 1
case case_selector2: selector1 break
statements
statement1; //
statement2; //block 2
. . . // False
break;
. . .
default: True
Case Block 1 break
statement1; // statements
selector2
statement2; //block n
. . . //
break;
False
}
True
Case Block 1 break
selectorN statements
False
Default Block
statements
When a switch is encountered, Java first evaluates the switch_expression, and jumps
to the case whose selector matches the value of the expression. The program executes
the statements in order from that point on until a break statement is encountered,
skipping then to the first statement after the end of the switch structure.
If none of the cases are satisfied, the default block is executed. Take note
however, that the default part is optional. A switch statement can have no default block.
Coding guidelines:
1. Deciding whether to use an if statement or a switch statement is a judgment call.
You can decide which to use, based on readability and other factors.
2. An if statement can be used to make decisions based on ranges of values or
conditions, whereas a switch statement can make decisions based only on a
single integer or character value. Also, the value provided to each case
statement must be unique.
Sample Problems:
1. Design a program accept letter and display if it is a Vowel or Consonant using switch
statement.
import java.io.*;
import java.util.*;
public class SampleSwitch
{
public static void main( String[] args ){
Scanner input = new Scanner(System.in);
char letter='a';
boolean vowel = false;
char choice;
do{
try{
System.out.println();
System.out.print("Enter letter: ");
letter = input.next().charAt(0);
}catch(Exception e){
System.out.print("Invalid Input");
}
switch(letter){
case 'a':
case 'A': System.out.println("Your Input character
"+letter+" is Vowel");
break;
case 'e':
case 'E': System.out.println("Your Input character
"+letter+" is Vowel");
break;
case 'i':
case 'I': System.out.println("Your Input character
}//end of main
}//end of class
Output:
Alternate Solution:
import java.io.*;
import java.util.*;
public class VowelConsonantAlternate {
public static void main(String[ ] arg)
{
Scanner input=new Scanner(System.in);
char ch;
int i = 0;
System.out.println();
System.out.print("Enter a character : ");
ch=input.next( ).charAt(0);
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
Programming Logic and Design using Java Programming
62
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : i++;
}
if(i == 1)
System.out.println("Entered character "+ch+" is
Vowel");
else
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println("Entered character "+ch+" is
Consonant");
else
System.out.println("Entered character " +ch +" is not
an alphabet");
}//end of main
}//end of class
Output:
2. Write a program that will allow the user to select a day of the week using the table
below.
import java.io.*;
import java.util.*;
public class DaySwitch{
public static void main(String[ ] arg)
{
Scanner input=new Scanner(System.in);
char choice;
Programming Logic and Design using Java Programming
63
int day = 0;
do{
try{
System.out.println();
System.out.print("Enter number of day: ");
day = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
}//end of catch block
switch (day) {
case 1:
System.out.println("Today is Monday");
break;
case 2:
System.out.println("Today is Tuesday");
break;
case 3:
System.out.println("Today is Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 5:
System.out.println("Today is Friday");
break;
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Invalid Input");
}
System.out.print("Do you want to try Again (Y/N): ");
choice = input.next().charAt(0);
}while ((choice == 'y') || (choice == 'Y'));
System.out.println("\nThank you, Goodbye!");
}//end of main
}//end of class
3. Design a program that generates the ask the Final Grade of students. Display the
equivalent as well as remarks as output based on the following scale.
import java.io.*;
import java.util.*;
public class FinalGrade{
public static void main(String[ ] arg)
{
Scanner input=new Scanner(System.in);
char choice;
int finalgrade = 0;
do{
try{
System.out.println();
System.out.print("Enter Final Grade: ");
finalgrade = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
case 89:
case 88:
case 87:
case 86:
case 85:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
equivalent to 1.75");
System.out.println("Very Statisfactory");
break;
case 84:
case 83:
case 82:
case 81:
case 80:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
Programming Logic and Design using Java Programming
66
equivalent to 2.00");
System.out.println("Very Statisfactory");
break;
case 79:
case 78:
case 77:
case 76:
case 75:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
equivalent to 2.25");
System.out.println("Statisfactory");
break;
case 74:
case 73:
case 72:
case 71:
case 70:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
equivalent to 2.50");
System.out.println("Statisfactory");
break;
case 69:
case 68:
case 67:
case 66:
case 65:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
equivalent to 2.75");
System.out.println("Statisfactory");
break;
case 64:
case 63:
case 62:
case 61:
case 60:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
equivalent to 3.00");
System.out.println("Fair");
break;
case 59:
case 58:
case 57:
case 56:
case 55:
System.out.println("\nYour Final Grade "+
finalgrade);
Programming Logic and Design using Java Programming
67
System.out.println("Your Final Grade is
equivalent to 4.00");
System.out.println("Conditional");
break;
default:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
equivalent to 5.00");
System.out.println("Failed");
break;
}
}
else
{
System.out.println("\nInvalid Grade");
}
System.out.print("Do you want to try Again (Y/N): ");
choice = input.next().charAt(0);
}while ((choice == 'y') || (choice == 'Y'));
System.out.println("\nThank you, Goodbye!");
}//end of main
}//end of class
Output:
initialization
FALSE
condition
Increment /
decrement
TRUE
As you can see, there are three parts of the for loop are the initialization (init) part, the
condition part, and the increment (inc) or decrement (dec) part. The sample of
incrementation formula is i++ or ++i, while the decrementation formula is --i or i--.
Note: The do-while statements execute its body at least once, before evaluating
the condition.
2. Decrementation Formula:
Examples:
i-- or --i
--n or n--
3. Accumulator Formula:
Examples:
acc=acc+n
sum=sum+n
total=total+n
The variable initialization (init) specifies the first value where the loop starts. The
conditional part specifies conditions to be evaluated or tested. If the condition is false, then
no action is taken, and the program pointer proceeds to the next statement after the loop.
If the conditional expression is evaluated to be true, then all the statements within the body
of the loop are executed. This looping process (iteration) is repeated as long as the
conditional expression remains true. After each iteration, the
incrementation/decrementation (inc/dec) part is executed, then the conditional
expression is reevaluated. In a simple for loop statement, the initialization part is executed
only once. This happens during the first time the program pointer points to the loop. But in
nested loop, the inner loop’s initialization part could be re-executed many times depending
on the condition set at the outer loop. This will happen every time the program pointer
reevaluates the condition of the outer loop to T (true).
We'll concentrate our discussion on the straightforward looping statement form for
the benefit of clarity and ease of understanding.
1
2
3
4
5
1 3 5 7 9 11 13 15
First Solution: Using for loop statement
We initialize the variable factorial with the value of 1 so that the computer would
know its first value. To compute the factorial of number (number!) is to multiply the product
of number to its preceding number all over again until the iteration process done by variable
i reaches the value 1. For example, the factorial value of 5 is 120. This is how it is
computed:
5! = 5*4*3*2*1
= 120
This way of computation is best suited with the use of decrementation formula i--
since the iteration process of variable I is to decrease by 1 each time the loop operation is
being performed.
Nested loop
Control structures in Java are statements that contain statements. In instance,
control structures can contain control structures. You have already seen several examples
of if statement inside loops, but any combination of one control structure inside another is
possible. In short, we can say that one structure is nested inside another (loop is within
another loop). The syntax of Java dose not set a limit on the number of levels of
nesting. The nested loop has the form: