Dragon/Lessons/Functions

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Functions[edit]

In this chapter we are going to learn about the next topics :-

  • Define functions
  • Call functions
  • Declare parameters
  • Send parameters
  • Variables Scope
  • Return Value

Define Functions[edit]

To define new function

Syntax:

	def <function_name> (parameters)
           {
		Block of statements
        
            }


Example:

	def hello()
          {
		showln "Hello from function"
           }

Call Functions[edit]

.. tip:: We can call the function before the function definition and the function code.

Example:

	hello()

	def hello()
          {
		showln "Hello from function"
           }


Example:

	first()  second()

	def first(){
          showln "message from the first function" 
            }

	def second(){
          showln "message from the second function" 
            }

Declare parameters[edit]

To declare the function parameters, write them in parentheses.

Example:

	def sum(x,y)
         {
           showln x+y
         }

Send Parameters[edit]

To send parameters to function, type the parameters inside () after the function name

Syntax:

	name(parameters)

Example:

	/* output
	** 8
	** 3000
	*/

	sum(3,5) sum(1000,2000)

	def sum(x,y)
        {
        showln x+y
        }


Variables Scope[edit]

The Dragon programming language uses `lexical scoping <http://en.wikipedia.org/wiki/Scope_%28computer_science%29#Lexical_scope_vs._dynamic_scope>`_ to determine the scope of a variable.

Variables defined inside functions (including function parameters) are local variables. Variables defined outside functions (before any function) are global variables.

Inside any function we can access the variables defined inside this function beside the global variables.

Example:

	// the program will print numbers from 10 to 1

	x = 10 				// x is a global variable.


		for(t = 1,t <11,t++)		// t is a local variable
			mycounter()	    // call function
		

	def mycounter(){

		showln x		// print the global variable value
		x--			//decrement
                }


Return Value[edit]

The function can return a value using the Return command.

Syntax:

	return [Expression]


Example:

	showln my(30,40)      //prints 70
       
        def my(a,b)
       { 
          return a+b
       }