Introduction to Computer Programming

Similar documents
Building Java Programs

Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs

Topic 5 for loops and nested loops

CSC 160 Introduction to Programming for Non-majors. Lecture 4 - Looping Around Loops I: Counting Loops. Why loops?

CS 112 Introduction to Programming

Building Java Programs Chapter 2

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

Building Java Programs Chapter 2

Recap: Assignment as an Operator CS 112 Introduction to Programming

Introduction to Computer Programming

Repetition with for loops

CS 112 Introduction to Programming

Chapter Legal intliterals: 22, 1, and d Results of intexpressions:

Primitive data, expressions, and variables

Building Java Programs

CSC 270 Survey of Programming Languages

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

Over and Over Again GEEN163

Example: Monte Carlo Simulation 1

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Midterm Examination (MTA)

Object Oriented Programming. Java-Lecture 1

Programming with Java

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Introduction to Java Unit 1. Using BlueJ to Write Programs

COMP 202 Java in one week

Building Java Programs

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Loops. CSE 114, Computer Science 1 Stony Brook University

ITERATION WEEK 4: EXMAPLES IN CLASS

AP Computer Science Unit 1. Writing Programs Using BlueJ

Basics of Java Programming

CS111: PROGRAMMING LANGUAGE II

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Introduction to Computer Programming

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

Full file at

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Introduction to Java & Fundamental Data Types

Course Outline. Introduction to java

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

4 WORKING WITH DATA TYPES AND OPERATIONS

CSE 1223: Introduction to Computer Programming in Java Chapter 1 Computer Basics

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

AP Computer Science Unit 1. Programs

First Java Program - Output to the Screen

CS110: PROGRAMMING LANGUAGE I

Loops. Repeat after me

CS141 Programming Assignment #6

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

Introduction to Algorithms and Data Structures

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java

ECE 122. Engineering Problem Solving with Java

Section 2.2 Your First Program in Java: Printing a Line of Text

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Input. Scanner keyboard = new Scanner(System.in); String name;

CSC 1051 Data Structures and Algorithms I

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Exercise (Revisited)

Java Coding 3. Over & over again!

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

CompSci 125 Lecture 11

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

Question: Total Points: Score:

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

COMP 202. Java in one week

Top-Down Program Development

Formatted Output (printf) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

AP Computer Science Unit 1. Writing Programs Using BlueJ

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Nested Loops. A loop can be nested inside another loop.

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

1. Find the output of following java program. class MainClass { public static void main (String arg[])

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

St. Edmund Preparatory High School Brooklyn, NY

Section 2.2 Your First Program in Java: Printing a Line of Text

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Full file at

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

CMSC131. Introduction to your Introduction to Java. Why Java?

true false Imperative Programming III, sections , 3.0, 3.9 Introductory Programming Control flow of programs While loops: generally Loops

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

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Combined Assignment Operators. Flow of Control. Increment Decrement Operators. Operators Precedence (Highest to Lowest) Slide Set 05: Java Loops

CSC 1051 Data Structures and Algorithms I

Darrell Bethea May 10, MTWRF 9:45-11:15 AM Sitterson 011

Building Java Programs

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Transcription:

Introduction to Computer Programming Lecture 3 Counting Loops Repetition with for Loops So far, repeating a statement is redundant: System.out.println("Homer says:"); System.out.println("I am so smart"); System.out.println("I am so smart"); System.out.println("I am so smart"); System.out.println("I am so smart"); System.out.println ("S-M-R-T... I mean S-M-A-R-T"); Java's for loop statement performs a task many times. System.out.println("Homer says:"); for (int i = 1; i <= 4; i++) { // repeat 4 times System.out.println("I am so smart"); System.out.println ("S-M-R-T... I mean S-M-A-R-T");

for Loop Syntax for (initialization; test; update) { statement; statement;... statement; Perform initialization once. Repeat the following: Check if the test is true. If not, stop. Execute the statements. Perform the update. header body Initialization for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); Tells Java what variable to use in the loop Performed once as the loop begins The variable is called a loop counter can use any name, not just i can start at any value, not just 1

Test for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); Tests the loop counter variable against a limit Uses comparison operators: < less than <= less than or equal to > greater than >= greater than or equal to Increment And Decrement There are shortcuts to increase or decrease a variable's value by 1 Shorthand version Equivalent Longer variable++; variable = variable + 1; --variable; variable = variable -1;

Increment And Decrement - Examples int x = 2; x++; // x = x + 1; // x now stores 3 double gpa = 2.5; gpa--; // gpa = gpa - 1; // gpa now stores 1.5 Modify-and-Assign There are shortcuts to modify a variable's value. Shorthand version Equivalent Longer variable += value; variable = variable + value; variable -= value; variable = variable - value; variable *= value; variable = variable * value; variable /= value; variable = variable / value; variable %= value; variable = variable % value;

Modify-and-Assign - Examples x += 3; // x = x + 3; gpa -= 0.5; // gpa = gpa - 0.5; number *= 2; // number = number * 2; Repetition Over A Range System.out.println("1 squared = " + 1 * 1); System.out.println("2 squared = " + 2 * 2); System.out.println("3 squared = " + 3 * 3); System.out.println("4 squared = " + 4 * 4); System.out.println("5 squared = " + 5 * 5); System.out.println("6 squared = " + 6 * 6); Intuition: "I want to print a line for each number from 1 to 6" The for loop does exactly that! for (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i)); "For each integer i from 1 through 6, print..."

Output: 1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16 Whoo! Loop walkthrough 4 1 2 3 for (int i = 1; i <= 4; i++) { System.out.println(i + " squared = " + (i * i)); 5System.out.println("Whoo!"); 1 5 2 4 3 Multi-Line Loop Body System.out.println("+----+"); for (int i = 1; i <= 3; i++) { System.out.println("\\ /"); System.out.println("/ \\"); System.out.println("+----+"); Output: +----+ \ / / \ \ / / \ \ / / \ +----+

Expressions for counter int hightemp = 5; for (int i = -3; i <= hightemp / 2; i++) { System.out.println(i * 1.8 + 32); Output: 26.6 28.4 30.2 32.0 33.8 35.6 System.out.print Prints without moving to a new line It allows you to print partial messages on the same line int highesttemp = 5; for (int i = -3; i <= highesttemp / 2; i++) { System.out.print((i * 1.8 + 32) + " "); Output: 26.6 28.4 30.2 32.0 33.8 35.6 We can concatenate " " to separate the numbers

Counting Down The update can use -- to make the loop count down. The test must say > instead of < System.out.print("T-minus "); for (int i = 10; i >= 1; i--) { System.out.print(i + ", "); System.out.println("blastoff!"); System.out.println("The end."); Output: T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff! The end. Generalizing HelloAgain We are going to write a program that allows the user to choose how many times to print the message Hi, there! Our algorithm will start as: 1. Find out how many time to print the message. 2. Print "Hi, there!" that many times.

Generalizing HelloAgain (continued) 1. Find out how many time to print the message. 2. Print "Hi, there!" that many times. System.out.println("How many times do you want to " + "say \"hello\"?"); totaltimes = keyb.nextint(); Generalizing HelloAgain (continued) System.out.println("How many times do you want to " + "say \"hello\"?"); totaltimes = keyb.nextint(); 2. Print "Hi, there!" that many times. 2. FOR Count goes from 1 TO TotalTimes 2.1 Write Hi, there!

Generalizing HelloAgain (continued) System.out.println ("How many times do you want to " + "say \"hello\"?"; totaltimes = keyb.nextint(); 2. FOR Count goes from 1 TO TotalTimes 2.1 Write Hi, there! for (count = 0; count < totaltimes; count++) System.out.println("Hello, again"); import java.util.scanner; The Revised HelloAgain public class HelloAgain3 { // HelloAgain3 - Write "Hello, again" as many times // as the user wants public static void main(string[] args) { Scanner keyb = new Scanner(System.in); int i, count, totaltimes; System.out.println("How many times do you want to " + "say \"hello\"?"); totaltimes = keyb.nextint(); for (count = 0; count < totaltimes; count++) System.out.println("Hello, again");

Example: Averaging n Numbers Let's get back to our original problem. We want to able to average any number of values. Let's start by outlining our algorithm: 1. Find out how many values there are. 2. Add up all the values. 3. Divide by the number of values 4. Print the result Refining Avgn 1. Find out how many values there are. 2. Add up all the values. 3. Divide by the number of values 4. Print the result System.out.println ("How many values are you going to enter?"); numvalues = keyb.nextint();

Refining Avgn System.out.println ("How many values are you going to enter?"); numvalues = keyb.nextint(); 2. Add up all the values. 3. Divide by the number of values 4. Print the result 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1 Get the next value 2.1.2 Add it to the total Refining Avgn System.out.println ("How many values are you going to enter?"); numvalues = keyb.nextint(); 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1 Get the next value 2.1.2 Add it to the total 3. Divide by the number of values 4. Print the result 2.0 Set the total to zero (initially there are no values)

Refining Avgn System.out.println ("How many values are you going to enter?"); numvalues = keyb.nextint(); 2.0 Set the total to zero (initially there are no values) 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1 Get the next value 2.1.2 Add it to the total 3. Divide by the number of values 4. Print the result 2.0 Set the total to zero (initially there are no values) Refining Avgn System.out.println ("How many values are you going to enter?"); numvalues = keyb.nextint(); 2.0 Set the total to zero (initially there are no values) 2.1 For CurrentValue goes from 1 to NumValues : 2.1.1 Get the next value 2.1.2 Add it to the total 3. Divide by the number of values 4. Print the result sum = 0.0; for (currentvalue = 1; currentvalue <= numvalues; currentvalue++) { System.out.println("What is the next value?"); value = keyb.nextint(); sum = sum + value;

Refining Avgn System.out.println ("How many values are you going to enter?"); numvalues = keyb.nextint(); sum = 0.0; for (currentvalue = 1; currentvalue <= numvalues; currentvalue++) { System.out.println("What is the next value?"); value = keyb.nextint(); sum = sum + value; 3. Divide by the number of values 4. Print the result average = sum / numvalues; System.out.println("The average is " + average); import java.util.scanner; The AverageN Program public class AverageN { //AverageN - Find the average of N values public static void main(string[] args) { Scanner keyb = new Scanner(System.in); double sum, average, value; int numvalues, currentvalue; //Find out how many values there are System.out.println ("How many values are you going to enter?"); numvalues = keyb.nextint();

// Read in each value and add it to the sum sum = 0.0; for (currentvalue = 1; currentvalue <= numvalues; currentvalue++) { System.out.println("What is the next value?"); value = keyb.nextint(); sum = sum + value; // Calculate and print out the average average = sum / numvalues; System.out.println("The average is " + average); Example: Interest Program Example - Write a program that calculates the interest that the Canarsie Indians would have accumulated if they had put the $24 that they had received for Manhattan Island in the bank at 5% interest. Input - none; all the values are fixed Output - Year and Principle Other Information - Principle is initially 24 Interest = Interest Rate * Principle New Principle = Old Principle + Interest

Example: Interest Program Our initial algorithm is: 1. Set the principle to 24 2. For every year since 1625, add 5% interest to the principle and print out the principle. Refining The Interest Algorithm 1. Set the principle to 24 2. For every year since 1625, add 5% interest to the principle and print out the principle. 2.1 FOR Year goes from 1625 TO Present: 2.1.1 Add 5% interest to the principle 2.1.2 Print the current principle

Refining The Interest Algorithm 1. Set the principle to 24 2.1 FOR Year goes from 1625 TO Present: 2.1.1 Add 5% interest to the principle 2.1.2 Print the current principle 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle Refining The Interest Algorithm 1. Set the principle to 24 2.1 FOR Year goes from 1625 TO Present: 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle 2.1.2 Print the current principle principle = 24;

Refining The Interest Algorithm principle = 24; 2.1 FOR Year goes from 1625 TO Present: 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle 2.1.2 Print the current principle for (year = 1625; year < present; year++) { Refining The Interest Algorithm principle = 24; for (year = 1625; year < present; year++) { 2.1.1.1 Calculate 5% Interest 2.1.1.2 Add the interest to the principle 2.1.2 Print the current principle interest = rate * principle; principle = principle + interest;

Refining The Interest Algorithm principle = 24; for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; 2.1.2 Print the current principle System.out.println("year = " + year + "\tprinciple = + principle); The Interest Program public class Interest { // Calculate the interest that the Canarsie // Indians could have accrued if they had // deposited the $24 in an bank account at // 5% interest. public static void main(string[] args) { final int present = 2014; int year; a named constant final double rate = 0.05; double interest, principle; // Set the initial principle at $24 principle = 24;

// For every year since 1625, add 5% interest // to the principle and print out // the principle for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; System.out.println("year = " + year + "\tprinciple = " + principle); Output from the Compound Interest Program What will our output look like? year = 1625 principle = 25.2 year = 1626 principle = 26.46 year = 1627 principle = 27.783 year = 1628 principle = 29.172150000000002 year = 2010 principle = 3.6247719022233915E9 year = 2011 principle = 3.8060104973345613E9 year = 2012 principle = 3.996311022201289E9 year = 2013 principle = 4.1961265733113537E9 This does not look the way we expect monetary amounts to be written!

System.out.printf() The method System.out.printf() gives us a way to write output that is formatted, i.e., we can control its appearance. We write the method: System.out.printf(ControlString, Arg1, Arg2,... ) The control string is a template for our output, complete with the text that will appear along with whatever values we are printing. System.out.printf(): Some Simple Examples System.out.printf() will print whatever is in the control string with a few exceptions: System.out.printf("This is a test"); System.out.printf("This is a test"). will produce: This is a testthis is a test If you want these to be on two separate lines: System.out.printf("This is a test\n"); System.out.printf("This is a test\n").

Special Characters There are a number of special characters that all begin with a backslash: \n new line \b \t backspace tab These can appear anywhere with a string of characters: System.out.printf("This is a test\nit is!!\n"); %d and %f The specifiers %d and %f allow a programmer to specify how many spaces a number will occupy and (in the case of float values) how many decimal places will be used. %nd will use at least n spaces to display the integer value in decimal (base 10) format. %w.df will use at least w spaces to display the value and will have exactly d decimal places.

Changing the width Number 182 182 182 182-182 -182-182 Formatting %2d %3d %5d %7d %4d %5d %7d Print as: 182 182 ``182 ``182-182 `-182 ```-182 Changing the width (continued) Number 23 23 23 23 11023 11023-11023 -11023 Formatting %1d %2d %6d %8d %4d %6d %6d %10d Print as: 23 23.23 23 11023.11023-11023..11023

Changing The Precision Number Formatting Prints as: 2.718281828 %8.5f `2.71828 2.718281828 %8.3f ```2.718 2.718281828 %8.2f ````2.72 2.718281828 %8.0f ````````3 2.718281828 %13.11f 2.71828182800 2.718281828 %13.12f 2.718281828000 The revised Compound program public class Interest { // Calculate the interest that the Canarsie // Indians could have accrued if they had // deposited the $24 in an bank account at // 5% interest. public static void main(string[] args) { final int present = 2014; int year; final double rate = 0.05; double interest, principle; // Set the initial principle at $24 principle = 24;

// For every year since 1625, add 5% interest // to the principle and print out // the principle for (year = 1625; year < present; year++) { interest = rate * principle; principle = principle + interest; System.out.printf ("year = %4d\tprinciple = $%13.2f\n", year, principle); The output from the Revised Compound Program Our output now looks like this: year = 1625 principle = $ 25.20 year = 1626 principle = $ 26.46 year = 1627 principle = $ 27.78 year = 1628 principle = $ 29.17 year = 2001 principle = $2336560287.43 year = 2002 principle = $2453388301.80 year = 2003 principle = $2576057716.89 year = 2004 principle = $2704860602.73