CS1101: Programming Methodology

Slides:



Advertisements
Similar presentations
Solving Problems with Repetition. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C# program Correctly.
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
CS1010 Programming Methodology
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
1 CS 177 Week 15 Recitation Slides Review. Announcements Final Exam on Sat. May 8th  PHY 112 from 8-10 AM Complete your online review of your classes.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
The switch Statement, DecimalFormat, and Introduction to Looping
CS1101: Programming Methodology
CS1101: Programming Methodology Aaron Tan.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology
General Programming Introduction to Computing Science and Programming I.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Chapter 12: How Long Can This Go On?
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
CS1010: Programming Methodology
Computer Programming 2 Lab(1) I.Fatimah Alzahrani.
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
WEEK 4 Class Activities Lecturer’s slides.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Practice and Evaluation. Practice Develop a java class called: SumCalculator.java which computes a sum of all integer from 1 to 100 and displays the result.
CS1101: Programming Methodology Aaron Tan.
C++ Programming Language Lecture 2 Problem Analysis and Solution Representation By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Structured Programming: Debugging and Practice by the end of this class you should be able to: debug a program using echo printing debug a program using.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CS1101: Programming Methodology
Chapter 4: Control Structures II
Chapter 5: Control Structures II
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
1 CS161 Introduction to Computer Science Topic #8.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
The Hashemite University Computer Engineering Department
© The McGraw-Hill Companies, 2006 Chapter 3 Iteration.
1 Project 2: Using Variables and Expressions. 222 Project 2 Overview For this project you will work with three programs Circle Paint Ideal_Weight What.
CS1101: Programming Methodology
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
Algorithms and Pseudocode
CS1010: Programming Methodology
CPSC 233 Tutorial 5 February 2 th /3 th, Java Loop Statements A portion of a program that repeats a statement or a group of statements is called.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Solving Problems with Repetition Version 1.0. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C#
General Condition Loop A general condition loop just loops while some condition remains true. Note that the body of the loop should (eventually) change.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Part 1 Learning Objectives To understand that variables are a temporary named location to store data and that programmers work with different data types.
Chapter 5: Control Structures II
CS1371 Introduction to Computing for Engineers
CS1010 Programming Methodology
Repetition-Counter control Loop
Building Java Programs
CS1100 Computational Engineering
Java Programming Loops
Chapter 5 Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Java Programming Loops
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

CS1101: Programming Methodology

Week 5: Selection Statements (cont’d) and Repetition Statements  Last week:  Chapter 4: Defining Your Own Classes – Part 1 (cont’d)  Chapter 5: Selection Statements  This week:  Chapter 5: Selection Statements (cont’d)  Chapter 6: Repetition Statements  Next week:  Chapter 6: Repetition Statements (cont’d)  Testing and Debugging (not in textbook) © CS1101 (AY Semester 1)Week5 - 2

Reminder Have you read the relevant chapters and PowerPoint files before coming to this lecture? Have you been filling your Progress Chart? Have you been asking questions in class/IVLE forums? Have you done the Quick Check questions in the textbook? Have you been writing programs and exploring on your own? © CS1101 (AY Semester 1)Week5 - 3

Last week’s Exercise #4: Matric Check Code (1/3) Algorithm for Matriculation check code  Matriculation number consists of 6 digits (ignore the ‘U’ in front)  Eg: U  Step 1: Multiply the 2 nd through 6 th digits with their corresponding weights 2, 6, 2, 4, 1 and sum them up.  Eg: 9      1 = = 79  Step 2: Divide step 1 result by 13 to obtain the remainder.  Eg: 79 % 13 = 1 © CS1101 (AY Semester 1)Week5 - 4

Last week’s Exercise #4: Matric Check Code (2/3) Algorithm for Matriculation check code (cont’d)  Step 3: Subtract step 2 result from 13.  Eg: 13 – 1 = 12  Step 4: Match step 3 result in this table for the check code.  Eg: The check code corresponding to 12 is ‘L’.  Therefore, the check code for U is ‘L’. Write a program CheckMatric.java © CS1101 (AY Semester 1)Week MBNAREUHWJXLY

Last week’s Exercise #4: Matric Check Code (3/3) Show me your program! How did you develop your program? How did you test your program? How did you debug your program? © CS1101 (AY Semester 1)Week5 - 6

Comparing Objects Refer to Thomas Wu’s slides  What is the difference between == and.equals()? © CS1101 (AY Semester 1)Week5 - 7

Comparing Real Numbers Real numbers, especially computed ones, are not represented accurately in computers. (Why?) Test out the program ExploreRealNumbers.java on some data.  What are the inputs where value2 is different from value1 ? To cater to such inaccuracy, we sometimes allow some ‘tolerance’ in the difference.  Instead of using == to compare, we may conclude that 2 values are “equal” if they are close enough  See ExploreRealNumbersV2.java © CS1101 (AY Semester 1)Week5 - 8

