Conditionals, Loops, and Style

Similar documents
Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

PROGRAMMING STYLE. Fundamentals of Computer Science I

CONDITIONAL EXECUTION

Variables and data types

CONDITIONAL EXECUTION

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Introduction. C provides two styles of flow control:

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Static methods. Not actually a valid Java static method. Fundamentals of Computer Science Keith Vertanen

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

1.3 Conditionals and Loops

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

Condi(onals and Loops

Loops. CSE 114, Computer Science 1 Stony Brook University

CS111: PROGRAMMING LANGUAGE II

1.3 Conditionals and Loops

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

1.3 Conditionals and Loops

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repetition, Looping. While Loop

AP CS Unit 3: Control Structures Notes

Learning Outcomes for this week. Inf1-OP. A Foundation for Programming. A Foundation for Programming

CSE 114 Computer Science I

CS 112 Introduction to Programming

Scope of this lecture. Repetition For loops While loops

Introduction to Java & Fundamental Data Types

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Java Bytecode (binary file)

More on methods and variables. Fundamentals of Computer Science Keith Vertanen

Lecture 3: Loops. While Loops. While Loops: Powers of Two. While Loops: Newton-Raphson Method

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

CS 177 Recitation. Week 1 Intro to Java

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Java Coding 3. Over & over again!

MODULE 02: BASIC COMPUTATION IN JAVA

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CSE 142/143 Unofficial Style Guide

1.3 Conditionals and Loops

Introduction to the Java Basics: Control Flow Statements

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

CS1150 Principles of Computer Science Loops (Part II)

CS 106 Introduction to Computer Science I

Primitive Data, Variables, and Expressions; Simple Conditional Execution

DATA TYPES AND EXPRESSIONS

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CMPT 125: Lecture 4 Conditionals and Loops

M e t h o d s a n d P a r a m e t e r s

TESTING AND DEBUGGING

Visual Programming. Lecture 3: Loops, Arrays. Mahmoud El-Gayyar

Lecture 3: Loops. While Loops. While Loops: Newton-Raphson Method. While Loops: Powers of Two

PROGRAMMING FUNDAMENTALS

2.3 Flow Control. Flow-Of-Control. If-Else: Leap Year. If-Else

Warmup : Name that tune!

Full file at

COMP-202 Unit 4: Programming with Iterations

Lecture 14. 'for' loops and Arrays

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

CS1004: Intro to CS in Java, Spring 2005

Lec 3. Compilers, Debugging, Hello World, and Variables

4 Programming Fundamentals. Introduction to Programming 1 1

STUDENT LESSON A12 Iterations

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

CP122 CS I. Iteration

Lecture 5: Methods CS2301

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

CS106A, Stanford Handout #30. Coding Style

COMP 111. Introduction to Computer Science and Object-Oriented Programming

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Assignment Marking Criteria

Last Class. While loops Infinite loops Loop counters Iterations

Chapter 2: Programming Concepts

Boolean evaluation and if statements. Making decisions in programs

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

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

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Repetition Structures

Introduction to Computer Science Unit 2. Notes

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2009

Transcription:

Conditionals, Loops, and Style yes x > y? no max = x; max = y; http://xkcd.com/292/ Fundamentals of Computer Science Keith Vertanen Copyright 2013

Control flow thus far public class ArgsExample public static void main(string [] args) time 0 String product = args[0]; time 1 int qty = Integer.parseInt(args[1]); time 2 double cost = Double.parseDouble(args[2]); time 3 time 4 time 5 time 6 double total = qty * cost; System.out.print("To buy " + qty); System.out.print(" " + product); System.out.println(" you will need $" + total); 2

Control flow Interesting and powerful programs need: To skip over some lines To repeat lines Conditionals sometimes skip parts Loops allow repetition of lines 3

if statement Common branching statement Evaluate a boolean expression If true, do some stuff If false, do some other stuff (optional) Note lack of semicolon! if (expression) statement1; statement2; if (expression) statement1; statement2; else statement3; statement4; 4

if statement 's optional if only one statement if (expression) statement1; if (expression) statement1; else statement2; Example: if (x > y) max = x; else max = y; yes x > y? no max = x; max = y; 5

if examples if (x < 0) x = -x; Take absolute value of x if (Math.random() < 0.5) money = money * 2; else money = 0.0; Make a double or nothing bet with 50-50 odds. if (x > y) int t = x; x = y; y = t; Put x and y into sorted order num = 0; if (args.length > 0) num = Integer.parseInt(args[0]); If a command line option is passed in, use it as the value for num. 6

Nested if Execute one of three options: if (category == 0) title = "Books"; else if (category == 1) title = "CDs"; else title = "Misc"; = if (category == 0) title = "Books"; else if (category == 1) title = "CDs"; else title = "Misc"; Both do exactly same thing Right probably more readable in general 7

while loop while-loop: common way to repeat code Evaluate a boolean expression If true, do a block a code Go back to start of while loop If false, skip over block while (expression) statement1; statement2; while loop with multiple statements in a block while (expression) statement1; while loop with a single statement 8

while loop example 1 Print out summations, 0 + 1 + 2 + + N public class Summation public static void main(string [] args) int limit = Integer.parseInt(args[0]); int i = 1; int sum = 0; while (i <= limit) sum += i; System.out.println("sum 0..." + i + " = " + sum); i++; % java Summation 4 sum 0...1 = 1 sum 0...2 = 3 sum 0...3 = 6 sum 0...4 = 10 9

while loop example 2 Print powers of 2 up to but not including limit public class Powers2 public static void main(string [] args) int limit = Integer.parseInt(args[0]); long total = 1; while (total < limit) System.out.println(total); total = total * 2; % java Powers2 16 1 2 4 8 10

while loop while (expression) statement1; statement2; while (expression); statement1; statement2; This semicolon is the entire body of the while loop! Almost never what you want. 11

while loop while (expression) statement1; statement2; while (expression) statement1; statement2; Only statement1 considered inside the while loop. Java doesn't care about indentation. But I do (and so does your TA). 12

for loop for-loop: another common type of loop Execute an initialization statement Evaluate a boolean expression If true, do code block then increment If false, done with loop for (init; expression; increment) statement1; statement2; 13

for loop versions for (init; expression; increment) statement1; statement2; block version for (init; expression; increment) statement1; single line version for (init; expression; increment); statement1; statement2; buggy version 14

for loop example Print out summations, 0 + 1 + 2 + + N public class SummationFor public static void main(string [] args) int limit = Integer.parseInt(args[0]); int sum = 0; for (int i = 1; i <= limit; i++) sum += i; System.out.println("sum 0..." + i + " = " + sum); 15

for loop anatomy Declare and initialize a variable for use inside and outside the loop body Condition which must be true to execute loop body Changes the loop counter variable int sum = 0; Declare and initialize a loop control variable for (int i = 1; i <= limit; i++) sum += i; System.out.println("sum 0..." + i + " = " + sum); Loop body, executes 0 or more times 16

do while loop do while loop Always executes loop body at least once Do a block a code Evaluate a boolean expression If expression true, do block again do statement1; statement2; while (condition); do while needs this semicolon! 17

do while example Draw random points in [0, 1) until we draw one in interval [left, right] public class DrawPoints public static void main(string[] args) double left = Double.parseDouble(args[0]); double right = Double.parseDouble(args[1]); double point = 0.0; int count = 0; do point = Math.random(); count++; while ((point < left) (point > right)); System.out.println(count + " random draws"); 18

do while example runs % java DrawPoints 0.1 0.2 9 random draws % java DrawPoints 0.1 0.2 2 random draws % java DrawPoints 0.1 0.11 74 random draws % java DrawPoints 0.1 0.2 198 random draws % java DrawPoints -0.2-0.1 (never terminates!) % java DrawPoints 0.2 0.1 (never terminates!) Infinite loop: possible for all loop types (while/for) Eclipse, hit the red stop button Command line, hit ctrl-c 19

Nested loops A loop inside another loop public class StarTriangle public static void main(string[] args) int limit = Integer.parseInt(args[0]); for (int i = 0; i < limit; i++) for (int j = 0; j <= i; j++) System.out.print("*"); System.out.println(); % java StarTriangle 4 * ** *** **** 20

Loop choice Does your loop need a counter variable? e.g. Going from 0 to N or N to 0 in fixed steps Use a for loop Counter variable is local to loop Harder to forget the increment/decrement Do you need an unknown number of loops? Use a while loop Do you need to loop at least once? Use a do while loop 21

http://www.flickr.com/photos/onepointzero/1381580071/sizes/l/in/photostream/ 22

Style: comments Comments help reader/grader understand your program Good comments explain why something is done Write comments before coding tricky bits Helps you formulate a plan Don't comment the obvious: i++; // Increment i by one // Two slashes means a comment only on this line /* Slash start means a comment that can go over multiple lines end with a start slash */ int dist = x + y; // Short comments can go here too 23

Variable names Style: naming things Begin with lowercase, uppercase each new word int totalwidgets; Class names Begin uppercase, then lowercase except for new words public class InventoryTracker Name exactly as in assignment description Constants All upper case, use _ between words double SPEED_LIGHT = 3.0e8; 24

Style: whitespace public class StarTriangle public static void main(string[] args) int limit = Integer.parseInt(args[0]); for (int i=0;i<limit;i++) for (int j = 0; j <= i; j++) System.out.print("*");System.out.println(); Indent each level of conditionals/loops Indent a fixed number of spaces (3-4) Eclipse can fix automatically, ctrl-a then ctrl-i Use blank lines to separate logical sections Only one statement per line 25

Style: whitespace for (int i=0;i<limit;i++) vs. for (int i = 0; i < limit; i++) a=b*c/d-(8.12*e); vs. a = b * c / d - (8.12 * e); //this is a comment //describing my code vs. // this is a comment // describing my code Use spaces between Statements in for loop Operators in math expressions After the // starting a comment 26

Style: whitespace Math. random (); vs. Math.random(); args [0]; vs. args[0]; i = i + 1 ; i = i + 1; vs. Do NOT use spaces between method class, dot, name, or ()'s array name and []'s statement and ending semicolon 27

Style: whitespace Use spaces to align parallel code if it makes it more readable Often helps to spot mistakes int numpoints = Integer.parseInt(args[0]); int startx = Integer.parseInt(args[0]); int starty = Integer.parseInt(args[2]); double velx = Integer.parseInt(args[3]); double vely = Integer.parseInt(args[4]); int numpoints = Integer.parseInt(args[0]); int startx = Integer.parseInt(args[0]); int starty = Integer.parseInt(args[2]); double velx = Integer.parseInt(args[3]); double vely = Integer.parseInt(args[4]); 28

Style: curly bracing public class HelloWorld public static void main(string [] args) System.out.println("Hello world!"); BSD-Allman style public class HelloWorld public static void main(string [] args) System.out.println("Hello world!"); K&R style public class HelloWorld public static void main(string [] args) System.out.println("Hello world!"); Choose a bracing style and stick to it! No mixing and matching! 29

Summary Program flow of control Conditionals skip sections if statement Loops repeat sections while loop, for loop, do while loop Conditionals and loops can be nested Best loop depends on the situation Style Makes code easier to read + grade Good style = fewer bugs http://xkcd.com/537/ 30