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 ofticketsat £5 each- Define it with a parameter:
function calculatePrice(tickets) - Calculate using the parameter:
price = tickets * 5 - Return the value:
return pricethenendfunction
- Define it with a parameter:
How do you call an existing function and keep the value it returns?
e.g. use
calculatePrice()for 3 tickets and store the result intotalPricetotalPrice = 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
greetthat prints a welcome for a name- Declare it with any parameters:
procedure greet(name) - Write the task, then end it:
print("Welcome " + name)…endprocedure - Call it by name with arguments:
greet("Sam")
- Declare it with any parameters:
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 arrayscoresinto a procedureprintAllUse 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 functiondoubleAllthat doubles each element of an array of numbers- Define it with an array parameter:
function doubleAll(nums) - Loop through and change each element:
nums[i] = nums[i] * 2 - Return the array:
return nums, called asnewList = doubleAll(scores)
- Define it with an array parameter: