Control Statements ReviewCSC 123Fall 2018
Howard Rosenthal
Lesson Goals� Review some of Java’s control structures� Review how to control the flow of a program via selection
mechanisms� Understand if, if-else, else-if and switch statements
� Build programs with nested layers of decision making� Building blocks of execution code
� Review how to deal with the dangling else� Understand the conditional operator� Review the following three repetition structures in Java, their
syntax, their similarities and differences, and how to avoid common errors when using them:� while� do-while� for
� Review nested looping� Review how to use break statements to exit a loop� Review and expand knowledge of blocks and scope
2
3
Control Structures in Java� There are three control structures in Java
� Sequence Structure� Built into Java� Ensures that statements execute one after the other in the order they
are written, unless directed otherwise
� Selection Structure Based on truth or falsity� In Java includes the if, if…else, if ... else if, and switch statements
� Repetition Structure Allows for repetition of the same group of statements multiple times, as long as a condition is met� In Java includes the do, do…while, for, and enhanced for statements� Also known as iteration statements or looping statements
4
Windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows how this decision is made. Start at the top of the chart then follow the line to the question: is it raining? The answer is either true or false. If the answer is true,
follow the line labeled True,perform the instructions in the box "wipers on",follow the line to "continue".
If the answer is false, follow the line labeled False, perform the instructions in the box "wipers off",follow the line to "continue".
Two Way Decisions
5
The windshield wiper decision is a two-way decision (sometimes called a binarydecision). The decision seems small, but in programming, complicated decisions are made by executing many small decisions.
The Basic Syntax of the if Statementif (boolean expression){
statement 1;statement 2;
o0o
statement n;}� The statements inside the block (delineated by a pair of braces) are executed only if the
boolean statement (in parentheses) is true� You should use the braces even if there is only a single statement inside the block even
though this isn’t required� No semicolon on the if statement� An if with a single statement following it does not require curly braces, however, it is best
to use them all the time at first
if (boolean expression)statement 1;
6
Basic Terminology� An if statement is also called a conditional or selection
statement� The phrase if (boolean expression) is called the if clause
� The boolean expression itself is called the condition� The statements inside the curly braces comprise a block � You can nest if statements inside each other
� Write out the statements that will add 3 to int x initialized to 4 if the boolean value y is true. Initialize y to either true or false.
7
Answer
8
boolean y = true;int x = 4;if (y == true)
x = x+3;
A Very Simple Examplepublic class SimpleIfStatementDemo1{
public static void main(String [] args){
//Declaring a variable "test" and initializing it with a value 10
int test = 10;
//Checking if "test" is greater than 5
if (test > 5){
//This block will be executed only if "test" is greater than 5System.out.printf("Success\n");
}
//The if block ends.System.out.printf("Executed successfully\n");
}}
9
The Basic Syntax of the if-else Statement� Similar to the if statement, but exclusively executes an alternative set of statement(s) if the conditional is false
if (boolean expression) // always evaluates to either true or false{
statement 1;statement 2;
o0o
statement n;}else{
statement a;statement b;
o0o
statement x;}
Note: Once again if there is only a single statement then braces are not required
if (boolean expression) // always evaluates to either true or falsestatement 1;
elsestatement a;
10
A Simple Example of if-elseimport java.util.Scanner;
public class NumberTester
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner( System.in );
int num;
System.out.printf ("Enter an integer: ");
num = keyboard.nextInt();
if ( num < 0 )
{
System.out.printf("The number is %d negative\n”, num);
num = num +5;
}
else
{
System.out.printf("The number %d is zero or positive\n”, num);
num = num -4;
}
System.out.printf("The number is now %d”, num );
System.out.printf("Good-bye for now\n");
}
}
11
if else if Syntax� Allows for testing for multiple different conditions� Only the first case that tests as true will be executed� If there is no else statement at the end then it is possible that none of the blocks are executedif (boolean expression) // always evaluates to either true or false{
statement 1;statement 2;
o0
statement n;}else if (boolean expression) // always evaluates to true or false{
statement a;statement b;
o0
statement x;}else //optional{
statement a;statement b;
o0
statement x;
}
12
An else if Example//This program assigns a letter grade based on a character gradeimport java.util.Scanner;class IfElseIfDemo {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);System.out.printf("Enter the grade: ");int testScore = keyboard.nextInt(); char grade; if (testScore >= 90) {
grade = 'A';} else if (testScore >= 80) {
grade = 'B'; } else if (testScore >= 70) {
grade = 'C'; } else if (testScore >= 60) {
grade = 'D'; } else {
grade = 'F'; }
System.out.printf("Grade = %c\n, grade); }
} 13
Note: • If you reverse the order then you would need to
compare from bottom to top using <=• Be careful in use of > vs. >=, etc.• Remember, for any particular level of if, else-if,
else, only the block after the first true statement is executed
A Note On boolean Expressions� Be careful when using float or double type variables in
boolean expressions� Since there is always limited precision the possibility of
an execution error exists, especially after more complex mathematical operations
� Example: (7.13*2.9)/(3.6*2.95) may be different than(7.13/(3.6*2.95))*2.9
See DecimalCompare.java and DecimalCompare2.java� With DecimalCompare and println you can see where the
difference shows up, which is far beyond the second decimal place
14
The Dangling if (1)� Rule - An else matches with the nearest, previous, unmatched if that's not in a block. if ( num > 0 ) {
if ( num < 10 ) // Previous unmatched ifSystem.out.printf( "aaa\n" );
else // Matches with previous unmatched ifSystem.out.printf( "bbb\n" );
}
In the example above, the else is indented with the inner if statement. It prints"bbb" only if num > 0 and num >= 10, which means it prints only if num is 10 or greater.
In the example below, the else is indented with the outer if statement. if ( num > 0 ) {
if ( num < 10 ) // Previous unmatched ifSystem.out.printf( "aaa\n" ) ;
else // Matches with previous unmatched ifSystem.out.printf( "bbb\n" ) ;
}
Which one does else match with? It picks the closest if unless there is a further clarification with the use of braces. This phenomenon of having to pick between one of two possible ifstatements is called the dangling else.
� Depending on which if the else is paired with, you can get different results. By now, you should know that Java doesn't pay attention to indentation. So both examples above are the same to Java, which means that it makes its determination based strictly on the syntax. To the Java Compiler there is no ambiguity (You can’t say “That’s not what I really meant”)
� The compiler doesn’t care about indenting. But you should for clarity
15
The Dangling if (2)� What if we wanted the else to match with the first if? Then, we need braces. if ( num > 0 ) // Previous unmatched if {
if ( num < 10 ) // Unmatched, but in blockSystem.out.printf( "aaa\n" ) ;
} else // Matches with previous unmatched if not in block
System.out.printf( "bbb\n" ) ; //This prints if num <= 0.
The else above matches with the previous, unmatched if not in the lower level block. This happens to be the outer if. There is an unmatched if that's the inner if, but that's in a block, so you can't match to it. Notice the else sits outside of the block. An else does not match to a previous if if the else is outside the block, where the closest if is found.
16
Dangling if Flows
17
if num > 0
if num <10
F
Print “aaa”
T
TPrint “bbb”
F
if num > 0
if num <10
F
Print “aaa”
T
TPrint “bbb”
F
The Dangling if – The Rules Summarized� Every else must match with a unique if. You can't have
two or more else matching to the same if. If there is no matching if for an else, then your program won't compile.
� Each else must be preceded by a valid if� Fortunately, your program fails to compile if you don't
do this. � Use Braces
� If you always use a block for if body and else body, then you can avoid confusion. However, it's useful to know the correct rules.
18
The switch Statement� The syntax of a switch statement looks like:
switch ( expr ) {
case literal1: case literal1 body
case literal2: case literal2 body
case literal3: case literal3 body
default: default body
}
� Unlike if statements which contain a condition in the parentheses, switch contains an expression. This expression must be type byte, short, int, char or String. (Note: String is a newer feature, and the book says only int or char). Wrapper classes or an evaluation of an enumeration type can also be
� The semantics of switch are: � Evaluate the expression� Begin looking at each case, starting top to bottom � If the value of the expression matches the case, then run the body � Note: The case keyword has to be followed by a literal or a constant expression. It can't be a range� If you run a break statement, you then exit the switch� If you don't run a break statement, and you are at the end of a body, run the next body. Keep
running bodies until you exit or hit a break statement � If no match is made to the cases, run the default, if it exists. The default case is always run last,
no matter where it appears. (It should be placed last, though). It is not mandatory to have a default statement.
19
Examples of the switch Statementint x = 4 ; switch ( x ) {
case 2: System.out.printf( "TWO\n" ) ; break ;
case 4: System.out.printf( "FOUR\n" ) ; break ;
case 6: System.out.printf( "SIX\n" ) ; break ;
default: System.out.printf( "DEFAULT\n" ) ;
}
See SwitchExample.java for full program� This evaluates x to 4. It skips case 2 since the value 4 doesn't match 2. It does match case 4. It runs
the body and prints “FOUR". Then it runs break and exits the switch.
20
Examples of the switch Statement (2)� Most of the times, you will end each case with break. Let's see what happens when you leave it out.
int x = 4 ; switch ( x ) {
case 2: System.out.printf( "TWO\n" ) ;
case 4: System.out.printf( "FOUR\n" ) ;
case 6: System.out.printf( "SIX\n" ) ;
default: System.out.printf( "DEFAULT\n" ) ;
}
� This prints out: FOUR SIX DEFAULT
� That's probably not what the user had in mind. Without the break, each time a body runs, it falls through and starts running the next body, and the next, after it matches the correct case.
� However, there are cases where you will want to execute multiple statements from multiple cases (see next example)
� See full program in SwitchExample2.java
21
Examples of the switch Statement (3)� You can combine cases together.int x = 4 ; switch ( x ) { case 1: case 3: case 5:
System.out.printf( "ODD\n" ) ; break ;
case 2: case 4: case 6:
System.out.printf( "EVEN\n" ) ; break ;
default: System.out.printf( "DEFAULT\n" ) ;
}
See full program as SwitchExample3.java
22
A Few Additional Notes On the switch Statement� Every switch statement can be implemented as an if/if
else type statement� It doesn’t always work the other way around
� Obviously if the if/else is doing more complex comparisons or using boolean values or floating point numbers, then this can’t be implemented in a switch statement
23
The Conditional Operator (1)� The conditional operator is used like this:
true-or-false-condition ? value-if-true : value-if-false� Here is how it works:
� The true-or-false-condition evaluates to true or false.� That value selects one choice:
� If the true-or-false-condition is true, then evaluate the expression between ? and :
� If the true-or-false-condition is false, then evaluate the expression between : and the end .
� The result of evaluation is the value of the entire conditional expression.
� This approach can be used in assignment statements
24
The Conditional Operator (2)
int a = 7, b = 21;System.out.printf ("The min is: %d\n” ,(a < b ? a : b ) );The output would be:The min is 7
25
The Conditional Operator (3)
double value = -34.569;double absValue;
absValue = ((value < 0 ) ? -value : value) ;------------- ------The constant value +34.569 is assigned to absValue
26
import java.util.Scanner; class RainTester {
public static void main (String[] args) {
Scanner keyboard = new Scanner( System.in ); String answer;System.out.printf("Is it raining? (Y or N): "); answer = keyboard.nextLine(); if ( answer.equals("Y") ) // is answer exactly "Y" ?
System.out.printf("Wipers On\n”); // true branch else
System.out.printf("Wipers Off\n"); // false branch }
}
An Example Using String Features
27
A Few Note For Good Programming… � Always check your programs through each of the else cases,
switch gates etc.� To do this you need to develop a set of test cases
� A test case has components that describe an input, action or event and an expected response, to determine if a feature of an application is working correctly
� Your test cases must be expansive enough to cover the full range of possibilities� For instance if there is a statementif (x>4)
you don’t need to test for every possibility greater than 4, but you need to test for at least one that is greater than 4, one that equals 4 and one that is less than 4.
� Typically we build a software test verification matrix
28
Sample Test Matrix
Y 2 3 4X1 R1 R2 R32 R4 R5 R65 R7 R8 R97 R10 R11 R12
29
• Test for all possible combinations• When there are multiple variables break the testing into smaller pieces• Always test for different and outlying conditions• Positive, zero and negative numbers• First and last number and some element in the middle when
processing a list
30
Introduction to Loops� Many of the tasks performed by computers require repetition, often massive
repetition
� Using repetitive syntax can make your code more concise and easier to write and debug
� Java has three types of repetitive constructs (also known as loops): while, do-while or for
� Loops are built out of several fundamental statements because there are three
things (in each of the three types of loops) that must be done correctly:
� The variables used to control the loop must be initialized correctly
� The ending condition for the loop must be tested correctly
� The body of the loop or the loop statement must change the condition that is tested – otherwise you can wind up with an infinite loop
� Overlooking one of these aspects results in a defective loop and a sometimes difficult to find program bug! Usually each of these three considerations is located in a different spot. No wonder that loops often go wrong!
� You have to plan out the logic of your program in order to effectively use loops and conditionals
� Anything that can be done with one loop structure can be done with either of the other two, but sometimes the logic makes one preferable to the other
31
Types of Loops
Type Description
counting loopUses a loop control variable to count upwards or downwards (usually by an integer increment.)Example: Keep going until you run 100 miles.
sentinel-controlled loop
Loop keeps going until a special value is encountered in the data.Example: Keep going until you hit a red light.
result-controlled loopLoop keeps going until a test determines that the desired result has been achieved.Example. Keep going until you reach your home.
32
Here is a program with a loop. It contains a while statement, followed by a block of code. Remember, a block is a group of statements enclosed in braces.
// Example of a while loop public class WhileLoopExample1{ public static void main (String[] args )
{ // start count out at one int count = 1; while ( count <= 3 ){
System.out.printf(“Count is: %d\n”, count ); count = count + 1; // add one to count
} System.out.printf( "Done with the loop\n”);
} }
The while Statement
33
The Basic Syntax of the while Statementwhile (condition){
statement 1;statement 2;
o0o
statement n;}� You execute through the entire block repetitively until the
condition is false unless you encounter a break statement� The break will typically occur based on a separate condition
tested with an if statement
34
Basic Terminology of the while Statement� The condition is a boolean expression: something that evaluates
to true or false� The condition can be complicated, using many relational
operators and logical operators.� Due to the precision of integers, integers are almost always used as
counters for loops� A single statement is allowed
� Without braces only one statement is executed inside the loop� The block or single executable statement is sometimes called the
loop body� If one of the statements in the while block doesn’t eventually
change the value of the condition then the loop goes on forever� The while loop may not be executed at all if the initial condition
is false� There is no semi-colon after the while statement
� If you put one there you will end the loop before it executes anything
35
• Here is a program with a loop• It contains a while statement, followed by a block of code• The condition is checked when entering the loop, and for each iteration• If the condition is false the loop is skipped over• Remember, a block is a group of statements enclosed in braces.
// Pseudocode examplepublic class WhileLoopExample2{ public static void main (String[] args )
{ int count = 2; // count is initialized while ( count >= 0 ) // count is tested {
System.out.printf( “Count is: %d\n”, count ); count = count - 1; // count is changed by -1
} System.out.printf( "Done counting down\n" );
} }
Counters Can Be Decremented Rather Than Incremented When The Need Arises
36
• Sometimes you want to ensure at least one execution of a loop so you use
a boolean flag set to true (or false depending on the statement)
/// Example of a while loop with flag
import java.util.Scanner;
public class WhileLoopFlag{
public static void main (String[] args )
{
int number, sum = 0;
boolean flag = true; // flag is initialized Scanner keyboard = new Scanner(System.in);
while ( flag == true) // flag is tested
{
System.out.printf( “Enter an integer value, with a zero ending the accumulation: ”);
number =keyboard.nextInt();if (number == 0)
flag = false;
else
sum = sum+number;
} System.out.printf(”Sum is %d\n”, sum);
}
}
Using a Flag To Guarantee Execution Of a While Statement
37
• Here is a program with a loop• It contains a do statement, followed by a block of code,
followed by a while statement• The condition is checked at the end of each execution of
the loop which is always executed at least once
// Example of a do-while loop that executes only oncepublic class DoWhileLoopExample{ public static void main (String[] args )
{ int count = 1000; // initialize do{
System.out.printf(“Count is: %d\n”, count ); count++ ;
}while ( count < 10 ); // test
System.out.printf( "Done with the loop\n" ); }
}
The do-while Statement
38
The Basic Syntax of the do-while Statement
do{
statement1;statement2;
o00
statementn;} while (condition);
39
Basic Terminology of the do-while Statement� The condition is a boolean expression: something that
evaluates to true or false� The condition can be complicated, using many relational
operators and logical operators� A single statement is allowed
� Without braces to create a block only one statement is executed inside the loop
� The block or single executable statement is sometimes called the loop body.
� The do-while is always executed at least once, if the do statement is executed
� There is a semi-colon after the while statement in a do-while
40
Here is a program with a loop. It contains a for statement, followed by a block of code. A block is a group of statements enclosed in braces.
// Example of a for loop public class ForLoopExample{ public static void main (String[] args )
{ int sum=0;
for ( int count = 0; count <= 5; count++ ) {
sum = sum + count ; System.out.printf(“Count is: %d”, count);
} System.out.printf( “\nSum is: %d\n”, sum );
} }
The for Statement
41
Initializationcount = 0
loop condition count <= 5
sum = sum + count
Print count
count++
Print sum
false
sum = 0
The Basic Syntax of the for Statement
for (initialization; loop condition; update statements){
statement1;statement2;
o00
statementn;}
42
Basic Terminology of the for Statement� initialization
� Used to initialize basic variables used in the loop condition
� More than one variable can be set, separated by commas
� You can declare the variable in the for statement, but then it is only valid within the for loop within which it is created
� for (int j=3, k=4; …; …)
� If no variables are set, you must have a ; before the loop condition – this
typically means that the variable has been set prior to the for statement
� The initialization portion of the for statement is only executed once,
each time you enter the loop.
� This allows you to nest loops
� loop condition� A boolean expression – evaluates as true or false
� Evaluated at the beginning of each loop
� Although this statement can be left out, leaving it out could lead to an infinite do loop, unless you execute a break statement inside the loop
43
Basic Terminology of the for Statement (2)� update statement(s)
� Increases or decreases a value, typically one or more used in the loop condition
� Always executed at the end of the loop body
� Can include more than one statement, separated by commas� for(…; …; i++, j= j+5)� Usually use postfix notation, but in this case prefix work exactly the same
� Notes:� If you are eliminating multiple parts of a for statement it may be better
to use a while or do-while
� Don’t stuff too many extraneous things into the for statement, you’ll confuse yourself
� Most people use for statements when executing a loop a specific number of times
44
Nested Loops� A nested loop is a (inner) loop that appears in the loop
body of another (outer) loop. � The inner or outer loop can be any type: while, do while,
or for. � For example, the inner loop can be a while loop while an
outer loop can be a for loop. Of course, they can be the same kind of loops too.
� Inner loops always stay completely inside their outer loops� An inner loop may be skipped over during the execution of
an outer loop� If the inner loop has a tested condition that starts out false or� If the loop is inside of an if block that isn’t executed, then that
loop wouldn’t be executed
45
Nested Loop Example// Example of nested loop that prints a rectangle of starspublic class NestedLoops{ public static void main (String[] args )
{ int height =5;int width = 4; for ( int i = 0 ; i < height ; i++ ) {
for ( int j = 0 ; j< width ; j++ ) {
System.out.printf( “%s”, "*" ) ; }System.out.printf( ”\n" ) ;
} }
}
46
The Multiplication Table Is A Good Example Of Nested Looping
47
1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 2 4 6 8 10 12 14 16 18
3 3 6 9 12 15 18 21 24 27
4 4 8 12 16 20 24 28 32 36
5 5 10 15 20 25 30 35 40 45
6 6 12 18 24 30 36 42 48 54
7 7 14 21 28 35 42 49 56 63
8 8 16 24 32 40 48 56 64 72
9 9 18 27 36 45 54 63 72 81
How Can We Use Loops To Help Construct This Table
1. Write the Top Rowa. Use a loop to write the numbers 1-9
2. Draw a horizontal line line3. For each row
a. Write the row numberb. Draw a vertical linec. For each column
1) Calculate the product2) Write the product
d. Skip to the next row
48
Now we’ll look at the solution in MultTable.java and MultTablePrintln.java
The break Statement� Used to immediately exit the innermost loop that the break is found within,
unless the loop is labeled� Loop is labeled with looplabelname: followed by the loop – the name begins
with an alpha character followed by alphas, number, $, _ characters� The next statement executed is the first statement beyond the scope of that
loop� If you label a loop the break statement can be used to exit through an outer
nesting
� We’ll look at SimpleBreakLoop.java and BreakLabeledLoop.java
� Note: any bock can be labeled, not just iterations� label:{� You can then use a break label; to to exit out of the block with the name label
49
The continue Statement� When executed in a repetition statement , the
remainder of the statements in that iteration of the loop body are skipped, and the next iteration test is executed.� In the for statement the update statements are executed
� We’ll look at the ContinueExample.java
50
The flag or sentinel� A flag or sentinel is a value appended to a data collection that signals the end
of the data.� The idea of a sentinel controlled loop is that there is a special value (the
sentinel) that is used to control when the loop is done. � In following code fragment, the user enters a zero when the sum is complete.
Zero is the sentinel. Here is how the program should work
import java.util.Scanner; // Add up integers entered by the user. // After the last integer, the user enters a 0class AddUpNumbers {
public static void main (String[] args ) {
Scanner keyboard = new Scanner( System.in ); int value, sum = 0; System.out.printf("Enter first integer (enter 0 to quit): “); value = keyboard.nextInt(); //we initialize value before entering the loopwhile ( value != 0 )
{sum = sum + value; System.out.printf(“Enter next integer (enter 0 to quit): “); value = keyboard.nextInt(); //update value inside the loop
} System.out.printf("Sum of the integers is: %d\n”, sum);
} }
51
The hasNext() Method of the Scanner class
� The hasNext() method keeps reading data unto there is no more data to read� When there is no more data to read it returns false
� Once we start reading from files (Chapter 9), that means that it will test to see if we have reached the end of the file
� Working interactively we can use a while or do while and enter <Ctrl> z on a Windows System or <Ctrl> d on a Mac to indicate end of data
� See HasNextTest.java
52
Bad Input Data� There are cases when erroneous data is entered
� There are many options
� Request revised data - preferred
� Exit the program
� In order to do either you must check the data first
� Note: Some inputs will cause the program to crash – Can you
name 0ne?
� We will learn how to capture error conditions and perform soft exits
Look at ErroneousData.java
We will look at GeneralAverage.java in a few minutes
53
Scope of a Variable (1)� A variable’s scope is determined by the highest level of braces
within which it is defined.� It works at that level and all nested level
� If you use the same variable name in an outer and nested blocks, an error will occur.� In Java you cannot have local variables with the same name in
overlapping scope� If you exit a block where a variable is defined you can reuse the
variable name� It’s values are separate from the originally named variable � Don’t use the same variable name twice in a program – it only
confuses things. (exception – may reuse loop counters)� You are allowed to continuously redeclare a variable in the same
statement within a loop – again this allows for nesting� Scope is extremely important to understand in nested loops.
� Once you leave the loop a variable declared in the loop no longer exists.
54
Scope of a Variable (2)// Demonstrate block scope.public class Scope {
public static void main(String args[]){
int n1; // Visible in mainn1 = 10;if (n1 == 10){// start new scope
int n2 = 20; // visible only to this block// n1 and n2 both visible here.System.out.printf(“n1 = %d n2 = %d\n”, n1, n2);
}// n2 = 100; // Error! n2 not known here// n1 is still visible here.System.out.printf("n1 is %d\n”, n1);
}}
55
Scope of a Variable (3)public class LifeTime {
public static void main(String args[]) {
int i;for(i = 0; i < 3; i++) {
int y = -1;System.out.printf("y is : %d\n”, y);
}}
}
� Variable “y” is declared inside for loop block� Each time when control goes inside “for loop block” the y variable is declared and used
in loop� When control goes out of the for loop then the variable becomes inaccessible
56
Scope of a Variable (4)public class ScopeInvalid {
public static void main(String args[]) {
int num = 1;{ // creates a new scope
int num = 2; // Compile-time error// num already defined
}}
}
public class ScopeValid {
public static void main(String args[]){{ // creates a new scope
int num = 1;}{ // creates a new scope
int num = 2; Okay – doesn’t overlap with the num in the prior b;ock}
}}
57
58
Programming Exercise 1Sort ThreeWrite a program that requests the entry of three integers and displays the numbers in order from lowest to highest.Note: You will need to test all possible cases
59
Programming Exercise 2TollFreeNumbers As of the year 2008, a 10 digit number that begins with 800, 888, 877, or 866 has been toll free. Write a program that reads in a 10 digit phone number and displays a message that states whether the number is toll free or not.Hints: Use long as the variable type, extract first three digits with integer arithmetic
60
Programming Exercises 3GradeConversion
A certain school assigns number grades ranging from
0-100. Write a program that queries the user for a
numerical score and converts the score to a letter
grade according to thee following criteria:
0-59:F; 60-69 D: 70-72, C-: 73-76, C: 77-79 C+;
80-82: B-; 83-86: B; 87-89: B+; 90-92: A-; 93-96: A;
97-100 A+
61
Programming Exercise 4GeneralAverageWrite a program that calculates the average of n test scores, such that each score is an integer in the range 0 to 100. There should be a minimum of two scores. Your program should first prompt for an integer n and then request n scores. There should be a minimum of two scores. Your program should also test for invalid data. If a user enters a number outside the correct range, the program should prompt for another value. Round the average to the closest integer.
62
Programming Exercise 5MorePicturesWrite a program that accepts an integer n and prints out the following picture of a diamond with 2n-1 rows1 X2 X X X3 X X X X X
……n XXXXXXXXXXX (2n-1 times)
…….
2n-1 X
63
Pseudo Code for More Pictures
Read in n to determine total number of rows as 2n-1Calculate the width = 2*n-1For each row in top half up from 1 to n
Calculate the number of x’s (2*rowNumber-1)Calculate the blanks = (width – numExes)/2Print the blanks (a loop)Print the X’s (a loop)Skip to next line
For each row in the bottom half from n-1 to 1Calculate the number of x’s (2*rowNumber-1)Calculate the blanks = (width – numExes)/2Print the blanks (a loop)Print the x’s (a loop)Skip to next line
64