Category: 4. Function

https://cdn3d.iconscout.com/3d/premium/thumb/function-3d-illustration-download-in-png-blend-fbx-gltf-file-formats–cogwheel-service-cog-miscellaneous-pack-illustrations-4312348.png?f=webp

  • What is Recursion?

    Dart Recursion is the method where a function calls itself as its subroutine. It is used to solve the complex problem by dividing it into sub-part. A function which is called itself again and again or recursively, then this process is called recursion.

    The iterators can be an option to solve problems, but recursion is recommended to the programmers to deal with complex problems because it is an effective approach of problem-solving technique. It requires less time and code to evaluate the same complex task.

    Recursion makes many calls to the same function; however, there should be a base case to terminate the recursion.

    Recursion uses the divide and conquers technique to solve a complex mathematical computation task. It divides the large task into small chunks.

    Recursion is not recommended to solve all types of problems. However, it is best for a few questions such as searching, sorting, Inorder/Preorder/Postorder, Tree Traversal, and DFS of Graph algorithms. But, while using recursion, it must be implemented carefully; otherwise, it turns into the infinite loop.

    What is base condition in recursion?

    void main() {  
    
       int factorial(int num){  
    
         
    
      if(num<=1) { // base case  
    
            return 1;  
    
      else{  
    
             return n*fact(n-1);  
    
     }  
    
    }      
    
    }  
    
    }  

      In the above example, the base case is defined as n<=1, and a larger value of a number can be solved by changing to a lesser one till the base case is matched.

      Note – The base case or valid terminating condition is required in recursion function; otherwise, it will turn into an infinite loop.

      Dart Recursive Function

      Recursive functions are quite similar to the other functions, but difference is to calling itself recursively. A recursive function repeats multiple times until it returns the final output. It allows programmers to solve complex problems with minimal code.

      How does recursion works?

      Let’s understand the concept of the recursion of the example of a factorial of a given number. In the following example, we will evaluate the factorial of n numbers. It is the series of the multiplication as follows.

      Factorial of n (n!) = n*(n-1)*(n-2)........1  
      Dart Recursion

      Characteristics of Recursive Function

      The characteristics of the recursive function are given below.

      • A recursive function is a unique form of a function where function calls itself.
      • A valid base case is required to terminate the recursive function.
      • It is slower than the iteration because of stack overheads.

      Let’s have a look at recursion syntax:

      Syntax:

      void recurse() {  
      
        //statement(s)  
      
       recurse();  
      
      //statement(s);  
      
      }  
      
      void main(){  
      
         //statement(s)  
      
        recurse();  
      
       //statement(s)  
      
      }

        Let’s understand the following example.

        Example – 1

        int factorial(int num){  
        
            
        
          //base case of recursion.   
        
          if(num<=1) { // base case  
        
                return 1;  
        
        }  
        
          else{  
        
                 return num*factorial(num-1);    //function call itself.  
        
         }  
        
        }  
        
        void main() {  
        
          var num = 5;  
        
          // Storing function call result in fact variable.  
        
          var fact = factorial(num);  
        
          print("Factorial Of 5 is: ${fact}");  
        
        } 

          Output:

          Factorial Of 10 is: 120
          

          Explanation:

          In the above example, the factorial() is a recursive function as it call itself. When we called the factorial() function by passing the integer value 5, it will recursively call itself by decreasing the number.

          The factorial() function will be called every time until it matched the base condition, or it is equal to one. It multiplied the number with factorial of the number. Consider the following explanation of the recursive call.

          factorial(5)              # 1st call with 5  
          
          5 * factorial(4)          # 2nd call with 4  
          
          5 * 4 * factorial(3)      # 3rd call with 3  
          
          5 * 4 * 3 * factorial(2)  # 4th call with 2  
          
          5 * 4 * 3 * 2 * 1         # return from 2nd call  
          
          120                    # return from 1st call 

            The recursion is ended when the number reduced to 1, and it is the base condition of recursion.

            A recursion function must have a base condition to avoid to infinite call.

            Disadvantage of Recursion

            • The recursive calls consume a lot of memory; that’s why these are inefficient.
            • The recursive functions are difficult to debug.
            • Sometimes, It is hard to follow the logic behind the recursion.
          1. The main() function

            The main() function is the top-level function of the Dart. It is the most important and vital function of the Dart programming language. The execution of the programming starts with the main() function. The main() function can be used only once in a program.

            It is responsible for all types of execution such as user-defined statements, functions, and libraries function. The program begins with main() function and we declares variable, and user defined executable statements inside it. The main function returns void and can have an optional List<String> parameter as arguments. The general syntax of the main() function is given below.

            Syntax:

            void main() {  
            
              // main function body  
            
            } 

              Example – 1

              void main()   
              
              {  
              
                print("Welcome To JavaTpoint");  
              
                  
              
               }  

                Output

                Welcome To JavaTpoint
                

                Dart Return Value

                Sometimes the function returns a value after evaluating the function statements to the point where it is called from. The return statement holds the result of the function, and it is transferred to the function call. The return keyword is used to represent the return statement. If the return statement not specified, then the function returns null. The return statement is optional to specify in function, but there can be only one return statement in a function.

                Syntax:

                return <expression/value>;  

                Dart value with Return Value

                Below is given syntax of return value.

                Syntax:

                return_type function_name()   
                
                {  
                
                   //statement(s);  
                
                  return value;  
                
                }  

                  Here is the description of the above syntax.

                  function_name – It represents the function name, which can be any valid identifier.

                  return type – It denotes the return type of the function. It can be any valid data type. The return must be matched with the return type of the function.

                  Let’s understand the following example –

                  Example –

                  void main() {  
                  
                    int mul(int a, int b){  
                  
                          int c = a*b;  
                  
                          return c;  
                  
                  }  
                  
                  print("The multiplication of two numbers: ${mul(10,20)}");  
                  
                  }

                  Output

                  The multiplication of two numbers: 200
                  
                1. Anonymous Function

                  We have learned the Dart Function, which is defined by using a user-define name. Dart also provides the facility to specify a nameless function or function without a name. This type of function is known as an anonymous function, lambda, or closure. An anonymous function behaves the same as a regular function, but it does not have a name with it. It can have zero or any number of arguments with an optional type annotation.

                  We can assign the anonymous function to a variable, and then we can retrieve or access the value of the closure based on our requirement.

                  An Anonymous function contains an independent block of the code, and that can be passed around in our code as function parameters. The syntax is as follows.

                  Syntax:

                  (parameter_list) {  
                  
                     statement(s)  
                  
                  }

                  Let’s consider the following example.

                  Example –

                  void main() {   
                  
                    var list = ["James","Patrick","Mathew","Tom"];  
                  
                    print("Example of anonymous function");  
                  
                    list.forEach((item) {  
                  
                        print('${list.indexOf(item)}: $item');  
                  
                  });  
                  
                  }

                  Output:

                  Example of anonymous function
                  0: James
                  1: Patrick
                  2: Mathew
                  3: Tom
                  

                  Explanation:

                  In the above example, we defined an anonymous function with an untype argument item. The function called for each item in the list and printed the strings with its specified index value.

                  If the function consists of one statement, then we can also write the above code in the following way.

                  list.forEach(  
                  
                  (item) => print("${list.indexOf(item)}: $item"));

                  It is equivalent to the previous code. You can verify it by paste in your dart pad and run.

                  Lexical Scope

                  As we have discussed in the Dart introduction, it is a lexical scope language which means the variable’s scope is decided at compile-time. The scope of the variable is determined when code is compiled. The variable behaves differently if they defined in the different curly braces. Let’s understand the following example.

                  Example –

                  bool topVariable = true;  
                  
                    
                  
                  void main() {  
                  
                    var inside_Main = true;  
                  
                   // Defining Nested Function   
                  
                     
                  
                   void myFunction() {  
                  
                      var inside_Function = true;  
                  
                       
                  
                   void nestedFunction() {  
                  
                        var inside_NestedFunction = true;  
                  
                        // This function is using all variable of the previous functions.  
                  
                        assert(topVariable);  
                  
                        assert(inside_Main);  
                  
                        assert(inside_Function);  
                  
                        assert(inside_NestedFunction);  
                  
                      }  
                  
                    }  
                  
                  } 

                    Observe the above code, the nestedFunction() used the variables of the previous function.

                    Lexical Closure

                    A lexical closure is referred to as a closure, is a function object that has access to variables in its lexical scope even when the function is used of its original scope. In other words, it provides access to an outer function’s scope from inner function. Let’s understand the following example.

                    Example –

                    void main() {  
                    
                     String initial() {  
                    
                         var name = 'Will Smith'; // name is a local variable created by init  
                    
                        
                    
                         void disp_Name() { // displayName() is the inner function, a closure  
                    
                               print(name); // use variable declared in the parent function  
                    
                      }  
                    
                      disp_Name();  
                    
                    }  
                    
                    init();  

                      Output

                      Will Smith
                      

                      Explanation:

                      In the above code, the initial() function created a local variable called name and function called disp_Name(). The disp_Name() function defined inside the initial() function and hence disp_Name() function has no local variable its own.

                      The inner function can access the variable of the outer functions. The function disp_Name() can access the name variable which is declared in the outer function, initial().

                    1. Function

                      Dart function is a set of codes that together perform a specific task. It is used to break the large code into smaller modules and reuse it when needed. Functions make the program more readable and easy to debug. It improves the modular approach and enhances the code reusability.

                      Suppose, we write a simple calculator program where we need to perform operations number of times when the user enters the values. We can create different functions for each calculator operator. By using the functions, we don’t need to write code for adding, subtracting, multiplying, and divide again and again. We can use the functions multiple times by calling.

                      The function provides the flexibility to run a code several times with different values. A function can be called anytime as its parameter and returns some value to where it called.

                      Advantages of Functions

                      The few benefits of the Dart function is given below.

                      • It increases the module approach to solve the problems.
                      • It enhances the re-usability of the program.
                      • We can do the coupling of the programs.
                      • It optimizes the code.
                      • It makes debugging easier.
                      • It makes development easy and creates less complexity.

                      Let’s understand the basic concept of functions.

                      Defining a Function

                      A function can be defined by providing the name of the function with the appropriate parameter and return type. A function contains a set of statements which are called function body. The syntax is given below.

                      Syntax:

                      return_type func_name (parameter_list):  
                      
                      {  
                      
                          //statement(s)  
                      
                         return value;  
                      
                      } 

                      Let’s understand the general syntax of the defining function.

                      • return_type – It can be any data type such as void, integer, float, etc. The return type must be matched with the returned value of the function.
                      • func_name – It should be an appropriate and valid identifier.
                      • parameter_list – It denotes the list of the parameters, which is necessary when we called a function.
                      • return value – A function returns a value after complete its execution.

                      Let’s understand the following example.

                      Example – 1

                      int mul(int a, int b){  
                      
                           int c;  
                      
                           c = a+b;  
                      
                           print("The sum is:${c}");  
                      
                      } 

                      Calling a Function

                      After creating a function, we can call or invoke the defined function inside the main() function body. A function is invoked simply by its name with a parameter list, if any. The syntax is given below.

                      Syntax:

                      fun_name(<argument_list>);  
                      
                      or  
                      
                      variable = function_name(argument);

                      Note – Calling function must be ended with semicolon (;).

                      When we call a function, the control is transferred to the called function. Then the called function executes all defined statements and returns the result to the calling function. The control returns to the main() function..

                      Example :

                      mul(10,20);  

                      Passing Arguments to Function

                      When a function is called, it may have some information as per the function prototype is known as a parameter (argument). The number of parameters passed and data type while the function call must be matched with the number of parameters during function declaration. Otherwise, it will throw an error. Parameter passing is also optional, which means it is not compulsory to pass during function declaration. The parameter can be two types.

                      Actual Parameter – A parameter which is passed during a function definition is called the actual parameter.

                      Formal Parameter – A parameter which is passed during a function call is called the formal parameter.

                      We will learn more about the parameter in the next tutorial.

                      Return a Value from Function

                      A function always returns some value as a result to the point where it is called. The return keyword is used to return a value. The return statement is optional. A function can have only one return statement. The syntax is given below.

                      Dart Function

                      Syntax:

                      return <expression/values>  

                      Example –

                      return result;  

                      Function Examples

                      Let’s understand the functions by using a program of adding two numbers using functions.

                      Dart Function with parameter and return value

                      In the following example, we are creating a sum() function to add two number.

                      Example – 1

                      void main() {  
                      
                        print("Example of add two number using the function");    
                      
                        // Creating a Function  
                      
                        
                      
                        int sum(int a, int b){  
                      
                                  // function Body  
                      
                                  int result;  
                      
                                  result = a+b;  
                      
                                  return result;  
                      
                      }  
                      
                      // We are calling a function and storing a result in variable c  
                      
                      var c = sum(30,20);  
                      
                      print("The sum of two numbers is: ${c}");  
                      
                      }

                      Output

                      Example of add two number using the function
                      The sum of two numbers is: 50
                      

                      Explanation:

                      In the above example, we declared a function named sum() and passed two integer variables as actual parameters. In the function body, we declared a result variable to store the sum of two numbers and returned the result.

                      In order to add two values, we called a function with the same name, passed formal parameters 30 and 20. The sum() returned a value which we stored in the variable c and printed the sum on the console.

                      Dart Function with No Parameter and Return Value

                      As we discussed earlier, the parameters are optional to pass while defining a function. We can create a function without parameter return value. The syntax is given below.

                      Syntax:

                      return_type func_name()   
                      
                      {  
                      
                             //Statement(s);  
                      
                             return value;  
                      
                      } 

                      Let’s understand the following example.

                      Example – 2

                      void main(){  
                      
                      // Creating a function without argument  
                      
                      String greetings(){  
                      
                         return "Welcome to JavaTpoint";  
                      
                      }  
                      
                      // Calling function inside print statement  
                      
                      print(greetings());  
                      
                      }

                      Output

                      Welcome to JavaTpoint
                      

                      Explanation:

                      In the above example, we created a function named greetings() without argument and returned the string value to the calling function. Then, we called the greeting() function inside the print statement and printed the result to the console.

                      Dart Function with No Parameter and without a Return Value

                      We can declare a function without parameter and no return value. The syntax is given below.

                      Syntax:

                      func_name() {  
                      
                       //statement  
                      
                      }  
                      
                      Or  
                      
                      void fun_name() {  
                      
                        //statement(s)  
                      
                      }

                      In the above general syntax-

                      void – It represents the function has no return type.

                      fun_name – It represents the function name.

                      Let’s understand the following example.

                      Example – 3

                      // Creating a function without argument  
                      
                      void greetings()  
                      
                      {  
                      
                         print("Welcome to JavaTpoint");  
                      
                      }  
                      
                      void main() {  
                      
                        print("The example of Dart Function");  
                      
                        // function callling  
                      
                        greetings();  
                      
                      }

                      Output

                      The example of Dart Function
                      Welcome to JavaTpoint
                      

                      Explanation:

                      In the above example, we created a function called greeting() outside the main() function and writing the print statement. Inside the main() function, we called the defined function and printed the output to console.

                      Dart Function with Parameter and without a Return Value

                      We are creating a function to find the given number is even or odd. Let’s understand the following example.

                      Example – 4

                      void main()   
                      
                      {  
                      
                        void number(int n){  
                      
                                 // Check the given number is even or odd  
                      
                                 if (n%2 ==0){  
                      
                                         print("The given number is even");  
                      
                                   }  
                      
                                 else {  
                      
                                        print("The given number is odd");  
                      
                                  }  
                      
                      }  
                      
                         number(20);  
                      
                      } 

                      Output

                      The given number is even