Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Similar documents
Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Basics of Java Programming variables, assignment, and input

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Java I/O and Control Structures

Java I/O and Control Structures Algorithms in everyday life

2: Basics of Java Programming

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

Algorithms and Conditionals

CSC 1051 Data Structures and Algorithms I

Lecture 3: Variables and assignment

CSC 1051 Data Structures and Algorithms I

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

CSC 1051 Data Structures and Algorithms I

ECE 122 Engineering Problem Solving with Java

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Selection Statements and operators

Selection and Repetition Revisited

Chapter. Let's explore some other fundamental programming concepts

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Selection and Repetition

Selection Statements and operators

Selection and Repetition Revisited

H212 Introduction to Software Systems Honors

Data Conversion & Scanner Class

Programming with Java

Iterators and File Input

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Conditional Statements

Selection and Repetition

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Computational Expression

COMP 202 Java in one week

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Object Oriented Programming. Java-Lecture 1

Elementary Programming

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Introduction to Arrays

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Chapter 2: Data and Expressions

Full file at

Chapter 2: Data and Expressions

COMP 202. Java in one week

JAVA OPERATORS GENERAL

Fundamentals of Programming Data Types & Methods

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Chapter 2 ELEMENTARY PROGRAMMING

AP Computer Science A

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Chapter 3. Selections

4 WORKING WITH DATA TYPES AND OPERATIONS

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

CMSC131. Introduction to your Introduction to Java. Why Java?

CS111: PROGRAMMING LANGUAGE II

A variable is a name for a location in memory A variable must be declared

Introduction to Computer Programming

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Operators in java Operator operands.

CEN 414 Java Programming

Mr. Monroe s Guide to Mastering Java Syntax

COMP Primitive and Class Types. Yi Hong May 14, 2015

Chapter 2 Elementary Programming

File I/O and Exceptions

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Chapter 2. Elementary Programming

Data Representation Classes, and the Java API

Using Classes and Objects

Basic Computation. Chapter 2

CS313D: ADVANCED PROGRAMMING LANGUAGE

Basics of Java Programming

Building Java Programs

Information Science 1

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Introduction to Software Development (ISD) David Weston and Igor Razgon

Building Java Programs

Program Fundamentals

Oct Decision Structures cont d

AP Computer Science Unit 1. Writing Programs Using BlueJ

Important Java terminology

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Building Java Programs Chapter 2

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

MODULE 02: BASIC COMPUTATION IN JAVA

Transcription:

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying: Java Software Solutions by Lewis & Loftus Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne

Algorithms in everyday life Source: http://xkcd.com/627/

Algorithms An algorithm is a specific set of instructions for carrying out a procedure or solving a problem, usually with the requirement that the procedure terminate at some point. Specific algorithms sometimes also go by the name method, procedure, or technique. The word "algorithm" is a distortion of al-khwārizmī [named after Muhammad ibn al-khwārizmī], a Persian mathematician who wrote an influential treatise about algebraic methods. Sources: http://mathworld.wolfram.com/algorithm.html and Wikipedia ( http://en.wikipedia.org/wiki/mu%e1%b8%a5ammad_ibn_m%c5%abs%c4%81_al-khw%c4%81rizm%c4%ab )

Algorithm Example: Input-Compute-Output pattern GPA problem: Write a program that computes and outputs the GPA, given the credits and quality points earned. Pseudocode: describe steps in simple, unambiguous language Variables: qp, credits, gpa Algorithm: 1. qp = input from user 2. credits = input from user 3. gpa = qp / credits 4. Print gpa

Java Program è //************************************************ // GPA.java Author: Joyce/Papalaskari // Demonstrates the use of Scanner. ************************************************** import java.util.scanner; Algorithm è Variables: qp, credits, gpa Algorithm: 1. qp = input from user 2. credits = input from user 3. gpa = qp / credits 4. Print gpa public class GPA { public static void main (String[] args) //--------------------------------------------- // Inputs quality points and credits and calcu //--------------------------------------------- { double qp, credits, gpa; Scanner scan = new Scanner(System.in); // input qp System.out.print ("Enter Quality Points > ") qp = scan.nextint(); // input credits System.out.print ("Enter Credits > "); credits = scan.nextint(); // calculate GPA gpa = qp / credits; Next: A closer look at variables & input in Java } } // print GPA System.out.println ("\n\tgpa: " + gpa);

Interactive Programs Input/Output Programs can use data obtained during runtime, eg: int age; String name; Scanner scan = new Scanner(System.in); output method System.out.print( Enter your name ); name = scan.next(); input method System.out.print( Enter your age ); age = scan.nextint(); );

Interactive Programs Input/Output In Java, you first need to create a Scanner object int age; String name; Scanner object Scanner scan = new Scanner(System.in); System.out.print( Enter your name ); name = scan.next(); input method (for String) System.out.print( Enter your age ); age = scan.nextint(); input method (for int)

