59
CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 http://www.cs.Princeton.EDU/IntroCS 1.1 Your First Program

CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007 1.1 Your First Program

Embed Size (px)

Citation preview

Page 1: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 • http://www.cs.Princeton.EDU/IntroCS

1.1 Your First Program

Page 2: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

2

Why Programming?

Idealized computer. "Please simulate the motion of a system of N heavenly bodies, subject to Newton's laws of motion and gravity."

Prepackaged software solutions. Great, if it does exactly what you need.

Computer programming. Art of making a computer do what you want.

Ada Lovelace Analytic Engine

Page 3: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

3

Languages

Machine languages. Tedious and error-prone.

“Natural” languages. Ambiguous and hard for computer to parse.

High-level programming languages. Acceptable tradeoff.

Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do. - Donald Knuth

Page 4: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

Real newspaper headlines (compiled by Rich Pattis)

Kids Make Nutritious Snacks.

Red Tape Holds Up New Bridge.

Police Squad Helps Dog Bite Victim.

Local High School Dropouts Cut in Half.

(BTW, computers and natural language processing? Yes, a sub-field! Also, computational linguistics, digital humanities, etc.)

4

Page 5: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

What’s a Program?

5

Page 6: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

Executing a Program

1: (Comment: Our goal is to find the row of students that has the moststudents who have birthdays in August.)

 2: For each row R in your section, do the following:3: Let N be the number of students in the current row R.4: If N is equal to 0, skip to instruction on line 17.5: Otherwise, N is greater than 0 -- do the following steps:

6: (Comment: the next section's goal is to count how many students7: For each student S in the row, do the following:8: Ask if his or her birthday is in August.9: If "yes", then add 1 to your count of August-birthdays in

this row.10: (End of the steps for each student in the row.) 11: (Comments: the next section's goal is to see if this is larger than

previous best.)12: If the count is larger than your maximum-so-far value, then do

the following:13: Update your maximum-so-far value to be the count for that

row.14: Let Row-ID be the name of the student sitting on the

aisle.15: (End of steps for when count > max-so-far.)16: (End of steps for when number of students N is greater than 0.)17: (Now, go to the next row! If no more rows, go to next step.) 18: Report the following:

"The row where Row-ID is on the aisle has maximum-so-far August birthdays. That is the most for any row in my section."

6

Page 7: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

7

Why Java?

Java features. Widely used. Widely available. Embraces full set of modern abstractions. Variety of automatic checks for mistakes in programs.

Java economy. Mars rover. Cell phones. Blu-ray Disc. Web servers. Medical devices. Supercomputing. …

James Goslinghttp://java.net/jag

$100 billion,5 million developers

Page 8: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

8

Why Java?

Java features. Widely used. Widely available. Embraces full set of modern abstractions. Variety of automatic checks for mistakes in programs.

Caveat.

There are only two kinds of programming languages: those people always [gripe] about and those nobody uses. - Bjarne Stroustrup

Page 9: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

9

Why Java?

Java features. Widely used. Widely available. Embraces full set of modern abstractions. Variety of automatic checks for mistakes in programs.

Caveat. No perfect language.

Our approach. Minimal subset of Java. Develop general programming skills that are applicable to:

C, C++, C#, Perl, Python, Ruby, Matlab, Fortran, Fortress, …

Page 10: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

10

A Rich Subset of the Java Language

Primitive Numeric Types

!=

==>=<=

<>--

/

+

%

-

++

*

Integer.parseInt()

Double.parseDouble()

Parsing

Math.max()Math.min()

Math.pow()Math.sqrt()

Math.PIMath.abs()

Math.log()

Math.sin()

Math Library

Math.exp()

Math.cos()System.out.println()

System.out.print()

System.out.printf()

System

for

if

Flow Control

while

else

!

||

true

Boolean

&&

false

;,

(

{

Punctuation

)

}

a[i]

new

a.length

Arrays

matches()charAt()

length()

+

String

compareTo()

""

booleanchar

long

int

Built-In Types

String

double

equals()toString()

main()new

public

class

Objects

private

static

Page 11: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 • http://www.cs.Princeton.EDU/IntroCS

Create, Compile, Execute

Page 12: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

12

Programming in Java

Programming in Java. Create the program by typing it into a text editor, and

save it as HelloWorld.java Read more: page 5 of textbook

HelloWorld.java

/******************************************* * Prints "Hello, World" * Everyone's first Java program. *******************************************/

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); }}

