As programs become larger, writing all the code inside main() can make the program difficult to understand.
C++ Functions help us divide a program into smaller, reusable blocks of code. For example, you can create one function to add numbers and another function to display a message.
What is a Function?
A function is a block of code that performs a specific task. Instead of writing the same code again and again, you can put it inside a function and call it whenever you need it.
Basic Syntax
returnType functionName() {
// code
}
For example:
#include <iostream>
using namespace std;
void sayHello() {
cout << "Hello, C++!";
}
int main() {
sayHello();
return 0;
}
Output:
Hello, C++!
Here, sayHello() is a function.
Calling a Function
Creating a function does not automatically run it. You need to call the function.
sayHello();
When C++ reaches this statement, it runs the code inside sayHello().
A function can be called multiple times:
#include <iostream>
using namespace std;
void sayHello() {
cout << "Hello!\n";
}
int main() {
sayHello();
sayHello();
sayHello();
return 0;
}
Output:
Hello!
Hello!
Hello!
Function Parameters
Functions can receive information using parameters.
For example:
#include <iostream>
using namespace std;
void greet(string name) {
cout << "Hello, " << name;
}
int main() {
greet("Rahul");
return 0;
}
Output:
Hello, Rahul
Here, name is a parameter.
You can pass different values when calling the function:
greet("Rahul");
greet("Anjali");
Multiple Parameters
A function can have more than one parameter.
#include <iostream>
using namespace std;
void addNumbers(int a, int b) {
cout << "Sum: " << a + b;
}
int main() {
addNumbers(10, 20);
return 0;
}
Output:
Sum: 30
Here, a and b receive the values 10 and 20.
Returning a Value
A function can return a value to the place where it was called.
For example:
#include <iostream>
using namespace std;
int addNumbers(int a, int b) {
return a + b;
}
int main() {
int result = addNumbers(10, 20);
cout << "Sum: " << result;
return 0;
}
Output:
Sum: 30
Here:
return a + b;
sends the result back to main(). Because the function returns an integer, its return type is int.
void Functions
A function that does not return a value can use void.
void sayHello() {
cout << "Hello!";
}
The sayHello() function simply performs a task and does not return anything.
Function Declaration
Sometimes you may want to call a function before writing its complete definition. In that case, you can declare the function first.
#include <iostream>
using namespace std;
void sayHello();
int main() {
sayHello();
return 0;
}
void sayHello() {
cout << "Hello, C++!";
}
Here:
void sayHello();
is called a function declaration. It tells the compiler that the function exists.
A Simple Example
Let’s create a function that checks whether a number is even or odd.
#include <iostream>
using namespace std;
void checkNumber(int number) {
if (number % 2 == 0) {
cout << "Even number";
} else {
cout << "Odd number";
}
}
int main() {
checkNumber(10);
return 0;
}
Output:
Even number
The function receives 10, checks the number, and displays the result.
Call by Value
In call by value, a copy of the variable is passed to the function. So, if we change the value inside the function, the original variable does not change.
#include <iostream>
using namespace std;
void changeValue(int number) {
number = 100;
}
int main() {
int number = 50;
cout << "Before function call: " << number << "\n";
changeValue(number);
cout << "After function call: " << number;
return 0;
}
Output:
Before function call: 50
After function call: 50
The value is still 50 because the function received a copy of the original value.
Call by Reference
In call by reference, the function works with the original variable. We use the & symbol with the parameter.
#include <iostream>
using namespace std;
void changeValue(int &number) {
number = 100;
}
int main() {
int number = 50;
cout << "Before function call: " << number << "\n";
changeValue(number);
cout << "After function call: " << number;
return 0;
}
Output:
Before function call: 50
After function call: 100
Here, the original value changes from 50 to 100.
Easy Difference
Call by Value
→ Sends a copy
→ Original value does not change
Call by Reference
→ Works with the original variable
→ Original value can change
Recursion
Recursion happens when a function calls itself.
Let’s create a simple program that counts down from 5.
#include <iostream>
using namespace std;
void countDown(int number) {
if (number == 0) {
return;
}
cout << number << "\n";
countDown(number - 1);
}
int main() {
countDown(5);
return 0;
}
Output:
54321
The function keeps calling itself using:
countDown(number-1);
The if condition stops the function when the number becomes 0.
A recursive function should always have a stopping condition. Otherwise, it can keep calling itself again and again.
Recursion Example: Factorial
Recursion can also be used to calculate a factorial.
For example:
5! = 5 × 4 × 3 × 2 × 1
Complete program:
#include <iostream>
using namespace std;
int factorial(int number) {
if (number == 1) {
return 1;
}
return number * factorial(number - 1);
}
int main() {
int number = 5;
int result = factorial(number);
cout << "Factorial of " << number << " is " << result;
return 0;
}
Output:
Factorial of 5 is 120
These three sections can be added to your existing chapter without changing the rest of your content.
Why Use Functions?
Functions make programs:
- Easier to read
- Easier to organize
- Easier to test
- Easier to reuse
- Easier to maintain
Instead of putting everything inside main(), you can divide a large program into smaller functions.
Key Points to Remember
- A function is a reusable block of code.
- A function performs a specific task.
- You call a function using its name followed by
(). - Parameters allow a function to receive values.
- A function can return a value using
return. voidis used when a function does not return a value.- Functions help keep large programs organized.
Mini Quiz
Mini Project
Mini Project: Student Result Calculator
Question:
Write a C++ program that calculates and displays a student’s result.
- Store marks for three subjects.
- Calculate the total marks.
- Calculate the average marks.
- Display the total and average.
- Check whether the student has passed or failed using
if/else. - Use functions to organize the program.
- Display the final result.
View Answer Code
#include <iostream>
using namespace std;
int calculateTotal(int mark1, int mark2, int mark3) {
return mark1 + mark2 + mark3;
}
double calculateAverage(int total) {
return total / 3.0;
}
void displayResult(int total, double average) {
cout << "Total: " << total << "\n";
cout << "Average: " << average << "\n";
if (average >= 40) {
cout << "Result: Pass";
} else {
cout << "Result: Fail";
}
}
int main() {
int mark1 = 75;
int mark2 = 68;
int mark3 = 82;
int total = calculateTotal(mark1, mark2, mark3);
double average = calculateAverage(total);
displayResult(total, average);
return 0;
}
What’s Next?
In the next chapter, we will learn about C++ Pointers and understand how pointers can store and work with memory addresses.
Frequently Asked Questions (FAQs)
Q1. What are C++ Functions?
C++ Functions are reusable blocks of code designed to perform specific tasks. They help divide large programs into smaller and manageable parts.
Q2. How do you create a C++ function?
A C++ function is created by specifying a return type, function name, parameters if needed, and a block of code containing the task to perform.
Q3. What are C++ function parameters?
C++ function parameters are variables that allow a function to receive values when it is called. For example, void greet(string name) has name as a parameter.
Q4. How does a C++ function return a value?
A C++ function return value is sent back using the return statement. The function’s return type must match the type of value it returns.
Q5. What is a C++ function declaration?
A C++ function declaration tells the compiler about a function before its complete definition appears. For example, void sayHello(); is a function declaration.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
