Sub Programs Flashcards

All 8 cards in this deck

What is the difference between a function and a procedure?

A function returns a value to the code that called it; a procedure carries out a task but returns no value.

What are the steps to write a function that takes a parameter and returns a value?

e.g. calculatePrice, giving the cost of tickets at £5 each

  1. Define it with a parameter: function calculatePrice(tickets)
  2. Calculate using the parameter: price = tickets * 5
  3. Return the value: return price then endfunction

How do you call an existing function and keep the value it returns?

e.g. use calculatePrice() for 3 tickets and store the result in totalPrice

totalPrice = calculatePrice(3) — the argument goes in the brackets and the return value is assigned with = (not ==).

What are the steps to write and then call a procedure?

e.g. a procedure greet that prints a welcome for a name

  1. Declare it with any parameters: procedure greet(name)
  2. Write the task, then end it: print("Welcome " + name) … endprocedure
  3. Call it by name with arguments: greet("Sam")

What is the difference between a local and a global variable?

A local variable can only be used inside the subprogram where it is declared; a global variable is declared in the main program and can be used by all subprograms.

True or false? A variable declared inside a procedure can still be used in the main program after the procedure ends.

False. It is a local variable, so it only exists within that subprogram.

How do you pass an array into a sub program?
e.g. pass the array scores into a procedure printAll

Use the array's name as the argument in the call: printAll(scores)
The parameter is then used like an array inside the sub program.

What are the steps to write a function that takes an array and returns an array?
e.g. a function doubleAll that doubles each element of an array of numbers

  1. Define it with an array parameter: function doubleAll(nums)
  2. Loop through and change each element: nums[i] = nums[i] * 2
  3. Return the array: return nums, called as newList = doubleAll(scores)