Вы находитесь на странице: 1из 37

DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Controlling Sequence Structures Using Loops

In the previous unit, we have discussed the concept of control structure wherein there are three types:
sequential, conditional and loop. The two control structures that we have defined are sequential and conditional.
In sequential control structure, statements are executed according to the order of their appearance on the
program, while in conditional control structure; conditions are to be evaluated first before the statements are
executed. In case of if, if-else and switch-case statements, the first line of these statements is the conditional
statement. The conditional statement affects the execution of the statements.

So far, we knew how to write programs that were executed in sequence and program that were
executed in sequence and programs that do different things depending on conditions detected by the program
but for this unit, we will study how to write programs that repeatedly execute a set of statements. We will use the
concept of a loop.

WHAT IS A LOOP?

A loop is a way of repeating lines of code. If you want to for example print Hello on the screen 10 times then you
can either use System.out.println 10 times or you can put 1 System.out.println in a loop that runs 10 times which
takes a lot less lines of code.

Consider first the following problem. Write a program that will output the numbers from 1 to 5. The
output should look like [FRS-DLSU]:

1
2
3
4
5

Using what presented so far, one possible solution to this problem is:

class loop
{
public static void main(String[] args)
{
System.out.println(“1”);
System.out.println(“2”);
System.out.println(“3”);
System.out.println(“4”);
System.out.println(“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? Following the solution above, we need to type in 95 more
System.out.println() statements, i.e., System.out.println(“6”); to System.out.println(“100”). To make the situation
worse, what if we would to output the values from 1 to 1000? Of course, we can still modify the program such
that we will need to have 1000 System.out.println() statements in the program.

Such solution, however, is totally unacceptable. Why?


 It would require a lot of typing (especially if you don’t know how to use copy and paste).
 The program source code will be quite long.
 An experienced programmer will laugh at such solution.

We say that such simple but poorly written solution was conceptualized using a brute-force approach. So
what’s a better way to write the program?

Trainers: William T. Aldana / Glenda D. Balmelero


1
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Before do the correct solution, try to understand the following program first:

class loop
{
public static void main(String[] args)
{
int ctr;

ctr=1;
System.out.println(ctr);

ctr=ctr + 1;
System.out.println(ctr);

ctr=ctr + 1;
System.out.println(ctr);

ctr=ctr + 1;
System.out.println(ctr);

ctr=ctr + 1;
System.out.println(ctr);

}
}

You would probably say that this program is not much better than the simple solution. Moreover, you would
probably comment that it is longer in terms of the source code, and takes more time in the operation. You are of
course right.

Notice, however, that the two statements, namely:


ctr=ctr + 1;
System.out.println(ctr);

are repeated several times. In fact, they are repeated while ctr is less than or equivalent to 5. This key idea will
allow the program to be rewritten using loops. 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 posed above 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 of a variable or of several variables


 condition (that would evaluate to either true or false); the condition check is usually made on the
current value of the variable initialized in (1) above.
 body (which maybe a single statement or a group of statements)
 a change of state which is usually a statement inside the body of the loop that changes the content of
the variable(s).

Trainers: William T. Aldana / Glenda D. Balmelero


2
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

In the case of the algorithm above:

 Initialization is:

initialize ctr to 1

 Condition is:

while ctr is less than or equal equivalent to 5

 Body of the loop is:

print the value of ctr


increment ctr by 1

 Statement that changes the content of variable is:

increment ctr by 1

Incrementing and decrementing

Operator Use Description

Increments op by 1; evaluates to the


++ op++
value of op before it was incremented

Increments op by 1; evaluates to the


++ ++op
value of op after it was incremented

Decrements op by 1; evaluates to the


-- op-- value of op before it was
decremented

Decrements op by 1; evaluates to the


-- --op
value of op after it was decremented

WHAT ARE THE LOOP CONTROL STRUCTURES AVAILABLE IN JAVA?

There are types of loop control structures in Java, namely:

 while loop
 for loop
 do while loop

Trainers: William T. Aldana / Glenda D. Balmelero


3
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

The 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:

while (expression)
{
statement(s);
change of state;
}

The while statement evaluates expression, which must return a boolean value. If the expression
evaluates to true, the while statement executes the statement(s) in the while block. The while statement
continues testing the expression and executing its block until the expression evaluates to false. Using the while
statement to print the values from 1 through 5 can be accomplished as in the following WhileDemo program:

class WhileDemo
{
public static void main(String[] args)
{
int counter;
counter = 1;
while (counter <= 5)
{
System.out.println("Counter is: " + counter);
counter++;
}
}
}

The program can be modified if ever you want to change the range of printed numbers, for example 1 to 100. In
order to do this, all you need to do is to modify the condition, from counter <= 5 change it to counter <= 100.

Exercise:

1. Consider the program above. What will happen if we remove the initialization counter = 1? This means
that the value of counter is not defined (garbage).
2. Consider again the original program. What will happen if we remove the curly brackets enclosing the
body of the loop?
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 counter >= 5 ?
4. Consider again the original program. What will happen when there is no counter++?
5. Write a program that will generate the numbers from 10 down to 1, i.e., 10, 9, 8, …., 2,1.

Trainers: William T. Aldana / Glenda D. Balmelero


4
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

 The increment (decrement) of variable needs not always 1. Consider for example the following:

Example 2: Write a program that will print all the odd numbers from 1 to 100.

class WhileDemo2
{
public static void main(String[] args)
{
int counter;
counter = 1;

while (counter <= 100)


{
System.out.println("Counter = " + counter);
counter=counter + 2;
}
}
}

 Variables are not limited to integers. Consider the following problem:

Example 3: Write a program that will print the values 0.0, 0.2, 0.4, 0.6, 0.8, 1.0.

class WhileDemo3
{
public static void main(String[] args)
{
double counter;

counter = 0.0;
while (counter <= 1.0)
{
System.out.printf("Counter = %.1f \n" , counter);
counter=counter + 0.2;
}
}
}

The for loop

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as
the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied.

The syntax for the for loop is as follows:

for (initialization; condition; change of state)


{
statement(s);
}

Trainers: William T. Aldana / Glenda D. Balmelero


5
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

The for loop is simply a shorthand way of expressing a while statement. For example, suppose you
have the following code:

counter = 1;
while (counter <= 5)
{
System.out.println("Counter is: " + counter);
counter++;
}

You can convert this into a for loop as follows:

for(counter=1; counter<=5; counter++)


{
System.out.println("Counter is: " + counter);
}

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); ,
Example:
 the body of loop;
 then change the state, and
 check the condition again
 if it is false, exit from the 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. For example, suppose you have the following loop:

a=1;
b=6;
while (a<b)
{
a++;
System.out.println(a);
}

You can place this into a for statement as well:

for(a=1, b=6; a<b; a++, System.out.println(a));

It is slightly confusing, but it is possible. The comma operator lets you separate several different statements in
the initialization and increment sections of the for loop(but not in the test section). Many programmers like to
pact a lot of information into a single line of code; but a lot of people think it makes the code harder to
understand, so they break it up.

Trainers: William T. Aldana / Glenda D. Balmelero


6
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Example 4: 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);
}
}
}

