Loops. GEEN163 Introduction to Computer Programming
|
|
- Erick Bailey
- 5 years ago
- Views:
Transcription
1 Loops GEEN163 Introduction to Computer Programming
2 Simplicity is prerequisite for reliability. Edsger W. Dijkstra
3 Programming Assignment A new programming assignment has been posted on Blackboard for this week The program requires you to write three programs from the given flowcharts Either problem 1 or problem 3 must be written with a GUI (but not both) Due by midnight on Friday, October 5
4 ZyBooks Reading Read chapter 7 of the online ZyBooks textbook Answer all of the participation questions in sections 7.1 through 7.9 Due by midnight on Thursday, October 4
5 One or the Other With an if else statement, either the if part or the else part are executed, but never both if ( logical expression ) { Executed only if true else { Executed only if false
6 nested if If the true part is another if, then it becomes a nested if if (cat == 3) else if (bull == 7) else x = 1; // cat is 3 and bull is 7 x = 2; // cat is 3 and bull is not 7 x = 3; // cat is not 3, bull doesn t matter
7 else if When the false part of an if-else is another if, it become an else if if ( cow > bull ) else dog = 5; if (cow == 0) dog = 3;
8 else if When the false part of an if-else is another if, it become an else if if ( cow > bull ) dog = 5; else if (cow == 0) dog = 3; // Java allows whitespace
9 One or maybe the Other With an else if statement, second if is evaluated only if the first if is false if ( logical 1 ) { Executed only if true else if ( logical 2 ){ Executed only if logical 1 is false and logical 2 is true
10 Connecting else to if An else statement is always related to the if of the previous block or statement if (cow == 3) if (bat == 7) dog = 1; // cow is 3 and bat is 7 else dog = 3; // cow is 3 and bat is not 7
11 What is displayed? int rabbit = 3, bunny = 5, hare = 7, pika = 9; if (rabbit < 4) if (bunny < hare) else pika = 2; pika = 6; System.out.println( pika ); A. 2 B. 4 C. 6 D. 9 E. none of the above
12 Conditional Assignment Java provides a little known method for putting an if statement in the middle of an expression logical expression? true part : false part dog = cat == 0? cow : goat; if cat is equal to zero, set dog to the value of cow, else set dog to the value of goat
13 Conditional Operator Example int cow= 3, cat = 5, dog = 7, goat = 17; dog = keyboard.nextint(); cow = (dog == 0? cat : goat) + 1; is the same as if (dog == 0 ) cow = cat + 1; else cow = goat + 1;
14 Conditional Used in a Method Call The conditional operator can be using almost any place an equation can be used System.out.println( "You "+ (score >= 50)? "pass" : "fail");
15 What is displayed? int wren = 2, robin = 5, hawk = 17; hawk = robin > 4? wren-1 : robin+ 2; System.out.println( hawk ); A. 1 B. 4 C. 7 D. 17 E. none of the above
16 Repeating Many programs do the same task many times Java provides several ways of creating a program loop while do while for
17 Java while statement A while statement is like an if statement that repeats until the logical expression is false int cat = 47, sum = 0; while (cat > 0) { cat = keyboard.nextint(); sum = sum + cat; System.out.println( sum );
18 Java while statement A while statement is like an if statement that repeats until the logical expression is false int cat = 47, sum = 0; while (cat > 0) { cat = keyboard.nextint(); sum = sum + cat; System.out.println( sum );
19 Loop Parts A while loop has a loop condition and a body The body is repeated while the loop condition is true while (loop condition ) { // loop body
20 while Flowchart comparison true false Do something
21 while loop operation When the program execution encounters a while statement, it will check the loop condition If the loop condition is false, the loop body will not be executed. Execution will continue with the statements after the loop body The body of the loop will be executed if the loop condition is true At the end of the body of the loop, the loop condition will be evaluated again. If it is true, the body of the loop will be executed again
22 { Brackets A while loop can be written without curly brackets around the loop body Without brackets, the loop body will be the one statement following the loop condition It is recommended that you always use brackets
23 Example Program This is a program to display the average of a series of numbers. The end of the list of numbers is denoted by a value of zero You calculate the average by adding all the values and then dividing by the number of values
24 import java.util.scanner; public class LoopExample { public static void main(string[] junk) { double num, avg, sum = 0.0; int count = 0; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number"); num = keyboard.nextdouble(); while (num!= 0.0) { sum = sum + num; count = count + 1; System.out.print("Enter a number"); num = keyboard.nextdouble(); avg = sum / count; System.out.println("The avg is " + avg);
25 Observations about the Program The program continues until a zero is read. The while loop checks for a zero We need to both sum the numbers and count how many numbers There was a priming read before the while and another read in the while loop body You should not divide until after the loop
26 Maybe Never The logical expression of a while loop is tested for the first time before the statement is executed If the logical expression is false the first time, the loop is never executed int hen = 5; while ( hen < 4 ) { hen = hen * hen; System.out.println( hen );// 5
27 A. 2 B. 4 C. 5 D. 8 What is displayed? int dog = 2, cat = 0; while ( cat < 3 ) { dog = dog + cat; cat = cat + 1; System.out.println( dog ); E. none of the above
28 Infinite Loops Many students have written programs with infinite loops. These programs have a loop that will repeat forever A program with an infinite loop will appear hung or stuck It is necessary that some statement inside a while loop modifies at least one of the variables used in the while statement s logical expression
29 Infinite Examples int cat = 5, bird = 7; while (bird > cat) { cow = bird + cat; while (bird > cat) { bird = bird + cat;
30 Looping a Specified Number of Times Frequently you may want your program to loop n times. int i = 1, n = 10; double principle= ; while (i <= n) { principle = principle * 1.05; i++; System.out.println("The value is "+ principle);
31 Looping a Specified Number of Times Computer scientist often count starting at zero int i = 0, n = 10; double principle= ; while (i < n) { principle = principle * 1.05; i++; System.out.println("The value is "+ principle);
32 What is displayed? int dog = 2, cat = 0; while ( dog > 0 ) { dog = dog + cat; cat = cat + 1; System.out.println(dog); A. 2 B. 4 C. 5 D. 8 E. none of the above
33 Caution The following loop is wrong because of the semicolon int i=0; Logic Error while (i < 10); { System.out.println("i is " + i); i = i + 1; 33
34 Flowchart Symbols while (dog == cat) dog = cat if( dog > 5 ) dog > 5 System.out.println(cow); goat = keyboard.nextint(); Output: cow input: goat
35 Flowchart to Find the Biggest
36 Java Program to Find the Biggest int number, biggest = 0; System.out.print("Enter a number >"); number = keyboard.nextint(); while (number!= 0) { if ( number > biggest ) { biggest = number; System.out.print("Enter a number >"); number = keyboard.nextint(); System.out.println("biggest is "+biggest);
37 Practice with your Team With the students around you, write a Java segment that sums all of the whole numbers from 1 to 47
38 Possible Solution int num = 1; int sum = 0; while (num <= 47) { sum = sum + num; num++;
39 Boolean Variables A boolean variable can be set to true or false or the result of a logical expression int x=3, y=5, z=7; boolean bat = true, bird = false; bird = x > y; bat = (x!= y) && (z > y); The expression is evaluated once and the boolean variable is then set to true or false Changing x,y or z will not change the value of the boolean variables after the above equations
40 What is displayed? int sum = 0, number = 47; while (sum < 100) { System.out.print("Enter a number >"); number = keyboard.nextint(); sum = sum + number; System.out.println( sum ); A. 0 B. 100 C. number greater or equal to 100 D. number less than 100 E. unknown
41 boolean variables in IF You can use a boolean variable in an if statement without a comparison. boolean problem = false; problem = true; if ( problem ) { System.out.println("look out");
42 boolean variable in a while boolean bear = true; int deer = keyboard.nextint(); while (bear) { // something if ( deer is weird ) bear = false; // some more stuff deer = keyboard.nextint();
43 boolean Methods A method can return a boolean (true or false) value boolean close(double cat, double dog) { if ( Math.abs(cat dog) < 0.01 ) { return true; return false;
44 A Shorter boolean Method A comparison results in a true or false value which can be returned boolean close(double cat, double dog) { return Math.abs(cat dog) < 0.01;
45 Using boolean Methods A boolean method can be used in an if double cobra = 0.666, mamba = 2.0 / 3.0; if ( close( cobra, mamba ) ) { System.out.println("same"); Other boolean methods include equals, equalsignorecase and others
46 boolean Variables Hold Logical Values A boolean variable can only hold the value true or false true and false are keywords, not strings, but they will print as strings int cat = 3, dog = 5; boolean fish = cat < dog; dog = -1; System.out.println("fish is "+ fish); will print fish is true
47 What is displayed? int cat = 11, dog = 5, cow = 7, goat = 1; boolean squid; squid = dog + cow == cat + 1; A. 1 dog = 3; if (squid ) B. 5 goat = 8; C. 8 else goat = 5; D. 12 System.out.println( goat ); E. none of the above
48 Input Validation Using a boolean int input; boolean good = false; while (!good ) { // repeat until good input System.out.println("Enter a number from 1-5"); input = keyboard.nextint(); if (input < 1 input > 5) { System.out.println("Pay attention!!"); else { good = true;
49 Thinking about programs If a program has to do something many times, it will need a loop The parts of the program that are not repeated will be outside the loop If a program does something different sometimes, the program will have an if statement
50 Write this in Java with your team good = 0 better = number good = better? yes display better good = better better = no good + number good 2
51 Complete the Program import java.util.scanner; public class Root { public static void main(string unused) { Scanner keyboard = new Scanner(System.in); int good = 0, better, number; System.out.print( Enter a number > ); number = keyboard.nextint(); // your Java here System.out.println( Answer is +better);
52 Possible Solution import java.util.scanner; public class Root { public static void main(string unused) { Scanner keyboard = new Scanner(System.in); int good = 0, better, number; System.out.print( Enter a number > ); number = keyboard.nextint(); better = number; while (good!= better) { good = better; better = (good + number/good) / 2; System.out.println( Answer is +better);
53 Summations in Mathematics In mathematics you can specify a sum as sum = which is equivalent to n i=1 1 2i sum = n
54 Summations in Java We can write the same sum in Java n sum = i=1 1 2i double sum = 0.0; int i = 1, n = something; while ( i <= n ) { sum += 1.0 / (2.0 * i); i++;
55 Calculating Terms A more complex summation is e x = xi i=0 i! = 1 + x + x2 2! + x3 3! + The factorial of a number n is 1*2*3* *n In this summation next term = previous term * x i
56 Sum in Java double x, sum, next, i = 2.0; // set x to a value sum = x; // first two terms next = x; while ( next > ) { next = next * x / i; sum += next; i = i + 1.0; // until only small changes
57 What while sums the numbers from low to high? int sum = 0, low = 3, high = 12, num; num = low; // which while goes here { sum = sum + num; num++; A. while ( num <= high ) B. while ( low <= high ) C. while ( num > high ) D. while ( sum!= high )
58 Programming Assignment A new programming assignment has been posted on Blackboard for this week The program requires you to write three programs from the given flowcharts Either problem 1 or problem 3 must be written with a GUI (but not both) Due by midnight on Friday, October 5
59 ZyBooks Reading Read chapter 7 of the online ZyBooks textbook Answer all of the participation questions in sections 7.1 through 7.9 Due by midnight on Thursday, October 4
Over and Over Again GEEN163
Over and Over Again GEEN163 There is no harm in repeating a good thing. Plato Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the
More informationUsing Classes. GEEN163 Introduction to Computer Programming
Using Classes GEEN163 Introduction to Computer Programming Unless in communicating with it one says exactly what one means, trouble is bound to result. Alan Turing talking about computers Homework The
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 informationDecisions, Decisions, Decisions. GEEN163 Introduction to Computer Programming
Decisions, Decisions, Decisions GEEN163 Introduction to Computer Programming You ve got to be very careful if you don t know where you are going, because you might not get there. Yogi Berra TuringsCraft
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 informationUsing Classes. GEEN163 Introduction to Computer Programming
Using Classes GEEN163 Introduction to Computer Programming The history of all previous societies has been the history of class struggles. Karl Marx Programming Assignment The first programming assignment
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 informationMore Methods GEEN163
More Methods GEEN163 There is method to her madness. TuringsCraft Read the material in chapter 7 of the textbook Answer the questions in section 7 of the TuringsCraft tutorial 4 points for each correct
More informationProblem Solving With Loops
To appreciate the value of loops, take a look at the following example. This program will calculate the average of 10 numbers input by the user. Without a loop, the three lines of code that prompt the
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 informationWhat two elements are usually present for calculating a total of a series of numbers?
Dec. 12 Running Totals and Sentinel Values What is a running total? What is an accumulator? What is a sentinel? What two elements are usually present for calculating a total of a series of numbers? Running
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 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 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 informationRepe$$on CSC 121 Fall 2015 Howard Rosenthal
Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationRepetition CSC 121 Fall 2014 Howard Rosenthal
Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationReview for the Third Exam COMP163
Review for the Third Exam COMP163 On the plains of hesitation lie the blackened bones of countless millions who at the dawn of victory lay down to rest, and in resting died. Adlai E. Stevenson to the United
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 information1 Short Answer (10 Points Each)
1 Short Answer (10 Points Each) 1. Write a for loop that will calculate a factorial. Assume that the value n has been input by the user and have the loop create n! and store it in the variable fact. Recall
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 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 informationCSE 114 Computer Science I
CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?
More informationLesson 7 Part 2 Flags
Lesson 7 Part 2 Flags A Flag is a boolean variable that signals when some condition exists in a program. When a flag is set to true, it means some condition exists When a flag is set to false, it means
More informationRepetition. Chapter 6
Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general
More informationRepetition. Chapter 6
Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general
More informationMethods & Classes COMP163
Methods & Classes COMP163 People think that computer science is the art of geniuses, but the actual reality is the opposite, just many people doing things that build on each other, like a wall of mini
More informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
More informationCONDITIONAL EXECUTION
CONDITIONAL EXECUTION yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I Outline Conditional Execution if then if then Nested if then statements Comparisons
More informationA+ Computer Science -
import java.util.scanner; or just import java.util.*; reference variable Scanner keyboard = new Scanner(System.in); object instantiation Scanner frequently used methods Name nextint() nextdouble() nextfloat()
More informationSFWR ENG/COMP SCI 2S03 Principles of Programming SOLUTIONS
SFWR ENG/COMP SCI 2S03 Principles of Programming SOLUTIONS Day Class Midterm Exam Dr. R. Khedri DURATION : 50 minutes McMaster University Midterm Exam (CAS) October 29, 2012 Please CLEARLY print: NAME:
More informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
More informationProgramming with Java
Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules
More informationChapter 6. Repetition. Asserting Java. Rick Mercer
Chapter 6 Repetition Asserting Java Rick Mercer Algorithmic Pattern: The Determinate loop We often need to perform some action a specific number of times: Produce 89 paychecks. Count down to 0 (take 1
More informationProgramming Constructs Overview. Method Call System.out.print( hello ); Method Parameters
Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October
More informationRepe$$on CSC 121 Spring 2017 Howard Rosenthal
Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when
More informationCIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION
CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1 Name SOLUTION Page Points Score 2 15 3 8 4 18 5 10 6 7 7 7 8 14 9 11 10 10 Total 100 1 P age 1. Program Traces (41 points, 50 minutes)
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 informationSt. Edmund Preparatory High School Brooklyn, NY
AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think
More informationCSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:
Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this
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 informationITERATION WEEK 4: EXMAPLES IN CLASS
Monday Section 2 import java.util.scanner; public class W4MSection2 { ITERATION WEEK 4: EXMAPLES IN CLASS public static void main(string[] args) { Scanner input1 = new Scanner (System.in); int CircleCenterX
More informationCSC 1051 Data Structures and Algorithms I
Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this
More informationJava Coding 3. Over & over again!
Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java
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 informationFull file at
Chapter 3 Flow of Control Multiple Choice 1) An if selection statement executes if and only if: (a) the Boolean condition evaluates to false. (b) the Boolean condition evaluates to true. (c) the Boolean
More informationAP COMPUTER SCIENCE A
AP COMPUTER SCIENCE A CONTROL FLOW Aug 28 2017 Week 2 http://apcs.cold.rocks 1 More operators! not!= not equals to % remainder! Goes ahead of boolean!= is used just like == % is used just like / http://apcs.cold.rocks
More informationCSC 1051 Data Structures and Algorithms I
Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this
More informationCOMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz
COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz The in-class quiz is intended to give you a taste of the midterm, give you some early feedback about
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 informationIntroduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017
Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor
More informationUniversity of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007
Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2007 Final Examination Question Max
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 informationExam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:
كلية الحاسبات وتقنية المعلوما Exam 2 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: November 22, 2015 Student Name: Student ID: Total Marks: 40 Obtained Marks: Instructions: Do not open this
More informationChapter 5 Lab Methods
Chapter 5 Lab Methods Lab Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation using the javadoc utility Introduction Methods
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 informationMidterm Examination (MTA)
M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and
More informationIntroduction to Computer Science I Spring 2010 Sample mid-term exam Answer key
Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key 1. [Question:] (15 points) Consider the code fragment below. Mark each location where an automatic cast will occur. Also find
More informationTerm 1 Unit 1 Week 1 Worksheet: Output Solution
4 Term 1 Unit 1 Week 1 Worksheet: Output Solution Consider the following what is output? 1. System.out.println("hot"); System.out.println("dog"); Output hot dog 2. System.out.print("hot\n\t\t"); System.out.println("dog");
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 informationCh. 6. User-Defined Methods
Ch. 6 User-Defined Methods Func5onal Abstrac5on Func5onal regarding func5ons/methods Abstrac5on solving a problem in a crea5ve way Stepwise refinement breaking down large problems into small problems The
More informationCS 152: Data Structures with Java Hello World with the IntelliJ IDE
CS 152: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Electrical and Computer Engineering building
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 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 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 informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
More informationChapter 4: Conditionals and Recursion
Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Agenda The modulus operator Random Number Generation Conditional Execution Alternative
More informationBuilding Java Programs
Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's
More informationChapter 3. Ch 1 Introduction to Computers and Java. Selections
Chapter 3 Ch 1 Introduction to Computers and Java Selections 1 The if-else Statement 2 Flow Chart Deconstructed Decision: Make a choice Start Terminator: Show start/stop points T boolean expression F true
More informationInterpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled
Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac
More informationThe action of the program depends on the input We can create this program using an if statement
The program asks the user to enter a number If the user enters a number greater than zero, the program displays a message: You entered a number greater than zero Otherwise, the program does nothing The
More informationThe for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming
The for Loop, Accumulator Variables, Seninel Values, and The Random Class CS0007: Introduction to Computer Programming Review General Form of a switch statement: switch (SwitchExpression) { case CaseExpression1:
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 informationChapter 3. Selections
Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of
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 informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements
WIT COMP1000 Simple Control Flow: if-else statements Control Flow Control flow is the order in which program statements are executed So far, all of our programs have been executed straight-through from
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 informationFlow of Control: Loops. Chapter 4
Flow of Control: Loops Chapter 4 Java Loop Statements: Outline The while statement The do-while statement The for Statement Java Loop Statements A portion of a program that repeats a statement or a group
More informationConditionals, Loops, and Style
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
More informationMore Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements
More Things We Can Do With It! More operators and expression types More s 11 October 2007 Ariel Shamir 1 Overview Variables and declaration More operators and expressions String type and getting input
More informationExample Program. public class ComputeArea {
COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for
More informationLinked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }
Linked Lists Since a variable referencing an object just holds the address of the object in memory, we can link multiple objects together to form dynamic lists or other structures. In our case we will
More informationCS1150 Principles of Computer Science Loops (Part II)
CS1150 Principles of Computer Science Loops (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Review Is this an infinite loop? Why (not)?
More informationBuilding Java Programs
Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1 self-check: Ch. 4 #2; Ch. 5 # 1-10 exercises: Ch. 4 #2, 4, 5, 8; Ch. 5 # 1-2 Copyright 2009
More informationChapter 1 Lab Algorithms, Errors, and Testing
Chapter 1 Lab Algorithms, Errors, and Testing Lab Objectives Be able to write an algorithm Be able to compile a Java program Be able to execute a Java program using the Sun JDK or a Java IDE Be able to
More informationFaculty of Science Midterm. COMP-202B - Introduction to Computing I (Winter 2008)
Student Name: Student Number: Section: Faculty of Science Midterm COMP-202B - Introduction to Computing I (Winter 2008) Friday, March 7, 2008 Examiners: Prof. Jörg Kienzle 18:15 20:15 Mathieu Petitpas
More informationCSC 1051 Data Structures and Algorithms I
Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this
More informationChapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );
Chapter 4 Loops Sections Pages Review Questions Programming Exercises 4.1 4.7, 4.9 4.10 104 117, 122 128 2 9, 11 13,15 16,18 19,21 2,4,6,8,10,12,14,18,20,24,26,28,30,38 Loops Loops are used to make a program
More informationCS 177 Recitation. Week 1 Intro to Java
CS 177 Recitation Week 1 Intro to Java Questions? Computers Computers can do really complex stuff. How? By manipulating data according to lists of instructions. Fundamentally, this is all that a computer
More informationCONDITIONAL EXECUTION
CONDITIONAL EXECUTION yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I Outline Conditional Execution if then if then Nested if then statements Comparisons
More informationSection 004 Spring CS 170 Exam 1. Name (print): Instructions:
CS 170 Exam 1 Section 004 Spring 2014 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than
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 informationIntroduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures
Introduction to Computer Science, Shimon Schocken, IDC Herzliya Lectures 3.1 3.2 Control Structures Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 1 Control structures A program
More informationSchool of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn
CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...
More informationFull file at
Chapter 3 Flow of Control Key Terms parentheses, p. 95 if-else, p. 95 if-else with multiple statements, p. 96 compound statements, p. 96 indenting, p. 98 multiway if-else, p. 98 switch statement, p. 101
More informationChapter 6. Repetition. Asserting Java. Rick Mercer
Chapter 6 Repetition Asserting Java Rick Mercer Algorithmic Pattern: The Determinate loop We often need to perform some action a specific number of times: Produce 89 paychecks. Count down to 0 (take 1
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 informationSection 002 Spring CS 170 Exam 1. Name (print): Instructions:
CS 170 Exam 1 Section 002 Spring 2015 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than
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 informationArrays. Eng. Mohammed Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays
More informationCOE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.
1 COE 212 Engineering Programming Welcome to Exam II Thursday April 21, 2016 Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F. Fawaz Name: Student ID: Instructions: 1. This exam is Closed Book.
More information