Interactive Programs Input/Output The Scanner class is part of the java.util class library, and must be imported into a program in order to be used The import statement goes at beginning of your program (above class definition) import java.util.scanner; public class GPA { public static void main (Stri //---------------------------

Interactive Programs Input/Output Summary: 1. import the Scanner class, i.e., add this before the class definition of your program: import java.util.scanner; 2. In your main method, before doing any input, declare and initialize the Scanner object Scanner scan = new Scanner(System.in); 3. Input away! System.out.print( Enter your name ); name = scan.next(); System.out.print( Enter your age ); age = scan.nextint();string

Interactive Programs Input/Output import java.util.scanner; Example public class TellMeAboutYou { public static void main(string[] args) { int age; String name; Scanner scan = new Scanner(System.in); System.out.print("Enter your name"); name = scan.next(); System.out.print("Enter your age"); age = scan.nextint(); Enter your name: Fiona Enter your age: 17 Pleased to meet you, Fiona! System.out.println("Pleased to meet you, " + name + "!"); } } name = scan.nextline(); Inspired by: http://www.onlineconversion.com/dogyears.htm

Scanner methods nextint() à input an int nextdouble() à input a double nextline() à input a String (until end of line) next() à input a String token (one word or other delimited chunk of text) White space (space, tab, new line) are used to separate input tokens

Variables & Assignment OVERVIEW Variable. A name that refers to a value of declared type. Literal. Programming language representation of a value. Assignment statement. Associates a value with a variable. type variable int age; declaration statement age = 18; assignment statement double x = 3.2, y = -0.80; literal combined declaration and assignment statement final int INCHES_PER_FOOT = 12; constant declaration (always initializes value) String name = scan.nextline(); input from user

Variable Declaration A variable is a name for a location of data in memory A variable must be declared by specifying the variable's name and the type of information that it will hold data type variable name int age; double x, y; String name;

Some types of data in Java type set of values literal values operations char String characters sequences of characters 'A' '@' "Hello World" jackie123" compare concatenate int integers 17 12345 add, subtract, multiply, divide,mod double floating-point numbers 3.1415 6.022e23 add, subtract, multiply, divide boolean truth values true false and, or, not

Assignment Statement Changes the value of a variable The assignment operator is the = sign total = 55 - discount; The expression on the right is evaluated and the result is stored in the variable on the left

Combined declaration and assignment A variable can be given an initial value in the declaration int age = 18; double x = 3.2, y = -0.80; String name = scan.nextline();

Combined declaration and assignment A variable can be given an initial value in the declaration - a new value can be assigned later: int age = 18; double x = 3.2, y = -0.80; String name = scan.nextline(); age = 19; x = x + 0.5; name = scan.nextline();

Combined declaration and assignment Note: CANNOT declare twice A variable can be given an initial value in the declaration - a new value can be assigned later: int age = 18; double x = 3.2, y = -0.80; String name = scan.nextline(); int age = 19; Error: declaring variable age again

Tracing the values of variables after each statement. age int age = 18; double x; String name = "Sherlock"; age = 19; x = 0.5; x = x + 0.2; name = name + "Holmes"; 18 19 x? 0.5 0.7 name Sherlock SherlockHolmes

Trace: TRY THIS: int a, b; a = 3; b = 4; int c = a; a = b; b = 5; b = c; Final values: a b c

Assignment operator Assignment ( = ) copies the value of the right side into the memory location associated with the left side It does not set up an ongoing equivalence int davesage = 21; int suesage = davesage; davesage = 22; System.out.println (davesage); // prints 22 System.out.println (suesage); // prints 21

CONSTANTS: like variables, but value cannot change declare using final modifier: final int INCHES_PER_FOOT = 12; final double LBS_PER_KG = 2.2; Convention: Use UPPER_CASE identifiers

Variables & Assignment SUMMARY Variable. A name that refers to a value of declared type. Literal. Programming language representation of a value. Assignment statement. Associates a value with a variable. type variable int age; declaration statement age = 18; assignment statement double x = 3.2, y = -0.80; literal combined declaration and assignment statement final int INCHES_PER_FOOT = 12; constant declaration (always initializes value) String name = scan.nextline(); input from user

Arithmetic Operators Addition Subtraction Multiplication Division Remainder + - * / % If either or both operands used by an arithmetic operator are floating point (e.g., type double), then the result is a floating point

Example int feet = 25; int inches = feet * INCHES_PER_FOOT; int seconds = 143; int minutes = seconds / 60; int remainingseconds = seconds % 60;

Division and Remainder If both operands are integers (e.g., type int), the division result is an integer (the fractional part is discarded): Integer Division: Remainder: 14 / 3 143 / 60 20 / 16 8 / 12 14 % 3 143 % 60 20 % 16 8 % 12

Operator Precedence example: result = total + count / max offset; What is the order of evaluation of sub-expressions? 1. Multiplication, division, remainder 2. addition, subtraction, string concatenation Operators with the same precedence: left àright Use parentheses to override default order more examples: a + b + c + d + e a / (b + c) - d % e a b / c + d * e a / (b * (c + (d - e)))

Increment and Decrement The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand The statement count++; is functionally equivalent to count = count + 1;

Review Java Program è //************************************************ // GPA.java Author: Joyce/Papalaskari // Demonstrates the use of Scanner. ************************************************** import java.util.scanner; Algorithm è Variables: qp, credits, gpa Algorithm: 1. qp = input from user 2. credits = input from user 3. gpa = qp / credits 4. Print gpa public class GPA { public static void main (String[] args) //--------------------------------------------- // Inputs quality points and credits and calcu //--------------------------------------------- { double qp, credits, gpa; Scanner scan = new Scanner(System.in); // input qp System.out.print ("Enter Quality Points > ") qp = scan.nextint(); // input credits System.out.print ("Enter Credits > "); credits = scan.nextint(); // calculate GPA gpa = qp / credits; } } // print GPA System.out.println ("\n\tgpa: " + gpa);

Writing an algorithm in pseudocode List the variables used. List the steps for solving the problem, in order. Try to be brief and unambiguous; use Java expressions only when it is simpler to specify a step in java than in English. Variables: qp, credits, gpa Algorithm: 1. qp = input from user 2. credits = input from user 3. gpa = qp / credits 4. Print gpa

Example Write an algorithm to solve the following problem: Input values representing a time duration in hours, minutes, and seconds and then calculate and output the equivalent total number of seconds.

Example Write an algorithm to solve the following problem: Input a value representing a number of seconds, then calculate and output the equivalent amount of time as a combination of hours, minutes, and seconds.