Top-down programming design

Similar documents
Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Lecture 5: Methods CS2301

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Chapter 6 Methods. Dr. Hikmat Jaber

CS115 Principles of Computer Science

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Iteration statements - Loops

Passing Array to Methods

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Methods. Eng. Mohammed Abdualal

Methods. CSE 114, Computer Science 1 Stony Brook University

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CS1150 Principles of Computer Science Methods

Important Java terminology

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Lecture #6-7 Methods

Loops and Expression Types

CS1150 Principles of Computer Science Arrays

CS-201 Introduction to Programming with Java

Loops. CSE 114, Computer Science 1 Stony Brook University

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

CS110: PROGRAMMING LANGUAGE I

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

AP CS Unit 3: Control Structures Notes

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

Chapter 7 User-Defined Methods. Chapter Objectives

Module 7: Arrays (Single Dimensional)

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Opening Problem EXAMPLE. 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average.

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods / Functions

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved

STUDENT LESSON A12 Iterations

Java-Array. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

JAVA Programming Concepts

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Chapter 3. Selections

CS171:Introduction to Computer Science II

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Repetition, Looping. While Loop

Loops. GEEN163 Introduction to Computer Programming

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

AP COMPUTER SCIENCE A

Question: Total Points: Score:

CMPT 125: Lecture 4 Conditionals and Loops

CS1150 Principles of Computer Science Methods

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Advanced Computer Programming

CONDITIONAL EXECUTION

Data Structure and Programming Languages

Problems with simple variables

Computer Science is...

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

CS115 Principles of Computer Science

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

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

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

Java Programming for Selenium

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

University of Palestine. Mid Exam Total Grade: 100

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Chapter 4: Control Structures I

Place your name tag here

Object-Oriented Programming

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Term 1 Unit 1 Week 1 Worksheet: Output Solution

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

Oct Decision Structures cont d

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Example: Monte Carlo Simulation 1

Section 004 Spring CS 170 Exam 1. Name (print): Instructions:

Spring 2010 Java Programming

CS Computers & Programming I Review_01 Dr. H. Assadipour

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

M e t h o d s a n d P a r a m e t e r s