Example 5: 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);
}
}
}

The 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. There is an alternative version that is sometimes
useful. This is the do statement which may be described as execute-before-test. This is sometimes
called a one-trip-loop referring to the fact that the loop “body” is always executed at least once.

The syntax for a do-while loop is as follows:

do
{
statement(s);
change of state;
} while (expression);

The statement(s) is always executed at least once. It is sometimes useful in interactive programs when the
user must provide some input and there is no sensible initial setting.

Trainers: William T. Aldana / Glenda D. Balmelero


7
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Example 6: To print the numbers from 1 to100 using a do while loop:

class doloop
{
public static void main(String[] args)
{

int counter;

counter=1; //initialization
do
{
System.out.println("Counter = " , counter); //body of the loop
counter++; //change of state
}
while (counter<=100); //condition
}
}

Example 7: To print the numbers 100 down to 0:

class doloop2
{
public static void main(String[] args)
{

int counter;

counter=100; //initialization
do
{
System.out.println("Counter = " , counter); //body of the loop
counter--; //change of state
}
while (counter>0); //condition
}
}

Trainers: William T. Aldana / Glenda D. Balmelero


8
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

CAN WE INCLUDE A LOOP INSIDE A LOOP?

Just like the other control structures such as sequential and conditional, 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.

Example 8:

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++;
}
}
}

Example 8:

Use a nested for loop to construct the 10 x 10 multiplication table.

class nestedloop
{

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

}
}
}

Trainers: William T. Aldana / Glenda D. Balmelero


9
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Increment & decrement operators

There are 2 Increment or decrement operators -> ++ and --. These two operators are unique in that they can be
written both before the operand they are applied to, called prefix increment/decrement, or after, called postfix
increment/decrement. The meaning is different in each case.

Example

x = 1;
y = ++x;
System.out.println(y);

prints 2, but

x = 1;
y = x++;
System.out.println(y);

prints 1

Source Code

//Count to ten

class UptoTen
{
public static void main (String args[])
{
int i;

for (i=1; i <=10; i++)


{
System.out.println(i);
}
}
}

When we write i++ we're using shorthand for i = i + 1. When we say i-- we're using shorthand for i = i - 1. Adding
and subtracting one from a number are such common operations that these special increment and decrement
operators have been added to the language.

Trainers: William T. Aldana / Glenda D. Balmelero


10
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

There's another short hand for the general add and assign operation, +=. We would normally write this as
i += 15. Thus if we wanted to count from 0 to 20 by two's we'd write:

class CountToTwenty
{
public static void main (String args[])
{
int i;

for (i=0; i <=20; i += 2) //Note Increment Operator by 2


{
System.out.println(i);
}
} //main ends here
}