Page 13: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

13

Programming in Java

Issue for Beginners Using Java. Confusing! What are those first two lines of code all about?! For now: think of the program you write as only being the line

“inside” that thing called main New program? Make a copy of this file HelloWorld.java, and

rename both the file and the class (line 1 of the code)

HelloWorld.java

/******************************************* * Prints "Hello, World" * Everyone's first Java program. *******************************************/

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); }}

Page 14: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

14

Programming in Java

Some things to note: Comments:

– not instructions for the computer, for human readers

– /* a comment */ or // comment to end of line Pairs of “delimiters”: {…} “…” (…) […]

– Curly-brackets: blocks of code that are one “unit” somehow (more on this later)

Spacing and Indentation: makes code easier for humans to read

HelloWorld.java

/******************************************* * Prints "Hello, World" * Everyone's first Java program. *******************************************/

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); }}

Page 15: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

15

Programming in Java

Programming in Java. Create the program by typing it into a text editor, and

save it as HelloWorld.java Compile it by typing at the command-line:

javac HelloWorld.java

This creates a Java bytecode file named: HelloWorld.class

command-line

% javac HelloWorld.java

(or click the Compile button in your IDE)

Page 16: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

16

Programming in Java

Programming in Java. Create the program by typing it into a text editor, and

save it as HelloWorld.java Compile it by typing at the command-line:

javac HelloWorld.java Execute it by typing at the command-line:

java HelloWorld

% javac HelloWorld.java

% java HelloWorldHello, World

command-line

(or click the Run button in your IDE)

Page 17: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

Interactive Development Environments (IDEs)

An IDE is a software tool that: Includes a “smart” editor for your language Lets you compile all your Java from within the tool Lets you run the compiled program from within the tool Supports debugging Supports many other programmer needs, especially for

large programs

Example IDEs for Java:DrJava (for beginners)Eclipse (powerful!)

Important to know how Java programs are built and run without using IDEs!

17

Page 18: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

18

Page 19: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

What you know after Lab 0!

A Java program is created in a .java file. First line defines the class/program and

the name. The name of the class must match name

of .java file Second line defines main() method. (For now) your program is set of

statements in main().

19

Page 20: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

What you know after Lab 0!

A Java statement ends in a semi-colon. Sometimes statements are grouped

inside { and }. Curly-brackets must nest properly. Comments are indicated by // or by /* ...

*/ How Java treats whitespace. Indentation and spacing are important

of human readers.

20

Page 21: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

What you know after Lab 0!

Data in a running program is stored in a variable.

Variables have a type (int, double, String).

Variables are declared with a name and type, and can be initialized.

Literal values can be assigned to variables.

21

Page 22: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

What you know after Lab 0!

Methods have a name and invoke some operation or function on some data.

Example: System.out.println("Hiya!"); Some methods return a value that can

be used. Example: Math.sqrt(100) Methods like these are part of Java's

Standard Library.

22

Page 23: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

What you know after Lab 0!

Java programs (.java files) are compiled. This creates a .class file. The class file contains machine

instructions. To run the program, execute the class

file.

23

Page 24: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

24

Page 25: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

A More Complicated Example (for Lab 0)

// This is a comment at the top of class/program Demo1public class Demo1 {

