CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
CSCI S-1 Section 5. Deadlines for Problem Set 3 Part A – Friday, July 10, 17:00 EST Parts B – Tuesday, July 14, 17:00 EST Getting the code examples from.
Computer Science 1620 Loops.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
MSc IT Programming Methodology (2). MODULE TEAM Dr Aaron Kans Dr Sin Wee Lee.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Advanced Computer Science Lesson 4: Reviewing Loops and Arrays Reading User Input.
Methods We write methods in our programs for many reasons:
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
1 Array basics. Data Structures Sometimes, we have data that have some natural structure to them  A few examples: Texts are sequences of characters Images.
Building java programs, chapter 5 Program logic and indefinite loops.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Building Java Programs Program Logic and Indefinite Loops.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Loops and Logic. Making Decisions Conditional operator Switch Statement Variable scope Loops Assertions.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
CSE 110 Midterm Review Hans and Carmine. If Statements If statements use decision logic In order to properly use if statements relational operators must.
Chapter VII: Arrays.
Java Fundamentals 4.
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Repetition-Counter control Loop
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
SELECTION STATEMENTS (1)
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Building Java Programs
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Building Java Programs
Building Java Programs
Building Java Programs
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Presentation transcript:

CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall

Quick Intro What is a program? o List of instructions a computer can follow Variable: is a name that refers to a location in memory o They store values which can be different types called Data Types Variables must be declared and initialized Primary data types are: o IntegerString o FloatChar o DoubleBoolean

If and If-Else Statements The If and If-Else statements use decision logic In order to properly use if and if-else statements, relational operators must be used. o == : equal o > : one value is greater than another o < : one value is less than another o != : not equal o compareTo() : method used to compare multiple Strings Whenever relational operators are used, a boolean value is returned