Naming Boolean Variables Good Boolean variable names make the code easier to understand Are these good names of Boolean variables?  boolean1  flag  isNotInvisible Are these good names of Boolean variables?  isValid  isPrime  toContinue © CS1101 (AY Semester 1)Week5 - 9

Exercise #5: Leap Year A year is a leap year if  It is divisible by 4 but not by 100; or  It is divisible by 400 Examples of leap year:  2004, 1980, 2000, 2400 Examples of non-leap year:  1997, 2001, 2006, 2100, 2200, 2300 Download LeapYear.java and correct it © CS1101 (AY Semester 1)Week5 - 10

Chapter 6: Repetition Statements Three syntactic flavours  while, do-while, for Nested loops Using break and continue in loop (Note that recursion – Section 6.10 Recursive Methods – is not in the CS1101 syllabus. We will cover it at the end of the course as a non-examinable topic.) © CS1101 (AY Semester 1)Week5 - 11

while, do-while, for Example: Print positive odd numbers < 100. © CS1101 (AY Semester 1)Week int i = 1; while (i < 100) { System.out.println(i); i += 2; } int i = 1; do { System.out.println(i); i += 2; } while (i < 100); for (int i=1; i<100; i+=2) System.out.println(i);

Another Very Common Mistake Besides the pitfalls mentioned in Thomas Wu’s book, here is another very common mistake. The following codes to display “Hello” 5 times compile and run, but give wrong result. Describe what will happen and correct the errors. © CS1101 (AY Semester 1)Week for (int x = 0; x < 5; x++); System.out.println("Hello"); int x = 0; while (x < 5); { System.out.println("Hello"); x++; }

Exercise #1 Complete OddIntegers.java to print odd integers between 1 and 39 inclusive. In your program, include 3 versions, using ‘for’, ‘while’ and ‘do-while’. Sample run: © CS1101 (AY Semester 1)Week

Exercise #2 Complete AsterisksV1.java to read in an integer n and print n asterisks on a single line. (If n is non-positive, then no asterisk will appear.) Sample runs: © CS1101 (AY Semester 1)Week Enter n: 7 ******* Done! Enter n: -2 Done!

Exercise #3: Nested Loops Download NestedLoopEx1.java, NestedLoopEx2.java and NestedLoopEx3.java. Hand trace the programs and write out the outputs without running the programs. Verify your answers by running the programs. © CS1101 (AY Semester 1)Week5 - 16

Using ‘break’ in loop (1/3) We have used ‘break’ in ‘switch’ statement. ‘break’ can also be used in a loop. Download BreakInLoop.java and run it. What do you understand about ‘break’? © CS1101 (AY Semester 1)Week5 - 17

Using ‘break’ in loop (2/3) Use ‘break’ sparingly, because using it violates the one-entry-one-exit control flow. A loop with ‘break’ can be rewritten into another without ‘break’. (See next slides.) Use ‘break’ only when it does not obfuscate readers. Example: Loop-and-half repetition control in Thomas Wu’s Chapter 6 slide 21. © CS1101 (AY Semester 1)Week5 - 18

Using ‘break’ in loop (3/3) Codes with and without ‘break’ – to add 10 integers entered by the user, or until a negative integer is encountered. © CS1101 (AY Semester 1)Week // with ‘break’ Scanner sc = new Scanner(System.in); int n, i, sum; sum = 0; i = 1; while (i <= 10) { n = sc.nextInt(); if (n < 0) break; sum += n; i++; } // without ‘break’ Scanner sc = new Scanner(System.in); int n, i, sum; sum = 0; i = 1; n = sc.nextInt(); while ((i = 0)) { sum += n; i++; n = sc.nextInt()); }

Using ‘continue’ in loop Download ContinueInLoop.java and run it. What do you understand about ‘continue’? ‘continue’ is even less used than ‘break’. © CS1101 (AY Semester 1)Week5 - 20

Strange Behaviour #2 Some students encountered this and wondered why. Download Strange2.java and test it. What happens?  You notice that you have no chance to enter the name! Why?  When you hit ‘enter’ after typing in the integer for the nextInt() method, the newline character is picked up by the nextLine() method. How to solve it?  One simple solution: add a nextLine() call to ‘trap’ this newline character. © CS1101 (AY Semester 1)Week5 - 21

Strange Behaviour #3 Download Strange3.java and test it. This is almost the same as the previous program, except that here you want the user to repeatedly enter name and height. When the user enters an empty name, the loop terminates. What happens when you run the program? Why? How do you correct it? © CS1101 (AY Semester 1)Week5 - 22

