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

C4 Control Structures Student Copy

c4

Uploaded by

RK Ordinario
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 views

C4 Control Structures Student Copy

c4

Uploaded by

RK Ordinario
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/ 38

CHAPTER 4 CONTROL STRUCTURES

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.

Decision/Conditional Control Structures


Decision/Conditional control structures are Java statements that allows us to select
and execute specific blocks of code while skipping other sections. There are four type of
decision/condition control structures that programmer can be used namely: If statement, if-
else statement, if-else-if-else statement, and switch statement.

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.

Programming Logic and Design using Java Programming


46
Syntax of if statement:
if (expression/condition)
statement;
or
if (/condition){
statement1; True False
statement2; Expression/
condition
……
}

Statement

Figure 5 Flowchart of if statement

If the expression/condition in the parenthesis evaluate to the boolean true,


statement is executed otherwise the expression/condition evaluates to false wherein no
action will be performed.

For example, given the code snippet,


int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");

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{

Programming Logic and Design using Java Programming


47
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");

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:

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;

Programming Logic and Design using Java Programming


48
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");

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:

If - else conditional statement


In if-else conditional statement, there are two given choices the computer could
make. However, the computer could only choose one of them. It’s like having two
girlfriends, you could only choose one to be with. The formal syntax of if-else is:

if (expression/condition)
statement;
else True False
Expression/
statement; condition

or

if (/condition){
statement1;
statement2;
Statement Statement
……
}
else {
statement1;
statement2;
……
}

Figure 6 Flowchart of if-else statement

Programming Logic and Design using Java Programming


49
Coding guidelines:
1. To avoid confusion, always place the statement or statements of an if or if-else
block inside brackets { }.
2. You can have nested if-else blocks. This means that you can have other if-else
blocks inside another if-else block. For example,
if( expression/condition ){
if( expression/condition ){
...}
} else {
...
}

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");

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:

Programming Logic and Design using Java Programming


50
2. Create a program that determine if the input value if even number or odd number.
Get the value from the user.

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");

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:

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

if (firstnum > secondnum)


System.out.println("The number " + firstnum + "
is greater than "+ secondnum);
else
System.out.println("The number " + secondnum +
" is greater than "+ firstnum);

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:

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;

Programming Logic and Design using Java Programming


52
do{
try{
System.out.println();
System.out.print("Enter monthly salary: ");
monthlysalary = Input.nextDouble();

}catch(InputMismatchException e){
System.out.println("Invalid Input!");
System.exit(0);
}//end of catch block

if ((monthlysalary > 0) && (monthlysalary <= 10000))


{
bonus = monthlysalary * 0.50;
frmtbonus.format("%.2f", bonus);
System.out.println("The bonus of employee is: "
+ frmtbonus);
}
else
{
bonus = 1000;
frmtbonus1.format("%.2f", bonus);
System.out.println("The bonus of employee is: "
+ frmtbonus1);
}

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:

if-else-if else conditional statement


With the use of if / else if / else conditional statements, the computer can decide
to choose one and only one of the given choices. Only those conditional statements and
expression(s) that were first proven true, are the ones to be chosen and its associated
statement(s) will be executed. This cascading of structures allows us to make more
complex selections. The formal syntax of if / else if / else is:

Programming Logic and Design using Java Programming


53
if (expression/condition1)
{
statement1;
statement2;
……
}
else if (expression/condition2)
{
statement1;
statement2;
……
}
else ifn (expression/condition)
{
statement1;
statement2;
……
}
else
{
statement1;
statement2;
……
}

Figure 7 Flowchart of if-else if- else statement

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.

Programming Logic and Design using Java Programming


54
import java.util.*;
public class Grades{
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
int grades = 0;
double equivalent = 0.00;
char choice;

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

if (grades >=98 && grades <=100)


{
equivalent = 1.00;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else if (grades >=95 && grades <=97)
{
equivalent = 1.25;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else if (grades >=91 && grades <=94)
{
equivalent = 1.50;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else if (grades >=88 && grades <=90)
{
equivalent = 1.75;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else if (grades >=85 && grades <=87)
{
equivalent = 2.00;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else if (grades >=82 && grades <=84)
{
equivalent = 2.25;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else if (grades >=79 && grades <=81)
{
equivalent = 2.50;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else if (grades >=76 && grades <=78)
{

Programming Logic and Design using Java Programming


55
equivalent = 2.75;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else if (grades >=75 && grades <=77)
{
equivalent = 3.00;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else if (grades >=0 && grades <=74)
{
equivalent = 5.00;
System.out.println("Your "+ grades + " is equivalent to " +
equivalent);
}
else
System.out.println("Please check your input grades!");

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:

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;

Programming Logic and Design using Java Programming


56
String cname;
String cname2;

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!");

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
Programming Logic and Design using Java Programming
57
Output:

3. Design a program accept letter and display if it is a Vowel or Consonant.

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");

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!");

Programming Logic and Design using Java Programming


58
}//end of main
}//end of class

Output:

Common Errors when using the if-else statements


1. The condition inside the if-statement does not evaluate to a boolean value. For
example,
//WRONG
int number = 0;
if( number ){
//some statements here
}
The variable number does not hold a Boolean value.
2. Using = instead of == for comparison. For example,
//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}

This should be written as,


//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}
3. Writing elseif instead of else if.

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.

Programming Logic and Design using Java Programming


59
The switch statement has an equivalent else conditional statement; it is called
default. It works and accomplishes the same thing. They are also both optional. Meaning,
they can be included or not in our program. If they are not needed or required in the problem
specs, why include them? But again, remember that in our previous examples, the else
statement is very helpful to catch the impossible input data and use also extensively for
data entry validation. The same thing also with the default command, we can use it to catch
some impossible input-data or to validate our data-entry. Here is the switch/case syntax:

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

Figure 8 Flowchart of switch statement

The switch_expression is an integer or character expression and, case_selector1,


case_selector2 and so on, are unique integer or character constants.

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.

Programming Logic and Design using Java Programming


60
NOTES:
• Unlike with the if statement, the multiple statements are executed in the
switch statement without needing the curly braces.
• When a case in a switch statement has been matched, all the statements
associated with that case are executed. Not only that, the statements
associated with the succeeding cases are also executed.
• To prevent the program from executing statements in the subsequent cases,
we use a break statement as our last statement.

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

Programming Logic and Design using Java Programming


61
"+letter+" is Vowel");
break;
case 'o':
case 'O': System.out.println("Your Input character
"+letter+" is Vowel");
break;
case 'u':
case 'U': System.out.println("Your Input character
"+letter+" is Vowel");
break;
default:
System.out.println("Consonant");
}

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:

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

Programming Logic and Design using Java Programming


64
Output:

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);

Programming Logic and Design using Java Programming


65
}//end of catch block
// finalgrade = (midgrade * 0.40) + (finaltengrade*0.60);
if (finalgrade >=0 && finalgrade<=100)
{
switch (finalgrade) {
case 100:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
equivalent to 1.00");
System.out.println("Outstanding");
break;
case 99:
case 98:
case 97:
case 96:
case 95:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
equivalent to 1.25");
System.out.println("Outstanding");
break;
case 94:
case 93:
case 92:
case 91:
case 90:
System.out.println("\nYour Final Grade "+
finalgrade);
System.out.println("Your Final Grade is
equivalent to 1.50");
System.out.println("Very Statisfactory");
break;

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:

Programming Logic and Design using Java Programming


68
Looping/Repetition Control Structures
The Looping/repetition control structures are Java statements that enable program
instructions to repeat a specific block of statements or sequence of statements a
predetermined number of times. The looping or iteration control structures are other names
for the repetition control structure. Looping is the process of repeatedly carrying out a set
of instructions up until a specific condition is attained, satisfied, or established and proven
to be untrue.

The three repetition control structures in Java are:


1. for loop
2. while loop
3. do-while loop

initialization

FALSE
condition

Increment /
decrement
TRUE

Block of code to be executed if


<condition is TRUE>

rest of the code

Figure 9 Flowchart of Looping Control Structures

The syntax of the for loop statement is:

for(initialization; condition; increment/decrement)


{
statemets;//block of code to be executed if condition is 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--.

The syntax of the while statement is:


initialization;
while(condition)
{
statements; //block of code to be executed if condition is true
increment; or decrement;
}

Programming Logic and Design using Java Programming


69
The syntax of the do - while statement is:
initialization;
do
{
statements;//block of code to be executed if condition is true
increment; or decrement;
} while(condition);

Note: The do-while statements execute its body at least once, before evaluating
the condition.

Incrementation, Decrementation, and Accumulator Formulas


These three formulas are often used in looping statements operation:
1. Incrementation Formula:
Examples:
i++ or ++i
++n or n++

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.

Programming Logic and Design using Java Programming


70
Sample Problem 1. Write a java program that generate the given sequence numbers
below:
Sequence Numbers

1
2
3
4
5

First Solution: Using for loop statement

Second Solution: Using while loop statement

Third Solution: Using do-while loop statement

Programming Logic and Design using Java Programming


71
Sample Problem 2. Create a program that will display odd numbers from 1 – 15 using
while statement
Sample Output:

1 3 5 7 9 11 13 15
First Solution: Using for loop statement

Second Solution: Using while loop statement

Third Solution: Using do-while loop statement

Programming Logic and Design using Java Programming


72
Sample Problem 3. Write a program that calculates the sum of the given sequence
numbers.
1 + 2 + 3 +4 + 5 + 6 + 7 + 8 + 9 + 10
First Solution: Using for loop statement

Second Solution: Using while loop statement

Third Solution: Using do-while loop statement

Programming Logic and Design using Java Programming


73
Sample Problem 4. Create a program that will display all the vowels from ‘a’ to ‘z’.
First Solution: Using for loop statement

Second Solution: Using while loop statement

Third Solution: Using do-while loop statement

Programming Logic and Design using Java Programming


74
Sample Problem 5. Create a program that will display all the vowels from ‘a’ to ‘z’.
First Solution: Using for loop statement

Second Solution: Using while loop statement

Third Solution: Using do-while loop statement

Programming Logic and Design using Java Programming


75
Sample Problem 6. Write a program that computes the factorial value of n (as input) and
displays it.
Sample Output:
Enter a number: 5
The factorial value of 5 is 120.
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.

Programming Logic and Design using Java Programming


76
Second Solution: Using while loop statement

Third Solution: Using do-while loop statement

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:

Programming Logic and Design using Java Programming


77
Sample Problem 1. Write a program that will display the following output:
1
22
333
4444
55555
Solve using nested for, while, and do-while statements.
First Solution: Using nested for loop statement

Second Solution: Using nested while loop statement

Third Solution: Using nested do-while loop statement

Programming Logic and Design using Java Programming


78
Sample Problem 2. Write a program that will display the following output:
1
22
123
1234
12345
Solve using nested for, while, and do-while statements.
First Solution: Using nested for loop statement

Second Solution: Using nested while loop statement

Third Solution: Using nested do-while loop statement

Programming Logic and Design using Java Programming


79
Sample Problem 3. Write a program that will display the following output:
55555
4444
333
22
1
Solve using nested for, while, and do-while statements.
First Solution: Using nested for loop statement

Second Solution: Using nested while loop statement

Third Solution: Using nested do-while loop statement

Programming Logic and Design using Java Programming


80
Sample Problem 4. Write a program that will display the following output:
54321
4321
321
21
1
Solve using nested for, while, and do-while statements.
First Solution: Using nested for loop statement

Second Solution: Using nested while loop statement

Third Solution: Using nested do-while loop statement

Programming Logic and Design using Java Programming


81
Sample Problem 5. Write a program that will display the multiplication table of 5 following
output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Solve using nested for, while, and do-while statements.
First Solution: Using nested for loop statement

Second Solution: Using nested while loop statement

Programming Logic and Design using Java Programming


82
Third Solution: Using nested do-while loop statement

Programming Logic and Design using Java Programming


83

You might also like