public static void main(String[] args) {

// program statements go inside method main System.out.println("Hello world!"); int x = 3; System.out.println("The value of variable x is: " + x);

x = x + 3; System.out.println("Now the value of variable x is: " +

x);

// continued….

25

Page 26: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

Lab 0 Example continued

double pi = 3.14; System.out.println("The value of variable pi is: " + pi);

double someValue = Math.sqrt(x); System.out.println("The sqrt of x is: " + someValue); System.out.println("The sqrt of 100 is: " +

Math.sqrt(100));

String message = "Psst! We said pi is " + pi + "!!!"; System.out.println("Message is: " + message);

// we're done! }

26

Page 27: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

Typical Scenario for Solving Problems with a Program

1. Gather requirements2. Develop high-level approach

1. Rough break-down of the parts (maybe)2. Algorithms3. Pseudo-code (maybe)

3. Choose language, and then choose IDE4. Design test cases (both “positive” and

“negative”)5. Iterate until requirements met (maybe

create new requirements!)1. Write code2. Test3. Debug (fix)

6. Use the finished code to solve the problem at hand

27

Page 28: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

Let’s Solve a Problem with a Program!

The book and booksite has many examples: http://www.cs.princeton.edu/introcs/12types/

Problem 1.2.18: If x and y represent a point (x,y) in a Cartesian plane, print the distance to the origin.– Version 2: find distance from (x1,y1) to (x2,y2)

Problem 1.2.25: Wind chill. Given the

temperature t and wind-speed v, we define the wind chill to be:

w = 35.74 + 0.6215 t - (0.4275 t - 35.75) v0.16 Write a program WindChill.java that reads two

double values t and v and prints out the wind chill. Use Math.pow(a, b) to compute ab.

28

Page 29: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 • http://www.cs.Princeton.EDU/IntroCS

1.2 Built-In Types of Data

Page 30: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

30

Built-in Data Types

Data type. A set of values and operations defined on those values.

add, subtract, multiply, divide

3.14156.022e23

floating point numbers

double

add, subtract, multiply, divide

1712345integersint

and, or, nottruefalsetruth valuesboolean

sequences of characters

characters

set of values operationsliteral valuestype

compare'A''@'

char

String concatenate"Hello World""CS is fun"

Page 31: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

31

Basics

Definitions.

Trace.

Page 32: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 • http://www.cs.Princeton.EDU/IntroCS

Text

Page 33: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

33

Text

String data type. Useful for program input and output.

Page 34: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

34

Subdivisions of a Ruler

% java Ruler1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

"1 2 1"

"1 2 1 3 1 2 1"

"1"

public class Ruler { public static void main(String[] args) { String ruler1 = "1"; String ruler2 = ruler1 + " 2 " + ruler1; String ruler3 = ruler2 + " 3 " + ruler2; String ruler4 = ruler3 + " 4 " + ruler3; System.out.println(ruler4); }} string concatenation

Page 35: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

35

Subdivisions of a Ruler

% java Ruler1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

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

String ruler1 = "1";

String ruler2 = ruler1 + " 2 " + ruler1;

String ruler3 = ruler2 + " 3 " + ruler2;

String ruler4 = ruler3 + " 4 " + ruler3;

System.out.println(ruler4); }}

Page 36: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 • http://www.cs.Princeton.EDU/IntroCS

Integers

Page 37: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

37

Integers

int data type. Useful for expressing algorithms.

Page 38: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); }}

% javac IntOps.java% java IntOps 1234 991234 + 99 = 13331234 * 99 = 1221661234 / 99 = 121234 % 99 = 46

38

Integer Operations

command-linearguments

Java automatically converts a, b , and rem to type String

1234 = 12*99 + 46

Page 39: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

public class IntOps { public static void main(String[] args) { int a = StdIn.readInt(); int b = StdIn.readInt();

int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); }}

39

Reading from the Keyboard (p. 126-127)

Calls to book’s library functionto read an int value from keyboard

• StdIn.readint() and StdIn.readDouble() etc. (see pages 127-127)• Library methods, just like sqrt() and System.out.println()• Not standard Java, but created by our textbook authors• Must have the Java file StdIn.java in same directory as your code

Page 40: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

40

Initializing Variables

Q. What happens if I forget to initialize the variable a or b? Java compiler does not allow this. Caveat: in other languages, variable initialized to arbitrary

value.

Q. What do you mean, arbitrary?

Page 41: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

41

Initializing Variables

Q. What happens if I forget to initialize the variable a or b? Java compiler does not allow this. Caveat: in other languages, variable initialized to arbitrary

value.

Q. What do you mean, arbitrary?

int main( int argc, char *argv[] ) { int whoops; printf( "%d\n", whoops );}

C code

uninitializedvariable

% gcc -o uninit uninit.c% uninit-1073746048

Page 42: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 • http://www.cs.Princeton.EDU/IntroCS

Floating-Point Numbers

Page 43: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

43

Floating-Point Numbers

double data type. Useful in scientific applications.

Page 44: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

44

Math Library

Page 45: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

45

Quadratic Equation

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

// parse coefficients from command-line double b = Double.parseDouble(args[0]); double c = Double.parseDouble(args[1]);

// calculate roots double discriminant = b*b - 4.0*c; double d = Math.sqrt(discriminant); double root1 = (-b + d) / 2.0; double root2 = (-b - d) / 2.0;

