Review of CSCI 1226 What You Should Already Know.

Slides:



Advertisements
Similar presentations
Introduction to Computing Science and Programming I
Advertisements

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While, Do, For Repetition Statements Introduction to Arrays
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.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: Scanner ; if/else reading: , 4.2, 4.6.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
Chapter 2 - Algorithms and Design
Java Programming: From the Ground Up
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create.
Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators, Constants, and Switching int and double)
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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 3.
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.
Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing.
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.
Textbook: Data Structures and the Java Collections Framework 3rd Edition by William Collins William Collins.
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
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
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)
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.
Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase()
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
By Mr. Muhammad Pervez Akhtar
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Building Java Programs Program Logic and Indefinite Loops.
CSCI S-1 Section 8. Coming Soon Problem Set Four (72 + 5/15 points) – Tuesday, July 21, 17:00 EST.
Review of CSCI 1226 More of What You Should Already Know.
Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
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.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Chapter VII: Arrays.
4. Java language basics: Function
Chapter 2 More on Math More on Input
Introduction To Repetition The for loop
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 7 Part 1 Edited by JJ Shepherd
Loop Structures.
Building Java Programs
Repeating Actions The "while" and "for" Controls Sections 4.1 & 4.2
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Building Java Programs
Computing Fundamentals
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
What You Should Already Know
Building Java Programs
Presentation transcript:

Review of CSCI 1226 What You Should Already Know

n Basic programming  program class: class declaration, main method  output: System.out, print & println  variables: declaration, assignment, arithmetic  data types: int, double, boolean, String  input using Scanners: »import, declare, and create »nextInt, nextDouble, next, nextLine »“tidying up” your input

What You Should Already Know n Comments  why and when we use them »to end-of-line: // … »multi-line: /* … */ »javadoc: /** … */ n Style  names and why they’re important  camelCase, CONSTANT_STYLE  indentation, spacing, line length

What You Should Already Know n Conditionals and boolean expressions  maybe do: the if control  comparisons: ==, !=,, >=  logical operators: !, &&, ||  exactly one of two: if-else  exactly (or at most) one of many: if-else-if n String methods that return boolean values  equals, equalsIgnoreCase, startsWith, …

What You Should Already Know n Loops  definite loops: the for loop (count controlled)  indefinite loops: the while loop »sentinel control: Read-Test-Process-Read »general control: Initialize-Test-Process-Update n Arrays  declare, create, get length of  standard loop for visiting every element

What You Should Already Know n Methods (using)  parts of the method call »location/owner, method name, arguments  return value (including void)  Math methods: pow, sqrt, random, …  Arrays methods: toString, sort  String methods: toUpper, toLower, length, …

What You Should Already Know n Methods (creating)  why we create methods »reuse, hiding, abstraction »the method’s task/purpose/job  creating a class of related static methods  parts of the method declaration »public static, return type, name, parameters »body (including return command)  what a stub is and why we make them

What You Should Already Know n Data Types (using)  class data types: String, Scanner, …  variables, objects, and reference: »String myName = “Mark”; »Scanner kbd = new Scanner(System.in);  asking objects questions »getting information about them: getters »changing their information: setters »getting them to do things

What You Should Already Know n Data Types (creating)  why we create data types: representation  creating a class for a data type  parts of the data type »instance variables (private) and constants (final) »constructors: assigning values, this(…) »creating getter and setter methods: this.___  static variables, constants, and methods »why, when, and how

Review Outline n Today:  conditionals, loops, and arrays n Tuesday:  methods n Thursday:  data types n New(ish) material starts in week 2

Purpose of a Conditional n Maybe do some command  need to know the conditions for doing it if the user says they want fries add fries to the order n Choose between multiple actions set the letter grade based on the percent grade: 80 or more: A; 70 to 79: B, 60 to 69: C, 50 to 59: D; otherwise F

Do or Do Not(*) n if user says “yes” to the question  say “FRIES!”  add the price of the fries to the total What sandwich? Big Greesie BIG GREESIE! Would you like fries with that? yes FRIES! What can I get you to drink? Cola COLA! That'll be $ What sandwich? Big Greesie BIG GREESIE! Would you like fries with that? no What can I get you to drink? Cola COLA! That'll be $9.94. (*) There is no try in CSCI 1226… Maybe add fries… Total depends…

Do or Do Not System.out.print(“What sandwich? ”); answer = kbd.nextLine(); System.out.println(answer.toUppercase() + “!”); total += 8.95; System.out.print(“Want fries with that? ”); answer = kbd.nextLine(); if (answer.startsWith(“y”)) { System.out.println(“FRIES!”); total += 1.99; }… …add fries to the order if they say they want fries…

