For 2 minutes write down whatever comes to mind about the last class
This could be topics you learned
Questions you had
Connections you made
Defining Functions
Functions are everywhere in programming!
You often use builtin ones such as IO.println
However, you can also define your own
Example: Sum 1 to N
Let’s say to write some code which sums the numbers from 1 to n and returns that sum
We could partially do this inside of main like this:
void main() {
int n = Integer.parseInt(IO.readln());
int result = 0;
int i = 1;
while (i <= n) {
result += i;
i++;
}
IO.println(result);
}
Example: 1 to N
void main() {
int n = Integer.parseInt(IO.readln());
int result = 0;
int i = 1;
while (i <= n) {
result += i;
i++;
}
IO.println(result);
}
Here you get the input from the outside, from the user of the program
You then take that input and do the calculation
Finally, you print the result since this is how you return the result to the user
Defining functions give you a way to take input from within the program, and return the result to another part of the code
Example: 1 to N as a Function
int sum1ToN(int n) {
int result = 0;
int i = 1;
while (i <= n) {
result += i;
i++;
}
return result;
}
Here we take the input, n, from another piece of code
We use this input to perform the calculation
Then we return the result back
Let’s directly compare the two
Comparison
void main() {
int n = Integer.parseInt(IO.readln());
int result = 0;
int i = 1;
while (i <= n) {
result += i;
i++;
}
IO.println(result);
}
int sum1ToN(int n) {
int result = 0;
int i = 1;
while (i <= n) {
result += i;
i++;
}
return result;
}
Using the function
int sum1ToN(int n) {
int result = 0;
int i = 1;
while (i <= n) {
result += i;
i++;
}
return result;
}
void main() {
// Call function with argument 10
IO.println(sum1ToN(10));
// We can also save the result into a variable
int result = sum1ToN(30);
// Then print it or do other thing with it
IO.println(result);
}
Why Functions?
Why bother making a function when we could do the same thing just in main?
We couldn’t reuse the version written in main
All the control was in the hands of the user rather than the programmer
We can even regain the ability to accept user input to guide the function:
int sum1ToN(int n) {
int result = 0;
int i = 1;
while (i <= n) {
result += i;
i++;
}
return result;
}
void main() {
int n = Integer.parseInt(IO.readln());
IO.println(sum1ToN(n));
}
Two Parts of Functions
Declaring the function does nothing other than allow us to use it later
This is the function definition itself
In order to execute the code inside we must call it
This is what we did inside main
Once we call it, it performs its code and then it might return a value back
We can save this value into a variable, print it, pass it to another function, etc.
Function Syntax
int sum1ToN(int n) {
int result = 0;
int i = 1;
while (i <= n) {
result += i;
i++;
}
return result;
}
The first line of a function declares its return type, name, and arguments