( &% class MyClass { }

Advanced if/else & Cumulative Sum

Introduction to Computer Science Unit 2. Notes

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Programming with Java

Transcription:

1

Top-down programming design Top-down design is a programming style, the mainstay of traditional procedural languages, in which design begins by specifying complex pieces and then dividing them into successively smaller pieces. Top-down design starts with an description of the overall system and usually consists of a hierarchical structure which contains more detailed descriptions of the system at each lower level. This method involves a hierarchical or tree-like structure for a system as illustrated by the following diagram: 2

Top-down programming design The technique for writing a program using top-down design is to write a main program (main method) that calls all the other methods it will need. If you have a big problem to solve, then a very effective method of working towards a solution is to break it down into smaller, more manageable problems. You can invoke the same method repeatedly. In fact, it is quite common and useful to do so. Methods can simplify a program by hiding a complex computation behind a single command. 3

Structured programming The use of methods will be our first step in the direction of structured. ( התכנות המבני ( programming Structured programming associated with a top-down approach to design where an overview of the system is first formulated, specifying but not detailing any first-level subsystems. Each subsystem is then refined in yet greater detail until the entire specification is reduced to base elements. 4

Methods - opening problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45 respectively. int sum = 0; for (int i = 1; i <= 10; i++) sum + = i; System.out.println("Sum from 1 to 10 is " + sum); int sum = 0; for (int i = 20; i <= 30; i++) sum + = i; System.out.println("Sum from 20 to 30 is " + sum); int sum = 0; for (int i = 35; i <= 45; i++) sum + = i; System.out.println("Sum from 35 to 45 is " + sum); 5

) שימוש חוזר ( reuse Cod Code reuse, also called software reuse, is the use of existing program code, or software knowledge, to build new software ( program code ). The reuse of programming code is a common technique which attempts to save time and energy by reducing redundant work. Reusable components are simply pre-built pieces of programming code designed to perform a specific function. Programmers have always reused sections of code, methods, functions, and procedures. The Java Math library is a good example of code reuse. One of the most compelling features about Java is code reuse.

Solution Method ( public static int sum(int i1, int i2) int sum = 0; for ( int i = i1; i <= i2; i++) sum += i; return sum; } // sum public static void main(string[ ] args) System.out.println("Sum from 1 to 10 is " + sum(1, 10)); System.out.println("Sum from 20 to 30 is " + sum(20, 30)); System.out.println("Sum from 35 to 45 is " + sum(35, 45)); } // main ) פעולה / שיטה Methods are time savers, in that they allow for the repetition of sections of code without retyping the code. Think of a method as a subprogram that acts on data and often returns a value. In certain other languages (C,Pascal,VB) methods are referred to as procedures and functions.

What are Methods? Each method has its own name. When that name is encountered in a program, the execution of the program branches to the body of that method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code. methods can be saved and utilized again and again in newly developed programs. The use of methods will be our first step in the direction of structured programming. 8

Defining Methods Modifiers: The modifier, which is optional, tells the compiler how to call the ) סוג גישה method.( method. This defines the access type of the Return Type: A method may return a value. The returnvaluetype is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnvaluetype is the keyword void. Method Name: This is the actual name of the method. The method name and the.(חתימה ( signature parameter list together constitute the method Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. Method Body: The method body contains a collection of statements that define what the method does. 9

Defining Methods In general, a method has the following syntax: modifier returnvaluetype methodname (list of parameters) Method body } method header method body modifier public static int max(int num1, int num2) int result; Define a method return value type if (num1 > num2) result = num1; else result = num2; method name formal parameters parameter list method signature Invoke a method int z = max(x, y); actual parameters (arguments) } return result; return value 10

Return Value Type A method may return a value. The returnvaluetype is the data type of the value the method returns. If the method does not return a value, the returnvaluetype is the keyword void. method header method body modifier public static int max(int num1, int num2) int result; Define a method return Return value value type type int if (num1 > num2) result = num1; else result = num2; method name formal parameters parameter list method signature Invoke a method int z = max(x, y); actual parameters (arguments) } return result; return value 11

Example 1 - defining method modifier Return value type Method name Variables defined in the method header are known as formal parameters. static double avg3(int a, int b, int c) // calculation average of 3 integers double ag = (double)(a+b+c)/3; return ag; } Returned value Method header Method body This method takes three parameters : a,b and c and returns their average ag. 12

Example 1 - calling a method int grade1,grade2,grade3 ; // student's grades double avgrade; // average grade System.out.println("Enter 3 grades "); grade1 = reader.nextint(); grade2 = reader.nextint(); grade3 = reader.nextint(); When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. avgrade = avg3(grade1,grade2,grade3); System.out.println( The avarage grade is : + avgrade); Choice 1 System.out.println( The avarage grade is : + avg3(grade1,grade2,grade3)); Choice2

Example 2 - defining method static boolean test(string str) boolean flag = true; // help variable int first = 0; // first letter int last = str.length( ) - 1; // last letter while (first<last && flag) //goes to the middle letter if (str.charat(first)!= str.charat(last)) else } } // while return flag; } // test flag = false; first++; last--; This method takes the string str as parameter and check it : If str is palindrome the method returns true, false otherwise. 14

Example 2 - calling a method public static void main(string[ ] args) int sum = 0; // number of palindromes for( int i = 0;i < 10;i++) } // for System.out.println("Enter the string : "); String s = reader.next(); if ( test(s) ) sum++; System.out.println("The number of palindromes is :" + sum); } // main Calling the method test. This main method reads 10 strings and finds the number of palindromes. 15

Example 3 - triangle area This program calculates triangle area using Heron's formula. public static double distance(double x1, double y1, double x2, double y2) return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } // distance public static double heron(double a, double b, double c) double p = (a+b+c)/2; return Math.sqrt(p*(p-a)*(p-b)*(p-c)); } // heron 16

Example 3 - calling a methods public static void main(string[ ] args) System.out.print("Input point 1 as x y: "); double x1 = reader.nextdouble(); double y1 = reader.nextdouble(); System.out.print("Input point 2 as x y: "); double x2 = reader.nextdouble(); double y2 = reader.nextdouble(); System.out.print("Input point 3 as x y: "); double x3 = reader.nextdouble(); double y3 = reader.nextdouble(); double a = distance(x1, y1, x2, y2); double b = distance(x1, y1, x3, y3); double c = distance(x3, y3, x2, y2); System.out.println("The area of the triangle is " + heron(a, b, c)); } // main Input point 1 as x y: 2 1 Input point 2 as x y: 3 7 Input point 3 as x y: 0 4 The area of the triangle is 7.5 17

VOID Methods There are two ways to call a method; the choice is based on whether the method returns a value or not. VOID type of method does not return any value. Example: This method prints values of two integers before and after swap. static void swap(int n1, int n2) System.out.println( \t Inside the swap method ); System.out.println( "\t\t Before swapping n1 is " + n1 + " n2 is " + n2); int temp = n1; // help variable n1 = n2; n2 = temp; System.out.println( "\t\t After swapping n1 is " + n1 + " n2 is " + n2); } // swap 18

Calling a void method A call to a void method must be a statement. This statement is like any Java statement terminated with a semicolon. static void printgrade(int score) if (score >= 90) System.out.println('A'); else if (score >= 80) System.out.println('B'); else System.out.println('C'); } // printgrade public static void main(string[ ] args) printgrade(78); // call a void method } //main This would produce following result: C 19

