Methods - PowerPoint PPT Presentation

1 / 12
About This Presentation
Title:

Methods

Description:

Just put in the input and it would generate and provide the result to the main function. ... Similarly, it is not necessary to put in parameters. E.g: void printHello ... – PowerPoint PPT presentation

Number of Views:41
Avg rating:3.0/5.0
Slides: 13
Provided by: asim
Category:
Tags: methods

less

Transcript and Presenter's Notes

Title: Methods


1
Methods
  • Introduced to remove repetitive pieces of code in
    your program
  • Transition from sequential programming to
    structured programming
  • Also known as functions

2
Example Initial Code
  • public static void main(String args)
  • int input1,input2 // Taken from user
  • int result11, result21 // Taken from user
  • .
  • for(int iinput1igt1i--) result1i
  • for(int jinputjgt1j--) result2j
  • .

3
Example Changed Code
  • public static void main(String args)
  • int input1,input2 // Taken from user
  • int result11, result21 // Taken from user
  • .
  • result1 factorial(input1)
  • result2 factorial(input2)
  • .

4
Method Definition
  • int factorial(int in)
  • int retvalue 1
  • for(int i in i gt 1 i )
  • retvalue i
  • return retvalue

5
Methods (Contd)
  • The factorial function is acting like a black
    box. Just put in the input and it would generate
    and provide the result to the main function.
  • The return types and the parameters types should
    be consistent with the variables used!

6
Methods (Contd)
  • It is not essential to return
  • Eg
  • void printName(String name)
  • System.out.println(name)

7
Methods (Contd)
  • Similarly, it is not necessary to put in
    parameters
  • E.g
  • void printHello()
  • System.out.println(Hello)
  • const String getConstantString()
  • const String s abc return s

8
Exercise I
  • Implement the following problem by using methods
    (i) Add, (ii) Factorial
  • User puts in two numbers input1 and input2
  • Returns add(factorial(input1)factorial(input2))

9
Solution
  • public class Main
  • public static void main(String args)
  • int input1, input2
  • int fact1, fact2
  • //inputs taken from user through console
  • fact1 factorial(input1)
  • fact2 factorial(input2)
  • System.out.println(Add(fact1, fact2))

10
Solution (Contd)
  • public static int factorial(int in)
  • int result 1
  • for(int i 1 i lt in i)
  • result i
  • return result

11
Solution (Contd)
  • public static int Add(int a, int b)
  • int r a b
  • return r
  • // Closing brace of class Main

12
Bonus Exercise II
  • Implement an add function between 2 positive
    integers. Previously you were not allowed to use
    the binary operators This time you are NOT EVEN
    allowed to use any kind of loops
  • Hint Try using the add function within the add
    function (recursive function)
Write a Comment
User Comments (0)
About PowerShow.com