Control Structures You have learned the 3 control structures:  Sequence  Selection  Repetition With these, you are able to solve any general problem! However, writing good programs is more than just learning the syntax:  Logic should be clear  Variables (especially Boolean variables) should be descriptive  Algorithm should be efficient (see Thomas Wu’s chapter 6 slide 8 on Finding GCD) © CS1101 (AY Semester 1)Week5 - 23

Exercise #4: Prime-Number (Take-home) Primality test is a classic programming problem  Given a positive integer, determine whether it is a prime number or not  A prime number has two distinct factors (divisors): 1 and itself. Examples: 2, 3, 5, 7, 11, … Write a program PrimeTest.java. Discuss this at this week’s discussion session. Sample runs: © CS1101 (AY Semester 1)Week Enter a positive integer: is a prime. Enter a positive integer: is not a prime.

Exercise #5: BallV2 (1/2) Do you still remember the Ball class we created? As promised, we will now enhance it to BallV2 with the following additional items:  Two additional integer data members xCoord and yCoord: the x- and y-coordinates of the centre of a BallV2 instance.  A method moveVertical (int dist) that moves a ball object vertically by dist value. This will update the yCoord of the ball object.  A method moveHorizontal (int dist) that moves a ball object horizontally by dist value. This will update the xCoord of the ball object. Write a program BallV2.java and an application program TestBallV2.java. © CS1101 (AY Semester 1)Week5 - 25

Exercise #5: BallV2 (2/2) A sample run of TestBallV2: © CS1101 (AY Semester 1)Week Enter colour: red Enter radius: 1.2 Enter centre’s x- and y- coordinates: 3 4 Colour is red Radius is 1.2 Centre is (3,4) Distance to move horizontally: -8 Distance to move vertically : 2 Centre is (-5,6) Your program should create an object of BallV2 with the user’s supplied values, then use the accessor methods on the object to retrieve the values for display.

Exercise #6: BallV2GUI (1/3) Let’s have some fun. You have seen an GUI version of Lab #2 Ex2 Elevator, now we shall have an GUI version for Ball. Let’s see how it works. You are given the following:  Canvas.class (if it doesn’t work, ask for the source code)  BallV2GUI.java  TestBallV2GUI.java You are to study the Java programs given, and complete the two methods in BallV2GUI.java  slowMoveHorizontal(int dist)  slowMoveVertical(int dist) © CS1101 (AY Semester 1)Week5 - 27

Exercise #6: BallV2GUI (2/3) Note that the display is 300 pixels by 300 pixels. In graphics, the larger the y-coordinate value, the further down. Sample run: © CS1101 (AY Semester 1)Week5 - 28

Exercise #6: BallV2GUI (3/3) Possible exercises (to try out on your own at home):  Currently the ball object is still displayed (in part) if portion of it goes outside the boundary of the 300x300 display window.  Modify the code TestBallV2GUI.java such if you enter a position of the centre that causes the ball to be displayed outside (partially or fully) the screen, you ask for the user to enter a new position. Repeat this until the position is valid (that is, the ball can be displayed in its entirety.)  Modify the methods moveHorizontal(int) and moveVertical() in BallV2GUI.java such that if the new position causes the ball to be outside (partially or fully) the screen, then it rejects the move and keeps the ball in its current position.  Modify the methods slowMoveHorizontal(int) and slowMoveVertical() in BallV2GUI.java such that once the ball object hits the edge of the window, it stops moving and that will be its final position.  Any other changes/enhancements that you can think of. © CS1101 (AY Semester 1)Week5 - 29

Next week Do you know how to play Master Mind? Please find out before you come for next week’s lecture! © CS1101 (AY Semester 1)Week5 - 30

Summary for Today Selection statements (cont’d) Repetition statements  ‘while’  ‘do-while’  ‘for’  break  continue © CS1101 (AY Semester 1)Week5 - 31

Announcements/Things-to-do (1/2) Complete the following  Do Quick Check questions in Chapter 6. Check out the answers (on CS1101 website) yourself.  Exercise 4: PrimeTest.java  Exercise 5: BallV2GUI.java To prepare for next week’s lecture:  Read Week6.ppt (topic “Testing and Debugging” is not found in your book)  Find out about the game Master Mind © CS1101 (AY Semester 1)Week5 - 32

Announcements/Things-to-do (2/2) Survey  We will conduct an online survey during lecture next week (no need to prepare) To prepare for this week’s discussion session:  Download “week5_discussion_qns.pdf” from module website, “CA – Discussion”.  Do the questions before you attend your discussion session. © CS1101 (AY Semester 1)Week5 - 33

End of File © CS1101 (AY Semester 1)Week5 - 34