Csc121 - Topic 6 Algorithm Design For Programs Using Modules (Functions)
Csc121 - Topic 6 Algorithm Design For Programs Using Modules (Functions)
#include <iostream>
using namespace std;
void duplicate (int& a, int& b, int & c); void duplicate (int& a, int& b, int & c)
int main() {
{ a*=2;
int x=1, y=3, z=7; b*=2;
duplicate (x,y,z); c+=2;
cout << "x="<<x<<", y=“<<y<<", z="<<z; }
return 0;
}
3.B - PARAMETER PASSING:
PASSING-BY-REFERENCE
• Reference arguments are indicated by the ampersand (&) following the
data type:
int& a
• When the function is called, a will become a reference to the argument.
• Since a reference to a variable is treated exactly the same as the variable
itself, then any changes made to the reference are passed through to the
argument!
void duplicate (int& a, int& b, int& c)
void duplicate (int& x int& y int& z
void duplicate (int& x, int& y, int& z);
3.B - PARAMETER PASSING:
PASSING-BY-REFERENCE
• Sometimes we need a function to return multiple values.
• However, functions can only have one return value.
• One way to return multiple values is using reference parameters.
• Advantages of Pass By Reference:
• It allows us to have the function change the value of the argument, which is
sometimes useful.
• Because a copy of the argument is not made, it is fast, even when used with
large structs or classes.
• We can return multiple values from a function.
3.B - PARAMETER PASSING:
PASSING-BY-REFERENCE
3.B - PARAMETER PASSING:
PASSING-BY-REFERENCE
3.C PARAMETER PASSING:
PASSING-BY-VALUE vs PASSING-BY-REFERENCE
4. ALGORITHM DEVELOPMENT FOR
MODULAR PROGRAMMING
(PSEUDOCODE AND FLOWCHART)
Example 1:
Calculate the sum and average of 2 numbers
Example 1:
Calculate the sum and average of 2 numbers
CORRECT WRONG
Example 1:
Calculate the sum and average of 2 numbers
Example 1:
Calculate the sum and average of 2 numbers
Example 2:
Calculate the area of one circle
Example 2:
Calculate the area of one circle
Example 2:
Calculate the area of one circle
THE END