Basic Programming Presented by: JENELYN R. MIRANDA Control Structures Second Quarter
Learning Objectives 23. Identify the two types of control structures 24. Enumerate the types of decision control structures
Java Statements
Java Control Structures decision control structures (if, else, switch) repetition control structures - loop (while, do-while, for) branching statements (break, continue, return)
Decision Control Structures if Structure if-else Structure if-else if-else Structure switch Statement
If Structure The if-Structure specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true .
If Structure The syntax for the if statement is: if (<condition>) <statement>; or if (<condition>) { <statement>; <statement>; }
If Structure This statement means that if the expression has a true value then the statement included within the if-statement, sometimes called the controlled statement is executed . If the value of the expression is false then the controlled statement is not executed
If Structure It is very important to enclose the <condition> in a pair of parentheses( ), forgetting the parentheses will result into a syntax error. If there are more than one statements included in the if-statement then these statements must be grouped in pair of curly brackets .
If Structure – Example 1 Write a program that determines whether an input integer value is NEGATIVE. Source Code
If Structure – Example 2 Write a program that determines whether the two integers are EQUIVALENT. Source Code
If Structure – Example 3 Write a program that allows the user to input an integer value representing the days of the week. Let 1 represent Monday, 2 Tuesday, 3 Wednesday, and so on. The output of the program should be the day of the week in words. An example is as follows: Input say in numeric form: 7 That day is Sunday! Have a nice day. Source Code
If-Else Structure The syntax for the if statement is: if (<condition>) <statement 1> [else <statement 2>]
If-Else Structure The first to be evaluated is the value of < condition >. If the result of <condition> is True, <statement 1> is executed, otherwise, <statement 2> is executed.
If else Structure – Example Write a program that determines whether a number is POSITIVE or NEGATIVE. Source Code
If-Else If-Else Structure Cascading if-else There are many situations that we need to cascade if-else statements to improve the program structure and make clearer for the user to understand (read).
Cascading if Example Write a program that allows the user to input the day by numeric code. The program then outputs the months in words. Source Code
nested if statement It is possible to include if-else statements within if-else statements . The term used to refer to such construction is called nested if statements . When this situation occurs, you must be sure to use the correct indention . Failure to do so can make understanding a program very difficult to follow.
nested if statement example Write a program that determines if a man is entitled to child benefit and a single parent supplement. A man is entitled a child benefit if he has children and a single parent supplement if he as no spouse. Source Code
Switch Statement The switch statement provides a very useful alternative to multiple if statements . It is used in conjunction with case and default statements.
Switch Statement The syntax for the switch – case statement is as follows: switch (<variable >) { case <value 1>: <statement 1>; [break;] case <value 2>: <statement 2>; [break;] [default: <statement>;] }
Switch Statement There are important things to remember when using a switch-case statement: The expression must always be enclosed within a pair parentheses The expression must evaluate to a whole number (integer); the use of a single precision and double precision floating point values will result to an error. The <variable> is tested if it is equivalent to any of <value 1>, <value 2> and so on. If it is equivalent to <value 1> for example, then <statement 1> will be executed.
Switch Statement There are important things to remember when using a switch-case statement: The break statement is optional . If it is present, it will cause the program to “break” or “jump” out of the switch-case and to execute the next statement following switch-case. If the break is not present, it will cause the program to execute the statement in the following case, i.e. <statement 2> above, causing a waterfall effect. The same applies to the other cases. If the < variable> is not equivalent to any of the values, then it will execute the <statement> in the default case , if it is present
Switch Example Write a program that allows the user to input the day by numeric code. The program then outputs the day in words. Source Code
Exercises 1. Write a program that reads in 3 term grades, compute for the average and determine the equivalent letter grade of the average. The resulting average should be rounded first and must not have a decimal point. If the average is from 96 to 100 the corresponding letter grade is ‘A’; 91 to 95 the grade is ‘B’; 86 – 90 is ‘C’; 81-85 is ‘D’, 76 to 80 is ‘E’; 75 and below is ‘F’.
Exercises 2. You were hired as a programmer by TNT – a phone company. TNT employs a metering scheme in computing the telephone bill. The metering scheme is as follows: Calls made on a weekday between 6:00 AM to 6:00 PM are charged at 2.50 pesos per minute. Calls made at other times during a weekday are charged a discounted rate of 2.00 per minute. Calls made anytime on a weekend are charged a weekend rate of 1.50 pesos per minute. Your job is to write a program that will ask the user to enter the following information: (a) an integer representing the day the call was made, let 1 be Monday, 2 Tuesday and so on, (b) and integer representing the time (in 24 hour format) the call started, (c) an integer representing the length of time or duration of the call in minute (assume that all calls are rounded to the next minute). The rate applied depends on the day the call was made and on the time the call was started. Based on the information entered, the program should print the bill corresponding to the call.
Exercises 3. Write a program that will accept an integer corresponding to a person’s age. Thereafter, your program should print the word “BABY” if the age is up to four years old, “CHILD” if the age is from five up to eleven, “TEENAGER”, if the age is from twelve to nineteen and “ADULT” if the age is from twenty up.
Exercises 4. You’ve been hired as a programmer by SMS – a mobile telecommunications company. You are to write a program that will ask the user to input the number of text messages incurred by its subscribers. The text messaging charge is then computed based on the number of text messages. The charge is zero for the first 200 messages/ Text messages beyond that are charged by 0.5 pesos per message. The program should output the charge incurred.
Exercises 5. Write a program to read in a year and report whether it is a leap year or not.
Exercises 6. Write a program that reads an integer and determines and prints whether it is odd or even.
Exercises 7. If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss he incurred.
Exercises 8. If the ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.
Exercises 9. A library charges a fine for every book returned late. For first 5 days the fine is 50 pesos, for 6-10 days fine is 200 pesos and above 10 days fine is 500 pesos. If you return the book after 30 days your membership will be cancelled. Write a program to accept the number of days the member is late to return the book and display the fine or the appropriate message.
Exercises 10. Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.
Learning Objectives 25. Enumerate the types of repetition control structures
repetition control structures (Loop) While For Do while
Consider the following problem.
Problem 1: Write a program that will output the numbers from 1 to 5. The output should look like: 1 2 3 4 5
This solution solves the problem. However, what will happen if we modify the problem such that we would like to output the values from 1 to 100? 1,000? 1,000,000?
Before we do the correct solution, try to understand the following program first:
Notice, that the two statements, namely: ctr=ctr + 1; System.out.println(ctr); are repeated several times.
They are repeated while ctr is less than or equivalent to 5 . This key idea will allow the program to be rewritten using loops .
What is Loop? A loop is a control structure that allows a statement or a group of statements to be executed several times .
One possible algorithm for the program is as follows: initialize ctr to 1 repeat the following while ctr is less than or equal equivalent to 5 print the value of ctr increment ctr by 1
A loop usually has the following components: initialization condition body of loop change of state
In the case of the algorithm above: initialize ctr to 1 repeat the following while ctr is less than or equal equivalent to 5 print the value of ctr increment ctr by 1 Initialization Body of Loop Condition Body of Loop Statement that changes the content of variable
Types of Loop While Loop For Loop Do While Loop
While Loop
While Loop The while statement continually executes a block of statements while a particular condition is true. The syntax for the while loop is as follows: initialization; while (expression) { statement(s); change of state; }
class WhileDemo { public static void main(String[] args){ int ctr; ctr = 1; while (ctr <= 5) { System.out.println(ctr); ctr++; } } } 1 2 3 4 5 Source Code Output Initialization Body of Loop Condition Change of State
Exercise Consider the While program. What will happen if we remove the initialization ctr = 1 ? This means that the value of ctr is not defined (garbage).
Exercise 2. Consider again the original program. What will happen if we remove the curly brackets enclosing the body of the loop? Infinite Loop
Exercise 3. Consider again the original program. What will happen if the programmer committed a typographical error, such that instead of pressing the less than symbol, the greater than symbol was pressed, i,e., the condition becomes ctr>= 5 ? The body of loop will never be executed
Exercise 4. Consider again the original program. What will happen when there is no ctr++ ? Infinite Loop
Infinite Loop An infinite loop (or endless loop ) is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition , having one that can never be met , or one that causes the loop to start over.
Exercise 5. Write a program that will generate the numbers from 1 to 10
Exercise 5. Write a program that will generate the EVEN numbers from 2 to 20
Exercise 5. Write a program that will generate the numbers from 10 down to 1, i.e., 10, 9, 8, …., 2,1.
The increment (decrement) of variable needs not always 1 . Consider for example the following:
Example 1: Write a program that will print all the odd numbers from 1 to 100.
For Loop The for loop is simply a shorthand way of expressing a while statement . The syntax for the for loop is as follows: for ( initialization ; condition ; change of state ) { statement(s); }
ctr = 1; while (ctr <= 5) { System.out.println(ctr); ctr++; } While Loop for(ctr=1; ctr<=5; ctr++) { System.out.println(ctr); } For Loop
To print numbers from 1 to 100 using a for loop, we can write: class fordemo { public static void main(String[] args){ int counter; for(counter = 1; counter<=100; counter++) { System.out.println("Counter = “ + counter); } } } For Loop
To print numbers from 100 down to 0: class fordemo2 { public static void main(String[] args){ int counter; for(counter = 100; counter>=0; counter--) { System.out.println("Counter = " , counter); } } } For Loop
For Loop The for loop is actually a “more compact” form of the while loop . The loop is executed as follows: perform initialization check the condition if it is true execute the statement(s); , the body of loop; then change the state, and check the condition again if it is false , exit from the loop.
For Loop Note that the while loop contains an initialization step (counter=1), a test step (counter<=5), and an increment step (counter++). The for loop lets you put all three parts onto one line , but you can put anything into those tree parts.
Do While Loop
Do While Loop The while statement may be described as test-before-execute . If the controlling expression is initially zero then the controlled statement is never executed .
Do While Loop The do statement may be described as execute-before-test . It is sometimes called a one-trip-loop referring to the fact that the loop “body” is always executed at least once .
Do While Loop The syntax for a do-while loop is as follows: do { statement(s); change of state; } while (expression);
Do While Loop vs While Loop
class DoWhileDemo1 { public static void main(String[] args) { int counter; counter = 1; do { System.out.println(counter); counter++; } while (counter <=100); } } Do While Loop To print the numbers from 1 to100 using a do while loop.
Do While Loop To print the numbers 100 down to 0: class DoWhileDemo2 { public static void main(String[] args) { int counter; counter = 100; do { System.out.println(counter); counter--; } while (counter >=1); } }
QUESTION: Say that a program is to add up a list of numbers entered by the user from the keyboard . Will a loop be used in this program?
The loop will add each integer the user enters to a sum . A counting loop could do this if we knew how many integers were in the list. But often users don't know this in advance, or would find it annoying to find out.
The idea of a sentinel controlled loop is that there is a special value (the " sentinel ") that is used to say when the loop is done. In the following example, the user will enter a zero to tell the program that the sum is complete.
import java.io.*; class sentinel { public static void main(String[] args) throws Exception { BufferedReader stdin=new BufferedReader( new InputStreamReader(System.in)); int sum=0, num; do { System.out.print("Enter an integer(enter 0 to quit): "); num=Integer.parseInt(stdin.readLine()); sum=sum+num; }while(num!=0); System.out.println("Sum of the integers: " + sum); } } Sentinel Controlled Loop
QUESTION: What would happen if the very first integer the user entered were "0"? The loop body would not execute even once. The program would print out: Sum of the integers: 0
PROBLEM Write a program that will compute and display the sum of the factorials of the numbers from 1 to n, where n is a nonnegative integer given by the user. Ex. If n = 3, then compute 1! + 2! + 3! = 9; thus display 9 If n = 4, then compute 1! + 2! + 3! + 4! = 33; thus display 33
Nested Loop it is possible to have a loop inside a loop, may it be a while, a for or a do while loop. We called this loop as a nested loop .
Problem Use a nested while loop to construct the 10 x 10 multiplication table.
class nestedloop { public static void main(String[] args) { int i,j; i=1; while(i<=10) { j=1; while(j<=10) { System.out.print("\t" + i*j); j++; } System.out.print("\n"); i++; } } }
class nestedloop2 { public static void main(String[] args) { int i,j; for(i=1; i<=10; i++) { for(j=1; j<=10; j++) System.out.print("\t" + i*j); System.out.print("\n"); } } }
class nestedloop2 { public static void main(String[] args) { int i,j; for(i=1; i<=10; i++) { j=1; while(j<=10) { System.out.print("\t" + i*j); j++; } System.out.print("\n"); } }
Summary A loop is a control structure that allows a statement or a group of statements to be executed several times . A loop usually has the following components: initialization condition body of loop change of state
Summary There are three types of loop While Loop For Loop Do While Loop The while statement continually executes a block of statements while a particular condition is true . The while statement may be described as test-before-execute .
Summary The for loop is simply a shorthand way of expressing a while statement . The do loop may be described as execute-before-test . The loop “body” is always executed at least once . In a sentinel controlled loop , there is a special value (the " sentinel ") that is used to say when the loop is done.
Summary It is possible to have a loop inside a loop , may it be a while , a for or a do while loop . We called this loop as a nested loop . An infinite loop (or endless loop ) is a sequence of instructions in a computer program which loops endlessly
Loop Exercises 1. Write a program that accepts a number n and display the sum of even numbers and the sum of odd numbers from 1 to n.
Loop Exercises 1. Write a program that accepts a number n and display the sum of even numbers and the sum of odd numbers from 1 to n.
Loop Exercises 2. Create a program that will ask the user to input the grades of student in a class. Use a sentinel-controlled loop to determine when the program should stop looping. Compute and display the sum and average of these grades.
-Glenda
Learning Objectives 26. Identify the types of branching statements in Java
Branching statements Branching statements allows us to redirect the flow of program execution. Java offers three branching statements: Break Continue Return
Break Statement
Break statement The break statement The continue statement
Break statement Sometimes we need to exit from a loop before the completion of the loop then we use break statement and exit from the loop and loop is terminated. The break statement is used in while loop, do - while loop, for loop and also used in the switch statement.
Continue statement Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement.
Continue statement There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions.
#include <iostream> using namespace std; int main() { int ctr; for (ctr = 1 ; ctr<= 10 ; ctr++ ) { cout << ctr << endl; if (ctr == 2) { //loop will now stop break; } } return 0; } 1 2 Source Code Output
#include <iostream> using namespace std; int main() { int ctr; for ( ctr = 1 ; ctr <= 10 ; ctr++ ) { cout<<"\n"<< ctr << "\t"; if ( ctr == 2 ) { continue; } cout<<"ctr is not 2"; } return 0; } Source Code Output
Continue Statement
Return Statement
Consider the following problem.
Summary
Summary break statement exit control from the loop continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions.