COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015
|
|
- Emma Norman
- 5 years ago
- Views:
Transcription
1 COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015
2 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours. Tutorial by Priya: Friday, 15 th May at 10:30 in TR3120 Reminder : Assignment submission on Sunday!!!
3 Correction To a Slide from Lecture 2 Escape Characters Use an escape sequence for punctuations or spacing. \n NewLine \t Tab \ To have double quotes inside a string \{ \( \; To escape special symbols \\ To escape the escape character!!!!!
4 Boolean Expressions Review What data type and value do the following expressions evaluate to? (5 / 4) < (5.0 / 4.0) ((int) 3.1 == 3) && (2.0 > 1) In the following expressions, is it possible to come up with an assignment to X and Y such that the expression evaluates to true? (X Y) (!Y!Y) (X &&!X) (!X (Y && Y))
5 Review Mathematical Expressions In which expression could the parentheses be removed without changing the value of the expression? x * (y + z) (y x) / 3 x * 3 /(y + 2) (y % 3) + 2 The value of 5 / 2.0 and the value of 5.0 / 2 are the same. TRUE FALSE What is the output? int i = 10; int n = i++; System.out.println( Value i = + i + and n = + n); n = ++i; System.out.println( Value i = + i + and n = + n);
6 if else, if else if : Review Every statement with if must also include else. TRUE [FALSE] What will be the value of b after the following section of code executes: int a = 4, b = 0; if (a < 3) b = 4; else if ( (a < 10) && (b>0) ) b = 3; else if ( (a > 5) (b!=0) ) b = 2; A. 1 B. 0 C. 3 D. 4
7 This Lecture Loops While Loop For Loop Arrays One step at a time.
8 Loops (Repetitions)
9 Recall: if statement if (Condition) { // some code here } // code here happens regardless Condition evaluates to type boolean The if statement defines a block of code that happens if condition evaluates to true.
10 Control Flow if statements let us choose whether to execute some code, or to choose between multiple blocks of code to execute. Another way to control the flow of the program: execute something multiple times. Example: Counting the number of Apples!! Our program would look something like,
11 int count = 0 Copy and Paste? if ( Basket_A is not Empty ) { count = count + 1;} else {System.out.println( No. of Apples = + count);} if ( Basket_A is not Empty ) { count = count + 1;} else {System.out.println( No. of Apples = + count);} if ( Basket_A is not Empty ) { count = count + 1;} else {System.out.println( No. of Apples = + count);}
12 I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly. I will complete my practice exercises regularly.
13 Problems 1. Annoying who wants to copy/paste that much 2. Error prone easy to make mistake 3. Difficult to maintain hard to edit or fix mistakes 4. Does not generalize what if something changes each time you execute it? 5. Variable number of steps what if you don't know how many steps you need?
14 Solution: Loops In Java, there are two main types of loops: while loops for loops
15 while Loops Syntax: <initialize> while ( <condition> ) { // block of code } // go here only after // we fail the condition check Note similarity to if statement's syntax: if ( <condition> ) { // block of code } // go here afterwards
16 if vs. while Syntactically, the only difference between if and while is that the keyword is different Semantically, the effect of while vs. if is that: while: code block is repeatedly executed as long as the condition is evaluated to be true. if: code block is executed at most once, if the condition is evaluated to be true.
17 while Loops
18 while Example int x = 0; while (x < 4) { } System.out.println("Write this again"); x++; The purpose of the variable x is to act as the loop counter. It keeps track of how many times the loop has run.
19 How does the while work? Trace the execution of the loop. How many times does it execute? int x = 0; while (x < 4) { } System.out.println("Write this again"); x++; Step 1 Step 2 Initialize Condition Check Condition Fail Step 3 Loop body Execution Once the condition fails
20 Iteration??? An iteration is a single execution of the instructions in the body of a loop. The previous loop had 4 iterations: first iteration: x = 0 second iteration: x = 1 third iteration: x = 2 fourth iteration: x = 3
21 When is the Condition Checked? The condition of a while loop is checked once per iteration of the loop, before the block of code is executed. int x = 0; while (x < 4) { x = x + 10; System.out.println( x is now at least 10 ); x = x - 10; x++; } How many times does this loop iterate for?
22 Practice Exercise What does this code do? Recall that % is the remainder operator. int i = 0; while (i < 100) { if (i % 3 == 0) { System.out.println(i); } i++; }
23 Practice Exercise What does this code do? int x = 0; while (x < 4) { System.out.println(x); } The above code creates an infinite loop. It goes on forever because we never change the value of x!!!!
24 Be Careful An extra, misplaced ; can ruin your program (and your day) int x = 0; while (x < 4); { x++; } This creates an infinite loop.
25 How Many Iterations 1 int x = 4; while (x > 4) { System.out.println("This is the song + that never ends. ); x++; }
26 How Many Iterations 2 int x = 6; while (x > 4) { System.out.println("This is the song that never ends. ); x--; }
27 How Many Iterations 3 int x = 6; while (x > 4) { System.out.println("This is the song that never ends. ); x++; }
28 How Many Iterations 4 int x = 3; while (x < 11) { System.out.println("This is the song that never ends. ); x += 2; }
29 How Many Iterations 5 int x = 3; while (x!= 10) { System.out.println("This is the song that never ends. ); x += 2; }
30 Off-By-One Error This code is supposed to print all positive values of x up until 5: int x = 1; while (x < 5) { System.out.println(x); x++; } How do we fix it?
31 Off-By-One Error Prevention To avoid off by one errors, you should always manually confirm the first step of a loop as well as the last step of a loop. Make sure the numbers are what you are expecting.
32 Template for n Repetitions If you have code that you want to perform a fixed number of times, one way to do that is with a while loop and a counter: int counter = 0; while (counter < n) { //whatever you want done counter++; }
33 i = 0 while i < 100 end write I will complete my practice exercises regularly. i++
34 Try it out!!! Write a program that repeatedly asks the user for their favourite course until the user enters "COMP 202" as the input.
35 Common Loop Theme Very often in loops, one will do three things: 1. Perform some initialization before the loop starts 2. Check a condition before each iteration of a loop 3. Perform some update step at the end of each iteration
36 Template for n Repetitions If you have code that you want to perform a fixed number of times, one way to do that is with a while loop and a counter: int counter = 0; Initialization while (counter < n) Condition before each iteration { //whatever you want done counter++; } Update at the end of each iteration
37 for Loops Because this pattern is so common, Java has a for loop, which is similar to a while loop, but has these three parts built in to the loop. for (initialization; condition; update) { // loop body }
38 for i = 1 to 100 next i end write I will complete my practice exercises regularly.
39 for Loops for (initialization; condition; update) { Happens once per loop only, before the first check of the condition // loop body Happens at the end of every iteration. Usually used to update a variable declared in the initialization } Happens before every iteration. If it evaluates to true, the loop body will run.
40 How does the for work? Trace the execution of the loop. for (int x = 0; x < 4; x++) { Step 1 Initialize Step 2 Condition Check Step 4 Update Condition Fail System.out.println("Write this again"); Step 3 Loop body Execution } Once the condition fails
41 for vs. while for (int i = 0; i < 4; i++) { System.out.println(i); } int i = 0; while (i < 4) { System.out.println(i); i++; } The only difference is that the variable i is still defined after the while loop, whereas it is no longer in scope and therefore doesn't exist anymore after the for loop. Could be a good thing don't mix up variables!
42 for Loop as a while Loop int x = 0; for (; x < 4; ) { System.out.println(x); x++; } You are unlikely to do this when writing good, readable code. But you can have any block of the for loop empty. One can even have all the blocks empty. (What would happen?) for ( ; ; ) { //Some operation }
43 When To Use Which One Indefinite number of iterations while e.g., Keep doing something until a certain event occurs, or while a certain condition is true. Fixed or easily calculable number of iterations for e.g., Go through all elements of a list (which we will see soon), or a fixed number of elements
44 Which loop to use? Which loop would you use for our original problem of counting the number of apples in a basket???
45 Example Question 1) What will the following code print? int count = 1; while (count <= 3) { System.out.print(count + " "); count++; } A B. 1 2 C. 3 D ) What will the following code print? ANSWER: ( A ) int count = 4; while (count < 4) { ANSWER: ( B ) System.out.print(count + " "); count++; } A B. Nothing printed C. 4 D
46 Example Question 1) What will the following code print? int count; for (count = 4; count > 1; count--) System.out.print(count + " "); ANSWER: ( C ) A B C D ) What will the following code print? int count; for (count = 8; count > 1; count--){ count--; System.out.print(count + " "); } ANSWER: ( D ) A B C D
47 Try it out!! A prime number is a positive integer >= 2 whose only divisors are 1 and itself. Write a program that checks whether an integer is prime. How to start? Hints: Break it down! How do you check if the candidate number has a particular divisor? Which numbers do you have to check as possible divisors?
48 Loopception (Nested Loops) Loop within a loop!! You can have multiple levels of loops! This is called having nested loops. This is often useful when we have data with multiple dimensions. e.g., print the multiplication table between 1 and 9, inclusive i.e., 1x1=1, 1x2=2, 1x3=3, 1x9 = 9 2x1=2, 2x2=4, 2x3=6, 2x9 = 18
49 One Row of the Table Suppose we have one fixed integer: int x = 4; for (int y = 1; y < 10; y++) { System.out.print(x + "x" + y + "=" + (x * y) + ", "); } System.out.println(); // add line break
50 All the Rows of the Table Now, add another for loop outside to have the integer range. for (int x = 1; x < 10; x++) { for (int y = 1; y < 10; y++) { System.out.print(x + "x" + y + "=" + (x * y) + ", "); } System.out.println(); // add line break } We declare and initialize a new y variable for each iteration of the outer loop!
51 Try it out!! Print a multiplication table, as above, but to avoid nearduplicates like 5x4 and 4x5, only print those entries where the first number is less than or equal to the second number (i.e., 4x5). Do not use if statements.
52 Arrays
53 Computing Mean We want to ask user to enter several numbers and give the mean as output. What would we do? 1)We need to ask the user to enter numbers and store the result into a variable. 2)We need to repeat this several times 3)As we go, we should store the sum of the numbers they have entered 4)At the end, divide by the total number of numbers they entered.
54 Computing Mean 1)We need to ask the user to enter numbers and store the result into a variable. Scanner 2)We need to repeat this several times For Loop 3)As we go, we should store the sum of the numbers they have entered Variable that we keep adding to 4)At the end, divide by the total number of numbers they entered. Store how many numbers are entered
55 import java.util.scanner; public class MeanProgram { } Computing Mean public static void main(string[] args) { final int TOTAL_NUM = 100; double total = 0; Scanner reader = new Scanner(System.in); for (int i = 0; i < TOTAL_NUM; i++) { double nextnumber = reader.nextdouble(); total += nextnumber; } System.out.println(total / TOTAL_NUM); }
56 Computing Mean What if we wanted to store all the numbers for later use??? Store the 100 numbers into 100 different, unrelated variables. int fml1, fml2, fml3, fml4, fml5, fml6, fml7, fml8, fml9, fml10, fml11, fml12, fml13, fml14, fml15, fml16, fml17, fml18, fml19, fml20, fml21, fml22, fml23, fml24, fml25, fml26, fml27, /*okay I'm tired of typing all these fml's. I need a drink now...*/ fml99, fml100;
57 Storing Multiple Values We often want to store multiple values of the same type: Daily high temperature in Montreal over the past 30 years Lines of text in a chat conversation Marks of students in COMP 202 This lets us compute things about the entire sequence of data by looping through each entry.
58 Not the Way to Go Declare one variable per entry? double mark1, mark2, mark3, mark4, mark5, mark6, mark7, mark8, mark9, mark10, mark11, mark12, // AAAAHHHHHHHHHHH! Annoying to read and write Error-prone, impossible to edit How do we loop through these variables?
59 Arrays An array is a container object that holds a fixed number of values of a single type. The length of the array is established when the array is created. After its creation, the length is fixed. e.g., we can have an array of ints, an array of doubles, an array of Strings, etc., but not an array that has both ints and doubles.
60 Array Variables Since an array conveniently groups together multiple items, we can access the values in the array by using the same variable. You can recognize an array variable by its []. String[] an array of Strings int[] an array of ints boolean[] an array of booleans double[] an array of doubles int[][] an array of arrays of ints
61 One Mystery Solved public static void main(string[] args) This is a String array called args. Though we still don't know what args does yet
62 Declaring Array Variables Exactly the same as before: type[] var_name; This creates a variable, but we still need to create the actual array object itself.
63 Creating Arrays: Method 1 At the same time as you declare the variable, surrounded by {} boolean[] toocold = {true, false, true, true, false}; double[] marks = {100.0, 100.0, 100.0, 100.0}; String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; This method doesn't work if you don't know the values before the program runs.
64 Creating Arrays int[] myarray = {1, 5, 6, 3}; 1) Allocate this memory. Find a free spot in memory that has enough space to hold four integers. 2) Store the address of the beginning of the memory that was just allocated into the variable myarray. myarray 3) Set values to this newly allocated memory. myarray
65 Creating Arrays: Method 2 type[] var_name = new type[size]; (omit type[] if var_name was already declared) int NSTUDENTS = 97; String[] studentnames = new String[NSTUDENTS]; double[] studentmarks = new double[nstudents];
66 Creating Arrays Declaring, allocating, and initializing arrays can also be broken up into multiple steps: int[] myarray; Variable myarray is created to point to an array. myarray = new int[4]; myarray myarray[0] = 1; myarray Indices 1 [0] [1] [2] [3]
67 Using An Array When you create an array of size n, you are creating n contiguous places in memory to store values of the same type. Refer to each element by its index, starting from 0. String[] instructors = { Sandeep", "Jackie", Juan"}; instructors[0] instructors[1] instructors[2] Sandeep" "Jackie" Juan"
68 Array Example Scores of 8 students: int [ ] scores = {100, 95, 25, 99, 39, 100, 100, 90} scores Indices [0] [1] [2] [3] [4] [5] [6] [7] Here is an array with 8 values in it. Each spot of the array has a value and an index. The value is any legitimate value of the type of the array, in this case int. The index is an integer. Interestingly the counting starts from 0 instead of 1. To get or set values of an array, we will use a similar syntax to a normal variable, except we have to specify which value of the array we wish to get or set. We do this by using the index.
69 Example: Compute Mean Mean of the class scores: int [ ] scores = {100, 95, 25, 99, 39, 100, 100, 90}; int sumscores = scores[0] + scores[1] + scores[2] + scores[3] + scores[4] + scores[5] + scores[6] + scores[7]; double avgscore = sumscores / 8; System.out.println(avgScore); I feel like there's a smarter way to do this
70 Example: Compute Mean int [ ] scores = {100, 95, 25, 99, 39, 100, 100, 90}; int i = 0; int sumscores = 0; while (i < 8) { sumscores = sumscores + scores[i]; i++; } double avgscore = sumscores / 8; System.out.println(avgScore);
71 Try it out: Be Even Smarter The previous code does not generalize: Assumes a fixed number of student scores (8) Use array_name.length to get the length of an array Change the previous example: To use a for loop instead of a while loop To use.length so that it works for arrays of any length.
72 Need to Initialize Values What happens if we do this? String[] names = new String[35]; // print first name System.out.println(names[0]); We get a null because we've created a place to store a String, but we haven't set its value yet. Remember to initialize the entries of your arrays if you use method 2!
73 Objects Arrays, Scanners, and Strings are Objects. You can tell because you need new to create them. (Well, except Strings. Strings are special.) In fact, except for the primitive data types (the ones that start with lowercase, like int, double, float, byte, boolean, etc.), everything in Java is an Object. Objects are data bundled with methods to work with the data, and properties.
74 Methods of Objects Some String methods:.equals(),.length(),.tolowercase() Some Scanner methods:.nextline(),.nextint(),.nextdouble() In general: object.method_name() Arrays have no methods. Instead, they have a property called length.length Because this is not a method, there is no () after
75 Example Question 1) Which of the following statements are valid array declarations? A. int number(); B. int number[]; C. double[] marks; D. number int[]; ANSWER: ( B and C ) 2) What will be the output of following Java code block? public static void main(string argv[]) { int ary[]=new int[]{1,2,3}; System.out.println(ary[1]); } A. 1 B. Compilation Error: Incorrect Syntax C. 2 D. Compilation Error: size of array must be defined ANSWER: ( C )
76 Example Question 3) What is the value of a[1] after the following code is executed? int[] a = {0, 2, 4, 1, 3}; for (int i = 0; i < a.length; i++) { a[i] = a[ a[ i ] ]; } A) 0 B) 1 C) 2 D) 3 E) 4 ANSWER: ( E )
77 Summary Control Flow While Loop For Loop Arrays
COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016
COMP-202: Foundations of Programming Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 Review What is the difference between a while loop and an if statement? What is an off-by-one
More informationCONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice
CONTENTS: Arrays Strings COMP-202 Unit 5: Loops in Practice Computing the mean of several numbers Suppose we want to write a program which asks the user to enter several numbers and then computes the average
More informationCOMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015 Announcements Assignment 2 posted and due on 30 th of May (23:30). Extra class tomorrow
More informationCONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops
COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables
More informationCOMP-202 Unit 4: Programming with Iterations
COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables
More informationCOMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon
More informationWarmup : Name that tune!
Warmup : Name that tune! Write, using a loop, Java code to print the lyrics to the song 99 Bottles of Beer on the Wall 99 bottles of beer on the wall. 99 bottles of beer. Take one down, pass it around,
More informationCOMP-202: Foundations of Programming. Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016
COMP-202: Foundations of Programming Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016 Review: for Loops for (initialization; condition; update) { Happens once per loop only, before the first check
More informationCOMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few
More informationWarm-Up: COMP Programming with Iterations 1
Warm-Up: Suppose I have a method with header: public static boolean foo(boolean a,int b) { if (a) return true; return b > 0; Which of the following are valid ways to call the method and what is the result?
More informationCOMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements
COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money
More informationLast Class. While loops Infinite loops Loop counters Iterations
Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationLoops. CSE 114, Computer Science 1 Stony Brook University
Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?
More informationSequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;
Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The
More informationCONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction
CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationBjarne Stroustrup. creator of C++
We Continue GEEN163 I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone. Bjarne Stroustrup creator
More informationCOMP-202: Foundations of Programming
COMP-202: Foundations of Programming Lecture 3: Basic data types Jackie Cheung, Winter 2016 Review: Hello World public class HelloWorld { } public static void main(string[] args) { } System.out.println("Hello,
More informationIntroduction to Java & Fundamental Data Types
Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains
More informationRepetition Structures
Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements
More informationCondition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.
Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes
More informationObject-Oriented Programming
Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,
More informationSchool of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15
Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL
More informationMIDTERM REVIEW. midterminformation.htm
MIDTERM REVIEW http://pages.cpsc.ucalgary.ca/~tamj/233/exams/ midterminformation.htm 1 REMINDER Midterm Time: 7:00pm - 8:15pm on Friday, Mar 1, 2013 Location: ST 148 Cover everything up to the last lecture
More informationIteration statements - Loops
Iteration statements - Loops : ) הוראות חזרה / לולאות ( statements Java has three kinds of iteration WHILE FOR DO... WHILE loop loop loop Iteration (repetition) statements causes Java to execute one or
More informationCOMP 202 Java in one week
COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of
More informationPlease answer the following questions. Do not re-code the enclosed codes if you have already completed them.
Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?
More informationCOMP 202 Java in one week
CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language
More informationTopic 5: Enumerated Types and Switch Statements
Topic 5: Enumerated Types and Switch Statements Reading: JBD Sections 6.1, 6.2, 3.9 1 What's wrong with this code? if (pressure > 85.0) excesspressure = pressure - 85.0; else safetymargin = 85.0 - pressure;!
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics
WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java
More informationLast Class. More on loops break continue A bit on arrays
Last Class More on loops break continue A bit on arrays public class February2{ public static void main(string[] args) { String[] allsubjects = { ReviewArray, Example + arrays, obo errors, 2darrays };
More informationDarrell Bethea May 25, 2011
Darrell Bethea May 25, 2011 Yesterdays slides updated Midterm on tomorrow in SN014 Closed books, no notes, no computer Program 3 due Tuesday 2 3 A whirlwind tour of almost everything we have covered so
More informationQ1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question
Page 1 of 6 Template no.: A Course Name: Computer Programming1 Course ID: Exam Duration: 2 Hours Exam Time: Exam Date: Final Exam 1'st Semester Student no. in the list: Exam pages: Student's Name: Student
More information! 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
Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is
More informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG 1 Notice Reading Assignment Chapter 1: Introduction to Java Programming Homework 1 It is due this coming Sunday
More informationRepetition with for loops
Repetition with for loops So far, when we wanted to perform a task multiple times, we have written redundant code: System.out.println( Building Java Programs ); // print 5 blank lines System.out.println(
More informationRepetition, Looping. While Loop
Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions
More informationBasic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java
Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection
More informationTopic 4 Expressions and variables
Topic 4 Expressions and variables "Once a person has understood the way variables are used in programming, he has understood the quintessence of programming." -Professor Edsger W. Dijkstra Based on slides
More informationCOMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016
COMP-202: Foundations of Programming Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016 More Tutoring Help The Engineering Peer Tutoring Services (EPTS) is hosting free tutoring sessions
More informationMichele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring
Michele Van Dyne Museum 204B mvandyne@mtech.edu http://katie.mtech.edu/classes/csci136 CSCI 136: Fundamentals of Computer Science II, Spring 2016 1 Review of Java Basics Data Types Arrays NEW: multidimensional
More informationIntroduction to the Java Basics: Control Flow Statements
Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared
More informationCONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2
CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,
More informationComputer Science is...
Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationboolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while
CSCI 150 Fall 2007 Java Syntax The following notes are meant to be a quick cheat sheet for Java. It is not meant to be a means on its own to learn Java or this course. For that you should look at your
More informationLast Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it
Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]
More informationCONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays
CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202
More informationBuilding Java Programs
Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 1 2 Data and expressions reading: 2.1 3 The computer s view Internally, computers store everything as 1 s and 0
More informationTop-Down Program Development
Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable
More informationMcGill University School of Computer Science COMP-202A Introduction to Computing 1
McGill University School of Computer Science COMP-202A Introduction to Computing 1 Midterm Exam Thursday, October 26, 2006, 18:00-20:00 (6:00 8:00 PM) Instructors: Mathieu Petitpas, Shah Asaduzzaman, Sherif
More informationChapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a
More informationIntroduction to Java Applications
2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use
More information2.8. Decision Making: Equality and Relational Operators
Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement
More informationComputer Programming I - Unit 5 Lecture page 1 of 14
page 1 of 14 I. The while Statement while, for, do Loops Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly. The while statement is one of three looping statements
More informationObject oriented programming. Instructor: Masoud Asghari Web page: Ch: 3
Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationExample: Computing prime numbers
Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will
More informationH212 Introduction to Software Systems Honors
Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing
More informationCourse Outline. Introduction to java
Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.
More informationJAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA
More informationData dependent execution order data dependent control flow
Chapter 5 Data dependent execution order data dependent control flow The method of an object processes data using statements, e.g., for assignment of values to variables and for in- and output. The execution
More informationLecture Set 2: Starting Java
Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural
More informationControls Structure for Repetition
Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power
More informationCOMP 110 Project 1 Programming Project Warm-Up Exercise
COMP 110 Project 1 Programming Project Warm-Up Exercise Creating Java Source Files Over the semester, several text editors will be suggested for students to try out. Initially, I suggest you use JGrasp,
More informationMotivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops
Chapter 5: Loops and Iteration CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations Suppose that you need to print a string (e.g.,
More informationDefinite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting
Unit 2, Part 2 Definite Loops Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting Let's say that we're using a variable i to count the number of times that
More informationCSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:
CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall alphonce@buffalo.edu Office hours: Tuesday 10:00 AM 12:00 PM * Wednesday 4:00 PM 5:00 PM Friday 11:00 AM 12:00 PM OR
More informationLecture Set 2: Starting Java
Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural
More informationPrimitive Data, Variables, and Expressions; Simple Conditional Execution
Unit 2, Part 1 Primitive Data, Variables, and Expressions; Simple Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Overview of the Programming Process Analysis/Specification
More informationprintf( Please enter another number: ); scanf( %d, &num2);
CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful
More informationL o o p s. for(initializing expression; control expression; step expression) { one or more statements }
L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat
More informationCOMP-202 Unit 9: Exceptions
COMP-202 Unit 9: Exceptions Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2 Exceptions An exception is an object that describes an unusual
More informationCS 170 Section 3, Spring 2015 Programming in Java Midterm Exam 1. Name (print):
Name (print): INSTRUCTIONS: o Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. o Do NOT communicate with anyone other than the professor/proctor for ANY reason
More informationCOMP 202. Java in one week
COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language
More informationTOPIC 2 INTRODUCTION TO JAVA AND DR JAVA
1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared
More informationSelec%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 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More informationCS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8
CS 302: INTRODUCTION TO PROGRAMMING Lectures 7&8 Hopefully the Programming Assignment #1 released by tomorrow REVIEW The switch statement is an alternative way of writing what? How do you end a case in
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #16 Loops: Matrix Using Nested for Loop In this section, we will use the, for loop to code of the matrix problem.
More informationLoops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)
Loops! Flow of Control: Loops (Savitch, Chapter 4) TOPICS while Loops do while Loops for Loops break Statement continue Statement CS 160, Fall Semester 2014 2 An Example while Loop Step- by- step int count
More informationHandout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.
Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8 Handout 5 Loops. Loops implement repetitive computation, a k a iteration. Java loop statements: while do-while for 1. Start with the while-loop.
More informationObject Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang
Object Oriented Programming and Design in Java Session 2 Instructor: Bert Huang Announcements TA: Yipeng Huang, yh2315, Mon 4-6 OH on MICE clarification Next Monday's class canceled for Distinguished Lecture:
More informationCompSci 125 Lecture 11
CompSci 125 Lecture 11 switch case The? conditional operator do while for Announcements hw5 Due 10/4 p2 Due 10/5 switch case! The switch case Statement Consider a simple four-function calculator 16 buttons:
More informationProgramming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3
Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationCISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.
CISC-124 20180115 20180116 20180118 We continued our introductory exploration of Java and object-oriented programming by looking at a program that uses two classes. We created a Java file Dog.java and
More informationScope of this lecture. Repetition For loops While loops
REPETITION CITS1001 2 Scope of this lecture Repetition For loops While loops Repetition Computers are good at repetition We have already seen the for each loop The for loop is a more general loop form
More informationConditional Execution
Unit 3, Part 3 Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Simple Conditional Execution in Java if () { else {
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationRepetition, Looping CS101
Repetition, Looping CS101 Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions
More informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative
More informationJava Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition
Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled
More informationProgramming Basics. Digital Urban Visualization. People as Flows. ia
Programming Basics Digital Urban Visualization. People as Flows. 28.09.2015 ia zuend@arch.ethz.ch treyer@arch.ethz.ch Programming? Programming is the interaction between the programmer and the computer.
More informationOct Decision Structures cont d
Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements
More informationCMPT 125: Lecture 3 Data and Expressions
CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,
More informationCOMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 13: Recursion Sandeep Manjanna, Summer 2015 Announcements Final exams : 26 th of June (2pm to 5pm) @ MAASS 112 Assignment 4 is posted and Due on 29 th of June
More informationObject Oriented Programming. Java-Lecture 6 - Arrays
Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types
More information