As you might guess there is a corresponding -= operator. If we wanted to count down from twenty to zero by
twos we could write: -=

class CountToZero
{
public static void main (String args[])
{
int i;
for (i=20; i >= 0; i -= 2) //Note Decrement Operator by 2
{
System.out.println(i);
}
}
}

Trainers: William T. Aldana / Glenda D. Balmelero


11
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Java - Break statement in java

The java programming language supports the following types of controlling statements such as:
1.The break statement
2.The continue statement
3.The return statement

Break: The break statement is used in many programming languages such as c, c++, java etc. 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.

Code of the program :

public class Break


{
public static void main(String[] args)
{
int i,j;

System.out.println("Prime numbers between 1 to 50 : ");

for (i = 1;i < 50;i++ )


{
for (j = 2;j < i;j++ )
{
if(i % j == 0)
{
break;
}
}

if(i == j)
{
System.out.print(" " + i);
}
}
}
}

Output of the program :

C:\myJava>javac Break.java

C:\myJava>java Break
The Prime number in between 1 - 50 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Trainers: William T. Aldana / Glenda D. Balmelero


12
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Java - Continue statement in Java

Continue: The continue statement is used in many programming languages such as C, C++, java etc.
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. 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.

In this program we will see that how the continue statement is used to stop the execution after that.

Here is the code of the program :

public class Continue{


public static void main(String[] args){
Thread t = new Thread();
int a = 0;
try{
for (int i=1;i<10;i++)
{
if (i == 5)
{
continue;
//control will never reach here (after the continue statement).
//a = i;
}
t.sleep(1000);
System.out.println("chandan");
System.out.println("Value of a : " + a);
}
}
catch(InterruptedException e){}
}
}

Output of the program :

If we write the code in the given program like this :


if (i == 5 )
{
continue;
a = i;
}

Then the program will generate a error on compile time like :

C:\myJava>javac Continue.java
Continue.java:12: unreachable statement
a = i;
^
1 error

Trainers: William T. Aldana / Glenda D. Balmelero


13
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

If we write the code in the given program like this :


if (i == 5 )
{
continue;
}

Then the program prints the output like:

C:\myJava>javac Continue.java

C:\myJava>java Continue
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0

Trainers: William T. Aldana / Glenda D. Balmelero


14
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Sentinel Controlled Loops

The previous several units have discussed loops, and counting loops in particular. The same statements that
are used to build counting loops are used to build other kinds of loops. This unit will look at a kind of loop called
a sentinel controlled loop.

Chapter Topics:

1. Sentinel-controlled loops.
2. Example programs: adding up a list of integers, and evaluating polynomials.
3. Using an if-else statement inside the loop body.
4. Matching up if's with else's.
5. Using a String value as a sentinel.

QUESTION 1:

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?

A good answer might be:

Yes; each iteration of the loop will add a new number to the sum.

Program to Add up User-entered Integers

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. (If you
have a column of integers, you would like to add them one by one until you reach the last one. It would be
annoying if you needed to count them first.)

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 this example, the user will enter a zero to tell the program that the sum is complete. The
general scheme of the program is given below:

import java.io.*;

// Add up all the integers that the user enters.


