C++ Methods Quick Notes at a
Glance
- What is a Function?
A function is a block of code that performs a specific task.
It helps in:
Code reusability
Easy debugging
Better program structure
Example:
#include <iostream>
using namespace std;
void greet() // function definition
{
cout << "Welcome to C++";
}
int main()
{
greet(); // function call
return 0;
}
- Function Declaration (Prototype)
It tells the compiler:
Function name
Return type
Parameters
Syntax: return_type function_name(parameter_list);
Example
#include <iostream>
using namespace std;
int add(int, int); // declaration
int main()
{
cout << add(3, 4);
return 0;
}
int add(int a, int b) // definition
{
return a + b;
}
- Function Definition
Contains the actual code of the function.
Example
int square(int n)
{
return n * n;
}
- Function Calling
RAMAKRISHNA ACADEMY 7003793770
1
C++ Methods Quick Notes at a
Glance
Executing a function by writing its name inside main() or another function.
Example
cout << square(5);
- Types of Functions
(a) Library Functions
Predefined functions available in C++.
Examples:
sqrt()
pow()
strlen()
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << sqrt(25);
return 0;
}
(b) User-Defined Functions
Functions created by the programmer.
void show()
{
cout << "User Defined Function";
}
- Function with Arguments & Return Value
Example
#include <iostream>
using namespace std;
int sum(int a, int b)
{
return a + b;
}
int main()
{
cout << sum(10, 20);
return 0;
}
- Call by Value
Copy of actual value is passed.
Changes inside function do NOT affect original value.
Example
#include <iostream>
using namespace std;
RAMAKRISHNA ACADEMY 7003793770
2
C++ Methods Quick Notes at a
Glance
void change(int x)
{
x = 50;
}
int main()
{
int a = 10;
change(a);
cout << a; // Output: 10
return 0;
}
- Call by Reference
Address of variable is passed.
Changes affect original value.
Example
#include <iostream>
using namespace std;
void change(int &x)
{
x = 50;
}
int main()
{
int a = 10;
change(a);
cout << a; // Output: 50
return 0;
}
- Inline Function
Function expanded at compile time
Used for small functions
Improves performance
Example
#include <iostream>
using namespace std;
inline int cube(int x)
{
return x * x * x;
}
int main()
{
cout << cube(3);
return 0;
}
- Recursive Function
A function that calls itself.
RAMAKRISHNA ACADEMY 7003793770
3
C++ Methods Quick Notes at a
Glance
Example: Factorial
#include <iostream>
using namespace std;
int fact(int n)
{
if(n == 0)
return 1;
else
return n * fact(n - 1);
}
int main()
{
cout << fact(5); // Output: 120
return 0;
}
- Advantages of Functions
Reduces code repetition
Improves readability
Easy testing & debugging
Modular programming
RAMAKRISHNA ACADEMY 7003793770
4