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

Similar documents
Conditionals, Loops, and Style

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)

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

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

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

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

Introduction. C provides two styles of flow control:

1.3 Conditionals and Loops

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

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

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

Condi(onals and Loops

1.3 Conditionals and Loops

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

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CS111: PROGRAMMING LANGUAGE II

1.3 Conditionals and Loops

Repetition, Looping. While Loop

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

CSE 114 Computer Science I

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

Scope of this lecture. Repetition For loops While loops

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

AP CS Unit 3: Control Structures Notes

CS 112 Introduction to Programming

Introduction to Java & Fundamental Data Types

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

MODULE 02: BASIC COMPUTATION IN JAVA

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

Java Bytecode (binary file)

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

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

Introduction to the Java Basics: Control Flow Statements

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

1.3 Conditionals and Loops

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

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

Java Coding 3. Over & over again!

CS 177 Recitation. Week 1 Intro to Java

CS1150 Principles of Computer Science Loops (Part II)

DATA TYPES AND EXPRESSIONS

CSE 142/143 Unofficial Style Guide

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

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

Full file at

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

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

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

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

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

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

CP122 CS I. Iteration

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

CMPT 125: Lecture 4 Conditionals and Loops

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CS106A, Stanford Handout #30. Coding Style

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

Primitive Data, Variables, and Expressions; Simple Conditional Execution

TESTING AND DEBUGGING

Chapter 2: Programming Concepts

Assignment Marking Criteria

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

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

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

4 Programming Fundamentals. Introduction to Programming 1 1

Warmup : Name that tune!

CS1004: Intro to CS in Java, Spring 2005

Lecture 14. 'for' loops and Arrays

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

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

CS 106 Introduction to Computer Science I

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

STUDENT LESSON A12 Iterations

PROGRAMMING FUNDAMENTALS

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

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

COMP-202 Unit 4: Programming with Iterations

CS 251 Intermediate Programming Coding Standards

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

Building Java Programs Chapter 2

Topics. Chapter 5. Equality Operators

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

Looping. Arizona State University 1

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

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

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

A Foundation for Programming

Lecture 5: Methods CS2301

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

CIS 110 Introduction to Computer Programming Summer 2018 Midterm. Recitation ROOM :

Transcription:

Conditionals, Loops, and Style Control flow thus far yes no x > y? max = x; max = y; public class ArgsExample time 0 String product = args[0]; time 1 int qty = Integer.parseInt(args[1]); time 2 double cost = Double.parseDouble(args[2]); time 3 double total = qty * cost; time 4 System.out.print("To buy " + qty); time 5 System.out.print(" " + product); http://xkcd.com/292/ time 6 System.out.println(" you will need $" + total); Fundamentals of Computer Science Keith Vertanen Copyright 2013 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) if (expression) if (expression) statement3; statement4; Note lack of semicolon! 4

if statement 's optional if only one statement if (expression) if (expression) if (x < 0) x = -x; Take absolute value of x if examples if (Math.random() < 0.5) money = money * 2; money = 0.0; Make a double or nothing bet with 50-50 odds. Example: if (x > y) max = x; max = y; yes x > y? no max = x; max = y; 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. 5 6 Nested if Execute one of three options: if (category == 0) title = "Books"; if (category == 1) title = "CDs"; title = "Misc"; = if (category == 0) title = "Books"; if (category == 1) title = "CDs"; title = "Misc"; while loop while-loop: common way to repeat code Evaluate a boolean expression If true, do a block a code, evaluate again If false, skip over block Both do exactly same thing Right probably more readable in general 7 while loop with multiple statements in a block while loop with a single statement 8

while loop example 1 Print out summations, 0 + 1 + 2 + + N while loop example 2 Print powers of 2 up to but not including limit public class Summation 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 public class Powers2 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 loop ; This semicolon is the entire body of the while loop! Almost never what you want. Only statement1 considered inside the while loop. Java doesn't care about indentation. But I do (and so does your TA). 11 12

for loop for loop versions 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) block version for (init; expression; increment) 13 for (init; expression; increment) for (init; expression; increment); single line version buggy version 14 for loop example Print out summations, 0 + 1 + 2 + + N public class SummationFor 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); Declare and initialize a variable for use inside and outside the loop body Declare and initialize a loop control variable for loop anatomy int sum = 0; for (int i = 1; i <= limit; i++) sum += i; System.out.println("sum 0..." + i + " = " + sum); Loop body, executes 0 or more times Condition which must be true to execute loop body Changes the loop counter variable 15 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 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 while (condition); do while needs this semicolon! 17 do point = Math.random(); count++; while ((point < left) (point > right)); System.out.println(count + " random draws"); 18 do while example runs Nested loops A loop inside another loop % java DrawPoints 0.1 0.2 9 random draws % java DrawPoints 0.1 0.2 2 random draws % java DrawPoints -0.2-0.1 (never terminates!) % java DrawPoints 0.2 0.1 (never terminates!) % java DrawPoints 0.1 0.11 74 random draws % java DrawPoints 0.1 0.2 198 random draws Infinite loop: possible for all loop types (while/for) Eclipse, hit the red stop button Command line, hit ctrl-c 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 * ** *** **** 19 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 http://www.flickr.com/photos/onepointzero/1381580071/sizes/l/in/photostream/ 21 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 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; 23 24

Style: whitespace 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(); for (int i=0;i<limit;i++) a=b*c/d-(8.12*e); //this is a comment //describing my code for (int i = 0; i < limit; i++) a = b * c / d - (8.12 * e); // this is a comment // describing my code 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 Use spaces between Statements in for loop Operators in math expressions After the // starting a comment 25 26 Math. random (); args [0]; Style: whitespace Math.random(); args[0]; Style: whitespace Use spaces to align parallel code if it makes it more readable Often helps to spot mistakes i = i + 1 ; i = i + 1; Do NOT use spaces between method class, dot, name, or ()'s array name and []'s statement and ending semicolon 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]); 27 28

Style: curly bracing public class HelloWorld System.out.println("Hello world!"); public class HelloWorld System.out.println("Hello world!"); public class HelloWorld System.out.println("Hello world!"); BSD-Allman style K&R style Choose a bracing style and stick to it! No mixing and matching! 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/ 29 30