Controlling Sequence Computer Programming
Controlling Sequence Computer Programming
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.
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?
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.
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.
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 is:
initialize ctr to 1
Condition is:
increment ctr by 1
while loop
for loop
do while loop
The while statement continually executes a block of statements while a particular condition is true.
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.
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;
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 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 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++;
}
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);
}
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.
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;
class fordemo2
{
public static void main(String[] args)
{
int counter;
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.
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.
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
}
}
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
}
}
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:
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:
class nestedloop
{
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");
}
}
}
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;
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.
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;
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);
}
}
}
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.
if(i == j)
{
System.out.print(" " + i);
}
}
}
}
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
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.
C:\myJava>javac Continue.java
Continue.java:12: unreachable statement
a = i;
^
1 error
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
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?
Yes; each iteration of the loop will add a new number to the sum.
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.*;
while ( value != 0 )
{
//add value to sum
The program is complete except for the loop body. Two of the three aspects of a loop are done:
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?
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.*;
while ( value != 0 )
{
//add value to sum
sum = sum + value;
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"?
The loop body would not execute even once. The program would print out:
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.)
C:\users\default\JavaLessons\chap18>java addUpNumbers
while ( value != 0 )
{
//add value to sum
sum = sum + value;
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?
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?
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;
while ( value != 0 )
{
//add value to sum
sum = sum + value;
When this modified program is run, the user dialog should look something like the following:
C:\users\default\JavaLessons\chap18>java addUpNumbers
Soon we will add additional statements to correct the dubious grammar in the second and third prompt.
QUESTION 5:
Fill in the blank so that the program matches the suggested output.
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;
while ( value != 0 )
{
//add value to sum
sum = sum + value;
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.
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.
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:
The prompt shows poor grammar for integers 21, 22, 23, 31, 32, 33 and so on. Let us regard this as acceptable.
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?
No. An if-else statement makes a binary decision, a choice between two options.
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;
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
The false-branch of the first if statement consists of another entire if statement. Fill in the blanks so that:
QUESTION 8:
Fill in the two blanks so that the nested if's make the correct choice.
if ( count+1 == 2 )
suffix = "nd";
else
if ( count+1 == 3 )
suffix = "rd";
else
suffix = "th";
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?
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?
1. 2 true branch
2. 3 false branch
3. 4 false branch
4. 5 false branch
Nested If Statement
if ( count+1 == 2 )
suffix = "nd"
else
if ( count+1 == 3 )
suffix = "rd";
else
suffix = "th";
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:
suffix = "th";
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 )
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:
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;
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.
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:
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;
}
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
}
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.
QUESTION 13:
(Thought Question:) The main topic of this chapter is sentinel-controlled loops. Must a sentinel be an integer?
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:
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:
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?
No — the user might want to see the value of the polynomial when x is 0.0. Any other value has the same
problem.
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.
class evalPoly
{
public static void main (String[] args ) throws IOException
{
while (response.equals("y"))
{
// Get a value for x.
}
}
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:
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?
java.io.*;
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 =
___________________________;
response = userin.___________________________;
}
}
}
QUESTION 16:
java.io.*;
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 =
___________________________;
response = userin.___________________________;
}
}
}
QUESTION 16:
There are several output commands but we will learn the use of System.out.printf() statement. The
syntax is:
The conversion characters tell the compiler what data type the variable or string will be.
%f float or double
%lf double
%c character
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.
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.
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.
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.
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.
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.
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
1
12
123
1234
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
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.
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.