Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Control Statements: Selection - if, switch and Common Forms, Lab Reports of Computer Science

An overview of control statements, specifically focusing on selection statements such as if and switch. It covers the two forms of the if statement, choosing between if and if/else, and examples of their usage. The document also introduces the switch statement and provides examples of its usage.

Typology: Lab Reports

Pre 2010

Uploaded on 08/18/2009

koofers-user-9qj
koofers-user-9qj šŸ‡ŗšŸ‡ø

10 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Mat 2170
Week 5
Control Statements – Selection
Spring 2009
1
Student Responsibilities
IReading: Textbook, Chapter 4
ILab 5
IAttendance
IEXAM 1 Thursday evening, 7:00pm
2
Chapter Four Overview – 4.3 – 4.4
Along with while and for, more control statements
Used to make decisions or choices
They do not cause iteration or looping
Iif
Iswitch
3
The if Statement — Two Forms
IThe first form is used when an operation is performed only if
a particular condition is true:
if (condition) {
statements to be executed if condition is true
}
IThe second form is used when there are two alternatives: one
for cases in which the condition is true and the other for
cases in which it is false:
if (condition) {
statements to be executed if condition is true
}
else {
statements to be executed if condition is false
}
4
Choosing Between if and if/else
INo hard–and–fast rule
IBest guideline: think ab out the problem description (in
English) — if it uses else or otherwise, there’s a good chance
you need to use if/else
IExample: supp ose we want to change the AverageList
program so it didn’t include any zero values in the average. A
single test is needed to ensure zero scores aren’t added in or
counted.
IHowever, if we wish to also count the non–zero scores, we
would need to add an else clause to increment a counter in
the case the value entered was equal to 0.
5
The AverageList Program - Checking For Zeroes
print("Average a list of non-negative integers.\n");
print("Enter one value per line, "+SENTINEL + " to end\n");
int total = 0;
int count = 0;
int value = readInt("Enter number, "+SENTINEL+" to end: ");
while (value != SENTINEL)
{
if (value != 0)
{
total += value;
count++;
}
value = readInt("Enter number, "+SENTINEL+" to end:");
}
if (count != 0)
println("Average is: " + (double) total / (double) count;
else
println("No valid values were entered.");
// private static final int SENTINEL = -1;
6
pf3
pf4
pf5

Partial preview of the text

Download Control Statements: Selection - if, switch and Common Forms and more Lab Reports Computer Science in PDF only on Docsity!

Mat 2170

Week 5

Control Statements – Selection

Spring 2009

1

Student Responsibilities

I Reading: Textbook, Chapter 4

I Lab 5

I Attendance

I EXAM 1 Thursday evening, 7:00pm

2

Chapter Four Overview – 4.3 – 4.

Along with while and for, more control statements

Used to make decisions or choices

They do not cause iteration or looping

I if

I switch

3

The if Statement — Two Forms

I The first form is used when an operation is performed only if

a particular condition is true:

if (condition) { statements to be executed if condition is true }

I The second form is used when there are two alternatives: one

for cases in which the condition is true and the other for

cases in which it is false:

if (condition) { statements to be executed if condition is true } else { statements to be executed if condition is false }

4

Choosing Between if and if/else

I No hard–and–fast rule

I Best guideline: think about the problem description (in

English) — if it uses else or otherwise, there’s a good chance

you need to use if/else

I Example: suppose we want to change the AverageList

program so it didn’t include any zero values in the average. A

single test is needed to ensure zero scores aren’t added in or

counted.

I However, if we wish to also count the non–zero scores, we

would need to add an else clause to increment a counter in

the case the value entered was equal to 0.

The AverageList Program - Checking For Zeroes

print("Average a list of non-negative integers.\n"); print("Enter one value per line, "+SENTINEL + " to end\n"); int total = 0; int count = 0; int value = readInt("Enter number, "+SENTINEL+" to end: "); while (value != SENTINEL) { if (value != 0) { total += value; count++; } value = readInt("Enter number, "+SENTINEL+" to end:"); }

if (count != 0) println("Average is: " + (double) total / (double) count; else println("No valid values were entered.");

// private static final int SENTINEL = -1;

The AverageList Program - Counting Zeroes

int total = 0; int count = 0; int zeroCount = 0; int value = readInt("Averaging list, "+SENTINEL+" to end:"); while (value != SENTINEL) { if (value != 0) { total += value; count++; } else zeroCount++; value = readInt("Enter number, "+SENTINEL+" to end:"); } if (count != 0) print("Average is: " + (double) total / (double) count + "\n"; else print("No valid values were entered.\n"); println("There were " + zeroCount + " 0’s in data.");

7

Common Forms of the if Statement

I Single line:

if (condition) statement;

I Multiline if statement with curly braces

if (condition) { statement

.. .more statements... }

8

The if Statement

ENTER

true

false

EXIT

Expression

Boolean (^) ACTION

if (Boolean Expression) { ... ACTION ... } ...

9

Example — if Statement

int sum = 0;

int n = readInt("Enter an integer: ");

if (n > 0) // if n is positive,

sum += n; // add it to sum

When the ACTION is a single statement, braces are optional.

10

Example — if Statement

int CDCollection = 0;

double AccountBalance = 58.90;

double CDPrice = readDouble("Enter cost: ");

if (AccountBalance >= CDPrice)

AccountBalance -= CDPrice;

CDCollection++;

When the ACTION is more than one statement, braces are required.

Common Forms — if/else

if (condition) { statements to be executed if condition is true } else { statements to be executed if condition is false }

Common Forms — Cascading if

if (condition 1 ) { statements 1 } else if (condition 2 ) { statements 2 } .. . else if (conditionnāˆ’ 1 ) { statementsnāˆ’ 1 } else { statementsn }

19

Cascading if Statements

BE (^1)

BE (^2)

BE (^) nāˆ’

BE (^) n

A 1

A 2

Anāˆ’

An An+

true

false

true

true

false

false

false

false

true

20

Example — Cascading if Statements

// Summing positive and negative values separately

int posSum = 0; int negSum = 0; int n = readInt("Enter value, "+SENTINEL+" to stop: "); while (n != SENTINEL) { if (n > 0) // if n is positive, posSum += n; // add to positive sum else if (n < 0) // if n is negative negSum += n; // add to negative sum else // if n is zero, inform user println("That value was zero"); n = readInt("Enter value, "+SENTINEL+" to stop: "); }

21

Do the else’s Matter?

// Summing positive and negative values separately // and counting number of times zero is entered

int posSum = 0; int negSum = 0; int zeroCount = 0; int n = readInt("Enter value, "+SENTINEL+" to stop: "); while (n != SENTINEL) { if (n > 0) // if n is positive, posSum += n; // add to positive sum if (n < 0) // if n is negative negSum += n; // add to negative sum else // if n is zero zeroCount++; // count it n = readInt("Enter value, "+SENTINEL+" to stop: "); }

22

Which is Required, a while or an if Statement?

to determine whether x is positive or not

to determine the sum of the values entered by a user

to eat cookies as long as the cookie jar is not empty

to find whether there is sufficient money to buy that CD

to balance a checkbook over several statements

to determine whether GOval C is Cyan

to process clients until the line is empty or it’s time to quit

to pick which direction to turn

to continue picking directions and moving until you arrive at

your destination

to discover whether any part of GRect R lies outside the

graphics window

The switch Statement

The switch statement provides a convenient syntax for choosing

from among a set of possible paths:

switch ( expr ) { case v 1 : statements executed if expr == v 1 break;

case v 2 : statements executed if expr == v 2 break;

...more case clauses if needed...

default: statements executed if no values match break; }

switch Statement Example

int month = readInt("Enter month (Jan=1): "); switch ( month ) { case 2: println("28 days, 29 in leap years"); break; case 4: case 6: case 9: case 11: println("30 days"); break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: println("31 days"); break; default: println("Illegal month number"); break; }