Introduction to Computer Programming Pre-AP Computer Science, Cycle 5

Preview:

Citation preview

Introduction to Computer ProgrammingPre-AP Computer Science, Cycle 5

Language of a Computer

• Computers are electronic devices; they work by

sending electronic signals

• Electronic signals represent information in binary,

using 0’s and 1’s

• This binary language is called machine language

• A single 0 or 1 is called a bit of data• Bit = binary digit

• A sequence of 0’s and 1’s is called binary code

Bytes?

• A sequence of 8 bits = 1 byte

10011101

• Kilobyte (KB) 1024 bytes• Megabyte (MB) 1024 KB• Gigabyte (GB) 1024 MB• Terabyte (TB) 1024 GB• Petabyte (PB) 1024 TB

BIT BYTE

Binary into Letters

• Binary code is translated into numbers, letters, and punctuation • Most common system: ASCII• American Standard Code for Information Interchange• 7 bits, or 128 different characters• ‘A’ 1000001

• Another common system: Unicode• 16 bits, or 65,536 different characters• Useful for languages other than English

• ‘A’ 0000000001000001

Evolution of Programming Languages

wages = rate * hours• Machine Code

100100 010001100110 010010 storage locations100010 010011 math operations

• Assembly LanguageLOAD rateMULT hoursSTOR wages

• High-level Language (C++, Java, Python, etc)wages = rate * hours;

Translating High-Level Languages to Machine Code

• Remember, computers only understand machine code

• Any other code must be translated back to machine code in order for the computer to execute the program

Translating to Machine Code

Editor • Where you write the code

Compiler• Checks the code for errors• Performs the translation process

Bytecode • Machine language

LoaderInterpreter

• Execute the code

Java Compiler and IDE• Compiler (JDK 7)• http://www.oracle.com/technetwork/java/javase/dow

nloads/jdk7-downloads-1880260.html• Accept the license agreement• Download Java SE Development Kit 7u51 for Windows

x64 (last one in the first table)

• IDE/Editor (jGRASP)• http://spider.eng.auburn.edu/user-cgi/grasp/grasp.pl?;

dl=download_jgrasp.html• Scroll down, then download/install jGRASP 2.0.0_07

for Windows

Test your Compiler

public class MyFirstJavaProgram{

public static void main(String[] args){

System.out.println(“Hello world!”);

}}

• Run the code by clicking on the red running man

Warm-up: February 18th

• Why do you need to translate high-level programming languages into machine language?

• Why would you prefer to write a program in a high-level programming language rather than a machine language?

Programming is Problem SolvingPAP Computer Science, Cycle 5

Programming is Problem Solving• Most computer programs set out to solve a problem

• Programming well requires good problem-solving skills

• Problem-solving skills can be developed through various techniques

Algorithm Development

1. Analyze the problem• Really understand what it’s asking for

2. Outline the project requirements• What information do I need to bring in?• What information needs to be stored?• What information needs to be outputted?

3. Design your algorithm 4. Implement the algorithm5. Verify the algorithm (test it)6. Maintain and improve program

Algorithm: Perimeter and Area of a RectangleFormulas: perimeter = 2*(length+width)

area = length * width

1. Get the length of the rectangle2. Get the width of the rectangle3. Find the perimeter using the perimeter equation4. Find the area using the area equation5. Output the length, width, perimeter, and area of

the rectangle

Computers are stupid! • They only do EXACTLY what you tell them to do

• They take NO information for granted

• They do not make assumptions

• They do not automatically fill in gaps in instructions

• They do not stop unless told to do so

• EVERY step must be outlined for them

Demonstration: Robot Ms. Alexander

• Take out a sheet of paper

• On the paper, write the steps necessary for Ms. Alexander to walk from the door to her chair and sit down

• Robot Ms. Alexander only knows how to take steps, bend her knees, and turn

Algorithm: Number-Guessing Game

• The computer picks a randomly generate number between 1 and 100• The user tries to guess the number• If the user’s guess is smaller than the number, the

computer says “too small, guess again”• If the user’s guess is larger than the number, the

computer says “too large, guess again”• The process repeats until the user guesses the

