Beginner Functions - 1
Beginner Functions - 1
1. Factorial
2. Function Intro
3. Sum()
4. Quizzes
5. Power function
6. Ceil/floor
7. Assignments
Factorial
Given an non negative integer N, the factorial of N is defined as follows:
Factorial Output
4! 4 * 3 * 2 * 1 = 24
3! 3*2*1=6
Question
What is the factorial of 5?
Choices
5
15
24
120
Code:
Question
Calculate
Choices
10
15
20
25
Explanation:
Small Question:
Functions
Give a real-life analogy. Suppose you need a screw-driver. First time you will buy that screw driver. From next time onwards you will use the same screw-driver.
Structure of a function:
Diagram/Flow Chart for Factorial function:
What is the need of a function? To reuse the code, i.e., we dont need to write the same code again and again.
Syntax of a function:
Factorial function:
Output:
120
We cannot call non static functions from inside static functions. Since the main function is static, so to call the factorial function from inside the main function, we
need to make the factorial function as static by writing the keyword static in front of it.
Code
Question
What is the output of the following code?
Choices
15
Error
None
Explanation: This is because we are not printing the answer in the code.
Question
What is the output of the following code?
static int sum(int a, int b){
return a + b;
}
Choices
Error
15
No output
System.out.println(max_of_two(5,9));
Output:
Code
Stress that the function needs to print the value rather than returning it.
static void product_of_two(int a, int b){
int product = a * b;
System.out.println(product);
}
The return type of the function changes from int to void . void data type is used to denote that the function is not returning anything.
product_of_two(5,9);
Output:
45
Question
What is the output of the following code?
Choices
Error
15
No output
Explanation: The return type of the function is wrong. You are returning an int, but the return type is set to void.
Question
What is the output of the following code?
Choices
15
25
Error
No output
Question
What is the output of the following code?
Choices
-36
36
6
Error
Question
What is the output of the following code?
Choices
81
9
90
115
Ceil Function
ceil(3.42) = 4
ceil(5.67) = 6
Question
What is the value of ceil(6.5) ?
Choices
6
7
8
9
Question
What is the value of ceil(6) ?
Choices
7
6
5
4
Question
What is the value of ceil(-3.4) ?
Choices
-3
-2
-4
-1
Question
What is the value of ceil(-4.5) ?
Choices
-3
-4
-5
-6
Floor Function
Given a number $x$, return the greatest integer that is $<= x$.
floor(3.2) = 3
floor(5.67) = 5
floor(6.5) = 6
floor(-3.4) = -4
floor(-4.5) = -5
floor(-7) = -7
Predefined functions
Functions which are already defined in the coding languages to make life simpler. Rules for using predefined functions.
1. Check parameters
2. Check return type
Examples:
1. Math.ceil()
2. Math.floor()
3. Math.power(a,b)
Math.ceil 1 double
Math.floor 1 double
Math.power 2 double
Math.random()
Math.abs()