Cascading If Statements n Else part can have an if command in it if (…) { …;// program might do this… } else if (…) { …;// …or this… } else if (…) { …;// …or this… } else { …;// …or this. }  program chooses one of those four things to do

Using Conditionals n Conditionals are used when you need to do only one of multiple possible actions  remembering that “do nothing” may be one of the possible actions n Look for “Do one of the following” or “if such-and-such, do …”

Building a Selection Structure n Enumerate the alternatives  what are the possible actions?  is do nothing one of the alternatives? print “It’s hot!” print “It’s warm.” print “It’s nice.” print “It’s cool.” print “It’s cold!”

Building a Selection Structure n Identify the conditions  when is each action the right thing to do? print “It’s hot!” print “It’s warm.” print “It’s nice.” print “It’s cool.” print “It’s cold!” 30 <= temp 25 <= temp < <= temp < 25 5 <= temp < 15 temp < 5

Building a Selection Structure n Sort the options  from “largest” to “smallest”…  …or from “smallest” to “largest” print “It’s hot!” print “It’s warm.” print “It’s nice.” print “It’s cool.” print “It’s cold!” 30 <= temp 25 <= temp < <= temp < 25 5 <= temp < 15 temp < 5

Building a Selection Structure n Assign if/else-if/else  first is if; last is else; others are else if print “It’s hot!” print “It’s warm.” print “It’s nice.” print “It’s cool.” print “It’s cold!” 30 <= temp 25 <= temp < <= temp < 25 5 <= temp < 15 temp < 5 if else if else

Building a Selection Structure n Simplify the conditions  drop the part that’s implied print “It’s hot!” print “It’s warm.” print “It’s nice.” print “It’s cool.” print “It’s cold!” 30 <= temp 25 <= temp 15 <= temp 5 <= temp We won’t get here unless temp < 30 Nor here unless temp < 5 if else if else

Building a Selection Structure n Add parentheses, indentation, braces, … if (30 <= temp) { System.out.print(“It’s hot!”); } else if (25 <= temp) { System.out.print(“It’s warm.” ); } else if (15 <= temp) { System.out.print(“It’s nice.” ); } else if (5 <= temp) { System.out.print(“It’s cool.” ); } else { System.out.print(“It’s cold!” ); }

Building a Selection Structure n If there is a do nothing option, leave it out if (30 <= temp) { System.out.print(“It’s hot!”); } else if (temp < 5) { System.out.print(“It’s cold!”); } print “It’s hot!” (do nothing) print “It’s cold!” 30 <= temp 5 <= temp < 30 temp < 5 { } else if (5 <= temp) { But be careful with the conditions!

Boolean Expressions n Comparison operators:  ==, !=,, >=  equals, not equals, less, less or equal, … (hours <= 40) n Logical operators combine conditions  and, or, not  &&, ||, !  parentheses recommended (needed for !) ((40 < hours) && (hours <= 60))

Combined Comparisons n Cannot combine comparisons like this: if (40 < hours <= 60) … n Need to break into two parts: if ((40 < hours) && (hours <= 60)) …

Combined Comparisons n Cannot combine comparisons like this: if (hours > 40 && 40 && <= 60)… n Need to say what’s less-than-or-equal-to 60  explicitly if ((hours > 40) && (hours 40) && (hours <= 60))…

Exercise n Write a conditional to set letterGrade based on numericGrade:  numericGrade in  letterGrade is ‘A’  numericGrade in  letterGrade is ‘B’  numericGrade in  letterGrade is ‘C’  numericGrade in  letterGrade is ‘D’  numericGrade less than 50  letterGrade is ‘F’  (assume numericGrade is )

Purpose of a Loop n Do something multiple times  write “Hello” ten times for count goes from 1 to 10 write “Hello” n Do same thing to many objects/values  add each number to a running total for each number in the list add that number to the running sum

How Many Times? n Do we know how many times the loop body will execute before we start the loop?  if so, we want to use a for loop  if not, then we want to use a while loop n Enter six assignment grades: for loop for (int a = 1; a <= 6; ++a) { … } n Add up numbers until negative: while loop while (num >= 0) { … }

Before, During, and After n Notice part that repeats, and parts that don’t Enter all your grades. Grade on A1: 100 Grade on A2: 90 Grade on A3: 95 Grade on A4: 0 Grade on A5: 100 Grade on A6: 95 Your average is 80.0 Before repeats Repeats (6 times) After repeats One repetition

Before, During & After System.out.println(“Enter all your grades.”); int numAsgn = 6; double sum = 0.0; for (int a = 1; a <= numAsgn; a++) { System.out.print(“Grade on A-” + a + “: ”); double grade = kbd.nextDouble(); kbd.nextLine(); sum += grade; } double ave = sum / numAsgn; System.out.println(“Your average is ” + ave); Before repeats Repeats (6 times) After repeats One repetition

Before, During, and After n Notice part that repeats, and parts that don’t Enter -1 to end. Enter first number: 100 Enter next number: 90 Enter next number: 95 Enter next number: 42 Enter next number: -1 The total is 327 Before repeats Repeats (until -1 entered) After repeats One repetition

Before, During & After int sum = 0.0; System.out.println(“Enter -1 to end.”); System.out.print(“Enter first number: ”); int num = kbd.nextInt();kbd.nextLine(); while (num >= 0){ sum += num; System.out.print(“Enter next number: ”); num = kbd.nextInt(); kbd.nextLine();} System.out.println(“The total is ” + sum); Before repeats Repeats (until -1 entered) After repeats One repetition

“Sentinel” Loops n Goes until a special value is entered  any number less than 0 for the last loop »even tho’ it asked specifically for -1 n Usually need to get 1 st value before the loop  then use the value (top of loop body)  get the next value last (bottom of loop body) »READ »TEST PROCESSPROCESS READREAD

“Sentinel” Loop int sum = 0.0; System.out.println(“Enter -1 to end.”); System.out.print(“Enter first number: ”); int num = kbd.nextInt();kbd.nextLine(); while (num >= 0){ sum += num; System.out.print(“Enter next number: ”); num = kbd.nextInt(); kbd.nextLine();} System.out.println(“The total is ” + sum); Read Test Read Process

Exercise n Write a loop to read in names, stopping when no name is entered. Say how many names there were. Who is in your class? Name (leave blank to end): Alex Name (leave blank to end): Bernard Name (leave blank to end): Cathy Name (leave blank to end): There are 3 students in your class. Remember: READ, test, process, read

Arrays n Array type is just another data type int anIntVar;// anIntVar’s type is int int[] aBunchOfIntVars;// aBunchOfIntVars’ type is int[] n Create by adding [] to a data type  any data type! double[] aBunchOfDoubleVars; String[] aBunchOfStringVars; Scanner[] aBunchOfScannerVars; int[][] aBunchOfIntArrayVars;

Arrays n Arrays need to be created with “new”  like Scanners double[] someNumbers = new double[20]; String[] someWords = new String[1000];  word after “new” matches the base data type »base data type = what kind of values are in the array  put the size of the array in the [brackets] »the size can be a variable, but it must have a value int howManyLines = kbd.nextInt(); kbd.nextLine(); String[] theLines = new String[howManyLines];

Arrays n An array is a collection/list of variables  each element is of the base type »int, double, String, … n Individual variables picked out using [] someNumbers[3]  brackets go right after the name of the array  number inside the brackets called the index  indexes (or indices) start at 0 (NOT 1!)

Array Loops n Array elements can be used individually… a[0] = a[1] + a[2] * a[3]; n …but usually used as a group/list  do same thing to each element of the array for (int i = 0; i < someNumbers.length; ++i) { someNumbers[i] = Math.sqrt(i); }  usually in a for loop »usually from 0 to less than the length of the array

Array Loop Upper Bounds n Every array knows how long it is  use its “dot-length property”  someNumbers.length, someWords.length, … n Or if you have a variable for its length… double[] grades = new double[numStu]; for (int i = 0; i < numStu; ++i) { … } n Do not use a “magic number” double[] grades = new double[100]; for (int i = 0; i < 100; ++i) { … } It’s error-prone (tends to add bugs to your program)

Use Arrays… n To remember lots of values  read & print 3 numbers in reverse is easy int a1, a2, a3; a1 = kbd.nextInt(); a2 = kbd.nextInt(); a3 = kbd.nextInt(); System.out.println(a3 + “ ” + a2 + “ ” + a1);  but read and print 300 numbers in reverse?!?! int[] a = new int[300]; for (int i = 0; i < a.length; i++) { a[i] = kbd.nextInt(); } for (int i = a.length – 1; i >= 0; i--) { Sop(a[i] + “ ”); } »well that was pretty easy, too!

Remember Values for Later Use // read and sum the numbers double[] temps = new double[7]; double sum = 0.0; S.o.p(“Enter ” + temps.length + “ daily highs.”); for (int i = 0; i < NUM_ITEMS; i++) { temps[i] = kbd.nextDouble(); // read the # temps[i] = kbd.nextDouble(); // read the # sum += num[i]; // add it to sum sum += num[i]; // add it to sum} kbd.nextLine(); // tidy up input stream // calculate the average double ave = sum / temps.length; // print the difference from the average of each for (int i = 0; i < temps.length; i++) { S.o.p((num[i] – ave)); S.o.p((num[i] – ave));} WeeklyTemps.java

Exercise n Create a program fragment to read in six grades, then print them in a table and show the average:  labels and grades separated by tabs  lines end after the labels/numbers are printed »so where does the System.out.println() go? A1 A2 A3 A4 A5 A Your average: 75.0

To Be Continued… n Chapters 5 and 6  Methods  Objects