correct number

Algorithm: Number-Guessing Game1. Generate a random number2. Save the random number in a variable called num3. Repeat the following steps until the player has

guessed the correct number:a. Prompt the user to enter a guessb. If guess = num, print “correct!”c. Otherwise, if guess < num, print “Too small!

Guess again!”d. Otherwise, if guess > num, print “Too large!

Guess again!”

Structured Programming

• Divide larger, more complex programming problems into smaller, more manageable problems

• Write code to solve the smaller problems, then use those answers to solve the large problem

• Also called top-down design, bottom-up design, stepwise refinement, and modular design

Example: Programming a TV RemoteProblem: We want to control a TV using a remote with

many different buttons

Number keys code

Volume keys code

Channel keys code

Object-Oriented Programming

• Analyze a problem to determine what the major components are, and create objects to represent these components

• Determine how these objects should be characterized, and how they should interact with each other

• Each object is given characteristics (properties)• Each object is given abilities (methods)

Example: Video Game Rentals

• Two main objects: video game and the customer

• Video game object• Data: title, genre, rating, # in stock, price• Operations: be scanned, inc/dec stock as copies are

rented/returned, be shelved• Customer object• Data: age, gender, renting history• Operations: rent a game, return a game, browse,

search by…

Structured vs OOP• Structured• Better for mathematical functions• Better for simple, single-step, or few-step problems

• Object-Oriented• Better for more complicated problems• Better for problems that use large amounts of related

information

• C, COBOL, FORTRAN, BASIC structured programming languages• C++, Java, Ruby, Python, Perl OOP programming

languages

Warm-up: February 19

• Develop an algorithm for the following problem:

Find the radius of a circle given the circle’s circumference.

Formula: circumference = 2*pi*radius

Warm-up: February 19

• Develop an algorithm for the following problem:

Find the radius of a circle given the circle’s circumference.

Formula: circumference = 2*pi*radius

1. Input the circumference and save in a variable2. Calculate radius by dividing the circumference by

(2*3.141)3. Output the radius

Basic Elements of a Java ProgramPAP Computer Science, Cycle 5

Example Code//*****************************************// Author: Rachel Alexander Date: 2/19/14// This code displays three lines of text//*****************************************

public class ASimpleJavaProgram{ public static void main(String[] args) { System.out.println(“Happy Wednesday!”); System.out.println(“Sum of 2 and 3 = “ + 5); System.out.println(“7 + 8 = “ + (7+8)); }}

Comments//*****************************************// Author: Rachel Alexander Date: 2/19/14// This code displays three lines of text//*****************************************

public class ASimpleJavaProgram{ public static void main(String[] args) { System.out.println(“Happy Wednesday!”); System.out.println(“Sum of 2 and 3 = “ + 5); System.out.println(“7 + 8 = “ + (7+8)); }}

Comments• It’s good programming practice to begin each code you write

with a comment listing the author of the program, the data last modified, and a short description of what the code does

• You should also comment key statements in a program

• Single line comments://This is a comment

• Multi-line comments:/* This comment can span many lines. */

Classes//*****************************************// Author: Rachel Alexander Date: 2/19/14// This code displays three lines of text//*****************************************

public class ASimpleJavaProgram{ public static void main(String[] args) { System.out.println(“Happy Wednesday!”); System.out.println(“Sum of 2 and 3 = “ + 5); System.out.println(“7 + 8 = “ + (7+8)); }}

Classes

• Classes are how we create objects in Java• Recall, Java is an object-oriented programming

language

• Each code we write must exist inside of a class

• This class we named ASimpleJavaProgram

• Public vs private classes will be discussed later

Methods//*****************************************// Author: Rachel Alexander Date: 2/19/14// This code displays three lines of text//*****************************************

public class ASimpleJavaProgram{ public static void main(String[] args) { System.out.println(“Happy Wednesday!”); System.out.println(“Sum of 2 and 3 = “ + 5); System.out.println(“7 + 8 = “ + (7+8)); }}

Methods

• Code within classes must be written inside of a method

• Methods are what cause actions to be performed in our Java code

