Download presentation
Presentation is loading. Please wait.
1
Methods & Functions
2
Methods A function is a code block containing a series of statements that are focused on producing a single result Functions differ from methods in that they return a value. The value type is predefined in the declaration of the function. Every function must contain at least one return statement outside of a conditional
3
int[] searchArray = new int[50]; //Create a new array of size 50
// void setup() { size(500,500); if( initArray(searchArray)){ find(50); //call find functions to find certain values find(12); find(76); } boolean initArray(int[] s) for(int j=0; j < s.length; j++) s[j] = random(1,100); //initialize array to random numbers return true; void find(int searchKey) boolean isFound = false; //set a 'flag' to see if we found the value for (int i = 0; i < searchArray.Length; i++) //loop through entire array values if (searchKey == searchArray[i]) //check for a match text("Found “ + str(searchKey) + ” at " + str(i), 100, 100); //write to console index of found value isFound = true; if(!isFound) //write out msg to console if we didn't find the value text("Sorry, could not find " + str(searchKey) + " in array", 100, 100); }// find
4
Methods vs Functions Method Function int squareANumber(int number)
No return type Method name Parameter(s) void squareANumber(int number) { int square = number * number; text(str(square),100, 100); } int squareANumber(int number) return number * number; Function Integer return type Function name Parameter(s) Return statement
5
Functions - return statement
At least one return statement must exist outside of a conditional int getValue() { if(!blocked) return -1; } return value;
6
Task 1. Write a small program that declares an int array called grades. This array will be of size 10 integer grade numbers (between 0 and 100) 2. Write a second array of strings called students. Initialize this second array manually with 10 names (“last, first”) of your choice. For the program write a method or function: a) void init() that initializes grades to random integers. b) void print() that writes the names of the students and their grade c) void set(int grade, String student) that sets a certain student’s grade to a specified grade d) int get(String student) that gets and returns a certain student’s grade e) void sort() that sorts the grades from lowest to highest
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.