Calling a void method - example static void revintnum(int num) int reversnum = 0; do int lastdigit = num%10; reversnum = (reversnum*10 )+ lastdigit; num = num/10; } while (num > 0); System.out.println(" That reversed number is : "+reversnum); } // revintnum public static void main(string[ ] args) for( int i = 0 ;i < 10; i++ ) System.out.print ("Enter an integer "); int x = reader.nextint(); revintnum(x); // call a void method } // for } // main This program reads 10 integers, reverses its digits mathematically and prints it. 20

Nesting of methods public static void main(string[] args)... A( parameters).. } // main A method can call more than one method in the same class. If a method in Java calls a method in the same class it is called nesting of methods. First method can call the second method the second method can call a third method and so on. A( )... B (parameters)... C (parameters)... } // A method When a method is called,the flow of control transfers to that method. B( )... } // B method When the method is done, control returns to the location where the call was made (next Java statement). C( )... } // C method 21

Nesting of methods - example public class NestMethTest static void display(int x,int y) System.out.println( "Value of X= + x); System.out.println( "Value of Y= + y); } // display static void add2(int a,int b) a + = 2; b + = 2; display(a,b); // call display method } // add2 static Scanner reader = new Scanner(System.in); public static void main(string[] args) System.out.print( Enter first number-> ); int num1 = reader.nextint(); // 4 System.out.print( Enter second number-> ); int num2 = reader.nextint(); // 7 add2(num1,num2); } // main } // class NestMethTest Output will be displayed as: Enter first number -> 4 Enter second number -> 7 Value of X= 6 Value of Y= 9 22

Passing Parameters by Values When calling a method, you need to provide arguments, which must be given in the same order and in the same type as their respective parameters in the method specification. This is known as parameter order association. When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as pass-by-value. לפי ערך) The (העברה variable is not affected, regardless of the changes made to the parameter inside the method. For simplicity, Java programmers often say passing an argument x to a parameter y, which actually means passing the value of x to y. 23

Example - Passing Parameters by Values Following program section demonstrates the effect of passing by value. The swap method is invoked by passing two arguments. The values of the arguments are not changed after the method is invoked. int num1 = 1; A call to a void method must be a statement. int num2 = 2; System.out.println("Before swap method, num1 is " + num1 + " and num2 is " + num2); swap(num1, num2); System.out.println("After swap method, num1 is " + num1 + " and num2 is " + num2); Before swap method, num1 is 1 and num2 is 2 Inside the swap method Before swapping n1 is 1 n2 is 2 After swapping n1 is 2 n2 is 1 After swap method, num1 is 1 and num2 is 2 This would produce following result.

The Scope of Variables The scope הכרה) (טווח of a variable is the part of the program where the variable can be referenced. A variable defined inside.(משתנים מקומים ( variable a method is referred to as a local The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used. A parameter is actually a local variable. The scope of a method parameter covers the entire method. You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.

The Scope of Variables A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration to the end of the block that contains the variable as shown below: Note : you cannot declare a local variable with the same name twice in nested blocks. 26

Scope of Local Variables, cont. It is fine to declare i in two non-nesting blocks public static void method1() int x = 1; int y = 1; } for ((int i i = 1; i < 10; i++) x += i; } for ((int i i = 1; i < 10; i++) y += i; } It is wrong to declare i in two nesting blocks public static void method2() int int i = = 1 ; 1; int sum = 0; for ((int i i = 1; i < 10; i++) sum += i; } } 27

Passing Arrays to methods Copies of argument values are sent to the method, where the copy is manipulated and in certain cases, one value may be returned. While the copied values may change in the method, the original values in main method did not change. The situation, when working with arrays, is somewhat different. If we were to make copies of arrays to be sent to methods, we could potentially be copying very large amounts of data. Not very efficient! ) העברה לפי כתובתה ( passed-by-reference. Arrays are Passing-by-reference means that when an array is passed as an argument, its memory address location is actually passed, referred to as its "reference". In this way, the contents of an array can be changed inside of a method, since we are dealing directly with the actual array and not with a copy of the array. 28

Passing Arrays to methods public static void printarray(int[ ] array) for (int i = 0; i < array.length; i++) System.out.print(array[i] + " "); } Invoke the method printarry: int [ ] list = 3, 1, 2, 6, 4, 2 }; Choice 1 printarray(list); Choice 2 Invoke the method printarray printarray(new int [ ] 3, 1, 2, 6, 4, 2 }); Anonymous array 29

