In C++, functions can be classified into built-in functions and user-defined functions.

Built-in Functions:

  • Provided by C++ or its libraries.

  • Already written, tested, and ready to use.

  • Examples: cout(), cin(), sqrt(), pow(), strlen()

User-defined Functions:

  • Written by the programmer.

  • Custom functions to perform specific tasks.

  • Examples: add(), multiply(), factorial(), greet()

Comparison Table

FeatureBuilt-in FunctionsUser-defined Functions
Written byCompiler/Programmer LibraryProgrammer
ReusabilityPredefinedCustomizable
ComplexityAlready tested and optimizedProgrammer needs to debug
FlexibilityFixedFully flexible
Examplessqrt(), abs(), strlen()add(), multiply(), factorial()

Examples of Built-in Functions

  1. sqrt() – Calculates square root

 
#include <iostream>

#include <cmath>

using namespace std;
int main() {
cout << sqrt(16); // Output: 4

return 0;
}
  1. pow() – Raises number to power

 
#include <iostream>

#include <cmath>

using namespace std;
int main() {
cout << pow(2, 3); // Output: 8

return 0;
}
  1. abs() – Absolute value

 
#include <iostream>
#include <cmath>

using namespace std;
int main() {
cout << abs(-10); // Output: 10
return 0;
 
}
  1. strlen() – Length of string

 
#include <iostream>

#include <cstring>
using namespace std;
int main() {
char str[] = "Hello";
cout << strlen(str); // Output: 5

return 0;
}
  1. toupper() – Converts character to uppercase

 
#include <iostream>

#include <cctype>
using namespace std;
int main() {
char ch = 'a';
cout << (char)toupper(ch); // Output: A

return 0;
}

Examples of User-defined Functions

  1. Function to add two numbers

 
int add(int a, int b) {
return a + b;
}
  1. Function to calculate factorial

 
int factorial(int n) {
if(n == 0) return 1;
return n * factorial(n-1);
}
  1. Function to check even or odd

 
bool isEven(int n) {
return n % 2 == 0;
}
  1. Function to greet a user

 
void greet(string name) {
cout << "Hello, " << name << "!";
}
  1. Function to find maximum of two numbers

 
int max(int a, int b) {
return (a > b) ? a : b;
}
  1. Function to calculate area of rectangle

 
float area(float length, float width) {
return length * width;
}
  1. Function to swap two numbers (pass by reference)

 
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
  1. Function to check prime number

 
bool isPrime(int n) {
if(n <= 1)
return false;
for(int i = 2; i*i <= n; i++) {
if(n % i == 0)
return false;
}
return true;
}
  1. Function to calculate sum of array elements

 
int sumArray(int arr[], int size) {
int sum = 0;
for(int i = 0; i < size; i++)
sum += arr[i];
return sum;
}
  1. Function to reverse a string

 
#include <algorithm>
void reverseString(char str[]) {
int n = strlen(str);
for(int i = 0; i < n/2; i++)
swap(str[i], str[n-i-1]);
}
  1. Function to print multiplication table

 
void printTable(int n) {
for(int i = 1; i <= 10; i++)
cout << n << " x " << i << " = " << n*i << endl;
}
  1. Function to find largest in array

 
int largest(int arr[], int size) {
int maxVal = arr[0];
for(int i = 1; i < size; i++)
if(arr[i] > maxVal)
maxVal = arr[i];
return maxVal;
}
  1. Function to calculate power recursively

 
int power(int base, int exp) {
if(exp == 0)
return 1;
return base * power(base, exp-1);
}
  1. Function to count digits in number

 
int countDigits(int n) {
int count = 0;
while(n) {
n /= 10;
count++;
}
return count;
}
  1. Function to convert Celsius to Fahrenheit

 
float cToF(float c) {
return (c * 9/5) + 32;
}
  1. Function to check palindrome number

 
bool isPalindrome(int n) {
int rev = 0, temp = n;
while(temp) {
rev = rev*10 + temp%10;
temp/=10;
}
return rev == n;
}
  1. Function to calculate GCD

 
int gcd(int a, int b) {
while(b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
  1. Function to calculate LCM

 
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
  1. Function to swap without temp variable

 
void swapNoTemp(int &a, int &b) {
a = a + b;
b = a - b;
a = a - b;
}
  1. Function to print Fibonacci series

 
void fibonacci(int n) {
int a = 0, b = 1;
for(int i = 0; i < n; i++) {
cout << a << " ";
int next = a + b;
a = b;
b = next;
}
}

Best Practices for Functions

  • One Task Per Function: Each function should do only one thing.

  • Use Meaningful Names: Name functions like calculateSum() instead of func1().

  • Keep Functions Small: Avoid very long functions.

  • Pass by Reference When Needed: For large data or arrays to improve efficiency.

  • Avoid Global Variables: Prefer parameters and return values.

  • Comment Functions: Write purpose, parameters, and return values.

  • Use Const Where Applicable: For data that shouldn’t be modified.

  • Reusability: Write functions that can be reused in multiple parts of your program.

Extra Related Concepts

  • Recursive Functions: Functions can call themselves.

  • Inline Functions: Use for small, frequently called functions.

  • Default Parameters: Provide default values if arguments are not passed.

  • Function Overloading: Same function name with different parameter types.

  • Return by Reference: For large objects to avoid copying.

  • Function Templates: Generic functions that work with multiple data types.

Common Best Practice Questions

  • When should you use built-in vs user-defined functions?

  • How can you improve efficiency when passing large arrays to functions?

  • Why should each function perform one specific task?

  • What is the difference between return by value and return by reference?

  • How can you avoid code duplication using functions?