Quick Example if(x==5){ //if the variable x has a value of 5 System.out.print(5); } else{ //if the above if statement is not true System.out.print(“Not a 5”);}

Sample Problem What is the output of this code? int i = 6; if(i > 10){ System.out.println(“Big number!”); }else if(i ==10){ System.out.println(“Almost big.”);} else {System.out.println(“Small number!”);} Small Number!

Loops Unlike If-Else statements, loops use iterative logic o Meaning, loops are used in order to perform the same operation multiple times Every loop requires four components: o initialization of a variable local to the loop o a stopping condition o incrementation or a modification statement o The operation or operations to be done within the loop

Quick Example for(int i = 0; i < 10: i++){ System.out.print(i + “,”); } What is the output of this loop? 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Sample Problem What is the output of the following code? Additionally, where is the incrementation statement, initialization, stopping condition, and operation to be done within the loop? int i = 10; while(i>0){ System.out.print(i + “, ”); i = i-2; } Initialization Stopping Condition Incrementation Statement Operation to be done within the loop Output: 10, 8, 6, 4, 2

Methods - Review What is a method? ●A method is a sequence of code instructions that are given a name ●A method exists within a class ●Several methods can exist within a class ●A method takes in 0 to many arguments (inputs) ●A method returns 0 or 1 return values (output) ●Code inside the method uses the arguments What is a method good for? ●Methods are useful when you need to execute the same set of instructions many times in your program (not in a loop) ●Methods are useful for breaking up code into smaller, more manageable logical chunks

Methods - Header/Definition and Example public static int sum (int num1, int num2) { int result = num1 + num2; return result; } A method header (also known as a definition) specifies four things: ●The name of the method ●The parameters of the method and their types ●The return type of the method ●Visibility and other modifiers

Method Practice How can we create a method that takes an integer as a parameter and returns the sum of all the numbers before and including that number -- e.g., = 15 public static int countDownSum(int num) { int total = 0; int startCountDown = num; for (int i = 0; i < startCountDown; i++) { total = total + num; num -= 1; //This is the same as num = num -1; } return total; }

Creating a Method - You Try Create a method header with the following properties: Its name is “rateMovie” It takes 2 arguments. One argument is a String corresponding to the name of a movie. The second is an integer value which is a rating of that movie. Nothing is returned. Solution: public static void rateMovie(String movieName, int rating)

Creating a Method - You Try Create a method that will calculate the volume of a box and return the sentence “Volume is large.” if the volume is greater than or equal to If the volume is less than your method should return the sentence “Volume is small.” Your method should also print the volume of the box to the console. Don’t worry about the units of the box. What parameters does the method require? Hint: There are 3 What is the return data type? Do you need to print out the volume of the box before or after the return statement?

Creating a Method - Possible Solution public static void main (String [] args) { System.out.println(boxSize(5.0, 7.0, 2.0)); } public static String boxSize(double length, double width, double height) { double volume = length * width * height; String result = “”; System.out.println(volume); if (volume >= 100) { result = “Volume is large.” } else { result = “Volume is small.” } return result; } Output of this program is: 70.0 Volume is small.

Classes and Objects Class: Defines the object type Object: an instance of a class An object has: o Variables o Methods Classes are used to define these for objects of its type Meaning, a class is a blueprint for an object of that class!

Brief Example public Class Rectangle{ public int width, height; public Rectangle(int height1, int width1){ width= width1; height = height1} public int perimeter(){ int perimeter = 2*length + 2*height return perimeter; }

Make Your Own Class! Make your own dog class that has: A constructor with two arguments: one String which will contain the name of the dog and an integer which will contain its age A method that will determine whether or not the dog is old based on the age (if age > 5 then the dog is old). This method doesn’t need to return anything. Once you are finished making the class, write the code that would create an object of the dog class.

Possible Solution public Class Dog{ public String name = “ ”; public int age = 0; public Dog(String thisName, int thisAge){ name = thisName; age = thisAge;} public void isOld(){ if(age > 5){System.out.println(“This is an old dog”);} else{ System.out.println(“This dog isn’t old!”);} } Dog fido = new Dog(“Fido”, 2);

Arrays - Review An array has these properties: Elements - These are the values or objects that make up the array. All of the elements in an array must be of the same type Length - The number of elements that make up the array. An array is fixed in length - Once you set the size of an array it cannot be changed The first element of an array is located at index 0 Array Syntax: [] = new [ ]; Elements unknown: int [] scores = new int[5]; Elements known: int [] scores = {90, 80, 75, 85, 90}

Arrays - Review int [] scores = new int [5]; scores[1] = 90; scores [2] = 80; int exam3 = 85; scores [3] = exam3; What element is at each index? What happens if you try this? int exam5 =scores[5] grades[5] = 100; //Out of bounds exception! //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

Array Practice How can we create an array with 3 elements and ask the user to fill the array with movie titles? We should then print each element of the array unless the title is “Star Wars”. If the title is “Star Wars” we should print “Please be awesome”.

Array Practice - Possible Solution Scanner scan = new Scanner(System.in); String [] movies = new String[3]; movies[0] = scan.nextLine(); movies[1] = scan.nextLine(); movies[2] = scan.nextLine(); for (int i = 0; i < movies.length; i++ { if (movies[i].equals(“Star Wars”)) { System.out.println(“Please be awesome”); } else { System.out.println(movies[i]); }

Array Practice - You Try What is the output of this program? int [] numbers = {1, 2, 3, 4, 5}; int var1 = 2; int var2 = 4; if (numbers[4] == variable 2) { numbers[1] = numbers[2]; } else { numbers[2] = var1; var2 = numbers[3]; } while (var2 > var1) { numbers[1] = numbers[1] +2; var1++ } numbers[4] = (numbers[3])/2; for (int i = 1; numbers.length > i; i++) { System.out.println(numbers[i]) } index numbers = [1], [2], [3], [4], [5] var1 = 2 var2 = 4 numbers = [1], [2], [2], [4], [5] var2 = 4 numbers = [1], [4], [2], [4], [5] : numbers = [1], [6], [2], [4], [5] var1 = 3 : var1 = 4 numbers = [1], [6], [2], [4], [2] Output:

ArrayLists ArrayLists expand and shrink dynamically as needed Some commonly used methods: add get size set ArrayList Syntax: ArrayList = new ArrayList (); Arraylist scores = new ArrayList ();

ArrayLists - You Try What is the output of this program? Arraylist scores = new ArrayList (); scores.add(50); scores.add(75); System.out.println(scores.size()); int removedScore = scores.remove(1); scores.add(removedScore + 10); scores.set(0, 100); scores.add(2, 85); for (int i = 0; i <scores.size(); i++) { System.out.println(scores.get(i)); } Output:

Recursive Methods A recursive method is a method which calls itself A couple of items are required for a recursive method: o Base case o Code that will aid in getting closer to the base case Quick example: public int factorial(int number) {if(number ==1 || number == 0){ return 1;} else{return factorial(number-1)*number;} }

Write your Own Recursive Method! Write a recursive method that will calculate the sum of all numbers up to a specific number (meaning, if the number is 5, calculate ). What is the base case? How can you get closer to the base case given a larger “size n” problem?

Possible Solution public int addition(int number) { if(number == 0){ return 0;} if(number ==1 |){ return 1;} else{return addition(number-1)+number;} }

Questions?

Extra Questions

Loops - Practice public static void main (String[] args) { for (int i = 0; i < 3; i++) { for (int j = 3; j > i; j--) { System.out.println(j) } System.out.println(); } What is the output of this program?

Solution

Methods - Practice Create a method that determines whether or not a positive integer number is even or odd. If the number is odd, your method should return -1. If it is even, your method should return 1. If the number is invalid (not positive), then your method should return 0.

Solution public static int isEven(int number) { int returnValue = 0; if (number > 0) { if (number % 2 == 0) { returnValue = 1; } else { returnValue = -1; } return returnValue; }

Arrays - Practice Write a program that will find the maximum and minimum value of an array that contains the values 0.12, 0.81, 0.45, 0.03, Then print out the max and min values.

Solution public static void main(String [] args) { double [] values = {0.12, 0.81, 0.45, 0.03, 0.80}; double max = values[0]; double min = values[0]; for (int i = 0; i < values.length; i++) { if (values[i] > max) { max = values[i]; } if (values[i] < min) { min = values[i] } System.out.println(“The maximum value is “ + max); System.out.println(“The minimum value is “ + min); }

Recursion-Practice What does this method do? When this method is called, will it return anything? public int addition(int number){ return addition(number-1)+number; } It won’t return anything and it will run forever since there is no stopping condition!