The statement Anonymous Array printarray( new int[ ] 3, 1, 2, 6, 4, 2 } ); creates an array using the following syntax: new datatype [ ] literal0, literal1,..., literalk } ; There is no explicit reference variable name for the array. Such array is called an anonymous array. 30

Example public static void main(string[ ] args) int x = 2; // x represents an int value int [ ] y = 89,20,37 }; // y represents an array of int values mex(x, y); // Invoke mex with actual arguments x and y System.out.println("x is : " + x); System.out.println("y[0] is : " + y[0]); } // main public static void mex(int number, int [ ] numbers) number = 100; // Assign a new value to formal parameter number numbers[0] = 55; // Assign a new value to numbers[0] } // mex To call a method that takes an array as argument, simply type the name of the array in the parentheses of the called method. This would produce x is : 2 y[0] is 55 y[0]

Returning an Array from a method Like a normal variable, an array can be returned from a method. This means that the method would return a variable (memory address) that carries various values. For example: The method reverse returns an array that is the reversal of another array: public static reverse(int [ ] list) int [ ] result = new int[ list.length ]; for ( int j = 0, int i = result.length - 1; i >= 0; i--, j++ ) return result ; } // reverse int [ ] When declaring the method, you must specify its data type. result[ j ] = list[ i ]; When the method ends, it would return an array represented by the name of its variable. 32

Example public static void main(string[ ] args) int [ ] a = 1,2,3,4,5 }; // a represents an array of int values printarr(a); // invoke method printarr with actual parameter a int [ ] b = reverse(a); // b array declaration and invoke method revers printarr(b); // invoke method printarr with actual parameter b } // main This would produce : 1 2 3 4 5 5 4 3 2 1 a 1 2 3 4 5 b 5 4 3 2 1 NOTE: Declaration of a reference to an integer array is not the same as declaring an array. A reference ( הפניה ) is simply a pointer to an array. 33

Last example Next program reads student s grades and calculates their average grades. If student s grade is less than the average grade, then program adds 5 points factor to this grade. The program prints all entered grades before and after upgrading. public static void main(string[ ] args) System.out.print( "Enter number of students : ); int num = reader.nextint(); // student s number input int [ ] arrgrades = inputgrades(num); // input student s grades printgrades(arrgrades); // print grades before update int avg = avggrades(arrgrades); // calculate average grade updgrades(arrgrades,avg); // update student s grades printgrades(arrgrades); // print grades after update } // main

Method inputgrades static int [ ] inputgrades(int n1) int grade; // student grade int [ ] a = new int[n1]; // array of grades int j = 0; // array index place holder while ( j < n1) do System.out.print("Enter the grades : "); grade = reader.nextint(); } while (grade < 0 grade > 100); a[ j++ ] = grade; } // outer while return a; } // method inputgrades 35

Rest methods static int avggrades(int [ ] b) int sum = 0; // sum of grades for(int i = 0;i < b.length;i++) sum+ = b[i]; return sum / b.length; } // avggrades static void updgrades(int[ ] c, int avg) for(int i =0;i < c.length;i++) if(c[i] < avg) c[i]+ = 5; } // updgrades static void printgrades(int[ ] d) for(int i = 0;i < d.length; i++) System.out.println(" The "+ (i+1) + " student s grade is " + d[i]); } // printgrades 36

The main method The main method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration must look like the following: public static void main(string [ ] args) Sometimes you will want to pass information into a program when you run it. This is accomplished by passing commandline arguments to main( ). A command-line argument is the information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ). 37

Java method overloading In Java method overloading ( העמסה ) means creating more than a single ). חתימה /כותרת הפעולה ( signatures method with same name with different For example: public class Overload public static void test(int a) System.out.println("a: " + a); } // test public static void test(int a, int b) System.out.println("a and b: " + a + "," + b); } // test public static double test(double a) System.out.println("double a: " + a); return a*a; } Next slide cont. } // test 38

Java method overloading, cont. public static void main(string args [ ]) double result; test(10); test(10, 20); result = test(5.5); System.out.println("Result : " + result); } // main } // Overload Output will be displayed as: a :10 a and b : 10,20 double a : 5.5 Result : 30.25 39

Java method overloading, cont. As you can see, method test( ) is overloaded three times. The first version takes one integer parameter: public static void test(int a) The second takes two integer parameters: public static void test(int a, int b) The third takes one double parameter: public static double test(double a) When an overloaded method is called, Java looks for : A match between the arguments used to call the method The method's parameters. However, this match need not always be exact. 40