// After the last integer to be added, the user will enter a 0.
//
class addUpNumbers
{
public static void main (String[] args ) throws IOException
{
BufferedReader userin = new BufferedReader (new InputStreamReader(System.in));
String inputData;
int value; // data entered by the user
int sum = 0; // initialize the sum

// get the first value


System.out.println( "Enter first integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData );

while ( value != 0 )

Trainers: William T. Aldana / Glenda D. Balmelero


15
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

{
//add value to sum

//get the next value from the user


}

System.out.println( "Sum of the integers: " + sum );


}
}

The program is complete except for the loop body. Two of the three aspects of a loop are done:

1. The loop is initialized correctly.


2. The condition in the while is correct.
3. (Preparing for the next iteration is not done yet.)

QUESTION 2:

It would be really good if you got out a scrap of paper and tried to complete this program. Lacking that, mentally
decide what should should go inside the loop body?

A good answer might be:

The completed program is given below.

Complete Add Up Program

Here is the completed program. Notice how the loop condition always has a "fresh" value to test. To make this
happen, the first value needs to be input before the loop starts. The remaining values are input at the bottom of
the loop body.

import java.io.*;

// Add up all the integers that the user enters.


// After the last integer to be added, the user will enter a 0.
//
class addUpNumbers
{
public static void main (String[] args ) throws IOException
{
BufferedReader userin = new BufferedReader
(new InputStreamReader(System.in));
String inputData;
int value; // data entered by the user
int sum = 0; // initialize the sum

// get the first value


System.out.println( "Enter first integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData ); // "fresh" value,
// about to be tested

Trainers: William T. Aldana / Glenda D. Balmelero


16
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

while ( value != 0 )
{
//add value to sum
sum = sum + value;

//get the next value from the user


System.out.println( "Enter next integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData ); // "fresh" value,
// about to be tested

System.out.println( "Sum of the integers: " + sum );


}
}

The statements that get the first value and the statements that get the remaining values are nearly the same.
This is OK. If you try to have just one set of input statements you will dangerously twist the logic of the program.

QUESTION 3:

What would happen if the very first integer the user entered were "0"?

A good answer might be:

The loop body would not execute even once. The program would print out:

Sum of the integers: 0

Example Program Run

The user must have a way to say that there are no integers to add. This might seem dumb in a small program
like this, but in larger programs with many options and more complicated processing it is often important to be
able to skip a loop. Sometimes the "twisted logic" that beginners use assumes that there will always be at least
one number to add. Big mistake.

Often the data that a loop processes is the result of a previous part of the program. That part of the program
might not have produced any data. For example, a monthly checking account report from a bank has to deal
with those months where the customer has written no checks.

Here is an example of this program working, I did this by copying the program to the clipboard, pasting into
NotePad, saving as a file, compiling, and running. (The color was added later.)

Trainers: William T. Aldana / Glenda D. Balmelero


17
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

C:\users\default\JavaLessons\chap18>java addUpNumbers

Enter first integer (enter 0 to quit):


12
Enter next integer (enter 0 to quit):
-3
Enter next integer (enter 0 to quit):
4
Enter next integer (enter 0 to quit):
0
Sum of the integers: 13

Here is the relevant section of the program:

// get the first value


System.out.println( "Enter first integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData );

while ( value != 0 )
{
//add value to sum
sum = sum + value;

//get the next value from the user


System.out.println( "Enter next integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData );

System.out.println( "Sum of the integers: " + sum );


}
}

The value "0" in this program is the sentinel value. When the loop starts up, it is not known how many times the
loop will execute. Even the user might not know; there might be a big, long list of numbers to be added and the
user might not know exactly how many there are.

QUESTION 4:

The value "0" in this program is the sentinel value. Could any other value be used?

A good answer might be:

No. You might decide that a special value like "9999" would be a good sentinel, but then what happens if this
number happens to occur in the list to be added up?

Trainers: William T. Aldana / Glenda D. Balmelero


18
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Improving the Prompt

With the value "0" as the sentinel, if that value occurs in the list to be added, it can be skipped without any
problem (since skipping it affects the sum the same way as adding it in.)

Here is the interesting part of the program again, with some additions to make the user prompt more "user
friendly:"

int count = 0;

// get the first value


System.out.println( "Enter first integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData );

while ( value != 0 )
{
//add value to sum
sum = sum + value;

//increment the count


__________________

//get the next value from the user


System.out.println( "Enter the " +
(count+1) + "th integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData );

System.out.println( "Sum of the " + count + " integers: " + sum );


}
}

When this modified program is run, the user dialog should look something like the following:

C:\users\default\JavaLessons\chap18>java addUpNumbers

Enter first integer (enter 0 to quit):


12
Enter the 2th integer (enter 0 to quit):
-3
Enter the 3th integer (enter 0 to quit):
4
Enter the 4th integer (enter 0 to quit):
-10
Enter the 5th integer (enter 0 to quit):
0
Sum of the 4 integers: 3

Soon we will add additional statements to correct the dubious grammar in the second and third prompt.

Trainers: William T. Aldana / Glenda D. Balmelero


19
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

QUESTION 5:

Fill in the blank so that the program matches the suggested output.

A good answer might be:

The complete program is given below.

Improved Prompt Program

You could have answered the question by mechanically writing in a statement to increment count, as the
documentation suggests. Hopefully you understand the larger context of what is going on. Often in
programming, several variables have to be kept coordinated like this. It is something of a juggling act.

int count = 0;

// get the first value


System.out.println( "Enter first integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData );

while ( value != 0 )
{
//add value to sum
sum = sum + value;

//increment the count


count = count + 1;

//get the next value from the user


System.out.println( "Enter the " +
(count+1) + "th integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData );
}

System.out.println( "Sum of the " + count + " integers: " + sum );


}
}

Let us work on correcting the grammar in the prompt. We will use nested if-else statements inside the loop
body. This will get somewhat complicated.

Trainers: William T. Aldana / Glenda D. Balmelero


20
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

QUESTION 6:

What suffix goes with each integer? E.g. 1 gets "st" to make 1st.

1. 1
2. 2
3. 3
4. 4 and higher.

A good answer might be:

1. 1 st
2. 2 nd
3. 3 rd
4. 4 up to 20 th

Different Suffixes

The first integer is prompted for outside of the loop. Inside the loop body, it would be nice to use the following
prompts:

Enter the 2nd integer (enter 0 to quit):


Enter the 3rd integer (enter 0 to quit):
Enter the 4th integer (enter 0 to quit):
Enter the 5th integer (enter 0 to quit):
Enter the 6th integer (enter 0 to quit):
.... and so on ....
Enter the 20th integer (enter 0 to quit):
Enter the 21th integer (enter 0 to quit):

The prompt shows poor grammar for integers 21, 22, 23, 31, 32, 33 and so on. Let us regard this as acceptable.

The statement to write to the monitor will be changed to this:

System.out.println( "Enter the " +


(count+1) + suffix + " integer (enter 0 to quit):" );

The variable suffix will be a reference to one of the Strings: "nd", "rd", or "th".

QUESTION 7:

A choice must be made from among three things. Can a single if-else statement do this?

Can a single if-else statement choose one of three options?

A good answer might be:

No. An if-else statement makes a binary decision, a choice between two options.

Trainers: William T. Aldana / Glenda D. Balmelero


21
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Nested If for a Three-way Choice

To make a three-way choice, a nested if is used. This is where an if-else statement is part of a the true-branch
(or false-branch) of another if-else statement. So the nested if will execute only when the outer if has already
made a choice between two branches. Here is a program fragment that does that to make a choice of one of the
three Strings.

String suffix;

..... // count is the number of integers added so far.


..... // count+1 will be the next integer to read

if ( count+1 ______________ )
suffix = "nd";
else
if ( count+1 ______________ ) // false-branch of first if
suffix = "rd"; // false-branch of first if
else // false-branch of first if
suffix = "th"; // false-branch of first if

System.out.println( "Enter the " +


(count+1) + suffix + " integer (enter 0 to quit):" );

The false-branch of the first if statement consists of another entire if statement. Fill in the blanks so that:

1. when (count+1) is 2 the suffix "nd" is chosen;


2. when (count+1) is 3 the suffix "rd" is chosen;
3. when (count+1) is 4 or higher the suffix "th" is chosen.

QUESTION 8:

Fill in the two blanks so that the nested if's make the correct choice.

A good answer might be:

if ( count+1 == 2 )
suffix = "nd";
else
if ( count+1 == 3 )
suffix = "rd";
else
suffix = "th";

System.out.println( "Enter the " +


(count+1) + suffix + " integer (enter 0 to quit):" );

Trainers: William T. Aldana / Glenda D. Balmelero


22
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

How the Three-way Choice Works

The first if makes a choice between its true branch and its false branch. Its false branch is complicated, but that
doesn't matter. Each branch of an if statement can be as complicated as needed. Here is the fragment again,
with the first if's true branch in blue and its false branch in red:

if ( count+1 == 2 )
suffix = "nd";
else
if ( count+1 == 3 )
suffix = "rd";
else
suffix = "th";

System.out.println( "Enter the " + (count+1) + suffix + " integer (enter 0 to quit):" );

For example, if (count+1) is equal to 2, the true branch is picked. The variable suffix gets "nd", and the false
branch is completely skipped.

QUESTION 9:

The expression (count+1) is always greater than 1. For each of the following possible values of (count+1) which
branch of the FIRST if will be executed?

value of count+1 which branch?

if ( count+1 == 2 ) 2
suffix = "nd";
else 3
if ( count+1 == 3 )
suffix = "rd"; 4
else
suffix = "th"; 5

For each of the following possible values of (count+1), which branch of the first if will be executed?

A good answer might be:

1. 2 true branch
2. 3 false branch
3. 4 false branch
4. 5 false branch

Trainers: William T. Aldana / Glenda D. Balmelero


23
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Nested If Statement

When (count+1) is equal to 3, the false branch is executed.

if ( count+1 == 2 )
suffix = "nd"
else
if ( count+1 == 3 )
suffix = "rd";
else
suffix = "th";

System.out.println( "Enter the " +


(count+1) + suffix + " integer (enter 0 to quit):" );

The false branch consists of an if statement. When this nested if statement is executed, its true branch will
execute, selecting the String "rd" for suffix. The next statement to execute is the println.

QUESTION 10:

What suffix is chosen if (count+1) is equal to 5?

What suffix is chosen if (count+1) is equal to 5?

A good answer might be:

suffix = "th";

Matching if's and else's

Here is how the nested if works when (count+1) is equal to 5:

if ( count+1 == 2 ) <--- false: go to false branch


suffix = "nd";
else
if ( count+1 == 3 ) <--- false: go to inner false branch
suffix = "rd";
else
suffix = "th"; <--- inner false branch exectued

When (count+1) is 4 or greater the "th" suffix will be chosen.

It is sometimes hard to see exactly how the if's and else's nest in programs like this. Braces can be used to
show what matches what, but lets starts with a rule that does not talk about that. The rule is:

Start with the first if and work downward. Each else matches the closest previous unmatched if. An if matches
only one else and an else matches only one if.

You should indent the program to show this, but remember that the compiler does not pay any attention to
indenting. Here is the program fragment again showing the matching ifs and elses.

if ( count+1 == 2 )

Trainers: William T. Aldana / Glenda D. Balmelero


24
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

suffix = "nd";
else
if ( count+1 == 3 )
suffix = "rd";
else
suffix = "th";

The "if" and "else" of a matching pair are part of one "if statement." For example, the red pair above make are
part of one statement so the over-all structure of the program fragment is:

if ( count+1 == 2 )
suffix = "nd";
else
false branch

Here is another example. It is not indented properly. Use the rule to figure out which ifs and ifs match.

if ( a == b )

if ( d == e )
total = 0;

else
total = total + a;

else
total = total + b;

QUESTION 11:

Match the ifs and elses.

A good answer might be:

Here is the example fragment properly indented and with matching ifs and elses colored the same.

if ( a == b )

if ( d == e )
total = 0;

else
total = total + a;

else
total = total + b;

Trainers: William T. Aldana / Glenda D. Balmelero


25
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Make Matches clear with Braces

Sometimes you must use braces { and } to say what you want. An else inside of a pair of braces must match an
if also inside that pair. Sometimes you don't need braces, but use them to make clear (to human readers) what
you intend. Here is the complete rule for matching ifs and elses:

Rule for Matching if and else: Within each pair of matching braces: start with the first if and work downward.
Each else matches the closest previous unmatched if. An if matches only one else and an else matches only
one if.

Here is a program fragment that uses braces:

if ( ch == 'q' )
{
if ( sum == 12 )
ch = 'b' ;
}
else
ch = 'x' ;

The blue if and blue else match. Without the braces, they would not match. Here is another, poorly indented,
fragement:

if ( a == b )
{
if ( d == e )
total = 0;

else
total = total + b;
}

QUESTION 12:

Match the ifs and elses.

A good answer might be:

In this case, the braces are not really needed, but are probably a good idea, for clarity:

if ( a == b )
{
if ( d == e )
total = 0;

else
total = total + b;
}

Trainers: William T. Aldana / Glenda D. Balmelero


26
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Complete Add Up Numbers Program

Here is the complete program that adds up user-entered integers. In now includes nested ifs that select the
proper ending for the numbers in the prompt:

import java.io.*;
// Add up all the integers that the user enters.
// After the last integer to be added, the user will enter a 0.
//
class addUpNumbers
{
public static void main (String[] args ) throws IOException
{
BufferedReader userin = new BufferedReader (new InputStreamReader(System.in));
String inputData;
String suffix;
int value; // data entered by the user
int count = 0; // how many integers have gone into the sum so far
int sum = 0; // initialize the sum
// get the first value
System.out.println( "Enter first integer (enter 0 to quit):" );
inputData = userin.readLine();
value = Integer.parseInt( inputData );

while ( value != 0 )
{
//add value to sum
sum = sum + value; // add current value to the sum
count = count + 1; // one more integer has gone into the sum

// prompt for the next value


if ( count+1 == 2 )
suffix = "nd";
else
if ( count+1 == 3 )
suffix = "rd";
else
suffix = "th";
System.out.println( "Enter the " + (count+1) + suffix +
" integer (enter 0 to quit):" );

//get the next value from the user


inputData = userin.readLine();
value = Integer.parseInt( inputData );

}
System.out.println( "Sum of the integers: " + sum );
}
}

The program is getting a little bit complicated. The logic involved in prompting the user for the next integer is
more complicated than the logic involved in doing the main job of adding up all the integers. It would be nice to
put the prompting logic into a separate method called something like "promptUser()". This will be a topic of a
future chapter.

Trainers: William T. Aldana / Glenda D. Balmelero


27
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

QUESTION 13:

(Thought Question:) The main topic of this chapter is sentinel-controlled loops. Must a sentinel be an integer?

A good answer might be:

No, probably not.

New Example

Sometimes the user is asked explicitly if the loop should continue. The user enters "yes" or "no" (or maybe "y" or
"n"). Now the sentinel is of type String or char. The next example illustrates this:

Say that you were interested in the value of the polynomial:

7x3- 3x2 + 4x - 12

for various values of x. The value x is a double precision value. For example, when x == 2.0 the polynomial is
equal to:

7*23- 3*22 + 4*2 - 12 = 7*8 - 3*4 + 8 - 12 = 40

The program lets the user enter various values for x and see the result for each one.

QUESTION 14:

Would using a special value of x (such as 0.0) as a sentinel work well in this program?

A good answer might be:

No — the user might want to see the value of the polynomial when x is 0.0. Any other value has the same
problem.

Trainers: William T. Aldana / Glenda D. Balmelero


28
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Testing the User's Response

In this program, no special number is suitable as a sentinel because any number is potential data. Because of
this, there must be a prompt that asks if the user wants to continue, and another prompt that asks for data.

Here is an outline of the program:

class evalPoly
{
public static void main (String[] args ) throws IOException
{

double x; // a value to use with the polynomial


String response = "y"; // "y" or "n"

while (response.equals("y"))
{
// Get a value for x.

// Evaluate the polynomial.

// Print out the result.

// Ask the user if the program should continue.


// The user's answer is "response".
}

}
}

It is often useful to work on one aspect of a program at a time. Let us first look at the "prompting and looping"
aspect and temporarily ignore the polynomial evaluation aspect.

The condition part of the while statement, response.equals("y") evaluates to true or false. Here is how this
happens:

1. response is a reference to a String object.


2. A String object has both data and methods (as do all objects).
3. The data part of response will be the characters that the user types.
4. There are several methods for a String object. The equals( String ) method tests if two Strings contain the
same characters.
5. response.equals("y") tests if the String response is equal to the String "y".
6. The result of the test is true or false.

In other words, the condition response.equals("y") asks: did the user type a "y"?

QUESTION 15:

The program will be doing input and output. Which of the Java packages should be imported?

A good answer might be:

java.io.*;

Trainers: William T. Aldana / Glenda D. Balmelero


29
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Reading the User's Response

Here is the program with some additional work done on the "prompting and looping" aspect:

import java.io.*;

class evalPoly
{
public static void main (String[] args ) throws IOException
{
BufferedReader userin =
___________________________;

double x; // a value to use with the polynomial


String response = "y"; // "y" or "n"

while ( response.equals( "y" ) )


{
// Get a value for x.

// Evaluate the polynomial.

// Print out the result.

// Ask the user if the program should continue.


// The user's answer is "response".
___________________________;

response = userin.___________________________;
}

}
}

QUESTION 16:

Fill in the three blanks.

A good answer might be:

java.io.*;

Trainers: William T. Aldana / Glenda D. Balmelero


30
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Reading the User's Response

Here is the program with some additional work done on the "prompting and looping" aspect:

import java.io.*;

class evalPoly
{
public static void main (String[] args ) throws IOException
{
BufferedReader userin =
___________________________;

double x; // a value to use with the polynomial


String response = "y"; // "y" or "n"

while ( response.equals( "y" ) )


{
// Get a value for x.

// Evaluate the polynomial.

// Print out the result.

// Ask the user if the program should continue.


// The user's answer is "response".
___________________________;

response = userin.___________________________;
}

}
}

QUESTION 16:

Fill in the three blanks.

Trainers: William T. Aldana / Glenda D. Balmelero


31
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

=Printing with printf=

There are several output commands but we will learn the use of System.out.printf() statement. The
syntax is:

System.out.printf (“<format string>” [,<argument list>]);

The format string contains;

o ordinary characters (excluding %)


o conversion specification – starting with %

The conversion specifications that are often used are:

The conversion characters tell the compiler what data type the variable or string will be.

%d int (the d is short for decimal)

%f float or double

%lf double

%e float or double, output in scientific notation (also known as standard form)

%c character

%s character string (char *)

Floating point numbers, by default, have six digits decimal places. To control the number of decimal places
reported with printf(), we can place .n between the %f or %lf (%.nf or %.nlf). The n is an integer value (greater
than or equal to zero, that indicates the number of digits after the decimal point.

Example: System.out.printf(“%.2f”, area);

Trainers: William T. Aldana / Glenda D. Balmelero


32
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Exercises

1. The process of finding the largest value (i.e., the maximum of a group of values) is used frequently in
computer applications. For example, a program that determines the winner of a sales contest would
input the number of units sold by each salesperson. The salesperson who sells the most units wins the
contest. Write a program that inputs a series of 10 integers and determines and prints the largest
integer. Your program should use at least the following three variables:

a. counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and to
determine when all 10 numbers have been processed).
b. number: The integer most recently input by the user.
c. largest: The largest number found so far.

2. Write an application that uses only the output statements

System.out.print( "* " );


System.out.print( " " );
System.out.println();

to display the checkerboard pattern that follows. Note that a System.out.println method call with no
arguments causes the program to output a single newline character. [Hint: Repetition statements are
required.]

3. Create a program that lets the user enter a number greater than zero and outputs the number given.
This procedure will be performed as long as the number is greater than zero. Use the while loop.

4. Create a program similar to the previous exercise but instead of using a while loop use the do-while
loop.

5. Write a program that will ask the user to enter a number n and display the numbers from 1 to n.

6. Write a program that will display the even numbers from 1 to 100.

7. Given the value of n from the user, write a program that will display the first n even numbers.
Ex. If n = 5, then display the first 5 even integers which are 2, 4, 6, 8, 10.

8. 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.

9. Write a program that will compute for n! that is the product of all numbers from 1 to n.

Trainers: William T. Aldana / Glenda D. Balmelero


33
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

10. Write a program that reads in a number n and outputs the sum of the squares of the numbers from 1 to
n. Ex. If n=3, then display 14 because 12 + 22 + 32 =14.

11. Write a program that will compute for and display the sum of the numbers divisible by 3 ranging from 1
to 100.

12. Write a program that will display the following:


4, 8, 12, 16, … , 496

13. Write a program that will ask the user to enter 10 numbers and display the largest number entered.

14. Write a program that will ask the user to enter 20 numbers and display on the screen the highest and
lowest of these numbers.

15. Write a program that will ask the user for a number and display all the factors of the number entered.

16. Construct a program to tell whether an input number is a palindrome. A palindrome is something that
the same read backwards and forwards, such as 12321.

17. Write a program to list the numbers from 0 to 25, their squares, and the fourth power. The output should
be in a neat 3-column format.

Number Square 4th power


0 0 0
1 1 1
. . .
. . .
25 625 390625

18. 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

19. Write a program that will display an n-by-n square of a asterisks given n.
Ex. If n = 4, display

****
****
****
****
20. Write a program that will display a pattern depending on n.

Ex. If n = 4, display if n = 3, display


* *
** **
*** ***
****

21. Given an input n assumed one-digit, display a patter.

Ex. If n = 4, display
1
12
123
1234

Trainers: William T. Aldana / Glenda D. Balmelero


34
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

22. Given an input n assumed one-digit, display a patter.

Ex. If n = 4, display

1234
123
12
1

23. Write a program that causes the output below to be printed using for-to-do loops.

1
12
123
1234
123
12
1

24. Given an input n assumed one-digit, display a pattern.

Ex. If n = 4, display

4321
432
43
4

25. Input a set of 50 numbers and find the sum of only those numbers which are divisible by 8.
26. Compute for and print the area of 10 circles with the radius given by the user.
27. Ask the user to input the grades of 10 students. Compute and print the average of their scores.
28. Create a program that will ask the user to input 5 numbers. Compute and print the sum of these
numbers.
29. A mail-order house sells five products whose retail prices are as follows: Product 1, $2.98; product 2,
$4.50; product 3, $9.98; product 4, $4.49 and product 5, $6.87. Write an application that reads a series
of pairs of numbers as follows:

a. product number
b. quantity sold

Your program should use a switch statement to determine the retail price for each product. It should
calculate and display the total retail value of all products sold. Use a sentinel-controlled loop to
determine when the program should stop looping and display the final results.

30. 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.

Trainers: William T. Aldana / Glenda D. Balmelero


35
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

31. ("The Twelve Days of Christmas" Song) Write an application that uses repetition and switch statements
to print the song "The Twelve Days of Christmas." One switch statement should be used to print the day
(i.e., "First," "Second," etc.). A separate switch statement should be used to print the remainder of each
verse.

The Twelve days of Christmas


my true love sent to me:
On the first day of Christmas Eight Maids a Milking
my true love sent to me: Seven Swans a Swimming
A Partridge in a Pear Tree Six Geese a Laying
Five Golden Rings
On the second day of Christmas Four Calling Birds
my true love sent to me: Three French Hens
Two Turtle Doves Two Turtle Doves
and a Partridge in a Pear Tree and a Partridge in a Pear Tree

On the third day of Christmas On the ninth day of Christmas


my true love sent to me: my true love sent to me:
Three French Hens Nine Ladies Dancing
Two Turtle Doves Eight Maids a Milking
and a Partridge in a Pear Tree Seven Swans a Swimming
Six Geese a Laying
On the fourth day of Christmas Five Golden Rings
my true love sent to me: Four Calling Birds
Four Calling Birds Three French Hens
Three French Hens Two Turtle Doves
Two Turtle Doves and a Partridge in a Pear Tree
and a Partridge in a Pear Tree
On the tenth day of Christmas
On the fifth day of Christmas my true love sent to me:
my true love sent to me: Ten Lords a Leaping
Five Golden Rings Nine Ladies Dancing
Four Calling Birds Eight Maids a Milking
Three French Hens Seven Swans a Swimming
Two Turtle Doves Six Geese a Laying
and a Partridge in a Pear Tree Five Golden Rings
Four Calling Birds
On the sixth day of Christmas Three French Hens
my true love sent to me: Two Turtle Doves
Six Geese a Laying and a Partridge in a Pear Tree
Five Golden Rings
Four Calling Birds On the eleventh day of Christmas
Three French Hens my true love sent to me:
Two Turtle Doves Eleven Pipers Piping
and a Partridge in a Pear Tree Ten Lords a Leaping
Nine Ladies Dancing
On the seventh day of Christmas Eight Maids a Milking
my true love sent to me: Seven Swans a Swimming
Seven Swans a Swimming Six Geese a Laying
Six Geese a Laying Five Golden Rings
Five Golden Rings Four Calling Birds
Four Calling Birds Three French Hens
Three French Hens Two Turtle Doves
Two Turtle Doves and a Partridge in a Pear Tree
and a Partridge in a Pear Tree
On the twelfth day of Christmas
On the eighth day of Christmas my true love sent to me:
12 Drummers Drumming

Trainers: William T. Aldana / Glenda D. Balmelero


36
DIVISION SPECIALIZED TRAINING-WORKSHOP IN ICT 2017 Java Lecture - Loop

Eleven Pipers Piping Five Golden Rings


Ten Lords a Leaping Four Calling Birds
Nine Ladies Dancing Three French Hens
Eight Maids a Milking Two Turtle Doves
Seven Swans a Swimming and a Partridge in a Pear Tree
Six Geese a Laying

Trainers: William T. Aldana / Glenda D. Balmelero


37

Вам также может понравиться