44
COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

Embed Size (px)

Citation preview

Page 1: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110:Introduction to Programming

Tyler JohnsonFeb 11, 2009

MWF 11:00AM-12:15PMSitterson 014

Page 2: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 20092

Announcements

Lab 3 due tomorrow by midnight

Program 1 has been graded

Page 3: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 20093

Questions?

Page 4: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 20094

Today in COMP 110

Programming with Loops

Programming Demo

Using the Debugger

Page 5: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 20095

Review

The while statement can be used to construct a loop in Java

while(Boolean_Expression) {Statement_1Statement_2…Statement_N

}

As long as Boolean_Expression is true, the statements in the loop body are executed

Page 6: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 20096

Review

Do-While Syntax

do {Statement_1Statement_2…Statement_N

} while (Boolean_Expression); //note the semicolon!

Execute Statements_1…NIf Boolean_Expression is true, repeat

Page 7: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 20097

Review

For Loop Syntax

for(Initializing_Action; Boolean_Expression; Update_Action) {

Statement_1Statement_2…Statement_N

}

Initializing_Action is used to initialize a counter variableBoolean_Expression is the stopping condition for the loopUpdate_Action is used to update a counter variable after the loop body is executed

Page 8: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 20098

Review

Choosing a loop

Do-WhileWhen you want the body to be executed at least onceUseful for checking user input

ForMore convenient/readable when the number of iterations is known beforehand, e.g. stored in some counter variable

WhileSafest choice, can be used to create any kind of loopWhen it might be necessary for the loop to iterate zero times

Page 9: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 20099

The Break Statement

Causes the immediately enclosing switch statement or loop to end

The remainder of the loop (or switch) is not executed

int i = 0;

while (i < 5) {

if(i == 3) break;

i++;}

//value of i is 3

Page 10: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200910

The Continue Statement

Causes the current loop iteration to end immediately

Execution resumes at the loop condition

for (int i = 0; i < 5, i++) {

if(i == 3) continue;

System.out.println(i + ", ");}

0, 1, 2, 4,

Output

Page 11: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200911

Break & Continue

Avoid using break and continue inside loops

Can make your programs difficult to understand!

Page 12: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200912

Nested Loops

It’s possible, and sometimes necessary to place loops inside other loops

This is called nestingJust like with nested if-statements

Page 13: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200913

Nested Loops

Example

int sum = 0;int i = 0;

