Procedural programming in Java

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
PAC Introduction to Methods Professor: Evan Korth New York University.
Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
Introduction to Computers and Programming Introduction to Methods in Java.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Math class methods & User defined methods Math class methods Math.sqrt(4.0) Math.random() java.lang is the library/package that provides Math class methods.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
CS 201 Functions Debzani Deb.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Review for Midterm 2 Nested loops & Math class methods & User defined methods.
Introduction to Computers and Programming Lecture 13: User defined methods Instructor: Evan Korth New York University.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
 2003 Prentice Hall, Inc. All rights reserved Introduction Modules –Small pieces of a problem e.g., divide and conquer –Facilitate design, implementation,
Introduction to Methods
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Introduction to Computers and Programming Lecture 14: User defined methods (cont) Professor: Evan Korth New York University.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Procedural programming in Java Methods, parameters and return values.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 15,16 Java’s Methods.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 : Top Down Design with Functions By Suraya Alias.
By Mr. Muhammad Pervez Akhtar
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Programming Fundamentals Enumerations and Functions.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Dale Roberts CSCI N305 Functions Declarations Department of Computer and Information Science, School of Science, IUPUI.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 7 User-Defined Methods.
Chapter 6: User-Defined Functions I
Programming Fundamentals Lecture #7 Functions
Introduction to Methods
Functions.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Functions Declarations CSCI 230
Chapter 6 Methods: A Deeper Look
Chapter 6: User-Defined Functions I
Lesson #6 Modular Programming and Functions.
CPS125.
Presentation transcript:

Procedural programming in Java

Procedural programming in Java A simple programming problem Problem definition A program is required which will take a string as a command line argument of any length and determine if the string represents a palindrome - i.e. a word which reads the same backwards as forwards. If the word is a palindrome, a message :- <command line argument> is a palindrome should be displayed. If not, the message should be :- <command line argument> is not a palindrome If the number of command line arguments is not equal to 1 an error message should be displayed.

Procedural programming in Java A simple programming problem Program design word : string * represents command line argument length : integer *represents length of word if there is one command line argument then set word = command line argument set length = length of word for all characters at pos in the first half of the word if char at pos not equal to char at length-pos then exit for end if end for if premature exit from loop then display not a palindrome else display palindrome display error message

