Chapter 5 Function
Chapter 5 Function
CHAPTER 5
Why use Function
You can simplify programming tasks by breaking
programs into smaller logical components.
Function are used to divide a large code into module, due
to this we can easily debug and maintain the code.
E.g. if we write a calculator programs at that time we can
write every logic in a separate function [For addition
sum(), for subtraction sub()].
Any function can be called many times.
Code Re-usability
#include<iostream.h> Sum:
33
int main()
{
sum(); // calling the function
return 0;
}
double x;
x = pow(2.0, 10.0);
Return Type
void main(){
int a=111, b=222;
swap(a, b); // passing value to function
cout<<"Value of a: "<< a <<endl;
cout<<"Value of b: "<< b <<endl;
}
Computer Programming 03/27/2025 22
Example: Call by Reference
function
#include<iostream.h>
void main(){
int a=111, b=222;
swap(&a, &b); // passing value to function
cout<<"Value of a: "<< a <<endl;
cout<<"Value of b: "<< b <<endl;
}
Computer Programming 03/27/2025 23
Summary: Argument
Passing
Arguments passed by value and by reference.
For example:
N.B., the return type of all these 4 functions are not same.
Overloaded functions may or may not have different return
type but it should have different argument(s).
double test(int a) { }
int test(int b) { }
Computer Programming
// ERROR CODE!!!03/27/2025 26