while(i < 10) {

for(int j = 0; j < 20; j++) sum = sum + j; //executes 10 * 20 times

i++; //executes 10 times, i = [0, 9]}

Page 14: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200914

Commas in For Statements

We can perform multiple initializations or updates using the comma operator

int n, c;int product;

for (n = 1, c = 1; n <= 5; c = c + 2, n++) { product = product * c * n;

}

System.out.println(product);

Page 15: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200915

Designing Loops

Creating a loop involves designing three things

Initialization of Variables

Loop Body

Stopping Condition

Page 16: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200916

Designing a Loop Body

How to determine what statements should be inside the body of a loop?

ExampleCalculate the sum of numbers entered by the user

Page 17: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200917

Designing a Loop Body

Output instructions to the userInitialize variablesPrompt user for inputRead a number into variable nextsum = sum + next;Prompt user for inputRead a number into variable nextsum = sum + next;Prompt user for inputRead a number into variable nextsum = sum + next;...Output sum

Repeated statementsbecome your loop body

Statements that are only done onceare not part of your loop body

Page 18: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200918

Pseudocode with Loop Body

Output instructions to the userInitialize variablesDo the following for the appropriate number of times:{ Prompt user for input Read a number into variable next sum = sum + next;}Output sum

Initializing statements

How do we end the loop?How many iterations?

Page 19: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200919

Initializing Statements

Variables used in your loop need to be initialized (set to a value) before the loopnext

Read a number into variable next

We read a new value for next before using it during each iteration of the loop so we do not need to initialize it

sumsum = sum + next;

sum is on the right side of an assignment statement. sum MUST have a valid value before the loop starts.

Page 20: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200920

Initialize Sum

What should sum be initialized to?

Consider the first iterationAfter executing the first iteration, the expected value of sum should be• sum == next (the first input value)

The assignment statement is• sum = sum + next;

Therefore, initial value of sum is• sum = 0;

Page 21: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200921

Loop with Initializations

Output instructions to the usersum = 0;Do the following for the appropriate number of times:{ Prompt user for input Read a number into variable next sum = sum + next;}Output sum

Initializing statements

Page 22: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200922

Ending Loops

How to choose a stopping condition for your loop?

Count-controlled loopsWhen you know number of loop iterationsfor(count = 0; count < iterations; count++)

User-controlled loopsAsk-before-iteratingSentinel value

BooleanThe value of a boolean indicates whether the loop should stop

Page 23: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200923

Count-Controlled Loops

A program to average exam scores input by the user

We know the size of the class is "numStudents"

double next, sum = 0, average;int i;

for(i = 0; i < numStudents; i++) { //# iterations is fixed

next = keyboard.nextDouble();sum = sum+next;

}

average = sum/numStudents;

Page 24: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200924

Off-by-One errors

Loop repeats one too many or one too few times

How many times do these loops iterate?

for (count = 1; count < 10; count++);Loop for count = [1,9] (9 iterations)

for (count = 0; count <= 10; count++);Loop for count = [0,10] (11 iterations)

for (count = 1; count <= 10; count++);Loop for count = [1,10] (10 iterations)

Page 25: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200925

Ask-Before-Iterating

Sometimes it is useful to have the user decide when a loop should end

String answer;

do {//perform some computationsSystem.out.print("Continue? yes/no");answer = keyboard.next();

} while (answer.equalsIgnoreCase("yes"));

Page 26: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200926

Sentinel Value

Signal end of input

System.out.print("Enter a negative number to end the loop");int next = keyboard.nextInt(); int sum = 0;

while (next >= 0) {sum = sum + next;System.out.print("Enter a number: ");next = keyboard.nextInt();

}

Page 27: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200927

Booleans

int next, sum = 0;boolean moreNumbers = true;Scanner keyboard = new Scanner(System.in);

while(moreNumbers ) {next = keyboard.nextInt();

if (next < 0) moreNumbers = false; //this will be the last

iterationelse

sum = sum + next;}

System.out.print("The sum is " + sum);

Page 28: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200928

Exercise

What does the following display?

int product = 1;int max = 20;

for(int i = 0; i <= max; i++)product = product * i;

System.out.println("The product is " + product);

The product is 0

Output

Page 29: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200929

Example Problem

Find the lowest and highest ages in the class

Page 30: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200930

Loop Body

Get age of student 1Update min/max agesGet age of student 2Update min/max ages......Get age of student 37 Update min/max agesEnd loopOutput min and max ages

Page 31: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200931

Min/Max Ages

int min = 2000; // initialize to large valueint max = 0; // initialize to small value

for (int count = 1; count <= 37; count++) {

//Ask student #count for age if (age > max) max = age; if (age < min) min = age;}//Output min and max ages

Page 32: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200932

Min/Max Ages

if (age > max) max = age;if (age < min) min = age;

Ages max min

0 2000

20 20 20

23 23 20

18 23 18

18 23 18

25 25 18

12 25 12

94 94 12

36 94 12

Page 33: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200933

Debugging

What to do if there’s something wrong with your program, but you’re not sure what?

Trace the variablesWatch the variables change as the program executes

Page 34: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200934

Tracing Variables

Two ways to trace variables

ManuallyUsing print statements

AutomaticallyUsing the debugger

Page 35: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200935

Manual Tracing

Insert print statements to output the values of variables

System.out.print("Enter a negative number to end the loop");int next = keyboard.nextInt(); int sum = 0;

while (next >= 0) {System.out.println(next);sum = sum + next;System.out.println(sum);System.out.print("Enter a number: ");next = keyboard.nextInt();

}

Page 36: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200936

Using a DEBUG flag

Use a DEBUG flag to disable the tracing of variables when no longer needed

final boolean DEBUG = true; //trace variables?…if(DEBUG) {

//print the values of variables}

Page 37: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200937

Automatic Tracing

Use a debuggerjGRASP provides an integrated debugger

Allows you to “step” through your program to see how variables change with each line of code

Page 38: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200938

Programming Demo

Hand-shaking problem

Given a group of n people, everyone shakes hands with everyone else

How many handshakes?

Page 39: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200939

Programming Demo

Example, n = 4

Person 1 shakes hands with Person 2Person 1 shakes hands with Person 3Person 1 shakes hands with Person 4Person 2 shakes hands with Person 3Person 2 shakes hands with Person 4Person 3 shakes hands with Person 4

6 handshakes

Page 40: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200940

Programming Demo

Example, n = 4

Person 1 shakes hands with Person 2 shakes hands with Person 3 shakes hands with Person 4Person 2 shakes hands with Person 3 shakes hands with Person 4Person 3 shakes hands with Person 4

6 handshakes

Page 41: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200941

Handshake Problem

1 2 3 4 5 6

1 X X X X X

2 X X X X

3 X X X

4 X X

5 X

6

n = 6

Outer Loop

Inner Loop

Page 42: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200942

Programming Demo

Implementation using nested loops

Page 43: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200943

Tutorial

Using the jGRASP Debugger

Page 44: COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014

COMP 110: Spring 200944

Friday

Recitation

BringLaptops (fully charged)TextbookQuestions about Program 2