Professional Documents
Culture Documents
ITE001 Module4 Functions2
ITE001 Module4 Functions2
Functions
Intended Learning Outcomes (ILOs)
• Problem: Write a program that will display two number using void function. Create a function name
"addTwoNumbers" with the data type void..
#include<iostream> //header file
using namespace std; OUTPUT:
void addTwoNumbers(int , int); //declaring function The sum is 12
• If you want the function to return a value, you can use a data type ( such
as int, string, etc.) instead of void, and use the return keyword inside the
function.
• Here is an example of returning values from function declaration:
int addTwoNumbers(int, int);
Example Returning Values from Functions ( with return value)
• Problem: Write a program that will display two number using returning values from function. Create a function name
"addTwoNumbers" with the data type int.
#include<iostream> //header file
OUTPUT:
using namespace std;
The sum is 12
int addTwoNumbers(int , int); declaring function
• This method copies the actual value of an argument into the formal parameter of the function. In
this case, changes made to the parameter inside the function have no effect on the argument.
• Copy of the argument’s value is passed to the function.
• Changes made to the formal parameter does not affect the actual parameter
Example Function Call by Value
• Problem: Write a program that will display swap the two number using function call by value. Create a function name
“swap" with the data type int.
#include<iostream>
//Function swap Code
using namespace std;
int swap(int x, int y){
int swap(int a, int b); // declaring function
int temp=x;
x = y;
main() {
y = temp;
int a=10, b=20;
} //end function
cout<<"Before Swap\n";
cout<<a <<" " << b;
OUTPUT:
swap(a,b); //calling the function swap Before swap:
cout<<"After Swap\n"; 1020
cout<<a <<" " << b; After swap:
} //end main 1020
Function - Call by Reference
• Problem: Write a program that will display swap the two number using function call by reference. Create a function name
“swap" with the data type int.
#include<iostream> //Function swap Code
using namespace std; int swap(int &x, int &y){
int swap(int &x, int &y); // declaring function int temp=x;
x = y;
main() { y = temp;
int a=10, b=20; } //end function
cout<<"Before Swap\n";
cout<<a <<" " << b;