• Each class can only have one “main” method, but unlimited amounts of other named methods

Example Code//*****************************************// Author: Rachel Alexander Date: 2/19/14// This code displays three lines of text//*****************************************

public class ASimpleJavaProgram{ public static void main(String[] args) { System.out.println(“Happy Wednesday!”); System.out.println(“Sum of 2 and 3 = “ + 5); System.out.println(“7 + 8 = “ + (7+8)); }}

Output

• System.out.println( ) is used to output information to the user

• You can output text, variables, lists, or even math

Example: System.out.println(“Happy Wednesday!”);

Happy Wednesday!

Output• You can output mutiple types of expressions in one line by

combining them with the ‘+’ operator

Example:System.out.println(“The sum of 2 and 3 = “ + 5 );

The sum of 2 and 3 = 5

Example:System.out.println(“7 + 8 = “ + (7 + 8));

7 + 8 = 15

Your Turn!Write a program that produces the following output:

******************************* Programming Assignment 1 ** PAP Computer Science ** Author: YOUR NAME ** Date: February 19, 2014 *******************************

CODE TEMPLATE:public class ASimpleJavaProgram{ public static void main(String[] args) { System.out.println(“TEXT GOES HERE”); }}

Warm-up: Thursday, Feb 20

• Name one way in which commenting code can be helpful.

• What is the command for generating output?

Warm-up: Thursday, Feb 20

• Name one way in which commenting code can be helpful.• Notes/reminders to yourself and others• Declare the author of the code/date last modified• Explain key lines of code

• What is the command for generating output? • System.out.println( )

Warm-Up: Friday, Feb 21

• Correct the 6 errors in the following code:

public CLASS warmup{ public static void main(String[] args) {

System.Out.PrintIN(“Hello!) }}

Warm-Up: Friday, Feb 21

• Correct the 6 errors in the following code:

public class warmup{ public static void main(String[] args) {

System.out.println(“Hello!”); }}

Advanced OutputPre-AP Computer Science, Cycle 5

Recall…

• Output is performed using the System.out.println() command

• Example:System.out.println(“Hello world!”);

• However, this is not the only command for output

Output Expressions

• System.out.println( )• Outputs onto a new line

• System.out.print( )• Outputs on the same line

• System.out.printf( )• Outputs with special formatting rules

Println vs Print

System.out.println(“Hello”);System.out.println(“there.”);

Hellothere.

System.out.print(“Hello”);System.out.print(“there.”);

Hello there.

Outputting Different Data Types

• Strings are enclosed in double quotes.• System.out.println(“Hello!”);

• Characters are enclosed in single quotes• System.out.println(‘A’);

• Numbers/variables are not enclosed in quotes• System.out.println(7);• System.out.println(4 + 12);• System.out.println(answer);

White Spaces

• Typically, Java ignores “white spaces”• Spaces• Enters• Tabs

• When outputting, some “white spacing” is allowed, while others are not allowed.

White SpacesSystem.out.print(“It’s sunny.”);System.out.println(“Let’s go outside.”);

It’s sunny. Let’s go outside.

System.out.println(“It’s sunny.” +“Let’s go outside.”);

It’s sunny. Let’s go outside.

System.out.println(“It’s sunny.Let’s go outside.”);

ERROR MESSAGE

Escape Sequences

• Escape sequences are used to output typically reserved characters• Slashes• “Enters”• Quotations• Tab

• Escape sequences always begin with a forward slash (\)• This is found ABOVE THE ENTER KEY

Common Escape SequencesEscape Sequence Description

\n Newline Cursor moves to beginning of next line

\t Tab Cursor moves to the next tab stop\b Backspace Cursor moves one space to the left\r Return Cursor moves to the beginning of the

current line (not to the next line)\\ Backslash Backslash is printed\’ Single quotation Single quotation mark is printed\” Double quotation Double quotation mark is printed

Escape Sequence Examples

• System.out.println(“Hello \nthere.”);Hellothere.

• System.out.println(“Strings are \”in quotes\”.”);Strings are “in quotes”.

• System.out.print(“\tThis is tabbed. \nThis is not.”);This is tabbed.

This is not.

Recommended