// print them out System.out.println(root1); System.out.println(root2); }}

Ex. Solve quadratic equation x2 + bx + c = 0.

Page 46: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

Testing. Some valid and invalid inputs.

46

% java Quadratic –3.0 2.02.01.0

% java Quadratic –1.0 –1.01.618033988749895-0.6180339887498949

% java Quadratic 1.0 1.0NaNNaN

% java Quadratic 1.0 hellojava.lang.NumberFormatException: hello

% java Quadratic 1.0java.lang.ArrayIndexOutOfBoundsException

Testing

command-line arguments

not a number

golden ratio

x2 – 3x + 2

x2 – x - 1

x2 + x + 1

Page 47: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 • http://www.cs.Princeton.EDU/IntroCS

Booleans

Page 48: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

48

Booleans

boolean data type. Useful to control logic and flow of a program.

Page 49: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

49

Comparisons

Comparisons. Take operands of one type and produce an operand of type boolean.

Page 50: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

50

Leap Year

Q. Is a given year a leap year?A. Yes if either (i) divisible by 400 or (ii) divisible by 4 but not 100.

public class LeapYear { public static void main(String[] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear;

// divisible by 4 but not 100 isLeapYear = (year % 4 == 0) && (year % 100 != 0); // or divisible by 400 isLeapYear = isLeapYear || (year % 400 == 0);

System.out.println(isLeapYear); }}

% java LeapYear 2004true% java LeapYear 1900false% java LeapYear 2000true

Page 51: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 • http://www.cs.Princeton.EDU/IntroCS

Type Conversion

Page 52: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

52

Type Conversion

Type conversion. Convert from one type of data to another. Automatic: no loss of precision; or with strings. Explicit: cast; or method.

Page 53: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

53

Random Integer

Ex. Generate a pseudo-random number between 0 and N-1.

public class RandomInt { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double r = Math.random(); int n = (int) (r * N);

System.out.println("random integer is " + n); }}

String to int (method)

double to int (cast) int to double (automatic)

int to String (automatic)% java RandomInt 6random integer is 3% java RandomInt 6random integer is 0% java RandomInt 10000random integer is 3184

double between 0.0 and 1.0

Page 54: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

54

Summary

A data type is a set of values and operations on those values. String text processing. double, int mathematical calculation. boolean decision making.

Be aware. Declare type of values. Convert between types when necessary. In 1996, Ariane 5 rocket exploded after takeoff

because of bad type conversion.

Page 55: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 • http://www.cs.Princeton.EDU/IntroCS

1.3 Conditionals and Loops

Page 56: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

56

Control Flow

Control flow. Sequence of statements that are actually executed in a

program. Conditionals and loops: enable us to choreograph control flow.

statement 2

statement 1

statement 4

statement 3 boolean 2true

false

statement 2

boolean 1

statement 3

false

statement 1

true

straight-line control flow control flow with conditionals and loops

Page 57: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

57

If-Else Statement

The if-else statement. A common branching structure. Check boolean condition. If true, execute some statements. Otherwise, execute other statements.

if (boolean expression) { statement T;}else { statement F;}

booleanexpression

statement F

falsetrue

if-else syntax

if-else flow chart

statement T

can be any sequenceof statements

Page 58: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

58

If-Else: Leap Year

If-else. Take different action depending on value of variable. If isLeapYear is true, then print "is a". Otherwise, print "isn't a ".

System.out.print(year + " ");

if (isLeapYear) { System.out.print("is a");}else { System.out.print("isn't a");}

System.out.println(" leap year");

Page 59: CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © 2007  1.1 Your First Program

59

Oblivious Sorting

Sort. Read in 3 integers and rearrange them in ascending order.

Puzzle 1. Sort 4 integers with 5 compare-exchanges.

Puzzle 2. Sort 6 integers with 12.

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

int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = Integer.parseInt(args[2]);

if (b > c) { int t = b; b = c; c = t; } if (a > b) { int t = a; a = b; b = t; } if (b > c) { int t = b; b = c; c = t; }

System.out.println(a + " " + b + " " + c); }}

read in 3 integersfrom command-line

swap b and c

% java Sort3 9 8 77 8 9

% java Sort3 2 1 71 2 7

swap a and b

swap b and c