Procedural programming in Java A simple programming problem Program code public class Palindrome { public static void main(String [] args) { String word; int length, pos = 0; if ( args.length == 1 ) { word = args[0]; length = word.length(); while ( pos <= length / 2) { if ( word.charAt(pos) != word.charAt(length - 1 - pos)) break; pos++; } //end while if ( pos > length / 2 ) System.out.println(word + “ is a palindrome”); else System.out.println(word + “ is not a palindrome”); } else System.err.println(“One command line argument only”); } //end main } //end class Palindrome

Procedural Programming in Java The square root algorithm The square root of a number can be calculated by taking a series of estimates. Each successive estimate is derived from the previous using the following formula :- new estimate = average of (old estimate + value/old estimate) This can be expressed as pseudo-code as follows :- value : integer *value who’s square root is required e1 : real *first estimate e2 : real *next estimate e2 = value / 2 *a crude way to start off with a first guess do set e1 to e2 set e2 to (e1 + value/e1)/2 while positive difference between e1 and e2 > accuracy required Note : In order to repeat the loop, the new estimate must become the old one next time round. Hence the need for - set e1 to e2

Procedural Programming in Java public class SquareRoot { public static void main(String [] args) { int value; double e1, e2; value = Integer.parseInt(args[0]); if (value > 0){ //now we can calculate square root e2 = value / 2; do { e1 = e2; e2 = (e1 + value / e1) / 2;} while (Math.abs(e1 - e2) > 0.0001); System.out.println("Square root = " + e2); } else System.err.println("Only positive arguments allowed"); } //end main } //end class SquareRoot Implementation of square-root program

Procedural Programming in Java Sub-programs in Java It is not desirable or practicable to place all code in one main program. As programs become larger and perhaps more people are working on them simultaneously, it is necessary to subdivide the code into sub-programs. These are called - subroutines (FORTRAN), procedures (PASCAL), functions (C) or methods (Java), but all refer to sub-programs. Use of methods allow you to :- Subdivide a large program into smaller pieces - easier to understand. Allow several people to work on different parts of the program at once. Factor out commonly occurring pieces of code and write only once. Avoid repetition and hence changes only made in one place. Create sub-programs which can be re-used in other applications. Minimise the amount of re-compilation when changes are made.

Procedural Programming in Java Parameterless methods public class Rabbit { public static void main(String [] args) { chatter(); //all methods must have a parameter chatter(); //list () even if it is empty chatter(); } //end main public static void chatter(){ System.out.println(“Hello and welcome to Java”); } //end chatter } //end class Rabbit Here, the method chatter() needs no additional information to do its job. Hence, nothing is passed to it as parameters and nothing is returned.

Procedural Programming in Java Method with parameters In this version of chatter(), the method needs to be told how often to repeat the message - the int repeat in the method header is a formal parameter, the 2 * x and the 5 in the method calls are actual parameters. public class Rabbit { public static void main(String [] args) { int x = 10; chatter(2 * x); //here an actual value (parameter) is passed chatter(5); //to tell the method how often to loop } //end main public static void chatter(int repeat){ for (int i = 0; i < repeat; i++) System.out.println(“Hello and welcome to Java”); } //end chatter } //end class Rabbit

Procedural Programming in Java Method with parameters Here, chatter() needs to be told what to say and how often. Formal parameters consist of lists of data type followed by name - int repeat, String message Actual parameters consist of a corresponding set of values - 5 , args[0] public class Rabbit { public static void main(String [] args) { int x = 10; chatter(x % 3, “Hello there”); //must send both repeat chatter(5, args[0]); //amount and message string } //end main public static void chatter(int repeat, String message){ for (int i = 0; i < repeat; i++) System.out.println(message); } //end chatter } //end class Rabbit

Procedural Programming in Java Method which return results Here, chatter() needs to be told what to say and how often. Formal parameters consist of lists of data type followed by name - int repeat, String message Actual parameters consist of a corresponding set of values - 5 , args[0] public class Rabbit { public static void main(String [] args) { int val = Integer.parseInt(args[0]); System.out.println(“Square root = “ + squareRoot(val)); } //end main public static double squareRoot(int value) { double e1, e2 = value / 2; //local variables known only to method do { e1 = e2; e2 = ( e1 + value / e1 ) / 2;} while (Math.abs(e1 - e2) > 1.0e-5); //use of scientific notation return e2; //result returned to calling program } //end squareRoot } //end class Rabbit

Important concept #1 Divide and Conquer: Break large programs into a series of smaller modules Helps manage complexity Makes it easier to build large programs Makes it easier to debug programs

Important concept #2 Abstraction: Most of the time, you need to know what a method does, but not how it actually does it. Also helps manage complexity You use other people’s code without knowing how it does it’s job.

Methods Declarations Methods Allow programmers to modularize programs Makes program development more manageable Software reusability Avoid repeating code Local variables Declared in method declaration Parameters Communicates information between methods via method calls

Method Declarations (cont.) General format of method declaration: modifiers return-value-type method-name( parameter1, …, parameterN ) { declarations and statements } Method can also return values: return expression;

As with variables naming methods is important Naming your methods As with variables naming methods is important You should give your methods names which clearly describe what the function is doing helps debugging helps others read your code Same rules as naming variables E.g. public static float calculateTax( int sale ) When you write about a method in an explanation use the parenthesis to indicate you are referencing a method (as opposed to a regular variable): E.g. //call squareInteger() to calculate the square

Good programming with methods A method should do one and only one useful action If you see names for your method that suggest multiple actions then it’s time to break it up into separate functions; for example, calculateTaxAndPrintReturnAndSaveFile(); -ugh If you do something more than once in a program, you should write a method for that action.

More Good Programming If you have written a method to do something in one project, and you need to do the same action in another project, you should reuse the method. In Java this is usually accomplished by using classes which we will not cover this semester.